mirror of
https://github.com/Monibuca/engine.git
synced 2025-10-17 06:00:48 +08:00
69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package config
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
|
|
"github.com/quic-go/quic-go"
|
|
"m7s.live/engine/v4/log"
|
|
)
|
|
|
|
type QuicConfig interface {
|
|
ListenQuic(context.Context, QuicPlugin) error
|
|
}
|
|
|
|
type Quic struct {
|
|
ListenAddr string
|
|
CertFile string
|
|
KeyFile string
|
|
}
|
|
|
|
func (q *Quic) ListenQuic(ctx context.Context, plugin QuicPlugin) error {
|
|
listener, err := quic.ListenAddr(q.ListenAddr, q.generateTLSConfig(), &quic.Config{
|
|
EnableDatagrams: true,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log.Infof("quic listen at %s", q.ListenAddr)
|
|
for {
|
|
conn, err := listener.Accept(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
go plugin.ServeQuic(conn)
|
|
}
|
|
}
|
|
|
|
func (q *Quic) generateTLSConfig() *tls.Config {
|
|
// key, err := rsa.GenerateKey(rand.Reader, 1024)
|
|
// if err != nil {
|
|
// panic(err)
|
|
// }
|
|
// template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
|
// certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
|
|
// if err != nil {
|
|
// panic(err)
|
|
// }
|
|
// keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
|
// certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
|
// tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
|
|
keyPair, err := tls.X509KeyPair(LocalCert, LocalKey)
|
|
if q.CertFile != "" || q.KeyFile != "" {
|
|
keyPair, err = tls.LoadX509KeyPair(q.CertFile, q.KeyFile)
|
|
}
|
|
if err != nil {
|
|
if Global.LogLang == "zh" {
|
|
log.Fatalf("加载证书失败: %v", err)
|
|
} else {
|
|
log.Fatalf("LoadX509KeyPair error: %v", err)
|
|
}
|
|
panic(err)
|
|
}
|
|
return &tls.Config{
|
|
Certificates: []tls.Certificate{keyPair},
|
|
NextProtos: []string{"monibuca"},
|
|
}
|
|
}
|