quic.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package config
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "github.com/quic-go/quic-go"
  6. "m7s.live/engine/v4/log"
  7. )
  8. type QuicConfig interface {
  9. ListenQuic(context.Context, QuicPlugin) error
  10. }
  11. type Quic struct {
  12. ListenAddr string `desc:"监听地址,格式为ip:port,ip 可省略默认监听所有网卡"`
  13. CertFile string `desc:"证书文件"`
  14. KeyFile string `desc:"私钥文件"`
  15. }
  16. func (q *Quic) ListenQuic(ctx context.Context, plugin QuicPlugin) error {
  17. listener, err := quic.ListenAddr(q.ListenAddr, q.generateTLSConfig(), &quic.Config{
  18. EnableDatagrams: true,
  19. })
  20. if err != nil {
  21. return err
  22. }
  23. log.Infof("quic listen at %s", q.ListenAddr)
  24. for {
  25. conn, err := listener.Accept(ctx)
  26. if err != nil {
  27. return err
  28. }
  29. go plugin.ServeQuic(conn)
  30. }
  31. }
  32. func (q *Quic) generateTLSConfig() *tls.Config {
  33. // key, err := rsa.GenerateKey(rand.Reader, 1024)
  34. // if err != nil {
  35. // panic(err)
  36. // }
  37. // template := x509.Certificate{SerialNumber: big.NewInt(1)}
  38. // certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
  39. // if err != nil {
  40. // panic(err)
  41. // }
  42. // keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
  43. // certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
  44. // tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
  45. keyPair, err := tls.X509KeyPair(LocalCert, LocalKey)
  46. if q.CertFile != "" || q.KeyFile != "" {
  47. keyPair, err = tls.LoadX509KeyPair(q.CertFile, q.KeyFile)
  48. }
  49. if err != nil {
  50. if Global.LogLang == "zh" {
  51. log.Fatalf("加载证书失败: %v", err)
  52. } else {
  53. log.Fatalf("LoadX509KeyPair error: %v", err)
  54. }
  55. panic(err)
  56. }
  57. return &tls.Config{
  58. Certificates: []tls.Certificate{keyPair},
  59. NextProtos: []string{"monibuca"},
  60. }
  61. }