diff --git a/api/client.go b/api/client.go index bad2dc8..115db5f 100644 --- a/api/client.go +++ b/api/client.go @@ -26,14 +26,14 @@ type ClientAPI struct { func (s *ClientAPI) GetTraffic(ctx context.Context, req *GetTrafficRequest) (*GetTrafficResponse, error) { log.Debug("API: GetTraffic") if req.User == nil { - return nil, common.NewError("user is unspecified") + return nil, common.NewError("User is unspecified") } if req.User.Hash == "" { req.User.Hash = common.SHA224String(req.User.Password) } valid, meter := s.auth.AuthUser(req.User.Hash) if !valid { - return nil, common.NewError("user " + req.User.Hash + " not found") + return nil, common.NewError("User " + req.User.Hash + " not found") } sent, recv := meter.Get() sentSpeed, recvSpeed := meter.GetSpeed() @@ -62,7 +62,7 @@ func RunClientAPI(ctx context.Context, config *conf.GlobalConfig, auth stat.Auth if err != nil { return err } - log.Info("client api service is running at", config.API.APIAddress) + log.Info("Client api service is running at", config.API.APIAddress) errChan := make(chan error, 1) go func() { errChan <- server.Serve(listener) diff --git a/api/server.go b/api/server.go index ee34896..318a574 100644 --- a/api/server.go +++ b/api/server.go @@ -29,7 +29,7 @@ func (s *ServerAPI) GetTraffic(stream TrojanServerService_GetTrafficServer) erro return err } if req.User == nil { - return common.NewError("user is unspecified") + return common.NewError("User is unspecified") } if req.User.Hash == "" { req.User.Hash = common.SHA224String(req.User.Password) @@ -38,7 +38,7 @@ func (s *ServerAPI) GetTraffic(stream TrojanServerService_GetTrafficServer) erro if !valid { stream.Send(&GetTrafficResponse{ Success: false, - Info: "invalid user " + req.User.Hash, + Info: "Invalid user " + req.User.Hash, }) continue } @@ -77,7 +77,7 @@ func (s *ServerAPI) SetUsers(stream TrojanServerService_SetUsersServer) error { return err } if req.User == nil { - return common.NewError("user is unspecified") + return common.NewError("User is unspecified") } if req.User.Hash == "" { req.User.Hash = common.SHA224String(req.User.Password) @@ -88,7 +88,7 @@ func (s *ServerAPI) SetUsers(stream TrojanServerService_SetUsersServer) error { if req.SpeedLimit != nil { valid, meter := s.auth.AuthUser(req.User.Hash) if !valid { - return common.NewError("failed to add new user") + return common.NewError("Failed to add new user") } meter.LimitSpeed(int(req.SpeedLimit.DownloadSpeed), int(req.SpeedLimit.UploadSpeed)) } @@ -97,7 +97,7 @@ func (s *ServerAPI) SetUsers(stream TrojanServerService_SetUsersServer) error { case SetUserRequest_Modify: valid, meter := s.auth.AuthUser(req.User.Hash) if !valid { - err = common.NewError("invalid user " + req.User.Hash) + err = common.NewError("Invalid user " + req.User.Hash) } else { meter.LimitSpeed(int(req.SpeedLimit.DownloadSpeed), int(req.SpeedLimit.UploadSpeed)) } @@ -161,7 +161,7 @@ func RunServerAPI(ctx context.Context, config *conf.GlobalConfig, auth stat.Auth if err != nil { return err } - log.Info("server api service is running at", config.API.APIAddress) + log.Info("Server api service is running at", config.API.APIAddress) errChan := make(chan error, 1) go func() { errChan <- server.Serve(listener) diff --git a/cert/cert.go b/cert/cert.go index 3960798..4f4cec6 100644 --- a/cert/cert.go +++ b/cert/cert.go @@ -46,13 +46,13 @@ func (u *User) GetPrivateKey() crypto.PrivateKey { func createAndSaveUserKey() (*ecdsa.PrivateKey, error) { _, err := os.Stat("user.key") if os.IsExist(err) { - return nil, common.NewError("user.key exists, cannot create new user") + return nil, common.NewError("User.key exists, cannot create new user") } userKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) common.Must(err) userKeyFile, err := os.Create("user.key") if err != nil { - return nil, common.NewError("failed to create user key file").Base(err) + return nil, common.NewError("Failed to create user key file").Base(err) } defer userKeyFile.Close() @@ -65,11 +65,11 @@ func createAndSaveUserKey() (*ecdsa.PrivateKey, error) { func loadUserKey() (*ecdsa.PrivateKey, error) { pemEncoded, err := ioutil.ReadFile("user.key") if err != nil { - return nil, common.NewError("failed to load user's key").Base(err) + return nil, common.NewError("Failed to load user's key").Base(err) } block, _ := pem.Decode([]byte(pemEncoded)) if block == nil { - return nil, common.NewError("failed to parse user's key").Base(err) + return nil, common.NewError("Failed to parse user's key").Base(err) } x509Encoded := block.Bytes return x509.ParseECPrivateKey(x509Encoded) @@ -165,24 +165,24 @@ func isFilesExist(nameList []string) bool { func RequestCert(domain, email string) error { if isFilesExist([]string{"server.key", "server.crt"}) { - return common.NewError("cert files(server.key, server.crt) already exist") + return common.NewError("Cert files(server.key, server.crt) already exist") } userKey, err := loadUserKey() if err != nil { - fmt.Println("failed to load user key, trying to create one..") + fmt.Println("Failed to load user key, trying to create one..") userKey, err = createAndSaveUserKey() if err != nil { return err } } else { - fmt.Println("found user.key, using exist user key") + fmt.Println("Found user.key, using exist user key") } cert, err := obtainCertificate(domain, email, userKey, nil) if err != nil { return err } if err := saveServerKeyAndCert(cert); err != nil { - return common.NewError("failed to save cert").Base(err) + return common.NewError("Failed to save cert").Base(err) } return nil } @@ -201,7 +201,7 @@ func RenewCert(domain, email string) error { return err } if err := saveServerKeyAndCert(cert); err != nil { - return common.NewError("failed to save cert").Base(err) + return common.NewError("Failed to save cert").Base(err) } return nil } diff --git a/cert/cli.go b/cert/cli.go index 6b9a92b..d0a65af 100644 --- a/cert/cli.go +++ b/cert/cli.go @@ -69,7 +69,7 @@ func RequestCertGuide() { } else { log.Info("domain_info.json found") if err := json.Unmarshal(data, info); err != nil { - log.Error(common.NewError("failed to parse domain_info.json").Base(err)) + log.Error(common.NewError("Failed to parse domain_info.json").Base(err)) return } } diff --git a/cert/option.go b/cert/option.go index 4dff7a8..40c7d82 100644 --- a/cert/option.go +++ b/cert/option.go @@ -33,11 +33,11 @@ func (c *certOption) Handle() error { RenewCertGuide() return nil case "INVALID": - return common.NewError("not specified") + return common.NewError("Not specified") default: - err := common.NewError("invalid args " + *c.mode) + err := common.NewError("Invalid args " + *c.mode) log.Error(err) - return common.NewError("invalid args") + return common.NewError("Invalid args") } } diff --git a/common/common.go b/common/common.go index 4e85e27..8ceb21d 100644 --- a/common/common.go +++ b/common/common.go @@ -11,7 +11,7 @@ import ( ) const ( - Version = "v0.4.8" + Version = "v0.4.9" ) type Runnable interface { diff --git a/common/option.go b/common/option.go index 8a9c0e9..02a9eb6 100644 --- a/common/option.go +++ b/common/option.go @@ -20,7 +20,7 @@ func PopOptionHandler() (OptionHandler, error) { } } if maxHandler == nil { - return nil, NewError("no option left") + return nil, NewError("No options left") } delete(handlers, maxHandler.Name()) return maxHandler, nil diff --git a/conf/conf.go b/conf/conf.go index 599ea2e..d83dcc8 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -44,6 +44,8 @@ type TLSConfig struct { ALPN []string `json:"alpn"` Curves string `json:"curves"` Fingerprint string `json:"fingerprint"` + ServePlainText bool `json:"serve_plain_text"` + RedirectWithTLS bool `json:"redirect_with_tls"` ClientHelloID *utls.ClientHelloID FallbackAddress *common.Address diff --git a/conf/parse.go b/conf/parse.go index 29c342a..7b54cea 100644 --- a/conf/parse.go +++ b/conf/parse.go @@ -22,27 +22,29 @@ func loadCommonConfig(config *GlobalConfig) error { //log settigns log.SetLogLevel(log.LogLevel(config.LogLevel)) if config.LogFile != "" { - log.Info("log will be written into", config.LogFile) + log.Info("Log will be written to", config.LogFile) file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { - return common.NewError("failed to access log file").Base(err) + return common.NewError("Failed to access the log file").Base(err) } log.SetOutput(file) } - //buffer size, 4KiB to 16MiB + //buffer size, 4KiB - 16MiB if config.BufferSize < 4 || config.BufferSize > 16384 { - return common.NewError("invalid buffer size, 4 KiB < buffer_size < 16384 Kib") + return common.NewError("Invalid buffer size, 4 KiB < buffer_size < 16384 KiB") } config.BufferSize *= 1024 //password settings if len(config.Passwords) == 0 { - if config.RunType == Client { - return common.NewError("no password found") + switch config.RunType { + case Client, NAT, Forward: + return common.NewError("No password found") + default: + log.Warn("Password is unspecified in config file") } - log.Warn("password is not specified in config file") } config.Hash = make(map[string]string) for _, password := range config.Passwords { @@ -86,13 +88,13 @@ func loadCommonConfig(config *GlobalConfig) error { } if !found { invalid = true - log.Warn("found invalid cipher name", specified) + log.Warn("Found invalid cipher ", specified) break } } if invalid && len(supportedSuites) >= 1 { - log.Warn("cipher list contains invalid cipher name, ignored") - log.Warn("here's a list of supported ciphers:") + log.Warn("\"cipher_suite\" contains invalid cipher name, ignored") + log.Warn("Here is a list of supported ciphers:") list := "" for _, c := range supportedSuites { list += c.Name + ":" @@ -106,23 +108,24 @@ func loadCommonConfig(config *GlobalConfig) error { //websocket settings if config.Websocket.Enabled { - log.Info("websocket enabled") + log.Info("Websocket enabled") if config.Websocket.Path == "" { - return common.NewError("websocket path is empty") + return common.NewError("Websocket path is empty") } if config.Websocket.Path[0] != '/' { - return common.NewError("websocket path must start with \"/\"") + return common.NewError("Websocket path must start with \"/\"") } if config.Websocket.HostName == "" { - log.Warn("websocket hostname is unspecified, using remote_addr \"", config.RemoteHost, "\" as hostname") + log.Warn("Websocket hostname is unspecified. Using remote_addr \"", config.RemoteHost, "\" as hostname") config.Websocket.HostName = config.RemoteHost if ip := net.ParseIP(config.RemoteHost); ip != nil && ip.To4() == nil { //ipv6 address config.Websocket.HostName = "[" + config.RemoteHost + "]" } } if config.Websocket.ObfuscationPassword != "" { - log.Info("websocket obfs enabled") + log.Info("Websocket obfuscation enabled") password := []byte(config.Websocket.ObfuscationPassword) + //hardcoded salt salt := []byte{48, 149, 6, 18, 13, 193, 247, 116, 197, 135, 236, 175, 190, 209, 146, 48} config.Websocket.ObfuscationKey = pbkdf2.Key(password, salt, 32, aes.BlockSize, sha256.New) } @@ -205,7 +208,7 @@ func loadClientConfig(config *GlobalConfig) error { config.TLS.SNI = config.RemoteHost } if config.TLS.CertPath == "" { - log.Info("cert of the remote server is not specified, using default CA list") + log.Info("Cert of the remote server is unspecified. Using default CA list") } else { caCertByte, err := ioutil.ReadFile(config.TLS.CertPath) if err != nil { @@ -214,9 +217,9 @@ func loadClientConfig(config *GlobalConfig) error { pool := x509.NewCertPool() ok := pool.AppendCertsFromPEM(caCertByte) if !ok { - log.Warn("invalid CA cert list") + log.Warn("Invalid CA cert list") } - log.Info("using custom CA list") + log.Info("Using custom CA list") pemCerts := caCertByte for len(pemCerts) > 0 { config.TLS.CertPool = pool @@ -232,15 +235,15 @@ func loadClientConfig(config *GlobalConfig) error { if err != nil { continue } - log.Trace("issuer:", cert.Issuer, "subject:", cert.Subject) + log.Trace("Issuer:", cert.Issuer, "Subject:", cert.Subject) } } //forward proxy settings if config.ForwardProxy.Enabled { - log.Info("forward proxy enabled") + log.Info("Forward proxy enabled") config.ForwardProxy.ProxyAddress = common.NewAddress(config.ForwardProxy.ProxyHost, config.ForwardProxy.ProxyPort, "tcp") - log.Debug("forward proxy:", config.ForwardProxy.ProxyAddress.String()) + log.Debug("Forward proxy", config.ForwardProxy.ProxyAddress.String()) } return nil @@ -259,24 +262,27 @@ func loadServerConfig(config *GlobalConfig) error { resp.Body.Close() } - if config.TLS.KeyPassword != "" { + //tls settings + if config.TLS.ServePlainText { + log.Warn("Server will now use plain text. TLS config is ignored") + } else if config.TLS.KeyPassword != "" { keyFile, err := ioutil.ReadFile(config.TLS.KeyPath) if err != nil { - return common.NewError("failed to load key file").Base(err) + return common.NewError("Failed to load key file").Base(err) } keyBlock, _ := pem.Decode(keyFile) if keyBlock == nil { - return common.NewError("failed to decode key file").Base(err) + return common.NewError("Failed to decode key file").Base(err) } decryptedKey, err := x509.DecryptPEMBlock(keyBlock, []byte(config.TLS.KeyPassword)) if err == nil { - return common.NewError("failed to decrypt key").Base(err) + return common.NewError("Failed to decrypt key").Base(err) } certFile, err := ioutil.ReadFile(config.TLS.CertPath) certBlock, _ := pem.Decode(certFile) if certBlock == nil { - return common.NewError("failed to decode cert file").Base(err) + return common.NewError("Failed to decode cert file").Base(err) } keyPair, err := tls.X509KeyPair(certBlock.Bytes, decryptedKey) @@ -288,14 +294,15 @@ func loadServerConfig(config *GlobalConfig) error { } else { keyPair, err := tls.LoadX509KeyPair(config.TLS.CertPath, config.TLS.KeyPath) if err != nil { - return common.NewError("failed to load key pair").Base(err) + return common.NewError("Failed to load key pair").Base(err) } config.TLS.KeyPair = []tls.Certificate{keyPair} } + if config.TLS.HTTPFile != "" { payload, err := ioutil.ReadFile(config.TLS.HTTPFile) if err != nil { - log.Warn("failed to load http response file", err) + log.Warn("Failed to load http response file", err) } config.TLS.HTTPResponse = payload } @@ -362,7 +369,7 @@ func ParseJSON(data []byte) (*GlobalConfig, error) { } case Relay: default: - return nil, common.NewError("invalid run type:" + string(config.RunType)) + return nil, common.NewError("Invalid run type:" + string(config.RunType)) } return config, nil diff --git a/docs/config.toml b/docs/config.toml index 6cefcc2..b62453b 100755 --- a/docs/config.toml +++ b/docs/config.toml @@ -16,7 +16,7 @@ enableMissingTranslationPlaceholders = false # Source Code repository section description = "An unidentifiable mechanism that helps you bypass GFW. " github_repository = "https://github.com/p4gefau1t/trojan-go" - version = "0.4.8" + version = "0.4.9" # Documentation repository section # documentation repository (set edit link to documentation repository) diff --git a/easy/easy.go b/easy/easy.go index 3af0d7f..3f29dc3 100644 --- a/easy/easy.go +++ b/easy/easy.go @@ -32,9 +32,9 @@ func (o *EasyOption) Handle() error { return common.NewError("empty") } if *o.password == "" { - log.Fatal("empty password is not allowed") + log.Fatal("Empty password is not allowed") } - log.Info("easy mode enabled, trojan-go will NOT use the config file") + log.Info("Easy mode enabled, trojan-go will NOT use the config file") if *o.client { clientConfigFormat := ` { @@ -49,19 +49,19 @@ func (o *EasyOption) Handle() error { } ` if *o.local == "" { - log.Warn("client local addr is unspecified, using 127.0.0.1:1080") + log.Warn("Client local addr is unspecified, using 127.0.0.1:1080") *o.local = "127.0.0.1:1080" } localHost, localPort, err := net.SplitHostPort(*o.local) if err != nil { - log.Fatal(common.NewError("invalid local addr format:" + *o.local).Base(err)) + log.Fatal(common.NewError("Invalid local addr format:" + *o.local).Base(err)) } remoteHost, remotePort, err := net.SplitHostPort(*o.remote) if err != nil { - log.Fatal(common.NewError("invalid remote addr format:" + *o.remote).Base(err)) + log.Fatal(common.NewError("Invalid remote addr format:" + *o.remote).Base(err)) } clientConfigJSON := fmt.Sprintf(clientConfigFormat, localHost, localPort, remoteHost, remotePort, *o.password) - log.Info("generated config:") + log.Info("Generated config:") log.Info(clientConfigJSON) config, err := conf.ParseJSON([]byte(clientConfigJSON)) if err != nil { @@ -93,23 +93,23 @@ func (o *EasyOption) Handle() error { } ` if *o.remote == "" { - log.Warn("server remote addr is unspecified, using 127.0.0.1:80") + log.Warn("Server remote addr is unspecified, using 127.0.0.1:80") *o.remote = "127.0.0.1:80" } if *o.local == "" { - log.Warn("server local addr is unspecified, using 0.0.0.0:443") + log.Warn("Server local addr is unspecified, using 0.0.0.0:443") *o.local = "0.0.0.0:443" } localHost, localPort, err := net.SplitHostPort(*o.local) if err != nil { - log.Fatal(common.NewError("invalid local addr format:" + *o.local).Base(err)) + log.Fatal(common.NewError("Invalid local addr format:" + *o.local).Base(err)) } remoteHost, remotePort, err := net.SplitHostPort(*o.remote) if err != nil { - log.Fatal(common.NewError("invalid remote addr format:" + *o.remote).Base(err)) + log.Fatal(common.NewError("Invalid remote addr format:" + *o.remote).Base(err)) } serverConfigJSON := fmt.Sprintf(serverConfigFormat, localHost, localPort, remoteHost, remotePort, *o.password, *o.cert, *o.key) - log.Info("generated config:") + log.Info("Generated config:") log.Info(serverConfigJSON) config, err := conf.ParseJSON([]byte(serverConfigJSON)) if err != nil { diff --git a/protocol/direct/outbound.go b/protocol/direct/outbound.go index 0b844f6..260d6e9 100644 --- a/protocol/direct/outbound.go +++ b/protocol/direct/outbound.go @@ -43,7 +43,7 @@ func NewOutboundConnSession(ctx context.Context, req *protocol.Request, config * if req.AddressType == common.DomainName && len(config.DNS) != 0 { //customized dns server ip, found := dnsCache.Get(req.DomainName) if found { - log.Trace("dns cache hit:", req.DomainName, "->", ip.(net.IP).String()) + log.Trace("DNS cache hit:", req.DomainName, "->", ip.(net.IP).String()) newConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{ IP: ip.(net.IP), Port: req.Port, @@ -53,7 +53,7 @@ func NewOutboundConnSession(ctx context.Context, req *protocol.Request, config * } goto done } - log.Trace("dns cache missed:", req.DomainName) + log.Trace("DNS cache missed:", req.DomainName) //find a avaliable dns server for _, s := range config.DNS { var dnsType conf.DNSType @@ -100,7 +100,7 @@ func NewOutboundConnSession(ctx context.Context, req *protocol.Request, config * } return tlsConn, nil } - return nil, common.NewError("invalid dns type :" + string(dnsType)) + return nil, common.NewError("Invalid dns type :" + string(dnsType)) }, } d := net.Dialer{ @@ -116,16 +116,16 @@ func NewOutboundConnSession(ctx context.Context, req *protocol.Request, config * log.Warn(err) } else { if ip := net.ParseIP(addr); ip != nil { - log.Trace("dns cache set", req.DomainName, "->", addr) + log.Trace("DNS cache set", req.DomainName, "->", addr) dnsCache.Set(req.DomainName, ip, cache.DefaultExpiration) } else { - log.Warn("invalid resolved addr", addr) + log.Warn("Invalid resolved addr", addr) } } break } if newConn == nil { - return nil, common.NewError("all dns servers are down") + return nil, common.NewError("All dns servers down") } } else { //default resolver @@ -163,7 +163,7 @@ func (o *DirectOutboundPacketSession) listenConn(req *protocol.Request, conn *ne n, addr, err := conn.ReadFromUDP(buf) conn.SetReadDeadline(time.Time{}) if err != nil { - log.Debug(common.NewError("packet session ends").Base(err)) + log.Debug(common.NewError("Packet session ends").Base(err)) return } if addr.String() != req.String() { @@ -187,7 +187,7 @@ func (o *DirectOutboundPacketSession) ReadPacket() (*protocol.Request, []byte, e case info := <-o.packetChan: return info.request, info.packet, nil case <-o.ctx.Done(): - return nil, nil, common.NewError("session closed") + return nil, nil, common.NewError("Session closed") } } diff --git a/protocol/http/inbound.go b/protocol/http/inbound.go index 283c17c..3a6f85b 100644 --- a/protocol/http/inbound.go +++ b/protocol/http/inbound.go @@ -79,7 +79,7 @@ func (i *HTTPInboundTunnelConnSession) parseRequest() (bool, error) { return false, err } if httpRequest.Method != "CONNECT" { - return true, common.NewError("not a connection") + return true, common.NewError("Not a connection") } i.bodyReader = httpRequest.Body i.httpRequest = httpRequest @@ -128,7 +128,7 @@ func NewHTTPInbound(rwc *common.RewindReadWriteCloser) (protocol.ConnSession, *p if !isHTTP { //invalid http format rwc.SetBufferSize(0) - return nil, nil, nil, common.NewError("failed to parse http header").Base(err) + return nil, nil, nil, common.NewError("Failed to parse http header").Base(err) } if err == nil { //http tunnel diff --git a/protocol/protocol.go b/protocol/protocol.go index e664609..34cf945 100644 --- a/protocol/protocol.go +++ b/protocol/protocol.go @@ -85,7 +85,7 @@ func ParseAddress(conn io.Reader, network string) (*common.Address, error) { byteBuf := [1]byte{} _, err := conn.Read(byteBuf[:]) if err != nil { - return nil, common.NewError("cannot read atype").Base(err) + return nil, common.NewError("Cannot read atype").Base(err) } addr := &common.Address{ AddressType: common.AddressType(byteBuf[0]), @@ -95,7 +95,7 @@ func ParseAddress(conn io.Reader, network string) (*common.Address, error) { var buf [6]byte _, err := conn.Read(buf[:]) if err != nil { - return nil, common.NewError("failed to read ipv4").Base(err) + return nil, common.NewError("Failed to read ipv4").Base(err) } addr.IP = buf[0:4] addr.Port = int(binary.BigEndian.Uint16(buf[4:6])) @@ -103,7 +103,7 @@ func ParseAddress(conn io.Reader, network string) (*common.Address, error) { var buf [18]byte conn.Read(buf[:]) if err != nil { - return nil, common.NewError("failed to read ipv6").Base(err) + return nil, common.NewError("Failed to read ipv6").Base(err) } addr.IP = buf[0:16] addr.Port = int(binary.BigEndian.Uint16(buf[16:18])) @@ -111,12 +111,12 @@ func ParseAddress(conn io.Reader, network string) (*common.Address, error) { _, err := conn.Read(byteBuf[:]) length := byteBuf[0] if err != nil { - return nil, common.NewError("failed to read length") + return nil, common.NewError("Failed to read length") } buf := make([]byte, length+2) _, err = conn.Read(buf) if err != nil { - return nil, common.NewError("failed to read domain") + return nil, common.NewError("Failed to read domain") } //the fucking browser uses ip as a domain name sometimes host := buf[0:length] @@ -132,7 +132,7 @@ func ParseAddress(conn io.Reader, network string) (*common.Address, error) { } addr.Port = int(binary.BigEndian.Uint16(buf[length : length+2])) default: - return nil, common.NewError("invalid dest type") + return nil, common.NewError("Invalid dest type") } addr.NetworkType = network return addr, nil diff --git a/protocol/simplesocks/simplesocks.go b/protocol/simplesocks/simplesocks.go index 1f719ca..e50014f 100644 --- a/protocol/simplesocks/simplesocks.go +++ b/protocol/simplesocks/simplesocks.go @@ -42,11 +42,11 @@ func (m *SimpleSocksConnSession) GetRequest() *protocol.Request { func (m *SimpleSocksConnSession) parseRequest() error { cmd, err := common.ReadByte(m.rwc) if err != nil { - return common.NewError("failed to read cmd").Base(err) + return common.NewError("Failed to read cmd").Base(err) } addr, err := protocol.ParseAddress(m.rwc, "tcp") if err != nil { - return common.NewError("failed to parse addr").Base(err) + return common.NewError("Failed to parse addr").Base(err) } req := &protocol.Request{ Address: addr, @@ -70,7 +70,7 @@ func NewInboundConnSession(conn io.ReadWriteCloser) (protocol.ConnSession, *prot rwc: conn, } if err := m.parseRequest(); err != nil { - return nil, nil, common.NewError("failed to parse mux request").Base(err) + return nil, nil, common.NewError("Failed to parse mux request").Base(err) } return m, m.request, nil } @@ -80,7 +80,7 @@ func NewOutboundConnSession(req *protocol.Request, conn io.ReadWriteCloser) (pro rwc: conn, } if err := m.writeRequest(req); err != nil { - return nil, common.NewError("failed to write mux request").Base(err) + return nil, common.NewError("Failed to write mux request").Base(err) } return m, nil } diff --git a/protocol/socks/inbound.go b/protocol/socks/inbound.go index c4853c9..63228f0 100644 --- a/protocol/socks/inbound.go +++ b/protocol/socks/inbound.go @@ -26,7 +26,7 @@ func (i *SocksConnInboundSession) checkVersion() error { return err } if version != 0x5 { - return common.NewError("unsupported socks version") + return common.NewError("Unsupported socks version") } return nil } @@ -50,19 +50,19 @@ func (i *SocksConnInboundSession) parseRequest() error { } cmd, err := i.rwc.ReadByte() if err != nil { - return common.NewError("cannot read cmd").Base(err) + return common.NewError("Cannot read cmd").Base(err) } i.rwc.Discard(1) switch protocol.Command(cmd) { case protocol.Connect, protocol.Associate: default: - return common.NewError("invalid command") + return common.NewError("Invalid command") } addr, err := protocol.ParseAddress(i.rwc, "tcp") if err != nil { - return common.NewError("cannot read request").Base(err) + return common.NewError("Cannot read request").Base(err) } request := &protocol.Request{ Address: addr, @@ -127,13 +127,13 @@ type SocksInboundPacketSession struct { func (i *SocksInboundPacketSession) parsePacket(rawPacket []byte) (*protocol.Request, []byte, error) { if len(rawPacket) <= 4 { - return nil, nil, common.NewError("packet too short") + return nil, nil, common.NewError("Malformed socks5 packet") } buf := bytes.NewBuffer(rawPacket) buf.Next(2) frag, _ := buf.ReadByte() if frag != 0 { - return nil, nil, common.NewError("fragment is not supported") + return nil, nil, common.NewError("Fragment is not supported") } addr, err := protocol.ParseAddress(buf, "udp") if err != nil { @@ -208,7 +208,7 @@ func (i *SocksInboundPacketSession) WritePacket(req *protocol.Request, packet [] defer i.tableMutex.Unlock() client, found := i.sessionTable[req.String()] if !found { - return 0, common.NewError("session not found") + return 0, common.NewError("Session not found: " + req.String()) } client.expire = time.Now().Add(protocol.UDPTimeout) log.Debug("udp write to", client.src, "req", req) diff --git a/protocol/tproxy/inbound.go b/protocol/tproxy/inbound.go index 520f653..7566431 100644 --- a/protocol/tproxy/inbound.go +++ b/protocol/tproxy/inbound.go @@ -40,7 +40,7 @@ func (i *TProxyInboundConnSession) GetRequest() *protocol.Request { func (i *TProxyInboundConnSession) parseRequest() error { addr, err := getOriginalTCPDest(i.conn.(*net.TCPConn)) if err != nil { - return common.NewError("failed to get original dst").Base(err) + return common.NewError("Failed to get original dst").Base(err) } req := &protocol.Request{ Address: &common.Address{ @@ -63,7 +63,7 @@ func NewInboundConnSession(conn net.Conn) (protocol.ConnSession, *protocol.Reque conn: conn, } if err := i.parseRequest(); err != nil { - return nil, nil, common.NewError("failed to parse request").Base(err) + return nil, nil, common.NewError("Failed to parse request").Base(err) } return i, i.reqeust, nil } @@ -108,11 +108,11 @@ func (i *NATInboundPacketSession) WritePacket(req *protocol.Request, packet []by defer i.tableMutex.Unlock() session, found := i.sessionTable[req.String()] if !found { - return 0, common.NewError("session not found " + req.String()) + return 0, common.NewError("Session not found " + req.String()) } conn, err := tproxy.DialUDP("udp", session.dst, session.src) if err != nil { - return 0, common.NewError("cannot dial to source").Base(err) + return 0, common.NewError("Cannot dial to source").Base(err) } defer conn.Close() return conn.Write(packet) @@ -167,7 +167,7 @@ func NewInboundPacketSession(ctx context.Context, config *conf.GlobalConfig) (pr } conn, err := tproxy.ListenUDP("udp", addr) if err != nil { - return nil, common.NewError("failed to listen udp addr").Base(err) + return nil, common.NewError("Failed to listen udp addr").Base(err) } ctx, cancel := context.WithCancel(ctx) i := &NATInboundPacketSession{ diff --git a/protocol/trojan/inbound.go b/protocol/trojan/inbound.go index dae2061..7e45444 100644 --- a/protocol/trojan/inbound.go +++ b/protocol/trojan/inbound.go @@ -43,7 +43,7 @@ func (i *TrojanInboundConnSession) Read(p []byte) (int, error) { } func (i *TrojanInboundConnSession) Close() error { - log.Info("user", i.passwordHash, "conn to", i.request, "closed", "sent:", common.HumanFriendlyTraffic(i.sent), "recv:", common.HumanFriendlyTraffic(i.recv)) + log.Info("User", i.passwordHash, "to", i.request, "closed", "sent:", common.HumanFriendlyTraffic(i.sent), "recv:", common.HumanFriendlyTraffic(i.recv)) i.cancel() return i.rwc.Close() } @@ -52,11 +52,11 @@ func (i *TrojanInboundConnSession) parseRequest(r *common.RewindReader) error { userHash := [56]byte{} n, err := r.Read(userHash[:]) if err != nil || n != 56 { - return common.NewError("failed to read hash").Base(err) + return common.NewError("Failed to read hash").Base(err) } valid, meter := i.auth.AuthUser(string(userHash[:])) if !valid { - return common.NewError("invalid hash:" + string(userHash[:])) + return common.NewError("Invalid hash:" + string(userHash[:])) } i.passwordHash = string(userHash[:]) i.meter = meter @@ -66,12 +66,12 @@ func (i *TrojanInboundConnSession) parseRequest(r *common.RewindReader) error { cmd, err := r.ReadByte() if err != nil { - return common.NewError("failed to read cmd").Base(err) + return common.NewError("Failed to read cmd").Base(err) } addr, err := protocol.ParseAddress(r, "tcp") if err != nil { - return common.NewError("failed to parse address").Base(err) + return common.NewError("Failed to parse address").Base(err) } req := &protocol.Request{ Command: protocol.Command(cmd), @@ -107,7 +107,7 @@ func NewInboundConnSession(ctx context.Context, conn net.Conn, config *conf.Glob //try to treat it as a websocket connection first ws, err := NewInboundWebsocket(i.ctx, rewindConn, config, shadowMan) if err != nil { - return nil, nil, common.NewError("invalid websocket request").Base(err) + return nil, nil, common.NewError("Invalid websocket request").Base(err) } if ws != nil { //a websocket conn, try to verify it @@ -120,7 +120,7 @@ func NewInboundConnSession(ctx context.Context, conn net.Conn, config *conf.Glob if err := i.parseRequest(newTrapsport.RewindReader); err != nil { //invalid ws, just simply close it ws.Close() - return nil, nil, common.NewError("invalid trojan header over websocket conn").Base(err) + return nil, nil, common.NewError("Invalid trojan header over websocket conn").Base(err) } return i, i.request, nil } @@ -132,8 +132,8 @@ func NewInboundConnSession(ctx context.Context, conn net.Conn, config *conf.Glob if err := i.parseRequest(rewindConn.R); err != nil { //not a valid trojan request, proxy it to the remote_addr rewindConn.R.Rewind() - err := common.NewError("invalid trojan header from " + conn.RemoteAddr().String()).Base(err) - shadowMan.CommitScapegoat(&shadow.Scapegoat{ + err := common.NewError("Invalid trojan header from " + conn.RemoteAddr().String()).Base(err) + shadowMan.SubmitScapegoat(&shadow.Scapegoat{ Conn: rewindConn, ShadowAddress: i.config.RemoteAddress, Info: err.Error(), diff --git a/protocol/trojan/outbound.go b/protocol/trojan/outbound.go index 5eba534..7ddcd3a 100644 --- a/protocol/trojan/outbound.go +++ b/protocol/trojan/outbound.go @@ -57,7 +57,7 @@ func (o *TrojanOutboundConnSession) Read(p []byte) (int, error) { } func (o *TrojanOutboundConnSession) Close() error { - log.Info("conn to", o.request, "closed", "sent:", common.HumanFriendlyTraffic(o.sent), "recv:", common.HumanFriendlyTraffic(o.recv)) + log.Info("Conn to", o.request, "closed", "sent:", common.HumanFriendlyTraffic(o.sent), "recv:", common.HumanFriendlyTraffic(o.recv)) return o.rwc.Close() } diff --git a/protocol/trojan/websocket.go b/protocol/trojan/websocket.go index 0c1bd8c..0d820cf 100644 --- a/protocol/trojan/websocket.go +++ b/protocol/trojan/websocket.go @@ -146,7 +146,7 @@ func NewOutboundWebosocket(conn net.Conn, config *conf.GlobalConfig) (io.ReadWri if config.LogLevel == 0 { state := tlsConn.ConnectionState() chain := state.VerifiedChains - log.Trace("websocket double tls handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) + log.Trace("Websocket double TLS handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) for i := range chain { for j := range chain[i] { log.Trace("subject:", chain[i][j].Subject, ", issuer:", chain[i][j].Issuer) @@ -192,7 +192,7 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global bufrw := bufio.NewReadWriter(bufio.NewReader(rewindConn), bufio.NewWriter(rewindConn)) httpRequest, err := http.ReadRequest(bufrw.Reader) if err != nil { - log.Debug(common.NewError("not a http request:").Base(err)) + log.Debug(common.NewError("Not a http request:").Base(err)) return nil, nil } @@ -201,12 +201,12 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global strings.ToLower(httpRequest.Header.Get("Upgrade")) != "websocket" { //check upgrade field //not a valid websocket conn rewindConn.R.Rewind() - shadowMan.CommitScapegoat(&shadow.Scapegoat{ + shadowMan.SubmitScapegoat(&shadow.Scapegoat{ Conn: rewindConn, ShadowAddress: config.RemoteAddress, - Info: "invalid http upgrade request from " + conn.RemoteAddr().String(), + Info: "Invalid http upgrade request from " + conn.RemoteAddr().String(), }) - return nil, common.NewError("invalid ws url or hostname") + return nil, common.NewError("Invalid websocket request" + conn.RemoteAddr().String()) } //this is a websocket upgrade request @@ -272,7 +272,7 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global if err != nil { rewindConn.R.Rewind() //proxy this to our own ws server - err = common.NewError("remote websocket " + conn.RemoteAddr().String() + "didn't send any valid iv").Base(err) + err = common.NewError("Remote websocket " + conn.RemoteAddr().String() + "didn't send any valid iv").Base(err) goat, err := getWebsocketScapegoat( config, url, @@ -281,10 +281,10 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global rewindConn, ) if err != nil { - log.Error(common.NewError("failed to obtain websocket scapegoat").Base(err)) + log.Error(common.NewError("Failed to obtain websocket scapegoat").Base(err)) wsConn.WriteClose(500) } else { - shadowMan.CommitScapegoat(goat) + shadowMan.SubmitScapegoat(goat) } return nil, err } @@ -304,7 +304,7 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global if tlsErr := tlsConn.Handshake(); tlsErr != nil { rewindConn.R.Rewind() //proxy this to our own ws server - tlsErr = common.NewError("invalid double tls handshake from" + conn.RemoteAddr().String()).Base(tlsErr) + tlsErr = common.NewError("Invalid double tls handshake from" + conn.RemoteAddr().String()).Base(tlsErr) goat, err := getWebsocketScapegoat( config, url, @@ -313,10 +313,10 @@ func NewInboundWebsocket(ctx context.Context, conn net.Conn, config *conf.Global rewindConn, ) if err != nil { - log.Error(common.NewError("failed to obtain websocket scapegoat").Base(err)) + log.Error(common.NewError("Failed to obtain websocket scapegoat").Base(err)) wsConn.WriteClose(500) } else { - shadowMan.CommitScapegoat(goat) + shadowMan.SubmitScapegoat(goat) } return nil, tlsErr } diff --git a/proxy/client/app.go b/proxy/client/app.go index e29f954..f571562 100644 --- a/proxy/client/app.go +++ b/proxy/client/app.go @@ -45,7 +45,7 @@ func NewAppManager(ctx context.Context, config *conf.GlobalConfig, auth stat.Aut auth: auth, } if config.Mux.Enabled { - log.Info("mux enabled") + log.Info("Mux enabled") c.transport = NewMuxPoolManager(ctx, config, auth) } else { c.transport = NewTLSManager(config) diff --git a/proxy/client/client.go b/proxy/client/client.go index cbf2b2b..1321dfa 100644 --- a/proxy/client/client.go +++ b/proxy/client/client.go @@ -46,7 +46,7 @@ func (c *Client) handleSocksConn(conn io.ReadWriteCloser) { rwc := common.NewRewindReadWriteCloser(conn) inboundConn, req, err := socks.NewInboundConnSession(rwc) if err != nil { - log.Error(common.NewError("failed to handle socks requests").Base(err)) + log.Error(common.NewError("Failed to handle socks requests").Base(err)) rwc.Close() return } @@ -57,7 +57,7 @@ func (c *Client) handleSocksConn(conn io.ReadWriteCloser) { //listenUDP() will handle the incoming udp packets localIP, err := c.config.LocalAddress.ResolveIP() if err != nil { - log.Error(common.NewError("invalid local address").Base(err)) + log.Error(common.NewError("Invalid local address").Base(err)) return } //bind port and IP @@ -73,19 +73,19 @@ func (c *Client) handleSocksConn(conn io.ReadWriteCloser) { c.associated.Signal() log.Debug("udp associated to", req) if err := inboundConn.(protocol.NeedRespond).Respond(); err != nil { - log.Error("failed to repsond") + log.Error("Failed to repsond") return } //stop relaying UDP once TCP connection is closed var buf [1]byte _, err = rwc.Read(buf[:]) - log.Debug(common.NewError("udp conn ends").Base(err)) + log.Debug(common.NewError("UDP conn ends").Base(err)) return } if err := inboundConn.(protocol.NeedRespond).Respond(); err != nil { - log.Error(common.NewError("failed to respond").Base(err)) + log.Error(common.NewError("Failed to respond").Base(err)) return } @@ -100,11 +100,11 @@ func (c *Client) handleSocksConn(conn io.ReadWriteCloser) { log.Error(err) return } - log.Info("[bypass] conn to", req) + log.Info("[Bypass] conn to", req) proxy.ProxyConn(c.ctx, inboundConn, outboundConn, c.config.BufferSize) return } else if policy == router.Block { - log.Info("[block] conn to", req) + log.Info("[Block] conn to", req) return } outboundConn, err := c.appMan.OpenAppConn(req) @@ -120,7 +120,7 @@ func (c *Client) handleHTTPConn(conn io.ReadWriteCloser) { rwc := common.NewRewindReadWriteCloser(conn) inboundConn, req, inboundPacket, err := http.NewHTTPInbound(rwc) if err != nil { - log.Error(common.NewError("failed to handle HTTP requests").Base(err)) + log.Error(common.NewError("Failed to handle HTTP requests").Base(err)) rwc.Close() return } @@ -129,7 +129,7 @@ func (c *Client) handleHTTPConn(conn io.ReadWriteCloser) { defer inboundConn.Close() if err := inboundConn.(protocol.NeedRespond).Respond(); err != nil { - log.Error(common.NewError("failed to respond").Base(err)) + log.Error(common.NewError("Failed to respond").Base(err)) return } @@ -144,21 +144,21 @@ func (c *Client) handleHTTPConn(conn io.ReadWriteCloser) { log.Error(err) return } - log.Info("[bypass]conn to", req) + log.Info("[Bypass] conn to", req) proxy.ProxyConn(c.ctx, inboundConn, outboundConn, c.config.BufferSize) return } else if policy == router.Block { - log.Info("[block]conn to", req) + log.Info("[Block] conn to", req) return } outboundConn, err := c.appMan.OpenAppConn(req) if err != nil { - log.Error(common.NewError("fail to start conn session").Base(err)) + log.Error(common.NewError("Fail to start conn session").Base(err)) return } defer outboundConn.Close() - log.Info("conn tunneling to", req) + log.Info("Conn tunneling to", req) proxy.ProxyConn(c.ctx, inboundConn, outboundConn, c.config.BufferSize) } else { //GET/POST requests defer inboundPacket.Close() @@ -169,7 +169,7 @@ func (c *Client) handleHTTPConn(conn io.ReadWriteCloser) { for { req, packet, err := inboundPacket.ReadPacket() if err != nil { - log.Error(common.NewError("failed to parse packet").Base(err)) + log.Error(common.NewError("Failed to parse packet").Base(err)) return } if req.String() == c.config.LocalAddress.String() { //loop @@ -254,7 +254,7 @@ func (c *Client) listenUDP(errChan chan error) { } outboundConn, err := c.appMan.OpenAppConn(req) if err != nil { - log.Error(common.NewError("failed to init udp tunnel").Base(err)) + log.Error(common.NewError("Failed to init udp tunnel").Base(err)) return } outboundPacket, err := trojan.NewPacketSession(outboundConn) @@ -285,14 +285,14 @@ func (c *Client) listenTCP(errChan chan error) { for { conn, err := listener.Accept() if err != nil { - errChan <- common.NewError("error occured when accepting conn").Base(err) + errChan <- common.NewError("Error occured when accepting conn").Base(err) return } rwc := common.NewRewindReadWriteCloser(conn) rwc.SetBufferSize(128) first, err := rwc.ReadByte() if err != nil { - log.Error(common.NewError("failed to obtain proxy type").Base(err)) + log.Error(common.NewError("Failed to obtain proxy type").Base(err)) rwc.Close() continue } @@ -307,7 +307,7 @@ func (c *Client) listenTCP(errChan chan error) { } func (c *Client) Run() error { - log.Info("client is running at", c.config.LocalAddress.String()) + log.Info("Client is running at", c.config.LocalAddress.String()) errChan := make(chan error, 3) go c.listenUDP(errChan) go c.listenTCP(errChan) @@ -325,7 +325,7 @@ func (c *Client) Run() error { } func (c *Client) Close() error { - log.Info("shutting down client..") + log.Info("Shutting down client..") c.cancel() if c.udpListener != nil { c.udpListener.Close() @@ -346,7 +346,7 @@ func (c *Client) Build(config *conf.GlobalConfig) (common.Runnable, error) { var rtr router.Router = &router.EmptyRouter{} if config.Router.Enabled { - log.Info("router enabled") + log.Info("Router enabled") rtr, err = router.NewRouter(&config.Router) if err != nil { log.Fatal(common.NewError("invalid router list").Base(err)) diff --git a/proxy/client/forward.go b/proxy/client/forward.go index 619666f..cb4d6c0 100644 --- a/proxy/client/forward.go +++ b/proxy/client/forward.go @@ -43,7 +43,7 @@ func (f *Forward) dispatchServerPacket(addr net.Addr) { outboundPacket, found := f.outboundPacketTable[addr.String()] f.outboundPacketTableLock.Unlock() if !found { - log.Error("addr key not found") + log.Error("Address key not found, expired?", addr.String()) return } payloadChan := make(chan []byte, 64) @@ -112,7 +112,7 @@ func (f *Forward) dispatchClientPacket() { func (f *Forward) listenUDP(errChan chan error) { listener, err := net.ListenPacket("udp", f.config.LocalAddress.String()) if err != nil { - errChan <- common.NewError("failed to listen udp") + errChan <- common.NewError("Failed to listen udp") return } f.udpListener = listener @@ -120,7 +120,7 @@ func (f *Forward) listenUDP(errChan chan error) { for { buf := make([]byte, protocol.MaxUDPPacketSize) n, addr, err := listener.ReadFrom(buf) - log.Info("packet from", addr, "tunneling to", f.config.TargetAddress) + log.Info("Packet from", addr, "tunneling to", f.config.TargetAddress) if err != nil { errChan <- err return @@ -135,7 +135,7 @@ func (f *Forward) listenUDP(errChan chan error) { func (f *Forward) listenTCP(errChan chan error) { listener, err := net.Listen("tcp", f.config.LocalAddress.String()) if err != nil { - errChan <- common.NewError("failed to listen local address").Base(err) + errChan <- common.NewError("Failed to listen local address").Base(err) return } f.tcpListener = listener @@ -147,12 +147,12 @@ func (f *Forward) listenTCP(errChan chan error) { for { inboundConn, err := listener.Accept() if err != nil { - errChan <- common.NewError("error occured when accepting conn").Base(err) + errChan <- common.NewError("Error occured when accepting conn").Base(err) } handle := func(inboundConn net.Conn) { outboundConn, err := f.appMan.OpenAppConn(req) if err != nil { - log.Error(common.NewError("failed to start outbound session").Base(err)) + log.Error(common.NewError("Failed to start outbound session").Base(err)) return } defer outboundConn.Close() @@ -163,7 +163,7 @@ func (f *Forward) listenTCP(errChan chan error) { } func (f *Forward) Run() error { - log.Info("forward is running at", f.config.LocalAddress) + log.Info("Forward is running at", f.config.LocalAddress) errChan := make(chan error, 2) go f.listenUDP(errChan) go f.listenTCP(errChan) @@ -176,7 +176,7 @@ func (f *Forward) Run() error { } func (f *Forward) Close() error { - log.Info("shutting down forward..") + log.Info("Shutting down forward..") f.cancel() if f.udpListener != nil { f.udpListener.Close() diff --git a/proxy/client/mux.go b/proxy/client/mux.go index 2b7035d..8160c21 100644 --- a/proxy/client/mux.go +++ b/proxy/client/mux.go @@ -42,7 +42,7 @@ type MuxManager struct { func (m *MuxManager) newMuxClient() (*muxClientInfo, error) { id := generateMuxID() if _, found := m.muxPool[id]; found { - return nil, common.NewError("duplicated id") + return nil, common.NewError("Duplicated id") } req := &protocol.Request{ Command: protocol.Mux, @@ -53,18 +53,18 @@ func (m *MuxManager) newMuxClient() (*muxClientInfo, error) { } rwc, err := m.transport.DialToServer() if err != nil { - return nil, common.NewError("failed to dail to remote server").Base(err) + return nil, common.NewError("Failed to dail to remote server").Base(err) } conn, err := trojan.NewOutboundConnSession(req, rwc, m.config, m.auth) if err != nil { rwc.Close() - log.Error(common.NewError("failed to dial tls tunnel").Base(err)) + log.Error(common.NewError("Failed to dial tls tunnel").Base(err)) return nil, err } client, err := smux.Client(conn, nil) common.Must(err) - log.Info("mux TLS tunnel established, id:", id) + log.Info("Mux TLS tunnel established, id:", id) return &muxClientInfo{ client: client, id: id, @@ -79,7 +79,7 @@ func (m *MuxManager) pickMuxClient() (*muxClientInfo, error) { for _, info := range m.muxPool { if info.client.IsClosed() { delete(m.muxPool, info.id) - log.Info("mux", info.id, "is dead") + log.Info("Mux client", info.id, "is dead") continue } if info.client.NumStreams() < m.config.Mux.Concurrency || m.config.Mux.Concurrency <= 0 { @@ -90,7 +90,7 @@ func (m *MuxManager) pickMuxClient() (*muxClientInfo, error) { select { case <-m.ctx.Done(): - return nil, common.NewError("mux manager closed") + return nil, common.NewError("Mux manager closed") default: } @@ -114,10 +114,10 @@ func (m *MuxManager) DialToServer() (io.ReadWriteCloser, error) { defer m.Unlock() delete(m.muxPool, info.id) info.client.Close() - log.Info("somthing wrong with mux client", info.id, ", closing") + log.Info("Somthing wrong with mux client", info.id, ", closing") return nil, err } - log.Debug("new mux conn established, client", info.id) + log.Info("New mux conn established with client", info.id) info.lastActiveTime = time.Now() return stream, nil } @@ -127,7 +127,7 @@ func (m *MuxManager) checkAndCloseIdleMuxClient() { if m.config.Mux.IdleTimeout <= 0 { muxIdleDuration = 0 checkDuration = time.Second * 10 - log.Warn("invalid mux idle timeout") + log.Warn("Invalid mux idle timeout") } else { muxIdleDuration = time.Duration(m.config.Mux.IdleTimeout) * time.Second checkDuration = muxIdleDuration / 4 @@ -139,23 +139,23 @@ func (m *MuxManager) checkAndCloseIdleMuxClient() { for id, info := range m.muxPool { if info.client.IsClosed() { delete(m.muxPool, id) - log.Info("mux", id, "is dead") + log.Info("Mux", id, "is dead") } else if info.client.NumStreams() == 0 && time.Now().Sub(info.lastActiveTime) > muxIdleDuration { info.client.Close() delete(m.muxPool, id) - log.Info("mux", id, "is closed due to inactive") + log.Info("Mux", id, "is closed due to inactive") } } if len(m.muxPool) != 0 { - log.Info("current mux pool conn num", len(m.muxPool)) + log.Info("Current mux pool clients: ", len(m.muxPool)) } m.Unlock() case <-m.ctx.Done(): - log.Debug("shutting down mux manager..") + log.Debug("Shutting down mux manager..") m.Lock() for id, info := range m.muxPool { info.client.Close() - log.Info("mux client", id, "closed") + log.Info("Mux client", id, "closed") } m.Unlock() return diff --git a/proxy/client/nat.go b/proxy/client/nat.go index 1ba5851..9f7eee1 100644 --- a/proxy/client/nat.go +++ b/proxy/client/nat.go @@ -33,7 +33,7 @@ type NAT struct { func (n *NAT) handleConn(conn net.Conn) { inboundConn, req, err := tproxy.NewInboundConnSession(conn) if err != nil { - log.Error(common.NewError("failed to start inbound session").Base(err)) + log.Error(common.NewError("Failed to start inbound session").Base(err)) return } defer inboundConn.Close() @@ -43,7 +43,7 @@ func (n *NAT) handleConn(conn net.Conn) { return } defer outboundConn.Close() - log.Info("[transparent]conn from", conn.RemoteAddr(), "tunneling to", req) + log.Info("[Tproxy] conn from", conn.RemoteAddr(), "tunneling to", req) proxy.ProxyConn(n.ctx, inboundConn, outboundConn, n.config.BufferSize) } @@ -100,7 +100,7 @@ func (n *NAT) listenTCP(errChan chan error) { } func (n *NAT) Run() error { - log.Info("nat is running at", n.config.LocalAddress) + log.Info("NAT is running at", n.config.LocalAddress) errChan := make(chan error, 2) go n.listenUDP(errChan) go n.listenTCP(errChan) @@ -113,7 +113,7 @@ func (n *NAT) Run() error { } func (n *NAT) Close() error { - log.Info("shutting down tproxy...") + log.Info("Shutting down NAT...") n.cancel() if n.listener != nil { n.listener.Close() diff --git a/proxy/client/tls.go b/proxy/client/tls.go index ba26af4..f400388 100644 --- a/proxy/client/tls.go +++ b/proxy/client/tls.go @@ -37,7 +37,7 @@ func (m *TLSManager) printConnInfo(conn net.Conn) { tlsConn := conn.(*tls.Conn) state := tlsConn.ConnectionState() chain := state.VerifiedChains - log.Trace("tls handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) + log.Trace("TLS handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) for i := range chain { for j := range chain[i] { log.Trace("subject:", chain[i][j].Subject, ", issuer:", chain[i][j].Issuer) @@ -47,7 +47,7 @@ func (m *TLSManager) printConnInfo(conn net.Conn) { tlsConn := conn.(*utls.UConn) state := tlsConn.ConnectionState() chain := state.VerifiedChains - log.Trace("utls handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) + log.Trace("UTLS handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) for i := range chain { for j := range chain[i] { log.Trace("subject:", chain[i][j].Subject, ", issuer:", chain[i][j].Issuer) @@ -79,10 +79,10 @@ func (m *TLSManager) dialTCP() (net.Conn, error) { } conn, err := net.DialTimeout(network, m.config.RemoteAddress.String(), protocol.GetRandomTimeoutDuration()) if err != nil { - return nil, common.NewError("failed to dial to remote server").Base(err) + return nil, common.NewError("Failed to dial to remote server").Base(err) } if err := sockopt.ApplyTCPConnOption(conn.(*net.TCPConn), &m.config.TCP); err != nil { - log.Warn(common.NewError("failed to apply tcp options").Base(err)) + log.Warn(common.NewError("Failed to apply tcp options").Base(err)) } return conn, nil } @@ -137,7 +137,7 @@ func (m *TLSManager) dialTLSWithFakeFingerprint() (*utls.UConn, error) { m.helloIDLock.Unlock() return client, err } - return nil, common.NewError("all client hello id tried but failed") + return nil, common.NewError("All client hello IDs tried but failed") } func (m *TLSManager) DialToServer() (io.ReadWriteCloser, error) { @@ -168,7 +168,7 @@ func (m *TLSManager) DialToServer() (io.ReadWriteCloser, error) { ws, err := trojan.NewOutboundWebosocket(transport, m.config) if err != nil { transport.Close() - return nil, common.NewError("failed to start websocket connection").Base(err) + return nil, common.NewError("Failed to start websocket connection").Base(err) } return ws, nil } @@ -214,10 +214,10 @@ func NewTLSManager(config *conf.GlobalConfig) *TLSManager { } id, found := table[config.TLS.Fingerprint] if found { - log.Debug("tls fingerprint loaded:", id.Str()) + log.Debug("TLS fingerprint loaded:", id.Str()) m.helloIDs = []utls.ClientHelloID{*id} } else { - log.Warn("invalid tls fingerprint:", config.TLS.Fingerprint, ", using default fingerprint") + log.Warn("Invalid TLS fingerprint:", config.TLS.Fingerprint, ", using default fingerprint") config.TLS.Fingerprint = "" } } diff --git a/proxy/option.go b/proxy/option.go index e0e79d0..4256f73 100644 --- a/proxy/option.go +++ b/proxy/option.go @@ -26,22 +26,22 @@ func (*proxyOption) Priority() int { func (c *proxyOption) Handle() error { log.Info("Trojan-Go", common.Version, "initializing") - log.Info("loading config file from", *c.args) + log.Info("Loading config file from", *c.args) //exit code 23 stands for initializing error, and systemd will not trying to restart it data, err := ioutil.ReadFile(*c.args) if err != nil { - log.Error(common.NewError("failed to read config file").Base(err)) + log.Error(common.NewError("Failed to read config file").Base(err)) os.Exit(23) } config, err := conf.ParseJSON(data) if err != nil { - log.Error(common.NewError("failed to parse config file").Base(err)) + log.Error(common.NewError("Failed to parse config file").Base(err)) os.Exit(23) } proxy, err := NewProxy(config) if err != nil { - log.Error(common.NewError("failed to launch proxy").Base(err)) + log.Error(common.NewError("Failed to launch proxy").Base(err)) os.Exit(23) } errChan := make(chan error) diff --git a/proxy/proxy.go b/proxy/proxy.go index bee6f1c..b326868 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -54,7 +54,7 @@ func ProxyPacket(ctx context.Context, a, b protocol.PacketReadWriter) { go copyPacket(b, a) select { case err := <-errChan: - log.Debug(common.NewError("packet proxy ends").Base(err)) + log.Debug(common.NewError("Packet proxy ends").Base(err)) case <-ctx.Done(): return } @@ -108,7 +108,7 @@ func ProxyPacketWithRouter(ctx context.Context, from protocol.PacketReadWriter, go copyToDst() select { case err := <-errChan: - log.Debug(common.NewError("packet proxy with routing ends").Base(err)) + log.Debug(common.NewError("Packet proxy with routing ends").Base(err)) case <-ctx.Done(): return } @@ -121,7 +121,7 @@ func NewProxy(config *conf.GlobalConfig) (common.Runnable, error) { if buildable, found := proxys[runType]; found { return buildable.Build(config) } - return nil, common.NewError("invalid run_type " + string(runType)) + return nil, common.NewError("Invalid run_type " + string(runType)) } func RegisterProxy(t conf.RunType, b Buildable) { @@ -139,7 +139,7 @@ func RegisterAPI(t conf.RunType, r APIRunner) { func RunAPIService(t conf.RunType, ctx context.Context, config *conf.GlobalConfig, auth stat.Authenticator) error { r, ok := apis[t] if !ok { - return common.NewError("api module for" + string(t) + "not found") + return common.NewError("API module for" + string(t) + "not found") } return r(ctx, config, auth) } diff --git a/proxy/relay/relay.go b/proxy/relay/relay.go index 46ed6dd..e4162e3 100644 --- a/proxy/relay/relay.go +++ b/proxy/relay/relay.go @@ -22,7 +22,7 @@ func (f *Relay) handleConn(conn net.Conn) { defer conn.Close() newConn, err := net.Dial("tcp", f.config.RemoteAddress.String()) if err != nil { - log.Error("failed to connect to remote endpoint:", err) + log.Error("Failed to connect to remote endpoint:", err) return } defer newConn.Close() @@ -30,11 +30,11 @@ func (f *Relay) handleConn(conn net.Conn) { } func (f *Relay) Run() error { - log.Info("relay is running at", f.config.LocalAddress) + log.Info("Relay is running at", f.config.LocalAddress) listener, err := net.Listen("tcp", f.config.LocalAddress.String()) f.listener = listener if err != nil { - return common.NewError("failed to listen local address").Base(err) + return common.NewError("Failed to listen local address").Base(err) } defer listener.Close() for { @@ -53,7 +53,7 @@ func (f *Relay) Run() error { } func (f *Relay) Close() error { - log.Info("shutting down relay..") + log.Info("Shutting down relay..") f.cancel() f.listener.Close() return nil diff --git a/proxy/server/server.go b/proxy/server/server.go index f3552fe..6f5bf30 100644 --- a/proxy/server/server.go +++ b/proxy/server/server.go @@ -36,7 +36,7 @@ func (s *Server) handleMuxConn(stream *smux.Stream) { inboundConn, req, err := simplesocks.NewInboundConnSession(stream) if err != nil { stream.Close() - log.Error(common.NewError("cannot start inbound session").Base(err)) + log.Error(common.NewError("Failed to init inbound session").Base(err)) return } switch req.Command { @@ -46,7 +46,7 @@ func (s *Server) handleMuxConn(stream *smux.Stream) { log.Error(err) return } - log.Info("mux tunneling to", req.String()) + log.Info("Mux conn tunneling to", req.String()) defer outboundConn.Close() proxy.ProxyConn(s.ctx, inboundConn, outboundConn, s.config.BufferSize) case protocol.Associate: @@ -55,17 +55,17 @@ func (s *Server) handleMuxConn(stream *smux.Stream) { inboundPacket, err := trojan.NewPacketSession(inboundConn) proxy.ProxyPacket(s.ctx, inboundPacket, outboundPacket) default: - log.Error(fmt.Sprintf("invalid command %d", req.Command)) + log.Error(fmt.Sprintf("Invalid command %d", req.Command)) return } } -func (s *Server) handleConn(conn *tls.Conn) { +func (s *Server) handleConn(conn net.Conn) { protocol.SetRandomizedTimeout(conn) inboundConn, req, err := trojan.NewInboundConnSession(s.ctx, conn, s.config, s.auth, s.shadow) if err != nil { //once the auth is failed, the conn will be took over by shadow manager. don't close it - log.Error(common.NewError("failed to start inbound session, remote:" + conn.RemoteAddr().String()).Base(err)) + log.Error(common.NewError("Failed to start inbound session, remote:" + conn.RemoteAddr().String()).Base(err)) return } protocol.CancelTimeout(conn) @@ -77,7 +77,7 @@ func (s *Server) handleConn(conn *tls.Conn) { for { stream, err := muxServer.AcceptStream() if err != nil { - log.Debug("mux conn from", conn.RemoteAddr(), "closed:", err) + log.Debug("Mux conn from", conn.RemoteAddr(), "closed:", err) return } go s.handleMuxConn(stream) @@ -95,9 +95,9 @@ func (s *Server) handleConn(conn *tls.Conn) { return } defer outboundPacket.Close() - log.Info("udp tunnel established") + log.Info("UDP tunnel established") proxy.ProxyPacket(s.ctx, inboundPacket, outboundPacket) - log.Debug("udp tunnel closed") + log.Debug("UDP tunnel closed") return } @@ -109,12 +109,12 @@ func (s *Server) handleConn(conn *tls.Conn) { } defer outboundConn.Close() - log.Info("conn from", conn.RemoteAddr(), "tunneling to", req.String()) + log.Info("Conn from", conn.RemoteAddr(), "tunneling to", req.String()) proxy.ProxyConn(s.ctx, inboundConn, outboundConn, s.config.BufferSize) } func (s *Server) ListenTCP(errChan chan error) { - log.Info("server is running at", s.config.LocalAddress) + log.Info("Server is running at", s.config.LocalAddress) var listener net.Listener listener, err := net.Listen("tcp", s.config.LocalAddress.String()) @@ -149,8 +149,12 @@ func (s *Server) ListenTCP(errChan chan error) { return } } - log.Info("conn accepted from", conn.RemoteAddr()) + log.Info("Conn accepted from", conn.RemoteAddr()) go func(conn net.Conn) { + if s.config.TLS.ServePlainText { + s.handleConn(conn) + return + } //using randomized timeout protocol.SetRandomizedTimeout(conn) @@ -164,15 +168,15 @@ func (s *Server) ListenTCP(errChan chan error) { if s.config.LogLevel == 0 { state := tlsConn.ConnectionState() - log.Trace("tls handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) + log.Trace("TLS handshaked", "cipher:", tls.CipherSuiteName(state.CipherSuite), "resume:", state.DidResume) } if err != nil { rewindConn.R.Rewind() - err = common.NewError("failed to perform tls handshake with " + conn.RemoteAddr().String()).Base(err) + err = common.NewError("Failed to perform tls handshake with " + conn.RemoteAddr().String()).Base(err) log.Warn(err) if s.config.TLS.FallbackAddress != nil { - s.shadow.CommitScapegoat(&shadow.Scapegoat{ + s.shadow.SubmitScapegoat(&shadow.Scapegoat{ Conn: rewindConn, ShadowAddress: s.config.TLS.FallbackAddress, Info: err.Error(), @@ -193,7 +197,7 @@ func (s *Server) ListenTCP(errChan chan error) { func (s *Server) Run() error { errChan := make(chan error, 2) if s.config.API.Enabled { - log.Info("api enabled") + log.Info("API enabled") go func() { errChan <- proxy.RunAPIService(conf.Server, s.ctx, s.config, s.auth) }() @@ -208,7 +212,7 @@ func (s *Server) Run() error { } func (s *Server) Close() error { - log.Info("shutting down server..") + log.Info("Shutting down server..") s.cancel() s.listener.Close() return nil diff --git a/router/mixed/geo.go b/router/mixed/geo.go index 7b7f3fd..e6534af 100644 --- a/router/mixed/geo.go +++ b/router/mixed/geo.go @@ -41,7 +41,8 @@ func (r *GeoRouter) matchDomain(fulldomain string) bool { case v2router.Domain_Regex: matched, err := regexp.Match(d.GetValue(), []byte(fulldomain)) if err != nil { - log.Error("invalid regex") + log.Error("Invalid regex") + return false } if matched { return true @@ -141,9 +142,9 @@ func (r *GeoRouter) LoadGeoData(geoipData []byte, ipCode []string, geositeData [ } } if found { - log.Info("geoip tag", c, "loaded") + log.Info("GeoIP tag", c, "loaded") } else { - log.Warn("geoip tag", c, "not found") + log.Warn("GeoIP tag", c, "not found") } } @@ -164,9 +165,9 @@ func (r *GeoRouter) LoadGeoData(geoipData []byte, ipCode []string, geositeData [ } } if found { - log.Info("geosite tag", c, "loaded") + log.Info("GeoSite tag", c, "loaded") } else { - log.Warn("geosite tag", c, "not found") + log.Warn("GeoSite tag", c, "not found") } } return nil diff --git a/router/mixed/mixed.go b/router/mixed/mixed.go index 006aa98..be2eb42 100644 --- a/router/mixed/mixed.go +++ b/router/mixed/mixed.go @@ -21,7 +21,7 @@ type MixedRouter struct { func (r *MixedRouter) match(rr router.Router, req *protocol.Request) bool { policy, err := rr.RouteRequest(req) if err != nil { - log.Warn(common.NewError("match error").Base(err)) + log.Warn(common.NewError("Match error").Base(err)) return false } if policy == router.Match { diff --git a/shadow/shadow.go b/shadow/shadow.go index 99cd0fb..95d117b 100644 --- a/shadow/shadow.go +++ b/shadow/shadow.go @@ -25,7 +25,7 @@ type ShadowManager struct { scapegoatChan chan *Scapegoat } -func (m *ShadowManager) CommitScapegoat(goat *Scapegoat) { +func (m *ShadowManager) SubmitScapegoat(goat *Scapegoat) { m.scapegoatChan <- goat log.Debug("scapegoat commited") } @@ -35,7 +35,7 @@ func (m *ShadowManager) handleScapegoat() { select { case goat := <-m.scapegoatChan: if goat.Info != "" { - log.Info("scapegoat: ", goat.Info) + log.Info("Scapegoat: ", goat.Info) } //cancel the deadline if conn, ok := goat.Conn.(net.Conn); ok { @@ -48,7 +48,7 @@ func (m *ShadowManager) handleScapegoat() { var err error goat.ShadowConn, err = net.Dial("tcp", goat.ShadowAddress.String()) if err != nil { - log.Error(common.NewError("failed to dial to shadow server").Base(err)) + log.Error(common.NewError("Failed to dial to shadow server").Base(err)) continue } } diff --git a/sockopt/other.go b/sockopt/other.go index 5699168..4b3b40e 100644 --- a/sockopt/other.go +++ b/sockopt/other.go @@ -12,6 +12,6 @@ import ( ) func ApplySocketOption(fd uintptr, config *conf.TCPConfig, isInbound bool) error { - log.Warn("tcp options is ignored in this os:", runtime.GOOS) + log.Warn("TCP options is ignored in this os:", runtime.GOOS) return nil } diff --git a/stat/mysql/mysql.go b/stat/mysql/mysql.go index ea26abc..9f0f2f0 100644 --- a/stat/mysql/mysql.go +++ b/stat/mysql/mysql.go @@ -33,7 +33,7 @@ func (a *DBAuth) updater() { s, err := a.db.Exec("UPDATE `users` SET `upload`=`upload`+?, `download`=`download`+? WHERE `password`=?;", recv, sent, hash) if err != nil { - log.Error(common.NewError("failed to update data to user").Base(err)) + log.Error(common.NewError("Failed to update data to user").Base(err)) continue } if r, err := s.RowsAffected(); err != nil { @@ -42,12 +42,12 @@ func (a *DBAuth) updater() { } } } - log.Info("buffered data has been written into the database") + log.Info("Buffered data has been written into the database") //update memory rows, err := a.db.Query("SELECT password,quota,download,upload FROM users") if err != nil { - log.Error(common.NewError("failed to pull data from the database").Base(err)) + log.Error(common.NewError("Failed to pull data from the database").Base(err)) time.Sleep(a.updateDuration) continue } @@ -56,7 +56,7 @@ func (a *DBAuth) updater() { var quota, download, upload int64 err := rows.Scan(&hash, "a, &download, &upload) if err != nil { - log.Error(common.NewError("failed to obtain data from the query result").Base(err)) + log.Error(common.NewError("Failed to obtain data from the query result").Base(err)) break } if download+upload < quota || quota < 0 { @@ -90,7 +90,7 @@ func NewDBAuth(ctx context.Context, config *conf.GlobalConfig) (stat.Authenticat config.MySQL.Database, ) if err != nil { - return nil, common.NewError("failed to connect to database server").Base(err) + return nil, common.NewError("Failed to connect to database server").Base(err) } memoryAuth, err := memory.NewMemoryAuth(ctx, config) if err != nil { diff --git a/stat/redis/redis.go b/stat/redis/redis.go index 1152251..57338af 100644 --- a/stat/redis/redis.go +++ b/stat/redis/redis.go @@ -32,7 +32,7 @@ func (m *RedisTrafficMeter) Count(sent, recv int) { `) if err := m.db.Do(evalScript.Cmd(nil, key, strconv.Itoa(recv), strconv.Itoa(sent))); err != nil { - log.Error(common.NewError("failed to update data to user").Base(err)) + log.Error(common.NewError("Failed to update data to user").Base(err)) } } @@ -59,7 +59,7 @@ type RedisAuthenticator struct { func (a *RedisAuthenticator) AuthUser(hash string) (bool, stat.TrafficMeter) { var exist bool if err := a.db.Do(radix.Cmd(&exist, "EXISTS", hash)); err != nil { - log.Error(common.NewError("failed to check user in DB").Base(err)) + log.Error(common.NewError("Failed to check user in DB").Base(err)) } if exist { return true, &RedisTrafficMeter{hash: hash, db: a.db, ctx: a.ctx} @@ -82,7 +82,7 @@ func NewRedisAuth(ctx context.Context, config *conf.GlobalConfig) (stat.Authenti } db, err := radix.NewPool("tcp", addr, 10, radix.PoolConnFunc(conn)) if err != nil { - return nil, common.NewError("failed to connect to database server").Base(err) + return nil, common.NewError("Failed to connect to database server").Base(err) } return &RedisAuthenticator{db: db, ctx: ctx}, nil } diff --git a/stat/stat.go b/stat/stat.go index edec78b..89302d4 100644 --- a/stat/stat.go +++ b/stat/stat.go @@ -39,7 +39,7 @@ func RegisterAuthCreator(name string, creator AuthCreator) { func NewAuth(ctx context.Context, name string, config *conf.GlobalConfig) (Authenticator, error) { creator, found := authCreators[name] if !found { - return nil, common.NewError("driver name " + name + " not found") + return nil, common.NewError("Auth driver name " + name + " not found") } return creator(ctx, config) } diff --git a/test/target.go b/test/target.go index 7595c9d..5a09dae 100644 --- a/test/target.go +++ b/test/target.go @@ -29,7 +29,7 @@ func RunEchoUDPServer(ctx context.Context) { if err != nil { return } - log.Info("echo from", addr) + log.Info("Echo from", addr) conn.WriteToUDP(buf[0:n], addr) } }() @@ -53,7 +53,7 @@ func RunMultipleUDPEchoServer(ctx context.Context) { if err != nil { return } - log.Info("echo from", addr) + log.Info("Echo from", addr) conn.WriteToUDP(buf[0:n], addr) } }()