dialer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package dtls
  2. import (
  3. "context"
  4. "github.com/pion/dtls/v2"
  5. "github.com/v2fly/v2ray-core/v5/common"
  6. "github.com/v2fly/v2ray-core/v5/common/environment"
  7. "github.com/v2fly/v2ray-core/v5/common/environment/envctx"
  8. "github.com/v2fly/v2ray-core/v5/common/net"
  9. "github.com/v2fly/v2ray-core/v5/common/session"
  10. "github.com/v2fly/v2ray-core/v5/transport/internet"
  11. )
  12. func dialDTLS(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (net.Conn, error) {
  13. transportConfiguration := streamSettings.ProtocolSettings.(*Config)
  14. newError("dialing DTLS to ", dest).WriteToLog()
  15. transportEnvironment := envctx.EnvironmentFromContext(ctx).(environment.TransportEnvironment)
  16. dialer := transportEnvironment.Dialer()
  17. rawConn, err := dialer.Dial(ctx, nil, dest, streamSettings.SocketSettings)
  18. if err != nil {
  19. return nil, newError("failed to dial to dest: ", err).AtWarning().Base(err)
  20. }
  21. config := &dtls.Config{}
  22. config.MTU = int(transportConfiguration.Mtu)
  23. config.ReplayProtectionWindow = int(transportConfiguration.ReplayProtectionWindow)
  24. switch transportConfiguration.Mode {
  25. case DTLSMode_PSK:
  26. config.PSK = func(bytes []byte) ([]byte, error) {
  27. return transportConfiguration.Psk, nil
  28. }
  29. config.PSKIdentityHint = []byte("")
  30. config.CipherSuites = []dtls.CipherSuiteID{dtls.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256}
  31. default:
  32. return nil, newError("unknow dtls mode")
  33. }
  34. return dtls.Client(rawConn, config)
  35. }
  36. func dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  37. newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx))
  38. conn, err := dialDTLS(ctx, dest, streamSettings)
  39. if err != nil {
  40. return nil, newError("failed to dial request to ", dest).Base(err)
  41. }
  42. return internet.Connection(conn), nil
  43. }
  44. func init() {
  45. common.Must(internet.RegisterTransportDialer(protocolName, dial))
  46. }