コード例 #1
0
ファイル: vmess.go プロジェクト: v2ray/v2ray-core
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
}
コード例 #2
0
ファイル: freedom.go プロジェクト: ylywyn/v2ray-core
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
}
コード例 #3
0
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
}
コード例 #4
0
func (v *StreamConfig) Build() (*internet.StreamConfig, error) {
	config := &internet.StreamConfig{
		Protocol: internet.TransportProtocol_TCP,
	}
	if v.Network != nil {
		protocol, err := (*v.Network).Build()
		if err != nil {
			return nil, err
		}
		config.Protocol = protocol
	}
	if strings.ToLower(v.Security) == "tls" {
		tlsSettings := v.TLSSettings
		if tlsSettings == nil {
			tlsSettings = &TLSConfig{}
		}
		ts, err := tlsSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build TLS config.")
		}
		config.SecuritySettings = append(config.SecuritySettings, ts)
		config.SecurityType = ts.Type
	}
	if v.TCPSettings != nil {
		ts, err := v.TCPSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build TCP config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_TCP,
			Settings: ts,
		})
	}
	if v.KCPSettings != nil {
		ts, err := v.KCPSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build mKCP config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_MKCP,
			Settings: ts,
		})
	}
	if v.WSSettings != nil {
		ts, err := v.WSSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build WebSocket config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_WebSocket,
			Settings: ts,
		})
	}
	return config, nil
}
コード例 #5
0
ファイル: dialer.go プロジェクト: ylywyn/v2ray-core
func DialKCP(ctx context.Context, dest v2net.Destination) (internet.Connection, error) {
	dest.Network = v2net.Network_UDP
	log.Info("KCP|Dialer: Dialing KCP to ", dest)

	src := internet.DialerSourceFromContext(ctx)
	id := internal.NewConnectionID(src, dest)
	conn := globalPool.Get(id)
	if conn == nil {
		rawConn, err := internet.DialSystem(src, dest)
		if err != nil {
			log.Error("KCP|Dialer: Failed to dial to dest: ", err)
			return nil, err
		}
		c := &ClientConnection{
			Conn: rawConn,
			id:   id,
		}
		go c.Run()
		conn = c
	}

	kcpSettings := internet.TransportSettingsFromContext(ctx).(*Config)

	clientConn := conn.(*ClientConnection)
	header, err := kcpSettings.GetPackerHeader()
	if err != nil {
		return nil, errors.Base(err).Message("KCP|Dialer: Failed to create packet header.")
	}
	security, err := kcpSettings.GetSecurity()
	if err != nil {
		return nil, errors.Base(err).Message("KCP|Dialer: Failed to create security.")
	}
	clientConn.ResetSecurity(header, security)
	conv := uint16(atomic.AddUint32(&globalConv, 1))
	session := NewConnection(conv, clientConn, globalPool, kcpSettings)

	var iConn internet.Connection
	iConn = session

	if securitySettings := internet.SecuritySettingsFromContext(ctx); securitySettings != nil {
		switch securitySettings := securitySettings.(type) {
		case *v2tls.Config:
			config := securitySettings.GetTLSConfig()
			if dest.Address.Family().IsDomain() {
				config.ServerName = dest.Address.Domain()
			}
			tlsConn := tls.Client(iConn, config)
			iConn = UnreusableConnection{Conn: tlsConn}
		}
	}

	return iConn, nil
}
コード例 #6
0
func (v *StreamConfig) Build() (*internet.StreamConfig, error) {
	config := &internet.StreamConfig{
		Network: v2net.Network_RawTCP,
	}
	if v.Network != nil {
		config.Network = (*v.Network).Build()
	}
	if strings.ToLower(v.Security) == "tls" {
		tlsSettings := v.TLSSettings
		if tlsSettings == nil {
			tlsSettings = &TLSConfig{}
		}
		ts, err := tlsSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build TLS config.")
		}
		config.SecuritySettings = append(config.SecuritySettings, ts)
		config.SecurityType = ts.Type
	}
	if v.TCPSettings != nil {
		ts, err := v.TCPSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build TCP config.")
		}
		config.NetworkSettings = append(config.NetworkSettings, &internet.NetworkSettings{
			Network:  v2net.Network_TCP,
			Settings: ts,
		})
	}
	if v.KCPSettings != nil {
		ts, err := v.KCPSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build mKCP config.")
		}
		config.NetworkSettings = append(config.NetworkSettings, &internet.NetworkSettings{
			Network:  v2net.Network_KCP,
			Settings: ts,
		})
	}
	if v.WSSettings != nil {
		ts, err := v.WSSettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build WebSocket config.")
		}
		config.NetworkSettings = append(config.NetworkSettings, &internet.NetworkSettings{
			Network:  v2net.Network_WebSocket,
			Settings: ts,
		})
	}
	return config, nil
}
コード例 #7
0
ファイル: dialer.go プロジェクト: v2ray/v2ray-core
func Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) {
	log.Info("Internet|TCP: Dailing TCP to ", dest)
	if src == nil {
		src = v2net.AnyIP
	}
	networkSettings, err := options.Stream.GetEffectiveNetworkSettings()
	if err != nil {
		return nil, err
	}
	tcpSettings := networkSettings.(*Config)

	id := internal.NewConnectionId(src, dest)
	var conn net.Conn
	if dest.Network == v2net.Network_TCP && tcpSettings.ConnectionReuse.IsEnabled() {
		conn = globalCache.Get(id)
	}
	if conn == nil {
		var err error
		conn, err = internet.DialToDest(src, dest)
		if err != nil {
			return nil, err
		}
		if options.Stream != nil && options.Stream.HasSecuritySettings() {
			securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
			if err != nil {
				log.Error("TCP: Failed to get security settings: ", err)
				return nil, err
			}
			tlsConfig, ok := securitySettings.(*v2tls.Config)
			if ok {
				config := tlsConfig.GetTLSConfig()
				if dest.Address.Family().IsDomain() {
					config.ServerName = dest.Address.Domain()
				}
				conn = tls.Client(conn, config)
			}
		}
		if tcpSettings.HeaderSettings != nil {
			headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
			if err != nil {
				return nil, errors.Base(err).Message("Interent|TCP: Failed to get header settings.")
			}
			auth, err := internet.CreateConnectionAuthenticator(tcpSettings.HeaderSettings.Type, headerConfig)
			if err != nil {
				return nil, errors.Base(err).Message("Internet|TCP: Failed to create header authenticator.")
			}
			conn = auth.Client(conn)
		}
	}
	return NewConnection(id, conn, globalCache, tcpSettings), nil
}
コード例 #8
0
ファイル: listener.go プロジェクト: ylywyn/v2ray-core
func NewListener(address v2net.Address, port v2net.Port, options internet.ListenOptions) (*Listener, error) {
	networkSettings, err := options.Stream.GetEffectiveTransportSettings()
	if err != nil {
		log.Error("KCP|Listener: Failed to get KCP settings: ", err)
		return nil, err
	}
	kcpSettings := networkSettings.(*Config)
	kcpSettings.ConnectionReuse = &ConnectionReuse{Enable: false}

	header, err := kcpSettings.GetPackerHeader()
	if err != nil {
		return nil, errors.Base(err).Message("KCP|Listener: Failed to create packet header.")
	}
	security, err := kcpSettings.GetSecurity()
	if err != nil {
		return nil, errors.Base(err).Message("KCP|Listener: Failed to create security.")
	}
	l := &Listener{
		header:   header,
		security: security,
		reader: &KCPPacketReader{
			Header:   header,
			Security: security,
		},
		sessions:      make(map[ConnectionID]*Connection),
		awaitingConns: make(chan *Connection, 64),
		running:       true,
		config:        kcpSettings,
	}
	if options.Stream != nil && options.Stream.HasSecuritySettings() {
		securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
		if err != nil {
			log.Error("KCP|Listener: Failed to get security settings: ", err)
			return nil, err
		}
		switch securitySettings := securitySettings.(type) {
		case *v2tls.Config:
			l.tlsConfig = securitySettings.GetTLSConfig()
		}
	}
	hub, err := udp.ListenUDP(address, port, udp.ListenOption{Callback: l.OnReceive, Concurrency: 2})
	if err != nil {
		return nil, err
	}
	l.hub = hub
	log.Info("KCP|Listener: listening on ", address, ":", port)
	return l, nil
}
コード例 #9
0
ファイル: server.go プロジェクト: ylywyn/v2ray-core
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
	space := app.SpaceFromContext(ctx)
	if space == nil {
		return nil, errors.New("Shadowsocks|Server: No space in context.")
	}
	if config.GetUser() == nil {
		return nil, protocol.ErrUserMissing
	}

	rawAccount, err := config.User.GetTypedAccount()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|Server: Failed to get user account.")
	}
	account := rawAccount.(*ShadowsocksAccount)

	s := &Server{
		config:  config,
		user:    config.GetUser(),
		account: account,
	}

	space.OnInitialize(func() error {
		s.packetDispatcher = dispatcher.FromSpace(space)
		if s.packetDispatcher == nil {
			return errors.New("Shadowsocks|Server: Dispatcher is not found in space.")
		}
		return nil
	})

	return s, nil
}
コード例 #10
0
ファイル: server.go プロジェクト: v2ray/v2ray-core
func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandlerMeta) (*Server, error) {
	if config.GetUser() == nil {
		return nil, protocol.ErrUserMissing
	}

	rawAccount, err := config.User.GetTypedAccount()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|Server: Failed to get user account.")
	}
	account := rawAccount.(*ShadowsocksAccount)

	s := &Server{
		config:  config,
		meta:    meta,
		user:    config.GetUser(),
		account: account,
	}

	space.InitializeApplication(func() error {
		if !space.HasApp(dispatcher.APP_ID) {
			return errors.New("Shadowsocks|Server: Dispatcher is not found in space.")
		}
		s.packetDispatcher = space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
		return nil
	})

	return s, nil
}
コード例 #11
0
ファイル: v2ray.go プロジェクト: v2ray/v2ray-core
func (v *InboundConnectionConfig) Build() (*core.InboundConnectionConfig, error) {
	config := new(core.InboundConnectionConfig)
	config.PortRange = &v2net.PortRange{
		From: uint32(v.Port),
		To:   uint32(v.Port),
	}
	if v.Listen != nil {
		if v.Listen.Family().IsDomain() {
			return nil, errors.New("Point: Unable to listen on domain address: " + v.Listen.Domain())
		}
		config.ListenOn = v.Listen.Build()
	}
	if v.StreamSetting != nil {
		ts, err := v.StreamSetting.Build()
		if err != nil {
			return nil, err
		}
		config.StreamSettings = ts
	}
	config.AllowPassiveConnection = v.AllowPassive

	jsonConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol)
	if err != nil {
		return nil, errors.Base(err).Message("Failed to load inbound config.")
	}
	ts, err := jsonConfig.(Buildable).Build()
	if err != nil {
		return nil, err
	}
	config.Settings = ts
	if len(v.Tag) > 0 {
		config.Tag = v.Tag
	}
	return config, nil
}
コード例 #12
0
ファイル: hub.go プロジェクト: ylywyn/v2ray-core
func ListenTCP(address v2net.Address, port v2net.Port, options internet.ListenOptions) (internet.Listener, error) {
	listener, err := net.ListenTCP("tcp", &net.TCPAddr{
		IP:   address.IP(),
		Port: int(port),
	})
	if err != nil {
		return nil, err
	}
	log.Info("TCP|Listener: Listening on ", address, ":", port)
	networkSettings, err := options.Stream.GetEffectiveTransportSettings()
	if err != nil {
		return nil, err
	}
	tcpSettings := networkSettings.(*Config)

	l := &TCPListener{
		acccepting:    true,
		listener:      listener,
		awaitingConns: make(chan *ConnectionWithError, 32),
		config:        tcpSettings,
	}
	if options.Stream != nil && options.Stream.HasSecuritySettings() {
		securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
		if err != nil {
			log.Error("TCP: Failed to get security config: ", err)
			return nil, err
		}
		tlsConfig, ok := securitySettings.(*v2tls.Config)
		if ok {
			l.tlsConfig = tlsConfig.GetTLSConfig()
		}
	}
	if tcpSettings.HeaderSettings != nil {
		headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
		if err != nil {
			return nil, errors.Base(err).Message("Internet|TCP: Invalid header settings.")
		}
		auth, err := internet.CreateConnectionAuthenticator(headerConfig)
		if err != nil {
			return nil, errors.Base(err).Message("Internet|TCP: Invalid header settings.")
		}
		l.authConfig = auth
	}
	go l.KeepAccepting()
	return l, nil
}
コード例 #13
0
ファイル: log.go プロジェクト: v2ray/v2ray-core
func InitErrorLogger(file string) error {
	logger, err := internal.NewFileLogWriter(file)
	if err != nil {
		return errors.Base(err).Message("Log: Failed to create error logger on file (", file, ")")
	}
	streamLoggerInstance = logger
	return nil
}
コード例 #14
0
ファイル: protocol.go プロジェクト: v2ray/v2ray-core
func EncodeUDPPacket(request *protocol.RequestHeader, payload *buf.Buffer) (*buf.Buffer, error) {
	user := request.User
	rawAccount, err := user.GetTypedAccount()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|UDP: Failed to parse account.")
	}
	account := rawAccount.(*ShadowsocksAccount)

	buffer := buf.NewSmall()
	ivLen := account.Cipher.IVSize()
	buffer.AppendSupplier(buf.ReadFullFrom(rand.Reader, ivLen))
	iv := buffer.Bytes()

	switch request.Address.Family() {
	case v2net.AddressFamilyIPv4:
		buffer.AppendBytes(AddrTypeIPv4)
		buffer.Append([]byte(request.Address.IP()))
	case v2net.AddressFamilyIPv6:
		buffer.AppendBytes(AddrTypeIPv6)
		buffer.Append([]byte(request.Address.IP()))
	case v2net.AddressFamilyDomain:
		buffer.AppendBytes(AddrTypeDomain, byte(len(request.Address.Domain())))
		buffer.Append([]byte(request.Address.Domain()))
	default:
		return nil, errors.New("Shadowsocks|UDP: Unsupported address type: ", request.Address.Family())
	}

	buffer.AppendSupplier(serial.WriteUint16(uint16(request.Port)))
	buffer.Append(payload.Bytes())

	if request.Option.Has(RequestOptionOneTimeAuth) {
		authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
		buffer.SetByte(ivLen, buffer.Byte(ivLen)|0x10)

		buffer.AppendSupplier(authenticator.Authenticate(buffer.BytesFrom(ivLen)))
	}

	stream, err := account.Cipher.NewEncodingStream(account.Key, iv)
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to create encoding stream.")
	}

	stream.XORKeyStream(buffer.BytesFrom(ivLen), buffer.BytesFrom(ivLen))
	return buffer, nil
}
コード例 #15
0
ファイル: protocol.go プロジェクト: v2ray/v2ray-core
func ReadTCPResponse(user *protocol.User, reader io.Reader) (buf.Reader, error) {
	rawAccount, err := user.GetTypedAccount()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to parse account.")
	}
	account := rawAccount.(*ShadowsocksAccount)

	iv := make([]byte, account.Cipher.IVSize())
	_, err = io.ReadFull(reader, iv)
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to read IV.")
	}

	stream, err := account.Cipher.NewDecodingStream(account.Key, iv)
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to initialize decoding stream.")
	}
	return buf.NewReader(crypto.NewCryptionReader(stream, reader)), nil
}
コード例 #16
0
ファイル: v2ray.go プロジェクト: ylywyn/v2ray-core
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
}
コード例 #17
0
ファイル: config.go プロジェクト: ylywyn/v2ray-core
func (v *Account) AsAccount() (protocol.Account, error) {
	cipher, err := v.GetCipher()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|Account: Failed to get cipher.")
	}
	return &ShadowsocksAccount{
		Cipher:      cipher,
		Key:         v.GetCipherKey(),
		OneTimeAuth: v.Ota,
	}, nil
}
コード例 #18
0
ファイル: dialer.go プロジェクト: ylywyn/v2ray-core
func Dial(ctx context.Context, dest v2net.Destination) (internet.Connection, error) {
	log.Info("Internet|TCP: Dailing TCP to ", dest)
	src := internet.DialerSourceFromContext(ctx)

	tcpSettings := internet.TransportSettingsFromContext(ctx).(*Config)

	id := internal.NewConnectionID(src, dest)
	var conn net.Conn
	if dest.Network == v2net.Network_TCP && tcpSettings.IsConnectionReuse() {
		conn = globalCache.Get(id)
	}
	if conn == nil {
		var err error
		conn, err = internet.DialSystem(src, dest)
		if err != nil {
			return nil, err
		}
		if securitySettings := internet.SecuritySettingsFromContext(ctx); securitySettings != nil {
			tlsConfig, ok := securitySettings.(*v2tls.Config)
			if ok {
				config := tlsConfig.GetTLSConfig()
				if dest.Address.Family().IsDomain() {
					config.ServerName = dest.Address.Domain()
				}
				conn = tls.Client(conn, config)
			}
		}
		if tcpSettings.HeaderSettings != nil {
			headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
			if err != nil {
				return nil, errors.Base(err).Message("Interent|TCP: Failed to get header settings.")
			}
			auth, err := internet.CreateConnectionAuthenticator(headerConfig)
			if err != nil {
				return nil, errors.Base(err).Message("Internet|TCP: Failed to create header authenticator.")
			}
			conn = auth.Client(conn)
		}
	}
	return internal.NewConnection(id, conn, globalCache, internal.ReuseConnection(tcpSettings.IsConnectionReuse())), nil
}
コード例 #19
0
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
}
コード例 #20
0
ファイル: protocol.go プロジェクト: v2ray/v2ray-core
func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
	user := request.User
	rawAccount, err := user.GetTypedAccount()
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to parse account.")
	}
	account := rawAccount.(*ShadowsocksAccount)

	iv := make([]byte, account.Cipher.IVSize())
	rand.Read(iv)
	_, err = writer.Write(iv)
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to write IV.")
	}

	stream, err := account.Cipher.NewEncodingStream(account.Key, iv)
	if err != nil {
		return nil, errors.Base(err).Message("Shadowsocks|TCP: Failed to create encoding stream.")
	}

	return buf.NewWriter(crypto.NewCryptionWriter(stream, writer)), nil
}
コード例 #21
0
ファイル: v2ray.go プロジェクト: v2ray/v2ray-core
func (v *OutboundDetourConfig) Build() (*core.OutboundConnectionConfig, error) {
	config := new(core.OutboundConnectionConfig)
	config.Tag = v.Tag

	if v.SendThrough != nil {
		address := v.SendThrough
		if address.Family().IsDomain() {
			return nil, errors.New("Point: Unable to send through: " + address.String())
		}
		config.SendThrough = address.Build()
	}

	if v.StreamSetting != nil {
		ss, err := v.StreamSetting.Build()
		if err != nil {
			return nil, err
		}
		config.StreamSettings = ss
	}

	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
	}

	if v.ProxySettings != nil {
		ps, err := v.ProxySettings.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Invalid outbound detour proxy settings.")
		}
		config.ProxySettings = ps
	}
	config.Settings = ts
	return config, nil
}
コード例 #22
0
ファイル: vmess.go プロジェクト: v2ray/v2ray-core
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
}
コード例 #23
0
ファイル: v2ray.go プロジェクト: v2ray/v2ray-core
func init() {
	core.RegisterConfigLoader(core.ConfigFormat_JSON, func(input io.Reader) (*core.Config, error) {
		jsonConfig := &Config{}
		decoder := json.NewDecoder(&json_reader.Reader{
			Reader: input,
		})
		err := decoder.Decode(jsonConfig)
		if err != nil {
			return nil, errors.Base(err).Message("Invalid V2Ray config.")
		}

		return jsonConfig.Build()
	})
}
コード例 #24
0
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
}
コード例 #25
0
ファイル: transport.go プロジェクト: ylywyn/v2ray-core
func (v *TransportConfig) Build() (*transport.Config, error) {
	config := new(transport.Config)

	if v.TCPConfig != nil {
		ts, err := v.TCPConfig.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build TCP config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_TCP,
			Settings: ts,
		})
	}

	if v.KCPConfig != nil {
		ts, err := v.KCPConfig.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build mKCP config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_MKCP,
			Settings: ts,
		})
	}

	if v.WSConfig != nil {
		ts, err := v.WSConfig.Build()
		if err != nil {
			return nil, errors.Base(err).Message("Failed to build WebSocket config.")
		}
		config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
			Protocol: internet.TransportProtocol_WebSocket,
			Settings: ts,
		})
	}
	return config, nil
}
コード例 #26
0
ファイル: v2ray.go プロジェクト: ylywyn/v2ray-core
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
}
コード例 #27
0
ファイル: socks.go プロジェクト: v2ray/v2ray-core
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
}
コード例 #28
0
ファイル: blackhole.go プロジェクト: ylywyn/v2ray-core
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
}
コード例 #29
0
ファイル: v2ray.go プロジェクト: v2ray/v2ray-core
func (v *InboundDetourConfig) Build() (*core.InboundConnectionConfig, error) {
	config := new(core.InboundConnectionConfig)
	if v.PortRange == nil {
		return nil, errors.New("Port range not specified in InboundDetour.")
	}
	config.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())
		}
		config.ListenOn = v.ListenOn.Build()
	}
	config.Tag = v.Tag
	if v.Allocation != nil {
		as, err := v.Allocation.Build()
		if err != nil {
			return nil, err
		}
		config.AllocationStrategy = as
	}
	if v.StreamSetting != nil {
		ss, err := v.StreamSetting.Build()
		if err != nil {
			return nil, err
		}
		config.StreamSettings = ss
	}
	config.AllowPassiveConnection = v.AllowPassive

	rawConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol)
	if err != nil {
		return nil, errors.Base(err).Message("Failed to load inbound detour config.")
	}
	ts, err := rawConfig.(Buildable).Build()
	if err != nil {
		return nil, err
	}
	config.Settings = ts
	return config, nil
}
コード例 #30
0
ファイル: v2ray.go プロジェクト: ylywyn/v2ray-core
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
}