Exemplo n.º 1
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)
}
Exemplo n.º 2
0
func (v *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) {
	timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
	account, err := header.User.GetTypedAccount()
	if err != nil {
		log.Error("VMess: Failed to get user account: ", err)
		return
	}
	idHash := v.idHash(account.(*vmess.InternalAccount).AnyValidID().Bytes())
	idHash.Write(timestamp.Bytes(nil))
	writer.Write(idHash.Sum(nil))

	buffer := make([]byte, 0, 512)
	buffer = append(buffer, Version)
	buffer = append(buffer, v.requestBodyIV...)
	buffer = append(buffer, v.requestBodyKey...)
	buffer = append(buffer, v.responseHeader, byte(header.Option))
	padingLen := dice.Roll(16)
	if header.Security.Is(protocol.SecurityType_LEGACY) {
		// Disable padding in legacy mode for a smooth transition.
		padingLen = 0
	}
	security := byte(padingLen<<4) | byte(header.Security)
	buffer = append(buffer, security, byte(0), byte(header.Command))
	buffer = header.Port.Bytes(buffer)

	switch header.Address.Family() {
	case v2net.AddressFamilyIPv4:
		buffer = append(buffer, AddrTypeIPv4)
		buffer = append(buffer, header.Address.IP()...)
	case v2net.AddressFamilyIPv6:
		buffer = append(buffer, AddrTypeIPv6)
		buffer = append(buffer, header.Address.IP()...)
	case v2net.AddressFamilyDomain:
		buffer = append(buffer, AddrTypeDomain, byte(len(header.Address.Domain())))
		buffer = append(buffer, header.Address.Domain()...)
	}

	if padingLen > 0 {
		pading := make([]byte, padingLen)
		rand.Read(pading)
		buffer = append(buffer, pading...)
	}

	fnv1a := fnv.New32a()
	fnv1a.Write(buffer)

	buffer = fnv1a.Sum(buffer)

	timestampHash := md5.New()
	timestampHash.Write(hashTimestamp(timestamp))
	iv := timestampHash.Sum(nil)
	aesStream := crypto.NewAesEncryptionStream(account.(*vmess.InternalAccount).ID.CmdKey(), iv)
	aesStream.XORKeyStream(buffer, buffer)
	writer.Write(buffer)

	return
}
Exemplo n.º 3
0
func (this *InboundDetourHandlerDynamic) GetConnectionHandler() (proxy.InboundHandler, int) {
	this.RLock()
	defer this.RUnlock()
	ich := this.ichs[dice.Roll(len(this.ichs))]
	until := int(this.config.GetAllocationStrategyValue().Refresh.GetValue()) - int((time.Now().Unix()-this.lastRefresh.Unix())/60/1000)
	if until < 0 {
		until = 0
	}
	return ich, int(until)
}
Exemplo n.º 4
0
func (this *InboundDetourHandlerDynamic) pickUnusedPort() v2net.Port {
	delta := int(this.config.PortRange.To) - int(this.config.PortRange.From) + 1
	for {
		r := dice.Roll(delta)
		port := this.config.PortRange.FromPort() + v2net.Port(r)
		_, used := this.portsInUse[port]
		if !used {
			return port
		}
	}
}
Exemplo n.º 5
0
func (v *ServerSpec) PickUser() *User {
	userCount := len(v.users)
	switch userCount {
	case 0:
		return nil
	case 1:
		return v.users[0]
	default:
		return v.users[dice.Roll(userCount)]
	}
}
Exemplo n.º 6
0
func pickString(arr []string) string {
	n := len(arr)
	switch n {
	case 0:
		return ""
	case 1:
		return arr[0]
	default:
		return arr[dice.Roll(n)]
	}
}
Exemplo n.º 7
0
func (v *UDPPayloadQueue) Enqueue(payload UDPPayload) {
	size := len(v.queue)
	idx := 0
	if size > 1 {
		idx = dice.Roll(size)
	}
	for i := 0; i < size; i++ {
		select {
		case v.queue[idx%size] <- payload:
			return
		default:
			idx++
		}
	}
}
Exemplo n.º 8
0
func (h *DynamicInboundHandler) allocatePort() v2net.Port {
	from := int(h.receiverConfig.PortRange.From)
	delta := int(h.receiverConfig.PortRange.To) - from + 1
	h.Lock()
	defer h.Unlock()

	for {
		r := dice.Roll(delta)
		port := v2net.Port(from + r)
		_, used := h.portsInUse[port]
		if !used {
			h.portsInUse[port] = true
			return port
		}
	}
}
Exemplo n.º 9
0
// Private: Visible for testing.
func (this *FreedomConnection) ResolveIP(destination v2net.Destination) v2net.Destination {
	if !destination.Address.Family().IsDomain() {
		return destination
	}

	ips := this.dns.Get(destination.Address.Domain())
	if len(ips) == 0 {
		log.Info("Freedom: DNS returns nil answer. Keep domain as is.")
		return destination
	}

	ip := ips[dice.Roll(len(ips))]
	var newDest v2net.Destination
	if destination.Network == v2net.Network_TCP {
		newDest = v2net.TCPDestination(v2net.IPAddress(ip), destination.Port)
	} else {
		newDest = v2net.UDPDestination(v2net.IPAddress(ip), destination.Port)
	}
	log.Info("Freedom: Changing destination from ", destination, " to ", newDest)
	return newDest
}
Exemplo n.º 10
0
// Private: Visible for testing.
func (v *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 {
	var id uint16
	v.Lock()
	if len(v.requests) > CleanupThreshold && v.nextCleanup.Before(time.Now()) {
		v.nextCleanup = time.Now().Add(CleanupInterval)
		go v.Cleanup()
	}

	for {
		id = uint16(dice.Roll(65536))
		if _, found := v.requests[id]; found {
			continue
		}
		log.Debug("DNS: Add pending request id ", id)
		v.requests[id] = &PendingRequest{
			expire:   time.Now().Add(time.Second * 8),
			response: response,
		}
		break
	}
	v.Unlock()
	return id
}
Exemplo n.º 11
0
func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
	ich := this.ich[dice.Roll(len(this.ich))]
	return ich, this.config.Allocation.Refresh
}
Exemplo n.º 12
0
func (v *InternalAccount) AnyValidID() *protocol.ID {
	if len(v.AlterIDs) == 0 {
		return v.ID
	}
	return v.AlterIDs[dice.Roll(len(v.AlterIDs))]
}
Exemplo n.º 13
0
func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (proxy.Inbound, net.Port, int) {
	w := h.workers[dice.Roll(len(h.workers))]
	return w.Proxy(), w.Port(), 9999
}
Exemplo n.º 14
0
func (this *ServerSpec) PickUser() *User {
	userCount := len(this.users)
	return this.users[dice.Roll(userCount)]
}
Exemplo n.º 15
0
func NewVideoChat(ctx context.Context, config interface{}) (interface{}, error) {
	return &VideoChat{
		sn: dice.Roll(65535),
	}, nil
}
Exemplo n.º 16
0
func NewTimestampGenerator(base Timestamp, delta int) TimestampGenerator {
	return func() Timestamp {
		rangeInDelta := dice.Roll(delta*2) - delta
		return base + Timestamp(rangeInDelta)
	}
}
Exemplo n.º 17
0
func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
	ich := this.ich[dice.Roll(len(this.ich))]
	return ich, int(this.config.GetAllocationStrategyValue().Refresh.GetValue())
}
Exemplo n.º 18
0
func TestDokodemoUDP(t *testing.T) {
	assert := assert.On(t)

	udpServer := &udp.Server{
		MsgProcessor: func(data []byte) []byte {
			buffer := make([]byte, 0, 2048)
			buffer = append(buffer, []byte("Processed: ")...)
			buffer = append(buffer, data...)
			return buffer
		},
	}
	_, err := udpServer.Start()
	assert.Error(err).IsNil()

	defer udpServer.Close()

	space := app.NewSpace()
	space.BindApp(dispatcher.APP_ID, dispatchers.NewDefaultDispatcher(space))
	ohm := proxyman.NewDefaultOutboundHandlerManager()
	ohm.SetDefaultHandler(
		freedom.NewFreedomConnection(
			&freedom.Config{},
			space,
			&proxy.OutboundHandlerMeta{
				Address: v2net.AnyIP,
				StreamSettings: &internet.StreamConfig{
					Network: v2net.Network_RawTCP,
				}}))
	space.BindApp(proxyman.APP_ID_OUTBOUND_MANAGER, ohm)

	data2Send := "Data to be sent to remote."

	port := v2net.Port(dice.Roll(20000) + 10000)
	dokodemo := NewDokodemoDoor(&Config{
		Address: &v2net.IPOrDomain{
			Address: &v2net.IPOrDomain_Ip{
				Ip: v2net.LocalHostIP.IP(),
			},
		},
		Port:        uint32(udpServer.Port),
		NetworkList: v2net.Network_UDP.AsList(),
		Timeout:     600,
	}, space, &proxy.InboundHandlerMeta{
		Address: v2net.LocalHostIP,
		Port:    port,
		StreamSettings: &internet.StreamConfig{
			Network: v2net.Network_RawTCP,
		}})
	defer dokodemo.Close()

	assert.Error(space.Initialize()).IsNil()

	err = dokodemo.Start()
	assert.Error(err).IsNil()
	assert.Port(port).Equals(dokodemo.Port())

	udpClient, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(port),
		Zone: "",
	})
	assert.Error(err).IsNil()
	defer udpClient.Close()

	udpClient.Write([]byte(data2Send))

	response := make([]byte, 1024)
	nBytes, addr, err := udpClient.ReadFromUDP(response)
	assert.Error(err).IsNil()
	assert.IP(addr.IP).Equals(v2net.LocalHostIP.IP())
	assert.Bytes(response[:nBytes]).Equals([]byte("Processed: " + data2Send))
}
Exemplo n.º 19
0
	"sync/atomic"

	"crypto/cipher"

	"v2ray.com/core/common/buf"
	"v2ray.com/core/common/dice"
	"v2ray.com/core/common/errors"
	"v2ray.com/core/common/log"
	v2net "v2ray.com/core/common/net"
	"v2ray.com/core/transport/internet"
	"v2ray.com/core/transport/internet/internal"
	v2tls "v2ray.com/core/transport/internet/tls"
)

var (
	globalConv = uint32(dice.Roll(65536))
	globalPool = internal.NewConnectionPool()
)

type ClientConnection struct {
	sync.RWMutex
	net.Conn
	id     internal.ConnectionId
	input  func([]Segment)
	reader PacketReader
	writer PacketWriter
}

func (o *ClientConnection) Overhead() int {
	o.RLock()
	defer o.RUnlock()
Exemplo n.º 20
0
func (h *DynamicInboundHandler) GetRandomInboundProxy() (proxy.Inbound, v2net.Port, int) {
	w := h.worker[dice.Roll(len(h.worker))]
	expire := h.receiverConfig.AllocationStrategy.GetRefreshValue() - uint32(time.Since(h.lastRefresh)/time.Minute)
	return w.Proxy(), w.Port(), int(expire)
}
Exemplo n.º 21
0
func (v *ServerSpec) PickUser() *User {
	userCount := len(v.users)
	return v.users[dice.Roll(userCount)]
}
Exemplo n.º 22
0
func (this *Account) AnyValidID() *protocol.ID {
	if len(this.AlterIDs) == 0 {
		return this.ID
	}
	return this.AlterIDs[dice.Roll(len(this.AlterIDs))]
}