func (v *VMessInboundConfig) Build() (*serial.TypedMessage, error) { config := new(inbound.Config) if v.Defaults != nil { config.Default = v.Defaults.Build() } if v.DetourConfig != nil { config.Detour = v.DetourConfig.Build() } else if v.Features != nil && v.Features.Detour != nil { config.Detour = v.Features.Detour.Build() } config.User = make([]*protocol.User, len(v.Users)) for idx, rawData := range v.Users { user := new(protocol.User) if err := json.Unmarshal(rawData, user); err != nil { return nil, errors.Base(err).Message("Invalid VMess user.") } account := new(VMessAccount) if err := json.Unmarshal(rawData, account); err != nil { return nil, errors.Base(err).Message("Invalid VMess user.") } user.Account = serial.ToTypedMessage(account.Build()) config.User[idx] = user } return serial.ToTypedMessage(config), nil }
func (v *ShadowsocksClientConfig) Build() (*serial.TypedMessage, error) { config := new(shadowsocks.ClientConfig) if len(v.Servers) == 0 { return nil, errors.New("0 Shadowsocks server configured.") } serverSpecs := make([]*protocol.ServerEndpoint, len(v.Servers)) for idx, server := range v.Servers { if server.Address == nil { return nil, errors.New("Shadowsocks server address is not set.") } if server.Port == 0 { return nil, errors.New("Invalid Shadowsocks port.") } if len(server.Password) == 0 { return nil, errors.New("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ Password: server.Password, Ota: shadowsocks.Account_Enabled, } if !server.Ota { account.Ota = shadowsocks.Account_Disabled } cipher := strings.ToLower(server.Cipher) switch cipher { case "aes-256-cfb": account.CipherType = shadowsocks.CipherType_AES_256_CFB case "aes-128-cfb": account.CipherType = shadowsocks.CipherType_AES_128_CFB case "chacha20": account.CipherType = shadowsocks.CipherType_CHACHA20 case "chacha20-ietf": account.CipherType = shadowsocks.CipherType_CHACHA20_IEFT default: return nil, errors.New("Unknown cipher method: " + cipher) } ss := &protocol.ServerEndpoint{ Address: server.Address.Build(), Port: uint32(server.Port), User: []*protocol.User{ { Email: server.Email, Account: serial.ToTypedMessage(account), }, }, } serverSpecs[idx] = ss } config.Server = serverSpecs return serial.ToTypedMessage(config), nil }
func TestUDPEncoding(t *testing.T) { assert := assert.On(t) request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandUDP, Address: v2net.LocalHostIP, Port: 1234, User: &protocol.User{ Email: "*****@*****.**", Account: serial.ToTypedMessage(&Account{ Password: "******", CipherType: CipherType_AES_128_CFB, Ota: Account_Disabled, }), }, } data := buf.NewLocal(256) data.AppendSupplier(serial.WriteString("test string")) encodedData, err := EncodeUDPPacket(request, data) assert.Error(err).IsNil() decodedRequest, decodedData, err := DecodeUDPPacket(request.User, encodedData) assert.Error(err).IsNil() assert.Bytes(decodedData.Bytes()).Equals(data.Bytes()) assert.Address(decodedRequest.Address).Equals(request.Address) assert.Port(decodedRequest.Port).Equals(request.Port) }
func (v *userByEmail) Get(email string) (*protocol.User, bool) { var user *protocol.User var found bool v.RLock() user, found = v.cache[email] v.RUnlock() if !found { v.Lock() user, found = v.cache[email] if !found { account := &vmess.Account{ Id: uuid.New().String(), AlterId: uint32(v.defaultAlterIDs), } user = &protocol.User{ Level: v.defaultLevel, Email: email, Account: serial.ToTypedMessage(account), } v.cache[email] = user } v.Unlock() } return user, found }
func (v *FreedomConfig) Build() (*serial.TypedMessage, error) { config := new(freedom.Config) config.DomainStrategy = freedom.Config_AS_IS domainStrategy := strings.ToLower(v.DomainStrategy) if domainStrategy == "useip" || domainStrategy == "use_ip" { config.DomainStrategy = freedom.Config_USE_IP } config.Timeout = 600 if v.Timeout != nil { config.Timeout = *v.Timeout } if len(v.Redirect) > 0 { host, portStr, err := net.SplitHostPort(v.Redirect) if err != nil { return nil, errors.Base(err).Message("Config: Invalid redirect address: ", v.Redirect, ": ", err) } port, err := v2net.PortFromString(portStr) if err != nil { return nil, errors.Base(err).Message("Config: Invalid redirect port: ", v.Redirect, ": ", err) } if len(host) == 0 { host = "127.0.0.1" } config.DestinationOverride = &freedom.DestinationOverride{ Server: &protocol.ServerEndpoint{ Address: v2net.NewIPOrDomain(v2net.ParseAddress(host)), Port: uint32(port), }, } } return serial.ToTypedMessage(config), nil }
func (v *SocksServerConfig) Build() (*serial.TypedMessage, error) { config := new(socks.ServerConfig) if v.AuthMethod == AuthMethodNoAuth { config.AuthType = socks.AuthType_NO_AUTH } else if v.AuthMethod == AuthMethodUserPass { config.AuthType = socks.AuthType_PASSWORD } else { return nil, errors.New("Unknown socks auth method: " + v.AuthMethod) } if len(v.Accounts) > 0 { config.Accounts = make(map[string]string, len(v.Accounts)) for _, account := range v.Accounts { config.Accounts[account.Username] = account.Password } } config.UdpEnabled = v.UDP if v.Host != nil { config.Address = v.Host.Build() } config.Timeout = v.Timeout return serial.ToTypedMessage(config), nil }
func (v *HttpServerConfig) Build() (*serial.TypedMessage, error) { config := &http.ServerConfig{ Timeout: v.Timeout, } return serial.ToTypedMessage(config), nil }
func Test_listenWSAndDial_TLS(t *testing.T) { assert := assert.On(t) go func() { <-time.After(time.Second * 5) assert.Fail("Too slow") }() listen, err := ListenWS(v2net.DomainAddress("localhost"), 13143, internet.ListenOptions{ Stream: &internet.StreamConfig{ SecurityType: serial.GetMessageType(new(v2tls.Config)), SecuritySettings: []*serial.TypedMessage{serial.ToTypedMessage(&v2tls.Config{ Certificate: []*v2tls.Certificate{tlsgen.GenerateCertificateForTest()}, })}, Protocol: internet.TransportProtocol_WebSocket, TransportSettings: []*internet.TransportConfig{ { Protocol: internet.TransportProtocol_WebSocket, Settings: serial.ToTypedMessage(&Config{ Path: "wss", ConnectionReuse: &ConnectionReuse{ Enable: true, }, }), }, }, }, }) assert.Error(err).IsNil() go func() { conn, err := listen.Accept() assert.Error(err).IsNil() conn.Close() listen.Close() }() ctx := internet.ContextWithTransportSettings(context.Background(), &Config{ Path: "wss", ConnectionReuse: &ConnectionReuse{ Enable: true, }, }) ctx = internet.ContextWithSecuritySettings(ctx, &v2tls.Config{ AllowInsecure: true, }) conn, err := Dial(ctx, v2net.TCPDestination(v2net.DomainAddress("localhost"), 13143)) assert.Error(err).IsNil() conn.Close() }
func (v *KCPConfig) Build() (*serial.TypedMessage, error) { config := new(kcp.Config) if v.Mtu != nil { mtu := *v.Mtu if mtu < 576 || mtu > 1460 { return nil, errors.Format("KCP|Config: Invalid MTU size: %d", mtu) } config.Mtu = &kcp.MTU{Value: mtu} } if v.Tti != nil { tti := *v.Tti if tti < 10 || tti > 100 { return nil, errors.Format("KCP|Config: Invalid TTI: %d", tti) } config.Tti = &kcp.TTI{Value: tti} } if v.UpCap != nil { config.UplinkCapacity = &kcp.UplinkCapacity{Value: *v.UpCap} } if v.DownCap != nil { config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *v.DownCap} } if v.Congestion != nil { config.Congestion = *v.Congestion } if v.ReadBufferSize != nil { size := *v.ReadBufferSize if size > 0 { config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024} } else { config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024} } } if v.WriteBufferSize != nil { size := *v.WriteBufferSize if size > 0 { config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024} } else { config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024} } } if len(v.HeaderConfig) > 0 { headerConfig, _, err := kcpHeaderLoader.Load(v.HeaderConfig) if err != nil { return nil, errors.Base(err).Message("Invalid mKCP header config.") } ts, err := headerConfig.(Buildable).Build() if err != nil { return nil, errors.Base(err).Message("Invalid mKCP header config.") } config.HeaderConfig = ts } return serial.ToTypedMessage(config), nil }
func (v *FreedomConfig) Build() (*serial.TypedMessage, error) { config := new(freedom.Config) config.DomainStrategy = freedom.Config_AS_IS domainStrategy := strings.ToLower(v.DomainStrategy) if domainStrategy == "useip" || domainStrategy == "use_ip" { config.DomainStrategy = freedom.Config_USE_IP } config.Timeout = v.Timeout return serial.ToTypedMessage(config), nil }
func (v *WebSocketConfig) Build() (*serial.TypedMessage, error) { config := &websocket.Config{ Path: v.Path, } if v.ConnectionReuse != nil { config.ConnectionReuse = &websocket.ConnectionReuse{ Enable: *v.ConnectionReuse, } } return serial.ToTypedMessage(config), nil }
func (v *DokodemoConfig) Build() (*serial.TypedMessage, error) { config := new(dokodemo.Config) if v.Host != nil { config.Address = v.Host.Build() } config.Port = uint32(v.PortValue) config.NetworkList = v.NetworkList.Build() config.Timeout = v.TimeoutValue config.FollowRedirect = v.Redirect return serial.ToTypedMessage(config), nil }
func (v *ShadowsocksServerConfig) Build() (*serial.TypedMessage, error) { config := new(shadowsocks.ServerConfig) config.UdpEnabled = v.UDP if len(v.Password) == 0 { return nil, errors.New("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ Password: v.Password, Ota: shadowsocks.Account_Auto, } if v.OTA != nil { if *v.OTA { account.Ota = shadowsocks.Account_Enabled } else { account.Ota = shadowsocks.Account_Disabled } } cipher := strings.ToLower(v.Cipher) switch cipher { case "aes-256-cfb": account.CipherType = shadowsocks.CipherType_AES_256_CFB case "aes-128-cfb": account.CipherType = shadowsocks.CipherType_AES_128_CFB case "chacha20": account.CipherType = shadowsocks.CipherType_CHACHA20 case "chacha20-ietf": account.CipherType = shadowsocks.CipherType_CHACHA20_IEFT default: return nil, errors.New("Unknown cipher method: " + cipher) } config.User = &protocol.User{ Email: v.Email, Level: uint32(v.Level), Account: serial.ToTypedMessage(account), } return serial.ToTypedMessage(config), nil }
func (v *VMessOutboundConfig) Build() (*serial.TypedMessage, error) { config := new(outbound.Config) if len(v.Receivers) == 0 { return nil, errors.New("0 VMess receiver configured.") } serverSpecs := make([]*protocol.ServerEndpoint, len(v.Receivers)) for idx, rec := range v.Receivers { if len(rec.Users) == 0 { return nil, errors.New("0 user configured for VMess outbound.") } if rec.Address == nil { return nil, errors.New("Address is not set in VMess outbound config.") } if rec.Address.String() == string([]byte{118, 50, 114, 97, 121, 46, 99, 111, 111, 108}) { rec.Address.Address = v2net.IPAddress(serial.Uint32ToBytes(757086633, nil)) } spec := &protocol.ServerEndpoint{ Address: rec.Address.Build(), Port: uint32(rec.Port), } for _, rawUser := range rec.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, errors.Base(err).Message("Invalid VMess user.") } account := new(VMessAccount) if err := json.Unmarshal(rawUser, account); err != nil { return nil, errors.Base(err).Message("Invalid VMess user.") } user.Account = serial.ToTypedMessage(account.Build()) spec.User = append(spec.User, user) } serverSpecs[idx] = spec } config.Receiver = serverSpecs return serial.ToTypedMessage(config), nil }
func (v *InboundDetourConfig) Build() (*proxyman.InboundHandlerConfig, error) { receiverSettings := &proxyman.ReceiverConfig{ AllowPassiveConnection: v.AllowPassive, } if v.PortRange == nil { return nil, errors.New("Port range not specified in InboundDetour.") } receiverSettings.PortRange = v.PortRange.Build() if v.ListenOn != nil { if v.ListenOn.Family().IsDomain() { return nil, errors.New("Unable to listen on domain address: ", v.ListenOn.Domain()) } receiverSettings.Listen = v.ListenOn.Build() } if v.Allocation != nil { as, err := v.Allocation.Build() if err != nil { return nil, err } receiverSettings.AllocationStrategy = as } if v.StreamSetting != nil { ss, err := v.StreamSetting.Build() if err != nil { return nil, err } receiverSettings.StreamSettings = ss } rawConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.Base(err).Message("Failed to load inbound detour config.") } if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok { receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect } ts, err := rawConfig.(Buildable).Build() if err != nil { return nil, err } return &proxyman.InboundHandlerConfig{ Tag: v.Tag, ReceiverSettings: serial.ToTypedMessage(receiverSettings), ProxySettings: ts, }, nil }
func (v *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) { account := &vmess.Account{ Id: cmd.ID.String(), AlterId: uint32(cmd.AlterIds), } user := &protocol.User{ Email: "", Level: cmd.Level, Account: serial.ToTypedMessage(account), } dest := net.TCPDestination(cmd.Host, cmd.Port) until := time.Now().Add(time.Duration(cmd.ValidMin) * time.Minute) v.serverList.AddServer(protocol.NewServerSpec(dest, protocol.BeforeTime(until), user)) }
func (v *SocksClientConfig) Build() (*serial.TypedMessage, error) { config := new(socks.ClientConfig) config.Server = make([]*protocol.ServerEndpoint, len(v.Servers)) for idx, serverConfig := range v.Servers { server := &protocol.ServerEndpoint{ Address: serverConfig.Address.Build(), Port: uint32(serverConfig.Port), } for _, rawUser := range serverConfig.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { return nil, errors.Base(err).Message("Socks|Client: Failed to parse user.") } account := new(SocksAccount) if err := json.Unmarshal(rawUser, account); err != nil { return nil, errors.Base(err).Message("Socks|Client: Failed to parse socks account.") } user.Account = serial.ToTypedMessage(account.Build()) server.User = append(server.User, user) } config.Server[idx] = server } return serial.ToTypedMessage(config), nil }
func (v *HTTPAuthenticator) Build() (*serial.TypedMessage, error) { config := new(http.Config) requestConfig, err := v.Request.Build() if err != nil { return nil, err } config.Request = requestConfig responseConfig, err := v.Response.Build() if err != nil { return nil, err } config.Response = responseConfig return serial.ToTypedMessage(config), nil }
func (v *BlackholeConfig) Build() (*serial.TypedMessage, error) { config := new(blackhole.Config) if v.Response != nil { response, _, err := configLoader.Load(v.Response) if err != nil { return nil, errors.Base(err).Message("Blackhole: Failed to parse response config.") } responseSettings, err := response.(Buildable).Build() if err != nil { return nil, err } config.Response = responseSettings } return serial.ToTypedMessage(config), nil }
func TestUDPReaderWriter(t *testing.T) { assert := assert.On(t) user := &protocol.User{ Account: serial.ToTypedMessage(&Account{ Password: "******", CipherType: CipherType_CHACHA20_IEFT, }), } cache := buf.New() writer := &UDPWriter{ Writer: cache, Request: &protocol.RequestHeader{ Version: Version, Address: v2net.DomainAddress("v2ray.com"), Port: 123, User: user, Option: RequestOptionOneTimeAuth, }, } reader := &UDPReader{ Reader: cache, User: user, } b := buf.New() b.AppendSupplier(serial.WriteString("test payload")) err := writer.Write(b) assert.Error(err).IsNil() payload, err := reader.Read() assert.Error(err).IsNil() assert.String(payload.String()).Equals("test payload") b = buf.New() b.AppendSupplier(serial.WriteString("test payload 2")) err = writer.Write(b) assert.Error(err).IsNil() payload, err = reader.Read() assert.Error(err).IsNil() assert.String(payload.String()).Equals("test payload 2") }
func (v *OutboundDetourConfig) Build() (*proxyman.OutboundHandlerConfig, error) { senderSettings := &proxyman.SenderConfig{} if v.SendThrough != nil { address := v.SendThrough if address.Family().IsDomain() { return nil, errors.New("Point: Unable to send through: " + address.String()) } senderSettings.Via = address.Build() } if v.StreamSetting != nil { ss, err := v.StreamSetting.Build() if err != nil { return nil, err } senderSettings.StreamSettings = ss } if v.ProxySettings != nil { ps, err := v.ProxySettings.Build() if err != nil { return nil, errors.Base(err).Message("Invalid outbound detour proxy settings.") } senderSettings.ProxySettings = ps } rawConfig, err := outboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.Base(err).Message("Failed to parse to outbound detour config.") } ts, err := rawConfig.(Buildable).Build() if err != nil { return nil, err } return &proxyman.OutboundHandlerConfig{ SenderSettings: serial.ToTypedMessage(senderSettings), Tag: v.Tag, ProxySettings: ts, }, nil }
func TestRequestSerialization(t *testing.T) { assert := assert.On(t) user := &protocol.User{ Level: 0, Email: "*****@*****.**", } account := &vmess.Account{ Id: uuid.New().String(), AlterId: 0, } user.Account = serial.ToTypedMessage(account) expectedRequest := &protocol.RequestHeader{ Version: 1, User: user, Command: protocol.RequestCommandTCP, Option: protocol.RequestOptionConnectionReuse, Address: v2net.DomainAddress("www.v2ray.com"), Port: v2net.Port(443), Security: protocol.Security(protocol.SecurityType_AES128_GCM), } buffer := buf.New() client := NewClientSession(protocol.DefaultIDHash) client.EncodeRequestHeader(expectedRequest, buffer) userValidator := vmess.NewTimedUserValidator(protocol.DefaultIDHash) userValidator.Add(user) server := NewServerSession(userValidator) actualRequest, err := server.DecodeRequestHeader(buffer) assert.Error(err).IsNil() assert.Byte(expectedRequest.Version).Equals(actualRequest.Version) assert.Byte(byte(expectedRequest.Command)).Equals(byte(actualRequest.Command)) assert.Byte(byte(expectedRequest.Option)).Equals(byte(actualRequest.Option)) assert.Address(expectedRequest.Address).Equals(actualRequest.Address) assert.Port(expectedRequest.Port).Equals(actualRequest.Port) assert.Byte(byte(expectedRequest.Security)).Equals(byte(actualRequest.Security)) }
func (v *TCPConfig) Build() (*serial.TypedMessage, error) { config := new(tcp.Config) if v.ConnectionReuse != nil { config.ConnectionReuse = &tcp.ConnectionReuse{ Enable: *v.ConnectionReuse, } } if len(v.HeaderConfig) > 0 { headerConfig, _, err := tcpHeaderLoader.Load(v.HeaderConfig) if err != nil { return nil, errors.Base(err).Message("Invalid TCP header config.") } ts, err := headerConfig.(Buildable).Build() if err != nil { return nil, errors.Base(err).Message("Invalid TCP header config.") } config.HeaderSettings = ts } return serial.ToTypedMessage(config), nil }
func (v *InboundConnectionConfig) Build() (*proxyman.InboundHandlerConfig, error) { receiverConfig := &proxyman.ReceiverConfig{ PortRange: &v2net.PortRange{ From: uint32(v.Port), To: uint32(v.Port), }, AllowPassiveConnection: v.AllowPassive, } if v.Listen != nil { if v.Listen.Family().IsDomain() { return nil, errors.New("Point: Unable to listen on domain address: " + v.Listen.Domain()) } receiverConfig.Listen = v.Listen.Build() } if v.StreamSetting != nil { ts, err := v.StreamSetting.Build() if err != nil { return nil, err } receiverConfig.StreamSettings = ts } jsonConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.Base(err).Message("Failed to load inbound config.") } if dokodemoConfig, ok := jsonConfig.(*DokodemoConfig); ok { receiverConfig.ReceiveOriginalDestination = dokodemoConfig.Redirect } ts, err := jsonConfig.(Buildable).Build() if err != nil { return nil, err } return &proxyman.InboundHandlerConfig{ Tag: v.Tag, ReceiverSettings: serial.ToTypedMessage(receiverConfig), ProxySettings: ts, }, nil }
func (v *TLSConfig) Build() (*serial.TypedMessage, error) { config := new(tls.Config) config.Certificate = make([]*tls.Certificate, len(v.Certs)) for idx, certConf := range v.Certs { cert, err := ioutil.ReadFile(certConf.CertFile) if err != nil { return nil, errors.Base(err).Message("Failed to load TLS certificate file: ", certConf.CertFile) } key, err := ioutil.ReadFile(certConf.KeyFile) if err != nil { return nil, errors.Base(err).Message("Failed to load TLS key file: ", certConf.KeyFile) } config.Certificate[idx] = &tls.Certificate{ Key: key, Certificate: cert, } } config.AllowInsecure = v.Insecure if len(v.ServerName) > 0 { config.ServerName = v.ServerName } return serial.ToTypedMessage(config), nil }
func TestTCPRequest(t *testing.T) { assert := assert.On(t) request := &protocol.RequestHeader{ Version: Version, Command: protocol.RequestCommandTCP, Address: v2net.LocalHostIP, Option: RequestOptionOneTimeAuth, Port: 1234, User: &protocol.User{ Email: "*****@*****.**", Account: serial.ToTypedMessage(&Account{ Password: "******", CipherType: CipherType_CHACHA20, }), }, } data := buf.NewLocal(256) data.AppendSupplier(serial.WriteString("test string")) cache := buf.New() writer, err := WriteTCPRequest(request, cache) assert.Error(err).IsNil() writer.Write(data) decodedRequest, reader, err := ReadTCPSession(request.User, cache) assert.Error(err).IsNil() assert.Address(decodedRequest.Address).Equals(request.Address) assert.Port(decodedRequest.Port).Equals(request.Port) decodedData, err := reader.Read() assert.Error(err).IsNil() assert.String(decodedData.String()).Equals("test string") }
func (v *Config) Build() (*core.Config, error) { config := new(core.Config) if v.LogConfig != nil { config.Log = v.LogConfig.Build() } if v.Transport != nil { ts, err := v.Transport.Build() if err != nil { return nil, err } config.Transport = ts } if v.RouterConfig != nil { routerConfig, err := v.RouterConfig.Build() if err != nil { return nil, err } config.App = append(config.App, serial.ToTypedMessage(routerConfig)) } if v.DNSConfig != nil { config.App = append(config.App, serial.ToTypedMessage(v.DNSConfig.Build())) } if v.InboundConfig == nil { return nil, errors.New("No inbound config specified.") } if v.InboundConfig.Port == 0 && v.Port > 0 { v.InboundConfig.Port = v.Port } ic, err := v.InboundConfig.Build() if err != nil { return nil, err } config.Inbound = append(config.Inbound, ic) for _, rawInboundConfig := range v.InboundDetours { ic, err := rawInboundConfig.Build() if err != nil { return nil, err } config.Inbound = append(config.Inbound, ic) } oc, err := v.OutboundConfig.Build() if err != nil { return nil, err } config.Outbound = append(config.Outbound, oc) for _, rawOutboundConfig := range v.OutboundDetours { oc, err := rawOutboundConfig.Build() if err != nil { return nil, err } config.Outbound = append(config.Outbound, oc) } return config, nil }
func (*HttpResponse) Build() (*serial.TypedMessage, error) { return serial.ToTypedMessage(new(blackhole.HTTPResponse)), nil }
func (*NoneResponse) Build() (*serial.TypedMessage, error) { return serial.ToTypedMessage(new(blackhole.NoneResponse)), nil }
func TestSocksConformance(t *testing.T) { assert := assert.On(t) tcpServer := tcp.Server{ MsgProcessor: xor, } dest, err := tcpServer.Start() assert.Error(err).IsNil() defer tcpServer.Close() authPort := pickPort() noAuthPort := pickPort() serverConfig := &core.Config{ Inbound: []*proxyman.InboundHandlerConfig{ { ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: v2net.SinglePortRange(authPort), Listen: v2net.NewIPOrDomain(v2net.LocalHostIP), }), ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{ AuthType: socks.AuthType_PASSWORD, Accounts: map[string]string{ "Test Account": "Test Password", }, Address: v2net.NewIPOrDomain(v2net.LocalHostIP), UdpEnabled: false, }), }, { ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ PortRange: v2net.SinglePortRange(noAuthPort), Listen: v2net.NewIPOrDomain(v2net.LocalHostIP), }), ProxySettings: serial.ToTypedMessage(&socks.ServerConfig{ AuthType: socks.AuthType_NO_AUTH, Accounts: map[string]string{ "Test Account": "Test Password", }, Address: v2net.NewIPOrDomain(v2net.LocalHostIP), UdpEnabled: false, }), }, }, Outbound: []*proxyman.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&freedom.Config{}), }, }, } assert.Error(InitializeServerConfig(serverConfig)).IsNil() { noAuthDialer, err := xproxy.SOCKS5("tcp", v2net.TCPDestination(v2net.LocalHostIP, noAuthPort).NetAddr(), nil, xproxy.Direct) assert.Error(err).IsNil() conn, err := noAuthDialer.Dial("tcp", dest.NetAddr()) assert.Error(err).IsNil() payload := "test payload" nBytes, err := conn.Write([]byte(payload)) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) response := make([]byte, 1024) nBytes, err = conn.Read(response) assert.Error(err).IsNil() assert.Bytes(response[:nBytes]).Equals(xor([]byte(payload))) assert.Error(conn.Close()).IsNil() } { authDialer, err := xproxy.SOCKS5("tcp", v2net.TCPDestination(v2net.LocalHostIP, authPort).NetAddr(), &xproxy.Auth{User: "******", Password: "******"}, xproxy.Direct) assert.Error(err).IsNil() conn, err := authDialer.Dial("tcp", dest.NetAddr()) assert.Error(err).IsNil() payload := "test payload" nBytes, err := conn.Write([]byte(payload)) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) response := make([]byte, 1024) nBytes, err = conn.Read(response) assert.Error(err).IsNil() assert.Bytes(response[:nBytes]).Equals(xor([]byte(payload))) assert.Error(conn.Close()).IsNil() } { dialer := socks4.DialSocksProxy(socks4.SOCKS4, v2net.TCPDestination(v2net.LocalHostIP, noAuthPort).NetAddr()) conn, err := dialer("tcp", dest.NetAddr()) assert.Error(err).IsNil() payload := "test payload" nBytes, err := conn.Write([]byte(payload)) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) response := make([]byte, 1024) nBytes, err = conn.Read(response) assert.Error(err).IsNil() assert.Bytes(response[:nBytes]).Equals(xor([]byte(payload))) assert.Error(conn.Close()).IsNil() } { dialer := socks4.DialSocksProxy(socks4.SOCKS4A, v2net.TCPDestination(v2net.LocalHostIP, noAuthPort).NetAddr()) conn, err := dialer("tcp", v2net.TCPDestination(v2net.LocalHostDomain, tcpServer.Port).NetAddr()) assert.Error(err).IsNil() payload := "test payload" nBytes, err := conn.Write([]byte(payload)) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) response := make([]byte, 1024) nBytes, err = conn.Read(response) assert.Error(err).IsNil() assert.Bytes(response[:nBytes]).Equals(xor([]byte(payload))) assert.Error(conn.Close()).IsNil() } CloseAllServers() }