func TestHubSocksOption(t *testing.T) { assert := assert.On(t) if os.Geteuid() != 0 { // This test case requires root permission. return } hub, err := ListenUDP(v2net.LocalHostIP, v2net.Port(0), ListenOption{ Callback: func(*buf.Buffer, *proxy.SessionInfo) {}, ReceiveOriginalDest: true, }) assert.Error(err).IsNil() conn := hub.Connection() fd, err := internal.GetSysFd(conn) assert.Error(err).IsNil() val, err := syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT) assert.Error(err).IsNil() assert.Int(val).Equals(1) val, err = syscall.GetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR) assert.Error(err).IsNil() assert.Int(val).Equals(1) }
func TestACKSegment(t *testing.T) { assert := assert.On(t) seg := &AckSegment{ Conv: 1, ReceivingWindow: 2, ReceivingNext: 3, Timestamp: 10, NumberList: []uint32{1, 3, 5, 7, 9}, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*AckSegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Uint32(seg2.ReceivingWindow).Equals(seg.ReceivingWindow) assert.Uint32(seg2.ReceivingNext).Equals(seg.ReceivingNext) assert.Int(len(seg2.NumberList)).Equals(len(seg.NumberList)) assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp) for i, number := range seg2.NumberList { assert.Uint32(number).Equals(seg.NumberList[i]) } }
func TestBufferedReader(t *testing.T) { assert := assert.On(t) content := buf.New() content.AppendSupplier(buf.ReadFrom(rand.Reader)) len := content.Len() reader := NewReader(content) assert.Bool(reader.Cached()).IsTrue() payload := make([]byte, 16) nBytes, err := reader.Read(payload) assert.Int(nBytes).Equals(16) assert.Error(err).IsNil() len2 := content.Len() assert.Int(len - len2).GreaterThan(16) nBytes, err = reader.Read(payload) assert.Int(nBytes).Equals(16) assert.Error(err).IsNil() assert.Int(content.Len()).Equals(len2) }
func TestPassiveTCPConnection(t *testing.T) { assert := assert.On(t) tcpServer := &tcp.Server{ MsgProcessor: func(data []byte) []byte { buffer := make([]byte, 0, 2048) buffer = append(buffer, []byte("Processed: ")...) buffer = append(buffer, data...) return buffer }, SendFirst: []byte("Server sends first."), } _, err := tcpServer.Start() assert.Error(err).IsNil() defer tcpServer.Close() assert.Error(InitializeServerSetOnce("test_1")).IsNil() socksPort := v2net.Port(50002) conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{ IP: []byte{127, 0, 0, 1}, Port: int(socksPort), }) assert.Error(err).IsNil() authRequest := socks5AuthMethodRequest(byte(0)) nBytes, err := conn.Write(authRequest) assert.Int(nBytes).Equals(len(authRequest)) assert.Error(err).IsNil() authResponse := make([]byte, 1024) nBytes, err = conn.Read(authResponse) assert.Error(err).IsNil() assert.Bytes(authResponse[:nBytes]).Equals([]byte{socks5Version, 0}) connectRequest := socks5Request(byte(1), v2net.TCPDestination(v2net.IPAddress([]byte{127, 0, 0, 1}), tcpServer.Port)) nBytes, err = conn.Write(connectRequest) assert.Int(nBytes).Equals(len(connectRequest)) assert.Error(err).IsNil() connectResponse := make([]byte, 1024) nBytes, err = conn.Read(connectResponse) assert.Error(err).IsNil() assert.Bytes(connectResponse[:nBytes]).Equals([]byte{socks5Version, 0, 0, 1, 0, 0, 0, 0, 6, 181}) actualResponse := make([]byte, 1024) nResponse, err := conn.Read(actualResponse) assert.Error(err).IsNil() assert.String(string(actualResponse[:nResponse])).Equals(string(tcpServer.SendFirst)) conn.Close() CloseAllServers() }
func TestTimeOutSettings(t *testing.T) { assert := assert.On(t) reader := NewTimeOutReader(8, nil) assert.Int(reader.GetTimeOut()).Equals(8) reader.SetTimeOut(8) // no op assert.Int(reader.GetTimeOut()).Equals(8) reader.SetTimeOut(9) assert.Int(reader.GetTimeOut()).Equals(9) }
func TestAuthenticationReaderWriterPartial(t *testing.T) { assert := assert.On(t) key := make([]byte, 16) rand.Read(key) block, err := aes.NewCipher(key) assert.Error(err).IsNil() aead, err := cipher.NewGCM(block) assert.Error(err).IsNil() payload := make([]byte, 8*1024) rand.Read(payload) cache := buf.NewLocal(16 * 1024) iv := make([]byte, 12) rand.Read(iv) writer := NewAuthenticationWriter(&AEADAuthenticator{ AEAD: aead, NonceGenerator: &StaticBytesGenerator{ Content: iv, }, AdditionalDataGenerator: &NoOpBytesGenerator{}, }, cache) nBytes, err := writer.Write(payload) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) assert.Int(cache.Len()).GreaterThan(0) _, err = writer.Write([]byte{}) assert.Error(err).IsNil() reader := NewAuthenticationReader(&AEADAuthenticator{ AEAD: aead, NonceGenerator: &StaticBytesGenerator{ Content: iv, }, AdditionalDataGenerator: &NoOpBytesGenerator{}, }, cache, false) actualPayload := make([]byte, 7*1024) nBytes, err = reader.Read(actualPayload) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(actualPayload)) assert.Bytes(actualPayload[:nBytes]).Equals(payload[:nBytes]) nBytes, err = reader.Read(actualPayload) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload) - len(actualPayload)) assert.Bytes(actualPayload[:nBytes]).Equals(payload[7*1024:]) _, err = reader.Read(actualPayload) assert.Error(err).Equals(io.EOF) }
func TestBufferWrite(t *testing.T) { assert := assert.On(t) buffer := NewLocal(8) nBytes, err := buffer.Write([]byte("abcd")) assert.Error(err).IsNil() assert.Int(nBytes).Equals(4) nBytes, err = buffer.Write([]byte("abcde")) assert.Error(err).IsNil() assert.Int(nBytes).Equals(4) assert.String(buffer.String()).Equals("abcdabcd") }
func TestBufferClear(t *testing.T) { assert := assert.On(t) buffer := NewBuffer().Clear() defer buffer.Release() payload := "Bytes" buffer.Append([]byte(payload)) assert.Int(buffer.Len()).Equals(len(payload)) buffer.Clear() assert.Int(buffer.Len()).Equals(0) }
func TestSendingWindow(t *testing.T) { assert := assert.On(t) window := NewSendingWindow(5, nil, nil) window.Push(0, []byte{}) window.Push(1, []byte{}) window.Push(2, []byte{}) assert.Int(window.Len()).Equals(3) window.Remove(1) assert.Int(window.Len()).Equals(3) assert.Uint32(window.FirstNumber()).Equals(0) window.Remove(0) assert.Int(window.Len()).Equals(1) assert.Uint32(window.FirstNumber()).Equals(2) window.Remove(0) assert.Int(window.Len()).Equals(0) window.Push(4, []byte{}) assert.Int(window.Len()).Equals(1) assert.Uint32(window.FirstNumber()).Equals(4) window.Push(5, []byte{}) assert.Int(window.Len()).Equals(2) window.Remove(1) assert.Int(window.Len()).Equals(2) window.Remove(0) assert.Int(window.Len()).Equals(0) }
func TestAllHeadersLoadable(t *testing.T) { assert := assert.On(t) noopAuth, err := CreatePacketHeader((*noop.Config)(nil)) assert.Error(err).IsNil() assert.Int(noopAuth.Size()).Equals(0) srtp, err := CreatePacketHeader((*srtp.Config)(nil)) assert.Error(err).IsNil() assert.Int(srtp.Size()).Equals(4) utp, err := CreatePacketHeader((*utp.Config)(nil)) assert.Error(err).IsNil() assert.Int(utp.Size()).Equals(4) }
func TestAllAuthenticatorLoadable(t *testing.T) { assert := assert.On(t) noopAuth, err := CreateAuthenticator("none", nil) assert.Error(err).IsNil() assert.Int(noopAuth.Overhead()).Equals(0) srtp, err := CreateAuthenticator("srtp", nil) assert.Error(err).IsNil() assert.Int(srtp.Overhead()).Equals(4) utp, err := CreateAuthenticator("utp", nil) assert.Error(err).IsNil() assert.Int(utp.Overhead()).Equals(4) }
func TestAllAuthenticatorLoadable(t *testing.T) { assert := assert.On(t) noopAuth, err := CreateAuthenticator(loader.GetType(new(noop.Config)), nil) assert.Error(err).IsNil() assert.Int(noopAuth.Overhead()).Equals(0) srtp, err := CreateAuthenticator(loader.GetType(new(srtp.Config)), nil) assert.Error(err).IsNil() assert.Int(srtp.Overhead()).Equals(4) utp, err := CreateAuthenticator(loader.GetType(new(utp.Config)), nil) assert.Error(err).IsNil() assert.Int(utp.Overhead()).Equals(4) }
func TestAllHeadersLoadable(t *testing.T) { assert := assert.On(t) noopAuth, err := CreatePacketHeader(serial.GetMessageType(new(noop.Config)), nil) assert.Error(err).IsNil() assert.Int(noopAuth.Size()).Equals(0) srtp, err := CreatePacketHeader(serial.GetMessageType(new(srtp.Config)), nil) assert.Error(err).IsNil() assert.Int(srtp.Size()).Equals(4) utp, err := CreatePacketHeader(serial.GetMessageType(new(utp.Config)), nil) assert.Error(err).IsNil() assert.Int(utp.Size()).Equals(4) }
func TestACKSegment(t *testing.T) { assert := assert.On(t) seg := &AckSegment{ Conv: 1, ReceivingWindow: 2, ReceivingNext: 3, Timestamp: 10, Count: 5, NumberList: []uint32{1, 3, 5, 7, 9}, } nBytes := seg.ByteSize() bytes := seg.Bytes(nil) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*AckSegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Uint32(seg2.ReceivingWindow).Equals(seg.ReceivingWindow) assert.Uint32(seg2.ReceivingNext).Equals(seg.ReceivingNext) assert.Byte(seg2.Count).Equals(seg.Count) assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp) for i := byte(0); i < seg2.Count; i++ { assert.Uint32(seg2.NumberList[i]).Equals(seg.NumberList[i]) } }
func TestShadowsocksServerConfigParsing(t *testing.T) { assert := assert.On(t) rawJson := `{ "method": "aes-128-cfb", "password": "******" }` rawConfig := new(ShadowsocksServerConfig) err := json.Unmarshal([]byte(rawJson), rawConfig) assert.Error(err).IsNil() ts, err := rawConfig.Build() assert.Error(err).IsNil() iConfig, err := ts.GetInstance() assert.Error(err).IsNil() config := iConfig.(*shadowsocks.ServerConfig) rawAccount, err := config.User.GetTypedAccount() assert.Error(err).IsNil() account, ok := rawAccount.(*shadowsocks.ShadowsocksAccount) assert.Bool(ok).IsTrue() assert.Int(account.Cipher.KeySize()).Equals(16) assert.Bytes(account.Key).Equals([]byte{160, 224, 26, 2, 22, 110, 9, 80, 65, 52, 80, 20, 38, 243, 224, 241}) }
func TestAdaptiveReader(t *testing.T) { assert := assert.On(t) rawContent := make([]byte, 1024*1024) reader := NewAdaptiveReader(bytes.NewBuffer(rawContent)) b1, err := reader.Read() assert.Error(err).IsNil() assert.Bool(b1.IsFull()).IsTrue() assert.Int(b1.Len()).Equals(alloc.BufferSize) b2, err := reader.Read() assert.Error(err).IsNil() assert.Bool(b2.IsFull()).IsTrue() assert.Int(b2.Len()).Equals(alloc.LargeBufferSize) }
func TestDnsAdd(t *testing.T) { assert := assert.On(t) space := app.NewSpace() outboundHandlerManager := proxyman.NewDefaultOutboundHandlerManager() outboundHandlerManager.SetDefaultHandler( freedom.NewFreedomConnection( &freedom.Config{}, space, &proxy.OutboundHandlerMeta{ Address: v2net.AnyIP, StreamSettings: &internet.StreamSettings{ Type: internet.StreamConnectionTypeRawTCP, }, })) space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, outboundHandlerManager) space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space)) domain := "local.v2ray.com" server := NewCacheServer(space, &Config{ NameServers: []v2net.Destination{ v2net.UDPDestination(v2net.IPAddress([]byte{8, 8, 8, 8}), v2net.Port(53)), }, }) space.BindApp(APP_ID, server) space.Initialize() ips := server.Get(domain) assert.Int(len(ips)).Equals(1) assert.IP(ips[0].To4()).Equals(net.IP([]byte{127, 0, 0, 1})) }
func TestCmdSegment(t *testing.T) { assert := assert.On(t) seg := &CmdOnlySegment{ Conv: 1, Cmd: CommandPing, Option: SegmentOptionClose, SendingNext: 11, ReceivinNext: 13, PeerRTO: 15, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*CmdOnlySegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Byte(byte(seg2.Command())).Equals(byte(seg.Command())) assert.Byte(byte(seg2.Option)).Equals(byte(seg.Option)) assert.Uint32(seg2.SendingNext).Equals(seg.SendingNext) assert.Uint32(seg2.ReceivinNext).Equals(seg.ReceivinNext) assert.Uint32(seg2.PeerRTO).Equals(seg.PeerRTO) }
func TestHttpProxy(t *testing.T) { assert := assert.On(t) httpServer := &v2http.Server{ Port: v2net.Port(50042), PathHandler: make(map[string]http.HandlerFunc), } _, err := httpServer.Start() assert.Error(err).IsNil() defer httpServer.Close() assert.Error(InitializeServerSetOnce("test_5")).IsNil() transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("http://127.0.0.1:50040/") }, } client := &http.Client{ Transport: transport, } resp, err := client.Get("http://127.0.0.1:50042/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(200) content, err := ioutil.ReadAll(resp.Body) assert.Error(err).IsNil() assert.String(string(content)).Equals("Home") CloseAllServers() }
func TestBadSegment(t *testing.T) { assert := assert.On(t) seg, buf := ReadSegment(nil) assert.Pointer(seg).IsNil() assert.Int(len(buf)).Equals(0) }
func TestNormalGetRequest(t *testing.T) { assert := assert.On(t) testPacketDispatcher := testdispatcher.NewTestPacketDispatcher(nil) port := v2net.Port(dice.Roll(20000) + 10000) httpProxy := NewServer( &Config{}, testPacketDispatcher, &proxy.InboundHandlerMeta{ Address: v2net.LocalHostIP, Port: port, StreamSettings: &internet.StreamSettings{ Type: internet.StreamConnectionTypeRawTCP, }}) defer httpProxy.Close() err := httpProxy.Start() assert.Error(err).IsNil() assert.Port(port).Equals(httpProxy.Port()) httpClient := &http.Client{} resp, err := httpClient.Get("http://127.0.0.1:" + port.String() + "/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(400) }
func Test1ByteDataSegment(t *testing.T) { assert := assert.On(t) b := buf.NewLocal(512) b.AppendBytes('a') seg := &DataSegment{ Conv: 1, Timestamp: 3, Number: 4, SendingNext: 5, Data: b, } nBytes := seg.ByteSize() bytes := make([]byte, nBytes) seg.Bytes()(bytes) assert.Int(len(bytes)).Equals(nBytes) iseg, _ := ReadSegment(bytes) seg2 := iseg.(*DataSegment) assert.Uint16(seg2.Conv).Equals(seg.Conv) assert.Uint32(seg2.Timestamp).Equals(seg.Timestamp) assert.Uint32(seg2.SendingNext).Equals(seg.SendingNext) assert.Uint32(seg2.Number).Equals(seg.Number) assert.Bytes(seg2.Data.Bytes()).Equals(seg.Data.Bytes()) }
func TestBlockHTTP(t *testing.T) { assert := assert.On(t) httpServer := &v2http.Server{ Port: net.Port(50042), PathHandler: make(map[string]http.HandlerFunc), } _, err := httpServer.Start() assert.Error(err).IsNil() defer httpServer.Close() assert.Error(InitializeServerSetOnce("test_5")).IsNil() transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("http://127.0.0.1:50040/") }, } client := &http.Client{ Transport: transport, } resp, err := client.Get("http://127.0.0.1:50049/") assert.Error(err).IsNil() assert.Int(resp.StatusCode).Equals(403) CloseAllServers() }
func TestSocksInboundConfig(t *testing.T) { assert := assert.On(t) rawJson := `{ "auth": "password", "accounts": [ { "user": "******", "pass": "******" } ], "udp": false, "ip": "127.0.0.1", "timeout": 5 }` config := new(SocksServerConfig) err := json.Unmarshal([]byte(rawJson), &config) assert.Error(err).IsNil() message, err := config.Build() assert.Error(err).IsNil() iConfig, err := message.GetInstance() assert.Error(err).IsNil() socksConfig := iConfig.(*socks.ServerConfig) assert.Bool(socksConfig.AuthType == socks.AuthType_PASSWORD).IsTrue() assert.Int(len(socksConfig.Accounts)).Equals(1) assert.String(socksConfig.Accounts["my-username"]).Equals("my-password") assert.Bool(socksConfig.UdpEnabled).IsFalse() assert.Address(socksConfig.Address.AsAddress()).Equals(net.LocalHostIP) assert.Uint32(socksConfig.Timeout).Equals(5) }
func TestRevParse(t *testing.T) { assert := assert.On(t) rev, err := RevParse("HEAD") assert.Error(err).IsNil() assert.Int(len(rev)).GreaterThan(0) }
func TestRepoVersion(t *testing.T) { assert := assert.On(t) version, err := RepoVersionHead() assert.Error(err).IsNil() assert.Int(len(version)).GreaterThan(0) }
func TestAdaptiveReader(t *testing.T) { assert := assert.On(t) rawContent := make([]byte, 1024*1024) buffer := bytes.NewBuffer(rawContent) reader := NewReader(buffer) b1, err := reader.Read() assert.Error(err).IsNil() assert.Bool(b1.IsFull()).IsTrue() assert.Int(b1.Len()).Equals(Size) assert.Int(buffer.Len()).Equals(cap(rawContent) - Size) b2, err := reader.Read() assert.Error(err).IsNil() assert.Bool(b2.IsFull()).IsTrue() assert.Int(buffer.Len()).Equals(1007616) }
func TestStringListLen(t *testing.T) { assert := assert.On(t) rawJson := `"a, b, c, d"` list := new(StringList) err := json.Unmarshal([]byte(rawJson), list) assert.Error(err).IsNil() assert.Int(list.Len()).Equals(4) }
func TestShadowsocksTCP(t *testing.T) { assert := assert.On(t) tcpServer := &tcp.Server{ Port: v2net.Port(50052), MsgProcessor: func(data []byte) []byte { buffer := make([]byte, 0, 2048) buffer = append(buffer, []byte("Processed: ")...) buffer = append(buffer, data...) return buffer }, } _, err := tcpServer.Start() assert.Error(err).IsNil() defer tcpServer.Close() assert.Error(InitializeServerSetOnce("test_6")).IsNil() for i := 0; i < 1; i++ { conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{ IP: []byte{127, 0, 0, 1}, Port: 50050, }) assert.Error(err).IsNil() payload := "dokodemo request." nBytes, err := conn.Write([]byte(payload)) assert.Error(err).IsNil() assert.Int(nBytes).Equals(len(payload)) //conn.CloseWrite() response := buf.New() finished := false expectedResponse := "Processed: " + payload for { err := response.AppendSupplier(buf.ReadFrom(conn)) assert.Error(err).IsNil() if err != nil { break } if response.String() == expectedResponse { finished = true break } if response.Len() > len(expectedResponse) { fmt.Printf("Unexpected response: %v\n", response.Bytes()) break } } assert.Bool(finished).IsTrue() conn.Close() } CloseAllServers() }
func TestBufferedWriter(t *testing.T) { assert := assert.On(t) content := buf.New() writer := NewWriter(content) assert.Bool(writer.IsBuffered()).IsTrue() payload := make([]byte, 16) nBytes, err := writer.Write(payload) assert.Int(nBytes).Equals(16) assert.Error(err).IsNil() assert.Bool(content.IsEmpty()).IsTrue() writer.SetBuffered(false) assert.Int(content.Len()).Equals(16) }