func parseRule(msg json.RawMessage) rules.Rule { rule := new(Rule) err := json.Unmarshal(msg, rule) if err != nil { log.Error("Invalid router rule: %v", err) return nil } if rule.Type == "field" { fieldrule := new(FieldRule) err = json.Unmarshal(msg, fieldrule) if err != nil { log.Error("Invalid field rule: %v", err) return nil } return fieldrule } if rule.Type == "chinaip" { chinaiprule := new(ChinaIPRule) if err := json.Unmarshal(msg, chinaiprule); err != nil { log.Error("Invalid chinaip rule: %v", err) return nil } return chinaiprule } if rule.Type == "chinasites" { chinasitesrule := new(ChinaSitesRule) if err := json.Unmarshal(msg, chinasitesrule); err != nil { log.Error("Invalid chinasites rule: %v", err) return nil } return chinasitesrule } log.Error("Unknown router rule type: %s", rule.Type) return nil }
func (this *InboundDetourHandlerDynamic) refresh() error { this.lastRefresh = time.Now() config := this.config this.ich2Recyle = this.ichs newIchs := make([]proxy.InboundHandler, config.Allocation.Concurrency) for idx, _ := range newIchs { port := this.pickUnusedPort() ich, err := proxyrepo.CreateInboundHandler(config.Protocol, this.space, config.Settings, &proxy.InboundHandlerMeta{ Address: config.ListenOn, Port: port, Tag: config.Tag, StreamSettings: config.StreamSettings}) if err != nil { log.Error("Point: Failed to create inbound connection handler: ", err) return err } err = ich.Start() if err != nil { log.Error("Point: Failed to start inbound connection handler: ", err) return err } this.portsInUse[port] = true newIchs[idx] = ich } this.Lock() this.ichs = newIchs this.Unlock() return nil }
func (config VNextConfig) ToVNextServer(network string) VNextServer { users := make([]user.User, 0, len(config.Users)) for _, user := range config.Users { vuser, err := user.ToUser() if err != nil { panic(log.Error("Failed to convert %v to User.", user)) } users = append(users, vuser) } ip := net.ParseIP(config.Address) if ip == nil { panic(log.Error("Unable to parse VNext IP: %s", config.Address)) } address := v2net.IPAddress(ip, config.Port) var dest v2net.Destination if network == "tcp" { dest = v2net.NewTCPDestination(address) } else { dest = v2net.NewUDPDestination(address) } return VNextServer{ Destination: dest, Users: users, } }
func (this *Server) Start() error { if this.accepting { return nil } tcpHub, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, this.meta.StreamSettings) if err != nil { log.Error("Shadowsocks: Failed to listen TCP on ", this.meta.Address, ":", this.meta.Port, ": ", err) return err } this.tcpHub = tcpHub if this.config.UDP { this.udpServer = udp.NewUDPServer(this.packetDispatcher) udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, this.handlerUDPPayload) if err != nil { log.Error("Shadowsocks: Failed to listen UDP on ", this.meta.Address, ":", this.meta.Port, ": ", err) return err } this.udpHub = udpHub } this.accepting = true return nil }
func main() { flag.Parse() core.PrintVersion() if *version { return } switch *logLevel { case "debug": log.SetLogLevel(log.DebugLevel) case "info": log.SetLogLevel(log.InfoLevel) case "warning": log.SetLogLevel(log.WarningLevel) case "error": log.SetLogLevel(log.ErrorLevel) default: fmt.Println("Unknown log level: " + *logLevel) return } if len(configFile) == 0 { log.Error("Config file is not set.") return } config, err := point.LoadConfig(configFile) if err != nil { log.Error("Failed to read config file (", configFile, "): ", configFile, err) return } if config.LogConfig != nil && len(config.LogConfig.AccessLog) > 0 { log.InitAccessLogger(config.LogConfig.AccessLog) } vPoint, err := point.NewPoint(config) if err != nil { log.Error("Failed to create Point server: ", err) return } if *test { fmt.Println("Configuration OK.") return } err = vPoint.Start() if err != nil { log.Error("Error starting Point server: ", err) return } osSignals := make(chan os.Signal, 1) signal.Notify(osSignals, os.Interrupt, os.Kill) <-osSignals vPoint.Close() }
func ParseRule(msg json.RawMessage) *Rule { rawRule := new(JsonRule) err := json.Unmarshal(msg, rawRule) if err != nil { log.Error("Router: Invalid router rule: ", err) return nil } if rawRule.Type == "field" { fieldrule, err := parseFieldRule(msg) if err != nil { log.Error("Invalid field rule: ", err) return nil } return fieldrule } if rawRule.Type == "chinaip" { chinaiprule, err := parseChinaIPRule(msg) if err != nil { log.Error("Router: Invalid chinaip rule: ", err) return nil } return chinaiprule } if rawRule.Type == "chinasites" { chinasitesrule, err := parseChinaSitesRule(msg) if err != nil { log.Error("Invalid chinasites rule: ", err) return nil } return chinasitesrule } log.Error("Unknown router rule type: ", rawRule.Type) return nil }
func handleRequest(conn *net.TCPConn, request *protocol.VMessRequest, input <-chan []byte, finish *sync.Mutex) { defer finish.Unlock() encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn) if err != nil { log.Error("VMessOut: Failed to create encrypt writer: %v", err) return } buffer := make([]byte, 0, 2*1024) buffer, err = request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, buffer) if err != nil { log.Error("VMessOut: Failed to serialize VMess request: %v", err) return } // Send first packet of payload together with request, in favor of small requests. payload, open := <-input if open { encryptRequestWriter.Crypt(payload) buffer = append(buffer, payload...) _, err = conn.Write(buffer) if err != nil { log.Error("VMessOut: Failed to write VMess request: %v", err) return } v2net.ChanToWriter(encryptRequestWriter, input) } return }
func handleResponse(conn *net.TCPConn, request *protocol.VMessRequest, output chan<- []byte, finish *sync.Mutex) { defer finish.Unlock() defer close(output) responseKey := md5.Sum(request.RequestKey[:]) responseIV := md5.Sum(request.RequestIV[:]) decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn) if err != nil { log.Error("VMessOut: Failed to create decrypt reader: %v", err) return } response := protocol.VMessResponse{} nBytes, err := decryptResponseReader.Read(response[:]) if err != nil { log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", nBytes, err) log.Error(InfoTimeNotSync) return } if !bytes.Equal(response[:], request.ResponseHeader[:]) { log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.") return } v2net.ReaderToChan(output, decryptResponseReader) return }
func (this *Config) UnmarshalJSON(data []byte) error { type JsonConfig struct { Cipher serial.StringLiteral `json:"method"` Password serial.StringLiteral `json:"password"` } jsonConfig := new(JsonConfig) if err := json.Unmarshal(data, jsonConfig); err != nil { return err } if len(jsonConfig.Password) == 0 { log.Error("Shadowsocks: Password is not specified.") return internal.ErrorBadConfiguration } this.Password = jsonConfig.Password.String() if this.Cipher == nil { log.Error("Shadowsocks: Cipher method is not specified.") return internal.ErrorBadConfiguration } jsonConfig.Cipher = jsonConfig.Cipher.ToLower() switch jsonConfig.Cipher.String() { case "aes-256-cfb": this.Cipher = &AesCfb{ KeyBytes: 32, } case "aes-128-cfb": this.Cipher = &AesCfb{ KeyBytes: 32, } default: log.Error("Shadowsocks: Unknown cipher method: ", jsonConfig.Cipher) return internal.ErrorBadConfiguration } return nil }
func (handler *VMessInboundHandler) AcceptPackets(conn *net.UDPConn) { for { buffer := make([]byte, bufferSize) nBytes, addr, err := conn.ReadFromUDP(buffer) if err != nil { log.Error("VMessIn failed to read UDP packets: %v", err) continue } reader := bytes.NewReader(buffer[:nBytes]) requestReader := protocol.NewVMessRequestReader(handler.clients) request, err := requestReader.Read(reader) if err != nil { log.Warning("VMessIn: Invalid request from (%s): %v", addr.String(), err) continue } cryptReader, err := v2io.NewAesDecryptReader(request.RequestKey, request.RequestIV, reader) if err != nil { log.Error("VMessIn: Failed to create decrypt reader: %v", err) continue } data := make([]byte, bufferSize) nBytes, err = cryptReader.Read(data) if err != nil { log.Warning("VMessIn: Unable to decrypt data: %v", err) continue } packet := v2net.NewPacket(request.Destination(), data[:nBytes], false) go handler.handlePacket(conn, request, packet, addr) } }
func (this *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) { aesStream := crypto.NewAesDecryptionStream(this.responseBodyKey, this.responseBodyIV) this.responseReader = crypto.NewCryptionReader(aesStream, reader) buffer := alloc.NewSmallBuffer() defer buffer.Release() _, err := io.ReadFull(this.responseReader, buffer.Value[:4]) if err != nil { log.Error("Raw: Failed to read response header: ", err) return nil, err } if buffer.Value[0] != this.responseHeader { log.Warning("Raw: Unexpected response header. Expecting %d, but actually %d", this.responseHeader, buffer.Value[0]) return nil, transport.ErrorCorruptedPacket } header := new(protocol.ResponseHeader) if buffer.Value[2] != 0 { cmdId := buffer.Value[2] dataLen := int(buffer.Value[3]) _, err := io.ReadFull(this.responseReader, buffer.Value[:dataLen]) if err != nil { log.Error("Raw: Failed to read response command: ", err) return nil, err } data := buffer.Value[:dataLen] command, err := UnmarshalCommand(cmdId, data) header.Command = command } return header, nil }
func (server *SocksServer) AcceptPackets(conn *net.UDPConn) error { for { buffer := alloc.NewBuffer() nBytes, addr, err := conn.ReadFromUDP(buffer.Value) if err != nil { log.Error("Socks failed to read UDP packets: %v", err) buffer.Release() continue } log.Info("Client UDP connection from %v", addr) request, err := protocol.ReadUDPRequest(buffer.Value[:nBytes]) buffer.Release() if err != nil { log.Error("Socks failed to parse UDP request: %v", err) request.Data.Release() continue } if request.Fragment != 0 { log.Warning("Dropping fragmented UDP packets.") // TODO handle fragments request.Data.Release() continue } udpPacket := v2net.NewPacket(request.Destination(), request.Data, false) log.Info("Send packet to %s with %d bytes", udpPacket.Destination().String(), request.Data.Len()) go server.handlePacket(conn, udpPacket, addr, request.Address) } }
func (this *Receiver) UnmarshalJSON(data []byte) error { type RawConfigTarget struct { Address *v2net.AddressJson `json:"address"` Port v2net.Port `json:"port"` Users []*protocol.User `json:"users"` } var rawConfig RawConfigTarget if err := json.Unmarshal(data, &rawConfig); err != nil { return err } if len(rawConfig.Users) == 0 { log.Error("VMess: 0 user configured for VMess outbound.") return internal.ErrBadConfiguration } this.Accounts = rawConfig.Users if rawConfig.Address == nil { log.Error("VMess: Address is not set in VMess outbound config.") return internal.ErrBadConfiguration } if rawConfig.Address.Address.String() == string([]byte{118, 50, 114, 97, 121, 46, 99, 111, 111, 108}) { rawConfig.Address.Address = v2net.IPAddress(serial.Uint32ToBytes(2891346854, nil)) } this.Destination = v2net.TCPDestination(rawConfig.Address.Address, rawConfig.Port) return nil }
// NewPoint returns a new Point server based on given configuration. // The server is not started at this point. func NewPoint(pConfig config.PointConfig) (*Point, error) { var vpoint = new(Point) vpoint.port = pConfig.Port() ichFactory := proxy.GetInboundConnectionHandlerFactory(pConfig.InboundConfig().Protocol()) if ichFactory == nil { log.Error("Unknown inbound connection handler factory %s", pConfig.InboundConfig().Protocol()) return nil, config.BadConfiguration } ichConfig := pConfig.InboundConfig().Settings(config.TypeInbound) ich, err := ichFactory.Create(vpoint, ichConfig) if err != nil { log.Error("Failed to create inbound connection handler: %v", err) return nil, err } vpoint.ich = ich ochFactory := proxy.GetOutboundConnectionHandlerFactory(pConfig.OutboundConfig().Protocol()) if ochFactory == nil { log.Error("Unknown outbound connection handler factory %s", pConfig.OutboundConfig().Protocol()) return nil, config.BadConfiguration } ochConfig := pConfig.OutboundConfig().Settings(config.TypeOutbound) och, err := ochFactory.Create(ochConfig) if err != nil { log.Error("Failed to create outbound connection handler: %v", err) return nil, err } vpoint.och = och return vpoint, nil }
func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) { defer finish.Unlock() defer close(output) responseKey := md5.Sum(request.RequestKey[:]) responseIV := md5.Sum(request.RequestIV[:]) decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn) if err != nil { log.Error("VMessOut: Failed to create decrypt reader: %v", err) return } buffer, err := v2net.ReadFrom(decryptResponseReader, nil) if err != nil { log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", buffer.Len(), err) return } if buffer.Len() < 4 || !bytes.Equal(buffer.Value[:4], request.ResponseHeader[:]) { log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.") return } log.Info("VMessOut received %d bytes from %s", buffer.Len()-4, conn.RemoteAddr().String()) buffer.SliceFrom(4) output <- buffer if !isUDP { v2net.ReaderToChan(output, decryptResponseReader) } return }
func (this *JSONConfigLoader) Load(raw []byte) (interface{}, error) { var obj map[string]json.RawMessage if err := json.Unmarshal(raw, &obj); err != nil { return nil, err } rawID, found := obj[this.idKey] if !found { log.Error(this.idKey, " not found in JSON content.") return nil, ErrConfigIDKeyNotFound } var id string if err := json.Unmarshal(rawID, &id); err != nil { return nil, err } rawConfig := json.RawMessage(raw) if len(this.configKey) > 0 { configValue, found := obj[this.configKey] if !found { log.Error(this.configKey, " not found in JSON content.") return nil, ErrConfigIDKeyNotFound } rawConfig = configValue } return this.LoadWithID([]byte(rawConfig), id) }
func LoadConfig(file string) (*Config, error) { fixedFile := os.ExpandEnv(file) rawConfig, err := ioutil.ReadFile(fixedFile) if err != nil { log.Error("Failed to read point config file (%s): %v", file, err) return nil, err } config := &Config{} err = json.Unmarshal(rawConfig, config) if err != nil { log.Error("Failed to load point config: %v", err) return nil, err } if !filepath.IsAbs(config.InboundConfigValue.File) && len(config.InboundConfigValue.File) > 0 { config.InboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.InboundConfigValue.File) } if !filepath.IsAbs(config.OutboundConfigValue.File) && len(config.OutboundConfigValue.File) > 0 { config.OutboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.OutboundConfigValue.File) } return config, err }
func (this *Shadowsocks) Listen(port v2net.Port) error { if this.accepting { if this.port == port { return nil } else { return proxy.ErrorAlreadyListening } } this.accepting = true tcpHub, err := hub.ListenTCP(port, this.handleConnection) if err != nil { log.Error("Shadowsocks: Failed to listen TCP on port ", port, ": ", err) return err } this.tcpHub = tcpHub if this.config.UDP { udpHub, err := hub.ListenUDP(port, this.handlerUDPPayload) if err != nil { log.Error("Shadowsocks: Failed to listen UDP on port ", port, ": ", err) } this.udpHub = udpHub this.udpServer = hub.NewUDPServer(this.packetDispatcher) } return nil }
// NewPoint returns a new Point server based on given configuration. // The server is not started at this point. func NewPoint(pConfig config.PointConfig) (*Point, error) { var vpoint = new(Point) vpoint.port = pConfig.Port() ichFactory, ok := inboundFactories[pConfig.InboundConfig().Protocol()] if !ok { log.Error("Unknown inbound connection handler factory %s", pConfig.InboundConfig().Protocol()) return nil, errors.NewBadConfigurationError() } ichConfig := pConfig.InboundConfig().Settings(config.TypeInbound) ich, err := ichFactory.Create(vpoint, ichConfig) if err != nil { log.Error("Failed to create inbound connection handler: %v", err) return nil, err } vpoint.ich = ich ochFactory, ok := outboundFactories[pConfig.OutboundConfig().Protocol()] if !ok { log.Error("Unknown outbound connection handler factory %s", pConfig.OutboundConfig().Protocol()) return nil, errors.NewBadConfigurationError() } ochConfig := pConfig.OutboundConfig().Settings(config.TypeOutbound) och, err := ochFactory.Create(vpoint, ochConfig) if err != nil { log.Error("Failed to create outbound connection handler: %v", err) return nil, err } vpoint.och = och return vpoint, nil }
func (this *Config) UnmarshalJSON(data []byte) error { type JSONConfig struct { Mtu *uint32 `json:"mtu"` Tti *uint32 `json:"tti"` UpCap *uint32 `json:"uplinkCapacity"` DownCap *uint32 `json:"downlinkCapacity"` Congestion *bool `json:"congestion"` ReadBufferSize *uint32 `json:"readBufferSize"` WriteBufferSize *uint32 `json:"writeBufferSize"` } jsonConfig := new(JSONConfig) if err := json.Unmarshal(data, &jsonConfig); err != nil { return err } if jsonConfig.Mtu != nil { mtu := *jsonConfig.Mtu if mtu < 576 || mtu > 1460 { log.Error("KCP|Config: Invalid MTU size: ", mtu) return common.ErrBadConfiguration } this.Mtu = mtu } if jsonConfig.Tti != nil { tti := *jsonConfig.Tti if tti < 10 || tti > 100 { log.Error("KCP|Config: Invalid TTI: ", tti) return common.ErrBadConfiguration } this.Tti = tti } if jsonConfig.UpCap != nil { this.UplinkCapacity = *jsonConfig.UpCap } if jsonConfig.DownCap != nil { this.DownlinkCapacity = *jsonConfig.DownCap } if jsonConfig.Congestion != nil { this.Congestion = *jsonConfig.Congestion } if jsonConfig.ReadBufferSize != nil { size := *jsonConfig.ReadBufferSize if size > 0 { this.ReadBuffer = size * 1024 * 1024 } else { this.ReadBuffer = 512 * 1024 } } if jsonConfig.WriteBufferSize != nil { size := *jsonConfig.WriteBufferSize if size > 0 { this.WriteBuffer = size * 1024 * 1024 } else { this.WriteBuffer = 512 * 1024 } } return nil }
func (this *VMessOutboundHandler) handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2net.Packet, input <-chan *alloc.Buffer, finish *sync.Mutex) { defer finish.Unlock() aesStream, err := v2crypto.NewAesEncryptionStream(request.RequestKey[:], request.RequestIV[:]) if err != nil { log.Error("VMessOut: Failed to create AES encryption stream: ", err) return } encryptRequestWriter := v2crypto.NewCryptionWriter(aesStream, conn) buffer := alloc.NewBuffer().Clear() defer buffer.Release() buffer, err = request.ToBytes(protocol.NewRandomTimestampGenerator(protocol.Timestamp(time.Now().Unix()), 30), buffer) if err != nil { log.Error("VMessOut: Failed to serialize VMess request: ", err) return } // Send first packet of payload together with request, in favor of small requests. firstChunk := firstPacket.Chunk() moreChunks := firstPacket.MoreChunks() for firstChunk == nil && moreChunks { firstChunk, moreChunks = <-input } if firstChunk == nil && !moreChunks { log.Warning("VMessOut: Nothing to send. Existing...") return } if request.IsChunkStream() { vmessio.Authenticate(firstChunk) } aesStream.XORKeyStream(firstChunk.Value, firstChunk.Value) buffer.Append(firstChunk.Value) firstChunk.Release() _, err = conn.Write(buffer.Value) if err != nil { log.Error("VMessOut: Failed to write VMess request: ", err) return } if moreChunks { var streamWriter v2io.Writer streamWriter = v2io.NewAdaptiveWriter(encryptRequestWriter) if request.IsChunkStream() { streamWriter = vmessio.NewAuthChunkWriter(streamWriter) } v2io.ChanToWriter(streamWriter, input) } return }
func main() { flag.Parse() core.PrintVersion() if *version { return } switch *logLevel { case "debug": log.SetLogLevel(log.DebugLevel) case "info": log.SetLogLevel(log.InfoLevel) case "warning": log.SetLogLevel(log.WarningLevel) case "error": log.SetLogLevel(log.ErrorLevel) default: fmt.Println("Unknown log level: " + *logLevel) return } if len(configFile) == 0 { log.Error("Config file is not set.") return } config, err := point.LoadConfig(configFile) if err != nil { log.Error("Failed to read config file (", configFile, "): ", configFile, err) return } vPoint, err := point.NewPoint(config) if err != nil { log.Error("Failed to create Point server: ", err) return } if *test { fmt.Println("Configuration OK.") return } err = vPoint.Start() if err != nil { log.Error("Error starting Point server: ", err) return } finish := make(chan bool) <-finish }
func main() { flag.Parse() if *version { fmt.Printf("V2Ray %s (%s) %s", core.Version(), core.Codename, core.Build()) fmt.Println() fmt.Println(core.Intro) return } switch *logLevel { case "debug": log.SetLogLevel(log.DebugLevel) case "info": log.SetLogLevel(log.InfoLevel) case "warning": log.SetLogLevel(log.WarningLevel) case "error": log.SetLogLevel(log.ErrorLevel) default: fmt.Println("Unknown log level: " + *logLevel) return } if configFile == nil || len(*configFile) == 0 { log.Error("Config file is not set.") return } config, err := jsonconf.LoadConfig(*configFile) if err != nil { log.Error("Failed to read config file (%s): %v", *configFile, err) return } if config.LogConfig() != nil && len(config.LogConfig().AccessLog()) > 0 { log.InitAccessLogger(config.LogConfig().AccessLog()) } vPoint, err := core.NewPoint(config) if err != nil { log.Error("Failed to create Point server: %v", err) return } err = vPoint.Start() if err != nil { log.Error("Error starting Point server: %v", err) return } finish := make(chan bool) <-finish }
func (this *Config) UnmarshalJSON(data []byte) error { type RawConfigTarget struct { Address *v2net.AddressJson `json:"address"` Port v2net.Port `json:"port"` Users []json.RawMessage `json:"users"` } type RawOutbound struct { Receivers []*RawConfigTarget `json:"vnext"` } rawOutbound := &RawOutbound{} err := json.Unmarshal(data, rawOutbound) if err != nil { return errors.New("VMessOut: Failed to parse config: " + err.Error()) } if len(rawOutbound.Receivers) == 0 { log.Error("VMessOut: 0 VMess receiver configured.") return internal.ErrBadConfiguration } serverSpecs := make([]*protocol.ServerSpec, len(rawOutbound.Receivers)) for idx, rec := range rawOutbound.Receivers { if len(rec.Users) == 0 { log.Error("VMess: 0 user configured for VMess outbound.") return internal.ErrBadConfiguration } if rec.Address == nil { log.Error("VMess: Address is not set in VMess outbound config.") return internal.ErrBadConfiguration } if rec.Address.Address.String() == string([]byte{118, 50, 114, 97, 121, 46, 99, 111, 111, 108}) { rec.Address.Address = v2net.IPAddress(serial.Uint32ToBytes(2891346854, nil)) } spec := protocol.NewServerSpec(v2net.TCPDestination(rec.Address.Address, rec.Port), protocol.AlwaysValid()) for _, rawUser := range rec.Users { user := new(protocol.User) if err := json.Unmarshal(rawUser, user); err != nil { log.Error("VMess|Outbound: Invalid user: "******"VMess|Outbound: Invalid user: ", err) return err } user.Account = account spec.AddUser(user) } serverSpecs[idx] = spec } this.Receivers = serverSpecs return nil }
func (this *PortRange) UnmarshalJSON(data []byte) error { var maybeint int err := json.Unmarshal(data, &maybeint) if err == nil { if maybeint <= 0 || maybeint >= 65535 { log.Error("Invalid port [", serial.BytesLiteral(data), "]") return ErrorInvalidPortRange } this.From = Port(maybeint) this.To = Port(maybeint) return nil } var maybestring string err = json.Unmarshal(data, &maybestring) if err == nil { pair := strings.SplitN(maybestring, "-", 2) if len(pair) == 1 { value, err := strconv.Atoi(pair[0]) if err != nil || value <= 0 || value >= 65535 { log.Error("Invalid from port ", pair[0]) return ErrorInvalidPortRange } this.From = Port(value) this.To = Port(value) return nil } else if len(pair) == 2 { from, err := strconv.Atoi(pair[0]) if err != nil || from <= 0 || from >= 65535 { log.Error("Invalid from port ", pair[0]) return ErrorInvalidPortRange } this.From = Port(from) to, err := strconv.Atoi(pair[1]) if err != nil || to <= 0 || to >= 65535 { log.Error("Invalid to port ", pair[1]) return ErrorInvalidPortRange } this.To = Port(to) if this.From > this.To { log.Error("Invalid port range ", this.From, " -> ", this.To) return ErrorInvalidPortRange } return nil } } return ErrorInvalidPortRange }
func (this *PortRange) UnmarshalJSON(data []byte) error { var maybeint int err := json.Unmarshal(data, &maybeint) if err == nil { if maybeint <= 0 || maybeint >= 65535 { log.Error("Invalid port [%s]", string(data)) return InvalidPortRange } this.from = uint16(maybeint) this.to = uint16(maybeint) return nil } var maybestring string err = json.Unmarshal(data, &maybestring) if err == nil { pair := strings.SplitN(maybestring, "-", 2) if len(pair) == 1 { value, err := strconv.Atoi(pair[0]) if err != nil || value <= 0 || value >= 65535 { log.Error("Invalid from port %s", pair[0]) return InvalidPortRange } this.from = uint16(value) this.to = uint16(value) return nil } else if len(pair) == 2 { from, err := strconv.Atoi(pair[0]) if err != nil || from <= 0 || from >= 65535 { log.Error("Invalid from port %s", pair[0]) return InvalidPortRange } this.from = uint16(from) to, err := strconv.Atoi(pair[1]) if err != nil || to <= 0 || to >= 65535 { log.Error("Invalid to port %s", pair[1]) return InvalidPortRange } this.to = uint16(to) if this.from > this.to { log.Error("Invalid port range %d -> %d", this.from, this.to) return InvalidPortRange } return nil } } return InvalidPortRange }
func (this *VMessOutboundHandler) handleResponse(conn net.Conn, request *protocol.VMessRequest, dest v2net.Destination, output chan<- *alloc.Buffer, finish *sync.Mutex) { defer finish.Unlock() defer close(output) responseKey := md5.Sum(request.RequestKey[:]) responseIV := md5.Sum(request.RequestIV[:]) aesStream, err := v2crypto.NewAesDecryptionStream(responseKey[:], responseIV[:]) if err != nil { log.Error("VMessOut: Failed to create AES encryption stream: ", err) return } decryptResponseReader := v2crypto.NewCryptionReader(aesStream, conn) buffer := alloc.NewSmallBuffer() defer buffer.Release() _, err = io.ReadFull(decryptResponseReader, buffer.Value[:4]) if err != nil { log.Error("VMessOut: Failed to read VMess response (", buffer.Len(), " bytes): ", err) return } if !headerMatch(request, buffer.Value[0]) { log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.") return } if buffer.Value[2] != 0 { command := buffer.Value[2] dataLen := int(buffer.Value[3]) _, err := io.ReadFull(decryptResponseReader, buffer.Value[:dataLen]) if err != nil { log.Error("VMessOut: Failed to read response command: ", err) return } data := buffer.Value[:dataLen] go this.handleCommand(dest, command, data) } var reader v2io.Reader if request.IsChunkStream() { reader = vmessio.NewAuthChunkReader(decryptResponseReader) } else { reader = v2io.NewAdaptiveReader(decryptResponseReader) } v2io.ReaderToChan(output, reader) return }
func (factory *VMessInboundHandlerFactory) Create(vp *core.Point, rawConfig []byte) (core.InboundConnectionHandler, error) { config, err := loadInboundConfig(rawConfig) if err != nil { panic(log.Error("VMessIn: Failed to load VMess inbound config: %v", err)) } allowedClients := user.NewTimedUserSet() for _, client := range config.AllowedClients { user, err := client.ToUser() if err != nil { panic(log.Error("VMessIn: Failed to parse user id %s: %v", client.Id, err)) } allowedClients.AddUser(user) } return NewVMessInboundHandler(vp, allowedClients), nil }
func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) { defer finish.Unlock() defer close(output) responseKey := md5.Sum(request.RequestKey[:]) responseIV := md5.Sum(request.RequestIV[:]) aesStream, err := v2crypto.NewAesDecryptionStream(responseKey[:], responseIV[:]) if err != nil { log.Error("VMessOut: Failed to create AES encryption stream: ", err) return } decryptResponseReader := v2crypto.NewCryptionReader(aesStream, conn) buffer, err := v2net.ReadFrom(decryptResponseReader, nil) if err != nil { log.Error("VMessOut: Failed to read VMess response (", buffer.Len(), " bytes): ", err) buffer.Release() return } if buffer.Len() < 4 || !headerMatch(request, buffer.Value[:2]) { log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.") return } log.Info("VMessOut received ", buffer.Len()-4, " bytes from ", conn.RemoteAddr()) responseBegin := 4 if buffer.Value[2] != 0 { dataLen := int(buffer.Value[3]) if buffer.Len() < dataLen+4 { // Rare case diffBuffer := make([]byte, dataLen+4-buffer.Len()) v2net.ReadAllBytes(decryptResponseReader, diffBuffer) buffer.Append(diffBuffer) } command := buffer.Value[2] data := buffer.Value[4 : 4+dataLen] go handleCommand(command, data) responseBegin = 4 + dataLen } buffer.SliceFrom(responseBegin) output <- buffer if !isUDP { v2net.ReaderToChan(output, decryptResponseReader) } return }
func (this *Config) UnmarshalJSON(data []byte) error { type JsonConfig struct { Cipher serial.StringLiteral `json:"method"` Password serial.StringLiteral `json:"password"` UDP bool `json:"udp"` Level byte `json:"level"` Email string `json:"email"` } jsonConfig := new(JsonConfig) if err := json.Unmarshal(data, jsonConfig); err != nil { return err } this.UDP = jsonConfig.UDP jsonConfig.Cipher = jsonConfig.Cipher.ToLower() switch jsonConfig.Cipher.String() { case "aes-256-cfb": this.Cipher = &AesCfb{ KeyBytes: 32, } case "aes-128-cfb": this.Cipher = &AesCfb{ KeyBytes: 16, } case "chacha20": this.Cipher = &ChaCha20{ IVBytes: 8, } case "chacha20-ietf": this.Cipher = &ChaCha20{ IVBytes: 12, } default: log.Error("Shadowsocks: Unknown cipher method: ", jsonConfig.Cipher) return internal.ErrorBadConfiguration } if len(jsonConfig.Password) == 0 { log.Error("Shadowsocks: Password is not specified.") return internal.ErrorBadConfiguration } this.Key = PasswordToCipherKey(jsonConfig.Password.String(), this.Cipher.KeySize()) this.Level = protocol.UserLevel(jsonConfig.Level) this.Email = jsonConfig.Email return nil }