diff --git a/app/dispatcher/impl/default.go b/app/dispatcher/impl/default.go index 4485d46f6..d4404b2da 100644 --- a/app/dispatcher/impl/default.go +++ b/app/dispatcher/impl/default.go @@ -26,31 +26,31 @@ func NewDefaultDispatcher(space app.Space) *DefaultDispatcher { } // Private: Used by app.Space only. -func (this *DefaultDispatcher) Initialize(space app.Space) error { +func (v *DefaultDispatcher) Initialize(space app.Space) error { if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) { return errors.New("DefaultDispatcher: OutboundHandlerManager is not found in the space.") } - this.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager) + v.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager) if space.HasApp(router.APP_ID) { - this.router = space.GetApp(router.APP_ID).(*router.Router) + v.router = space.GetApp(router.APP_ID).(*router.Router) } return nil } -func (this *DefaultDispatcher) Release() { +func (v *DefaultDispatcher) Release() { } -func (this *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay { +func (v *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay { direct := ray.NewRay() - dispatcher := this.ohm.GetDefaultHandler() + dispatcher := v.ohm.GetDefaultHandler() destination := session.Destination - if this.router != nil { - if tag, err := this.router.TakeDetour(session); err == nil { - if handler := this.ohm.GetHandler(tag); handler != nil { + if v.router != nil { + if tag, err := v.router.TakeDetour(session); err == nil { + if handler := v.ohm.GetHandler(tag); handler != nil { log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].") dispatcher = handler } else { @@ -64,14 +64,14 @@ func (this *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ra if session.Inbound != nil && session.Inbound.AllowPassiveConnection { go dispatcher.Dispatch(destination, alloc.NewLocalBuffer(32).Clear(), direct) } else { - go this.FilterPacketAndDispatch(destination, direct, dispatcher) + go v.FilterPacketAndDispatch(destination, direct, dispatcher) } return direct } // Private: Visible for testing. -func (this *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) { +func (v *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) { payload, err := link.OutboundInput().Read() if err != nil { log.Info("DefaultDispatcher: No payload towards ", destination, ", stopping now.") diff --git a/app/dispatcher/testing/dispatcher.go b/app/dispatcher/testing/dispatcher.go index d194eae7c..5aad956da 100644 --- a/app/dispatcher/testing/dispatcher.go +++ b/app/dispatcher/testing/dispatcher.go @@ -30,10 +30,10 @@ func NewTestPacketDispatcher(handler func(destination v2net.Destination, traffic } } -func (this *TestPacketDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay { +func (v *TestPacketDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay { traffic := ray.NewRay() - this.Destination <- session.Destination - go this.Handler(session.Destination, traffic) + v.Destination <- session.Destination + go v.Handler(session.Destination, traffic) return traffic } diff --git a/app/dns/nameserver.go b/app/dns/nameserver.go index e9766fda9..6ca797110 100644 --- a/app/dns/nameserver.go +++ b/app/dns/nameserver.go @@ -58,50 +58,50 @@ func NewUDPNameServer(address v2net.Destination, dispatcher dispatcher.PacketDis } // Private: Visible for testing. -func (this *UDPNameServer) Cleanup() { +func (v *UDPNameServer) Cleanup() { expiredRequests := make([]uint16, 0, 16) now := time.Now() - this.Lock() - for id, r := range this.requests { + v.Lock() + for id, r := range v.requests { if r.expire.Before(now) { expiredRequests = append(expiredRequests, id) close(r.response) } } for _, id := range expiredRequests { - delete(this.requests, id) + delete(v.requests, id) } - this.Unlock() + v.Unlock() expiredRequests = nil } // Private: Visible for testing. -func (this *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 { +func (v *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 { var id uint16 - this.Lock() - if len(this.requests) > CleanupThreshold && this.nextCleanup.Before(time.Now()) { - this.nextCleanup = time.Now().Add(CleanupInterval) - go this.Cleanup() + v.Lock() + if len(v.requests) > CleanupThreshold && v.nextCleanup.Before(time.Now()) { + v.nextCleanup = time.Now().Add(CleanupInterval) + go v.Cleanup() } for { id = uint16(dice.Roll(65536)) - if _, found := this.requests[id]; found { + if _, found := v.requests[id]; found { continue } log.Debug("DNS: Add pending request id ", id) - this.requests[id] = &PendingRequest{ + v.requests[id] = &PendingRequest{ expire: time.Now().Add(time.Second * 8), response: response, } break } - this.Unlock() + v.Unlock() return id } // Private: Visible for testing. -func (this *UDPNameServer) HandleResponse(dest v2net.Destination, payload *alloc.Buffer) { +func (v *UDPNameServer) HandleResponse(dest v2net.Destination, payload *alloc.Buffer) { msg := new(dns.Msg) err := msg.Unpack(payload.Value) if err != nil { @@ -115,14 +115,14 @@ func (this *UDPNameServer) HandleResponse(dest v2net.Destination, payload *alloc ttl := DefaultTTL log.Debug("DNS: Handling response for id ", id, " content: ", msg.String()) - this.Lock() - request, found := this.requests[id] + v.Lock() + request, found := v.requests[id] if !found { - this.Unlock() + v.Unlock() return } - delete(this.requests, id) - this.Unlock() + delete(v.requests, id) + v.Unlock() for _, rr := range msg.Answer { switch rr := rr.(type) { @@ -144,7 +144,7 @@ func (this *UDPNameServer) HandleResponse(dest v2net.Destination, payload *alloc close(request.response) } -func (this *UDPNameServer) BuildQueryA(domain string, id uint16) *alloc.Buffer { +func (v *UDPNameServer) BuildQueryA(domain string, id uint16) *alloc.Buffer { buffer := alloc.NewBuffer() msg := new(dns.Msg) msg.Id = id @@ -162,24 +162,24 @@ func (this *UDPNameServer) BuildQueryA(domain string, id uint16) *alloc.Buffer { return buffer } -func (this *UDPNameServer) DispatchQuery(payload *alloc.Buffer) { - this.udpServer.Dispatch(&proxy.SessionInfo{Source: pseudoDestination, Destination: this.address}, payload, this.HandleResponse) +func (v *UDPNameServer) DispatchQuery(payload *alloc.Buffer) { + v.udpServer.Dispatch(&proxy.SessionInfo{Source: pseudoDestination, Destination: v.address}, payload, v.HandleResponse) } -func (this *UDPNameServer) QueryA(domain string) <-chan *ARecord { +func (v *UDPNameServer) QueryA(domain string) <-chan *ARecord { response := make(chan *ARecord, 1) - id := this.AssignUnusedID(response) + id := v.AssignUnusedID(response) - this.DispatchQuery(this.BuildQueryA(domain, id)) + v.DispatchQuery(v.BuildQueryA(domain, id)) go func() { for i := 0; i < 2; i++ { time.Sleep(time.Second) - this.Lock() - _, found := this.requests[id] - this.Unlock() + v.Lock() + _, found := v.requests[id] + v.Unlock() if found { - this.DispatchQuery(this.BuildQueryA(domain, id)) + v.DispatchQuery(v.BuildQueryA(domain, id)) } else { break } @@ -192,7 +192,7 @@ func (this *UDPNameServer) QueryA(domain string) <-chan *ARecord { type LocalNameServer struct { } -func (this *LocalNameServer) QueryA(domain string) <-chan *ARecord { +func (v *LocalNameServer) QueryA(domain string) <-chan *ARecord { response := make(chan *ARecord, 1) go func() { diff --git a/app/dns/server.go b/app/dns/server.go index bb267e4f8..877080299 100644 --- a/app/dns/server.go +++ b/app/dns/server.go @@ -65,44 +65,44 @@ func NewCacheServer(space app.Space, config *Config) *CacheServer { return server } -func (this *CacheServer) Release() { +func (v *CacheServer) Release() { } // Private: Visible for testing. -func (this *CacheServer) GetCached(domain string) []net.IP { - this.RLock() - defer this.RUnlock() +func (v *CacheServer) GetCached(domain string) []net.IP { + v.RLock() + defer v.RUnlock() - if record, found := this.records[domain]; found && record.A.Expire.After(time.Now()) { + if record, found := v.records[domain]; found && record.A.Expire.After(time.Now()) { return record.A.IPs } return nil } -func (this *CacheServer) Get(domain string) []net.IP { - if ip, found := this.hosts[domain]; found { +func (v *CacheServer) Get(domain string) []net.IP { + if ip, found := v.hosts[domain]; found { return []net.IP{ip} } domain = dns.Fqdn(domain) - ips := this.GetCached(domain) + ips := v.GetCached(domain) if ips != nil { return ips } - for _, server := range this.servers { + for _, server := range v.servers { response := server.QueryA(domain) select { case a, open := <-response: if !open || a == nil { continue } - this.Lock() - this.records[domain] = &DomainRecord{ + v.Lock() + v.records[domain] = &DomainRecord{ A: a, } - this.Unlock() + v.Unlock() log.Debug("DNS: Returning ", len(a.IPs), " IPs for domain ", domain) return a.IPs case <-time.After(QueryTimeout): @@ -115,12 +115,12 @@ func (this *CacheServer) Get(domain string) []net.IP { type CacheServerFactory struct{} -func (this CacheServerFactory) Create(space app.Space, config interface{}) (app.Application, error) { +func (v CacheServerFactory) Create(space app.Space, config interface{}) (app.Application, error) { server := NewCacheServer(space, config.(*Config)) return server, nil } -func (this CacheServerFactory) AppId() app.ID { +func (v CacheServerFactory) AppId() app.ID { return APP_ID } diff --git a/app/proxy/proxy.go b/app/proxy/proxy.go index cfe5b213f..04708ce00 100644 --- a/app/proxy/proxy.go +++ b/app/proxy/proxy.go @@ -35,12 +35,12 @@ func NewOutboundProxy(space app.Space) *OutboundProxy { return proxy } -func (this *OutboundProxy) RegisterDialer() { - internet.ProxyDialer = this.Dial +func (v *OutboundProxy) RegisterDialer() { + internet.ProxyDialer = v.Dial } -func (this *OutboundProxy) Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) { - handler := this.outboundManager.GetHandler(options.Proxy.Tag) +func (v *OutboundProxy) Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) { + handler := v.outboundManager.GetHandler(options.Proxy.Tag) if handler == nil { log.Warning("Proxy: Failed to get outbound handler with tag: ", options.Proxy.Tag) return internet.Dial(src, dest, internet.DialerOptions{ @@ -53,7 +53,7 @@ func (this *OutboundProxy) Dial(src v2net.Address, dest v2net.Destination, optio return NewProxyConnection(src, dest, stream), nil } -func (this *OutboundProxy) Release() { +func (v *OutboundProxy) Release() { } @@ -83,53 +83,53 @@ func NewProxyConnection(src v2net.Address, dest v2net.Destination, stream ray.Ra } } -func (this *ProxyConnection) Read(b []byte) (int, error) { - if this.closed { +func (v *ProxyConnection) Read(b []byte) (int, error) { + if v.closed { return 0, io.EOF } - return this.reader.Read(b) + return v.reader.Read(b) } -func (this *ProxyConnection) Write(b []byte) (int, error) { - if this.closed { +func (v *ProxyConnection) Write(b []byte) (int, error) { + if v.closed { return 0, io.ErrClosedPipe } - return this.writer.Write(b) + return v.writer.Write(b) } -func (this *ProxyConnection) Close() error { - this.closed = true - this.stream.InboundInput().Close() - this.stream.InboundOutput().Release() - this.reader.Release() - this.writer.Release() +func (v *ProxyConnection) Close() error { + v.closed = true + v.stream.InboundInput().Close() + v.stream.InboundOutput().Release() + v.reader.Release() + v.writer.Release() return nil } -func (this *ProxyConnection) LocalAddr() net.Addr { - return this.localAddr +func (v *ProxyConnection) LocalAddr() net.Addr { + return v.localAddr } -func (this *ProxyConnection) RemoteAddr() net.Addr { - return this.remoteAddr +func (v *ProxyConnection) RemoteAddr() net.Addr { + return v.remoteAddr } -func (this *ProxyConnection) SetDeadline(t time.Time) error { +func (v *ProxyConnection) SetDeadline(t time.Time) error { return nil } -func (this *ProxyConnection) SetReadDeadline(t time.Time) error { +func (v *ProxyConnection) SetReadDeadline(t time.Time) error { return nil } -func (this *ProxyConnection) SetWriteDeadline(t time.Time) error { +func (v *ProxyConnection) SetWriteDeadline(t time.Time) error { return nil } -func (this *ProxyConnection) Reusable() bool { +func (v *ProxyConnection) Reusable() bool { return false } -func (this *ProxyConnection) SetReusable(bool) { +func (v *ProxyConnection) SetReusable(bool) { } diff --git a/app/proxyman/proxyman.go b/app/proxyman/proxyman.go index 28e6fead4..b5fdaa3ec 100644 --- a/app/proxyman/proxyman.go +++ b/app/proxyman/proxyman.go @@ -33,37 +33,37 @@ func NewDefaultOutboundHandlerManager() *DefaultOutboundHandlerManager { } } -func (this *DefaultOutboundHandlerManager) Release() { +func (v *DefaultOutboundHandlerManager) Release() { } -func (this *DefaultOutboundHandlerManager) GetDefaultHandler() proxy.OutboundHandler { - this.RLock() - defer this.RUnlock() - if this.defaultHandler == nil { +func (v *DefaultOutboundHandlerManager) GetDefaultHandler() proxy.OutboundHandler { + v.RLock() + defer v.RUnlock() + if v.defaultHandler == nil { return nil } - return this.defaultHandler + return v.defaultHandler } -func (this *DefaultOutboundHandlerManager) SetDefaultHandler(handler proxy.OutboundHandler) { - this.Lock() - defer this.Unlock() - this.defaultHandler = handler +func (v *DefaultOutboundHandlerManager) SetDefaultHandler(handler proxy.OutboundHandler) { + v.Lock() + defer v.Unlock() + v.defaultHandler = handler } -func (this *DefaultOutboundHandlerManager) GetHandler(tag string) proxy.OutboundHandler { - this.RLock() - defer this.RUnlock() - if handler, found := this.taggedHandler[tag]; found { +func (v *DefaultOutboundHandlerManager) GetHandler(tag string) proxy.OutboundHandler { + v.RLock() + defer v.RUnlock() + if handler, found := v.taggedHandler[tag]; found { return handler } return nil } -func (this *DefaultOutboundHandlerManager) SetHandler(tag string, handler proxy.OutboundHandler) { - this.Lock() - defer this.Unlock() +func (v *DefaultOutboundHandlerManager) SetHandler(tag string, handler proxy.OutboundHandler) { + v.Lock() + defer v.Unlock() - this.taggedHandler[tag] = handler + v.taggedHandler[tag] = handler } diff --git a/app/router/condition.go b/app/router/condition.go index 8721fe461..637322b4b 100644 --- a/app/router/condition.go +++ b/app/router/condition.go @@ -20,13 +20,13 @@ func NewConditionChan() *ConditionChan { return &condChan } -func (this *ConditionChan) Add(cond Condition) *ConditionChan { - *this = append(*this, cond) - return this +func (v *ConditionChan) Add(cond Condition) *ConditionChan { + *v = append(*v, cond) + return v } -func (this *ConditionChan) Apply(session *proxy.SessionInfo) bool { - for _, cond := range *this { +func (v *ConditionChan) Apply(session *proxy.SessionInfo) bool { + for _, cond := range *v { if !cond.Apply(session) { return false } @@ -34,8 +34,8 @@ func (this *ConditionChan) Apply(session *proxy.SessionInfo) bool { return true } -func (this *ConditionChan) Len() int { - return len(*this) +func (v *ConditionChan) Len() int { + return len(*v) } type AnyCondition []Condition @@ -45,13 +45,13 @@ func NewAnyCondition() *AnyCondition { return &anyCond } -func (this *AnyCondition) Add(cond Condition) *AnyCondition { - *this = append(*this, cond) - return this +func (v *AnyCondition) Add(cond Condition) *AnyCondition { + *v = append(*v, cond) + return v } -func (this *AnyCondition) Apply(session *proxy.SessionInfo) bool { - for _, cond := range *this { +func (v *AnyCondition) Apply(session *proxy.SessionInfo) bool { + for _, cond := range *v { if cond.Apply(session) { return true } @@ -59,8 +59,8 @@ func (this *AnyCondition) Apply(session *proxy.SessionInfo) bool { return false } -func (this *AnyCondition) Len() int { - return len(*this) +func (v *AnyCondition) Len() int { + return len(*v) } type PlainDomainMatcher struct { @@ -73,13 +73,13 @@ func NewPlainDomainMatcher(pattern string) *PlainDomainMatcher { } } -func (this *PlainDomainMatcher) Apply(session *proxy.SessionInfo) bool { +func (v *PlainDomainMatcher) Apply(session *proxy.SessionInfo) bool { dest := session.Destination if !dest.Address.Family().IsDomain() { return false } domain := dest.Address.Domain() - return strings.Contains(domain, this.pattern) + return strings.Contains(domain, v.pattern) } type RegexpDomainMatcher struct { @@ -96,13 +96,13 @@ func NewRegexpDomainMatcher(pattern string) (*RegexpDomainMatcher, error) { }, nil } -func (this *RegexpDomainMatcher) Apply(session *proxy.SessionInfo) bool { +func (v *RegexpDomainMatcher) Apply(session *proxy.SessionInfo) bool { dest := session.Destination if !dest.Address.Family().IsDomain() { return false } domain := dest.Address.Domain() - return this.pattern.MatchString(strings.ToLower(domain)) + return v.pattern.MatchString(strings.ToLower(domain)) } type CIDRMatcher struct { @@ -121,15 +121,15 @@ func NewCIDRMatcher(ip []byte, mask uint32, onSource bool) (*CIDRMatcher, error) }, nil } -func (this *CIDRMatcher) Apply(session *proxy.SessionInfo) bool { +func (v *CIDRMatcher) Apply(session *proxy.SessionInfo) bool { dest := session.Destination - if this.onSource { + if v.onSource { dest = session.Source } if !dest.Address.Family().Either(v2net.AddressFamilyIPv4, v2net.AddressFamilyIPv6) { return false } - return this.cidr.Contains(dest.Address.IP()) + return v.cidr.Contains(dest.Address.IP()) } type IPv4Matcher struct { @@ -144,15 +144,15 @@ func NewIPv4Matcher(ipnet *v2net.IPNet, onSource bool) *IPv4Matcher { } } -func (this *IPv4Matcher) Apply(session *proxy.SessionInfo) bool { +func (v *IPv4Matcher) Apply(session *proxy.SessionInfo) bool { dest := session.Destination - if this.onSource { + if v.onSource { dest = session.Source } if !dest.Address.Family().Either(v2net.AddressFamilyIPv4) { return false } - return this.ipv4net.Contains(dest.Address.IP()) + return v.ipv4net.Contains(dest.Address.IP()) } type PortMatcher struct { @@ -165,8 +165,8 @@ func NewPortMatcher(portRange v2net.PortRange) *PortMatcher { } } -func (this *PortMatcher) Apply(session *proxy.SessionInfo) bool { - return this.port.Contains(session.Destination.Port) +func (v *PortMatcher) Apply(session *proxy.SessionInfo) bool { + return v.port.Contains(session.Destination.Port) } type NetworkMatcher struct { @@ -179,8 +179,8 @@ func NewNetworkMatcher(network *v2net.NetworkList) *NetworkMatcher { } } -func (this *NetworkMatcher) Apply(session *proxy.SessionInfo) bool { - return this.network.HasNetwork(session.Destination.Network) +func (v *NetworkMatcher) Apply(session *proxy.SessionInfo) bool { + return v.network.HasNetwork(session.Destination.Network) } type UserMatcher struct { @@ -193,11 +193,11 @@ func NewUserMatcher(users []string) *UserMatcher { } } -func (this *UserMatcher) Apply(session *proxy.SessionInfo) bool { +func (v *UserMatcher) Apply(session *proxy.SessionInfo) bool { if session.User == nil { return false } - for _, u := range this.user { + for _, u := range v.user { if u == session.User.Email { return true } @@ -215,12 +215,12 @@ func NewInboundTagMatcher(tags []string) *InboundTagMatcher { } } -func (this *InboundTagMatcher) Apply(session *proxy.SessionInfo) bool { +func (v *InboundTagMatcher) Apply(session *proxy.SessionInfo) bool { if session.Inbound == nil || len(session.Inbound.Tag) == 0 { return false } - for _, t := range this.tags { + for _, t := range v.tags { if t == session.Inbound.Tag { return true } diff --git a/app/router/config.go b/app/router/config.go index bb297e1b3..2491e0dce 100644 --- a/app/router/config.go +++ b/app/router/config.go @@ -13,16 +13,16 @@ type Rule struct { Condition Condition } -func (this *Rule) Apply(session *proxy.SessionInfo) bool { - return this.Condition.Apply(session) +func (v *Rule) Apply(session *proxy.SessionInfo) bool { + return v.Condition.Apply(session) } -func (this *RoutingRule) BuildCondition() (Condition, error) { +func (v *RoutingRule) BuildCondition() (Condition, error) { conds := NewConditionChan() - if len(this.Domain) > 0 { + if len(v.Domain) > 0 { anyCond := NewAnyCondition() - for _, domain := range this.Domain { + for _, domain := range v.Domain { if domain.Type == Domain_Plain { anyCond.Add(NewPlainDomainMatcher(domain.Value)) } else { @@ -36,12 +36,12 @@ func (this *RoutingRule) BuildCondition() (Condition, error) { conds.Add(anyCond) } - if len(this.Cidr) > 0 { + if len(v.Cidr) > 0 { ipv4Net := v2net.NewIPNet() ipv6Cond := NewAnyCondition() hasIpv6 := false - for _, ip := range this.Cidr { + for _, ip := range v.Cidr { switch len(ip.Ip) { case net.IPv4len: ipv4Net.AddIP(ip.Ip, byte(ip.Prefix)) @@ -69,20 +69,20 @@ func (this *RoutingRule) BuildCondition() (Condition, error) { } } - if this.PortRange != nil { - conds.Add(NewPortMatcher(*this.PortRange)) + if v.PortRange != nil { + conds.Add(NewPortMatcher(*v.PortRange)) } - if this.NetworkList != nil { - conds.Add(NewNetworkMatcher(this.NetworkList)) + if v.NetworkList != nil { + conds.Add(NewNetworkMatcher(v.NetworkList)) } - if len(this.SourceCidr) > 0 { + if len(v.SourceCidr) > 0 { ipv4Net := v2net.NewIPNet() ipv6Cond := NewAnyCondition() hasIpv6 := false - for _, ip := range this.SourceCidr { + for _, ip := range v.SourceCidr { switch len(ip.Ip) { case net.IPv4len: ipv4Net.AddIP(ip.Ip, byte(ip.Prefix)) @@ -110,12 +110,12 @@ func (this *RoutingRule) BuildCondition() (Condition, error) { } } - if len(this.UserEmail) > 0 { - conds.Add(NewUserMatcher(this.UserEmail)) + if len(v.UserEmail) > 0 { + conds.Add(NewUserMatcher(v.UserEmail)) } - if len(this.InboundTag) > 0 { - conds.Add(NewInboundTagMatcher(this.InboundTag)) + if len(v.InboundTag) > 0 { + conds.Add(NewInboundTagMatcher(v.InboundTag)) } if conds.Len() == 0 { diff --git a/app/router/router.go b/app/router/router.go index 33b4c862c..1d4fe5aef 100644 --- a/app/router/router.go +++ b/app/router/router.go @@ -53,13 +53,13 @@ func NewRouter(config *Config, space app.Space) *Router { return r } -func (this *Router) Release() { +func (v *Router) Release() { } // Private: Visible for testing. -func (this *Router) ResolveIP(dest v2net.Destination) []v2net.Destination { - ips := this.dnsServer.Get(dest.Address.Domain()) +func (v *Router) ResolveIP(dest v2net.Destination) []v2net.Destination { + ips := v.dnsServer.Get(dest.Address.Domain()) if len(ips) == 0 { return nil } @@ -74,20 +74,20 @@ func (this *Router) ResolveIP(dest v2net.Destination) []v2net.Destination { return dests } -func (this *Router) takeDetourWithoutCache(session *proxy.SessionInfo) (string, error) { - for _, rule := range this.rules { +func (v *Router) takeDetourWithoutCache(session *proxy.SessionInfo) (string, error) { + for _, rule := range v.rules { if rule.Apply(session) { return rule.Tag, nil } } dest := session.Destination - if this.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() { + if v.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() { log.Info("Router: Looking up IP for ", dest) - ipDests := this.ResolveIP(dest) + ipDests := v.ResolveIP(dest) if ipDests != nil { for _, ipDest := range ipDests { log.Info("Router: Trying IP ", ipDest) - for _, rule := range this.rules { + for _, rule := range v.rules { if rule.Apply(&proxy.SessionInfo{ Source: session.Source, Destination: ipDest, @@ -103,12 +103,12 @@ func (this *Router) takeDetourWithoutCache(session *proxy.SessionInfo) (string, return "", ErrNoRuleApplicable } -func (this *Router) TakeDetour(session *proxy.SessionInfo) (string, error) { +func (v *Router) TakeDetour(session *proxy.SessionInfo) (string, error) { //destStr := dest.String() - //found, tag, err := this.cache.Get(destStr) + //found, tag, err := v.cache.Get(destStr) //if !found { - tag, err := this.takeDetourWithoutCache(session) - //this.cache.Set(destStr, tag, err) + tag, err := v.takeDetourWithoutCache(session) + //v.cache.Set(destStr, tag, err) return tag, err //} //return tag, err diff --git a/app/router/routing_table.go b/app/router/routing_table.go index 02d4e3991..a763a9d9a 100644 --- a/app/router/routing_table.go +++ b/app/router/routing_table.go @@ -11,12 +11,12 @@ type RoutingEntry struct { expire time.Time } -func (this *RoutingEntry) Extend() { - this.expire = time.Now().Add(time.Hour) +func (v *RoutingEntry) Extend() { + v.expire = time.Now().Add(time.Hour) } -func (this *RoutingEntry) Expired() bool { - return this.expire.Before(time.Now()) +func (v *RoutingEntry) Expired() bool { + return v.expire.Before(time.Now()) } type RoutingTable struct { @@ -30,38 +30,38 @@ func NewRoutingTable() *RoutingTable { } } -func (this *RoutingTable) Cleanup() { - this.Lock() - defer this.Unlock() +func (v *RoutingTable) Cleanup() { + v.Lock() + defer v.Unlock() - for key, value := range this.table { + for key, value := range v.table { if value.Expired() { - delete(this.table, key) + delete(v.table, key) } } } -func (this *RoutingTable) Set(destination string, tag string, err error) { - this.Lock() - defer this.Unlock() +func (v *RoutingTable) Set(destination string, tag string, err error) { + v.Lock() + defer v.Unlock() entry := &RoutingEntry{ tag: tag, err: err, } entry.Extend() - this.table[destination] = entry + v.table[destination] = entry - if len(this.table) > 1000 { - go this.Cleanup() + if len(v.table) > 1000 { + go v.Cleanup() } } -func (this *RoutingTable) Get(destination string) (bool, string, error) { - this.RLock() - defer this.RUnlock() +func (v *RoutingTable) Get(destination string) (bool, string, error) { + v.RLock() + defer v.RUnlock() - entry, found := this.table[destination] + entry, found := v.table[destination] if !found { return false, "", nil } diff --git a/app/space.go b/app/space.go index 5e18b9010..87977e470 100644 --- a/app/space.go +++ b/app/space.go @@ -60,12 +60,12 @@ func NewSpace() Space { } } -func (this *spaceImpl) InitializeApplication(f ApplicationInitializer) { - this.appInit = append(this.appInit, f) +func (v *spaceImpl) InitializeApplication(f ApplicationInitializer) { + v.appInit = append(v.appInit, f) } -func (this *spaceImpl) Initialize() error { - for _, f := range this.appInit { +func (v *spaceImpl) Initialize() error { + for _, f := range v.appInit { err := f() if err != nil { return err @@ -74,32 +74,32 @@ func (this *spaceImpl) Initialize() error { return nil } -func (this *spaceImpl) HasApp(id ID) bool { - _, found := this.cache[id] +func (v *spaceImpl) HasApp(id ID) bool { + _, found := v.cache[id] return found } -func (this *spaceImpl) GetApp(id ID) Application { - obj, found := this.cache[id] +func (v *spaceImpl) GetApp(id ID) Application { + obj, found := v.cache[id] if !found { return nil } return obj } -func (this *spaceImpl) BindApp(id ID, application Application) { - this.cache[id] = application +func (v *spaceImpl) BindApp(id ID, application Application) { + v.cache[id] = application } -func (this *spaceImpl) BindFromConfig(name string, config interface{}) error { +func (v *spaceImpl) BindFromConfig(name string, config interface{}) error { factory, found := applicationFactoryCache[name] if !found { return errors.New("Space: app not registered: " + name) } - app, err := factory.Create(this, config) + app, err := factory.Create(v, config) if err != nil { return err } - this.BindApp(factory.AppId(), app) + v.BindApp(factory.AppId(), app) return nil } diff --git a/common/crypto/io.go b/common/crypto/io.go index fa5bfdf03..98ed242bf 100644 --- a/common/crypto/io.go +++ b/common/crypto/io.go @@ -19,20 +19,20 @@ func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader { } } -func (this *CryptionReader) Read(data []byte) (int, error) { - if this.reader == nil { +func (v *CryptionReader) Read(data []byte) (int, error) { + if v.reader == nil { return 0, common.ErrObjectReleased } - nBytes, err := this.reader.Read(data) + nBytes, err := v.reader.Read(data) if nBytes > 0 { - this.stream.XORKeyStream(data[:nBytes], data[:nBytes]) + v.stream.XORKeyStream(data[:nBytes], data[:nBytes]) } return nBytes, err } -func (this *CryptionReader) Release() { - this.reader = nil - this.stream = nil +func (v *CryptionReader) Release() { + v.reader = nil + v.stream = nil } type CryptionWriter struct { @@ -47,15 +47,15 @@ func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter { } } -func (this *CryptionWriter) Write(data []byte) (int, error) { - if this.writer == nil { +func (v *CryptionWriter) Write(data []byte) (int, error) { + if v.writer == nil { return 0, common.ErrObjectReleased } - this.stream.XORKeyStream(data, data) - return this.writer.Write(data) + v.stream.XORKeyStream(data, data) + return v.writer.Write(data) } -func (this *CryptionWriter) Release() { - this.writer = nil - this.stream = nil +func (v *CryptionWriter) Release() { + v.writer = nil + v.stream = nil } diff --git a/common/io/buffered_reader.go b/common/io/buffered_reader.go index 8aeb55bca..65d6244d2 100644 --- a/common/io/buffered_reader.go +++ b/common/io/buffered_reader.go @@ -22,47 +22,47 @@ func NewBufferedReader(rawReader io.Reader) *BufferedReader { } } -func (this *BufferedReader) Release() { - this.Lock() - defer this.Unlock() +func (v *BufferedReader) Release() { + v.Lock() + defer v.Unlock() - this.buffer.Release() - this.buffer = nil - this.reader = nil + v.buffer.Release() + v.buffer = nil + v.reader = nil } -func (this *BufferedReader) Cached() bool { - return this.cached +func (v *BufferedReader) Cached() bool { + return v.cached } -func (this *BufferedReader) SetCached(cached bool) { - this.cached = cached +func (v *BufferedReader) SetCached(cached bool) { + v.cached = cached } -func (this *BufferedReader) Read(b []byte) (int, error) { - this.Lock() - defer this.Unlock() +func (v *BufferedReader) Read(b []byte) (int, error) { + v.Lock() + defer v.Unlock() - if this.reader == nil { + if v.reader == nil { return 0, io.EOF } - if !this.cached { - if !this.buffer.IsEmpty() { - return this.buffer.Read(b) + if !v.cached { + if !v.buffer.IsEmpty() { + return v.buffer.Read(b) } - return this.reader.Read(b) + return v.reader.Read(b) } - if this.buffer.IsEmpty() { - _, err := this.buffer.FillFrom(this.reader) + if v.buffer.IsEmpty() { + _, err := v.buffer.FillFrom(v.reader) if err != nil { return 0, err } } - if this.buffer.IsEmpty() { + if v.buffer.IsEmpty() { return 0, nil } - return this.buffer.Read(b) + return v.buffer.Read(b) } diff --git a/common/io/buffered_writer.go b/common/io/buffered_writer.go index 2d0a663ec..892f0278c 100644 --- a/common/io/buffered_writer.go +++ b/common/io/buffered_writer.go @@ -21,17 +21,17 @@ func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter { } } -func (this *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) { - this.Lock() - defer this.Unlock() +func (v *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) { + v.Lock() + defer v.Unlock() - if this.writer == nil { + if v.writer == nil { return 0, io.ErrClosedPipe } totalBytes := int64(0) for { - nBytes, err := this.buffer.FillFrom(reader) + nBytes, err := v.buffer.FillFrom(reader) totalBytes += int64(nBytes) if err != nil { if err == io.EOF { @@ -39,69 +39,69 @@ func (this *BufferedWriter) ReadFrom(reader io.Reader) (int64, error) { } return totalBytes, err } - this.FlushWithoutLock() + v.FlushWithoutLock() } } -func (this *BufferedWriter) Write(b []byte) (int, error) { - this.Lock() - defer this.Unlock() +func (v *BufferedWriter) Write(b []byte) (int, error) { + v.Lock() + defer v.Unlock() - if this.writer == nil { + if v.writer == nil { return 0, io.ErrClosedPipe } - if !this.cached { - return this.writer.Write(b) + if !v.cached { + return v.writer.Write(b) } - nBytes, _ := this.buffer.Write(b) - if this.buffer.IsFull() { - this.FlushWithoutLock() + nBytes, _ := v.buffer.Write(b) + if v.buffer.IsFull() { + v.FlushWithoutLock() } return nBytes, nil } -func (this *BufferedWriter) Flush() error { - this.Lock() - defer this.Unlock() +func (v *BufferedWriter) Flush() error { + v.Lock() + defer v.Unlock() - if this.writer == nil { + if v.writer == nil { return io.ErrClosedPipe } - return this.FlushWithoutLock() + return v.FlushWithoutLock() } -func (this *BufferedWriter) FlushWithoutLock() error { - defer this.buffer.Clear() - for !this.buffer.IsEmpty() { - nBytes, err := this.writer.Write(this.buffer.Value) +func (v *BufferedWriter) FlushWithoutLock() error { + defer v.buffer.Clear() + for !v.buffer.IsEmpty() { + nBytes, err := v.writer.Write(v.buffer.Value) if err != nil { return err } - this.buffer.SliceFrom(nBytes) + v.buffer.SliceFrom(nBytes) } return nil } -func (this *BufferedWriter) Cached() bool { - return this.cached +func (v *BufferedWriter) Cached() bool { + return v.cached } -func (this *BufferedWriter) SetCached(cached bool) { - this.cached = cached - if !cached && !this.buffer.IsEmpty() { - this.Flush() +func (v *BufferedWriter) SetCached(cached bool) { + v.cached = cached + if !cached && !v.buffer.IsEmpty() { + v.Flush() } } -func (this *BufferedWriter) Release() { - this.Flush() +func (v *BufferedWriter) Release() { + v.Flush() - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - this.buffer.Release() - this.buffer = nil - this.writer = nil + v.buffer.Release() + v.buffer = nil + v.writer = nil } diff --git a/common/io/chain_writer.go b/common/io/chain_writer.go index 1d8a8b353..325793c60 100644 --- a/common/io/chain_writer.go +++ b/common/io/chain_writer.go @@ -18,10 +18,10 @@ func NewChainWriter(writer Writer) *ChainWriter { } } -func (this *ChainWriter) Write(payload []byte) (int, error) { - this.Lock() - defer this.Unlock() - if this.writer == nil { +func (v *ChainWriter) Write(payload []byte) (int, error) { + v.Lock() + defer v.Unlock() + if v.writer == nil { return 0, io.ErrClosedPipe } @@ -39,7 +39,7 @@ func (this *ChainWriter) Write(payload []byte) (int, error) { bytesWritten += size size = 0 } - err := this.writer.Write(buffer) + err := v.writer.Write(buffer) if err != nil { return bytesWritten, err } @@ -48,9 +48,9 @@ func (this *ChainWriter) Write(payload []byte) (int, error) { return bytesWritten, nil } -func (this *ChainWriter) Release() { - this.Lock() - this.writer.Release() - this.writer = nil - this.Unlock() +func (v *ChainWriter) Release() { + v.Lock() + v.writer.Release() + v.writer = nil + v.Unlock() } diff --git a/common/io/chan_reader.go b/common/io/chan_reader.go index af7dde672..e9a8d853d 100644 --- a/common/io/chan_reader.go +++ b/common/io/chan_reader.go @@ -21,42 +21,42 @@ func NewChanReader(stream Reader) *ChanReader { } // Private: Visible for testing. -func (this *ChanReader) Fill() { - b, err := this.stream.Read() - this.current = b +func (v *ChanReader) Fill() { + b, err := v.stream.Read() + v.current = b if err != nil { - this.eof = true - this.current = nil + v.eof = true + v.current = nil } } -func (this *ChanReader) Read(b []byte) (int, error) { - if this.eof { +func (v *ChanReader) Read(b []byte) (int, error) { + if v.eof { return 0, io.EOF } - this.Lock() - defer this.Unlock() - if this.current == nil { - this.Fill() - if this.eof { + v.Lock() + defer v.Unlock() + if v.current == nil { + v.Fill() + if v.eof { return 0, io.EOF } } - nBytes, err := this.current.Read(b) - if this.current.IsEmpty() { - this.current.Release() - this.current = nil + nBytes, err := v.current.Read(b) + if v.current.IsEmpty() { + v.current.Release() + v.current = nil } return nBytes, err } -func (this *ChanReader) Release() { - this.Lock() - defer this.Unlock() +func (v *ChanReader) Release() { + v.Lock() + defer v.Unlock() - this.eof = true - this.current.Release() - this.current = nil - this.stream = nil + v.eof = true + v.current.Release() + v.current = nil + v.stream = nil } diff --git a/common/io/reader.go b/common/io/reader.go index 3355f1014..2e4288e0e 100644 --- a/common/io/reader.go +++ b/common/io/reader.go @@ -30,9 +30,9 @@ func NewAdaptiveReader(reader io.Reader) *AdaptiveReader { } // Read implements Reader.Read(). -func (this *AdaptiveReader) Read() (*alloc.Buffer, error) { - buffer := this.allocate().Clear() - _, err := buffer.FillFrom(this.reader) +func (v *AdaptiveReader) Read() (*alloc.Buffer, error) { + buffer := v.allocate().Clear() + _, err := buffer.FillFrom(v.reader) if err != nil { buffer.Release() return nil, err @@ -41,6 +41,6 @@ func (this *AdaptiveReader) Read() (*alloc.Buffer, error) { return buffer, nil } -func (this *AdaptiveReader) Release() { - this.reader = nil +func (v *AdaptiveReader) Release() { + v.reader = nil } diff --git a/common/io/writer.go b/common/io/writer.go index c77dd3836..fd469ae45 100644 --- a/common/io/writer.go +++ b/common/io/writer.go @@ -27,10 +27,10 @@ func NewAdaptiveWriter(writer io.Writer) *AdaptiveWriter { } // Write implements Writer.Write(). Write() takes ownership of the given buffer. -func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error { +func (v *AdaptiveWriter) Write(buffer *alloc.Buffer) error { defer buffer.Release() for !buffer.IsEmpty() { - nBytes, err := this.writer.Write(buffer.Value) + nBytes, err := v.writer.Write(buffer.Value) if err != nil { return err } @@ -39,6 +39,6 @@ func (this *AdaptiveWriter) Write(buffer *alloc.Buffer) error { return nil } -func (this *AdaptiveWriter) Release() { - this.writer = nil +func (v *AdaptiveWriter) Release() { + v.writer = nil } diff --git a/common/loader/type.go b/common/loader/type.go index 9a31305ca..84349a5d5 100644 --- a/common/loader/type.go +++ b/common/loader/type.go @@ -30,20 +30,20 @@ func GetInstance(messageType string) (interface{}, error) { return reflect.New(mType).Interface(), nil } -func (this *TypedSettings) Load(message proto.Message) error { +func (v *TypedSettings) Load(message proto.Message) error { targetType := GetType(message) - if targetType != this.Type { - return errors.New("Have type " + this.Type + ", but retrieved for " + targetType) + if targetType != v.Type { + return errors.New("Have type " + v.Type + ", but retrieved for " + targetType) } - return proto.Unmarshal(this.Settings, message) + return proto.Unmarshal(v.Settings, message) } -func (this *TypedSettings) GetInstance() (interface{}, error) { - instance, err := GetInstance(this.Type) +func (v *TypedSettings) GetInstance() (interface{}, error) { + instance, err := GetInstance(v.Type) if err != nil { return nil, err } - if err := proto.Unmarshal(this.Settings, instance.(proto.Message)); err != nil { + if err := proto.Unmarshal(v.Settings, instance.(proto.Message)); err != nil { return nil, err } return instance, nil diff --git a/common/log/config.go b/common/log/config.go index 7f25654bf..0c659d8b5 100644 --- a/common/log/config.go +++ b/common/log/config.go @@ -1,24 +1,24 @@ package log -func (this *Config) Apply() error { - if this == nil { +func (v *Config) Apply() error { + if v == nil { return nil } - if this.AccessLogType == LogType_File { - if err := InitAccessLogger(this.AccessLogPath); err != nil { + if v.AccessLogType == LogType_File { + if err := InitAccessLogger(v.AccessLogPath); err != nil { return err } } - if this.ErrorLogType == LogType_None { + if v.ErrorLogType == LogType_None { SetLogLevel(LogLevel_Disabled) } else { - if this.ErrorLogType == LogType_File { - if err := InitErrorLogger(this.ErrorLogPath); err != nil { + if v.ErrorLogType == LogType_File { + if err := InitErrorLogger(v.ErrorLogPath); err != nil { return err } } - SetLogLevel(this.ErrorLogLevel) + SetLogLevel(v.ErrorLogLevel) } return nil diff --git a/common/log/internal/log_entry.go b/common/log/internal/log_entry.go index 318c71ac8..c66849ed7 100644 --- a/common/log/internal/log_entry.go +++ b/common/log/internal/log_entry.go @@ -38,17 +38,17 @@ type ErrorLog struct { Values []interface{} } -func (this *ErrorLog) Release() { - for index := range this.Values { - this.Values[index] = nil +func (v *ErrorLog) Release() { + for index := range v.Values { + v.Values[index] = nil } - this.Values = nil + v.Values = nil } -func (this *ErrorLog) String() string { - values := make([]string, len(this.Values)+1) - values[0] = this.Prefix - for i, value := range this.Values { +func (v *ErrorLog) String() string { + values := make([]string, len(v.Values)+1) + values[0] = v.Prefix + for i, value := range v.Values { values[i+1] = InterfaceToString(value) } return strings.Join(values, "") @@ -61,12 +61,12 @@ type AccessLog struct { Reason interface{} } -func (this *AccessLog) Release() { - this.From = nil - this.To = nil - this.Reason = nil +func (v *AccessLog) Release() { + v.From = nil + v.To = nil + v.Reason = nil } -func (this *AccessLog) String() string { - return strings.Join([]string{InterfaceToString(this.From), this.Status, InterfaceToString(this.To), InterfaceToString(this.Reason)}, " ") +func (v *AccessLog) String() string { + return strings.Join([]string{InterfaceToString(v.From), v.Status, InterfaceToString(v.To), InterfaceToString(v.Reason)}, " ") } diff --git a/common/log/internal/log_writer.go b/common/log/internal/log_writer.go index d89920da9..b30799594 100644 --- a/common/log/internal/log_writer.go +++ b/common/log/internal/log_writer.go @@ -17,11 +17,11 @@ type LogWriter interface { type NoOpLogWriter struct { } -func (this *NoOpLogWriter) Log(entry LogEntry) { +func (v *NoOpLogWriter) Log(entry LogEntry) { entry.Release() } -func (this *NoOpLogWriter) Close() { +func (v *NoOpLogWriter) Close() { } type StdOutLogWriter struct { @@ -36,12 +36,12 @@ func NewStdOutLogWriter() LogWriter { } } -func (this *StdOutLogWriter) Log(log LogEntry) { - this.logger.Print(log.String() + platform.LineSeparator()) +func (v *StdOutLogWriter) Log(log LogEntry) { + v.logger.Print(log.String() + platform.LineSeparator()) log.Release() } -func (this *StdOutLogWriter) Close() { +func (v *StdOutLogWriter) Close() { time.Sleep(500 * time.Millisecond) } @@ -52,32 +52,32 @@ type FileLogWriter struct { cancel *signal.CancelSignal } -func (this *FileLogWriter) Log(log LogEntry) { +func (v *FileLogWriter) Log(log LogEntry) { select { - case this.queue <- log.String(): + case v.queue <- log.String(): default: // We don't expect this to happen, but don't want to block main thread as well. } log.Release() } -func (this *FileLogWriter) run() { - this.cancel.WaitThread() - defer this.cancel.FinishThread() +func (v *FileLogWriter) run() { + v.cancel.WaitThread() + defer v.cancel.FinishThread() for { - entry, open := <-this.queue + entry, open := <-v.queue if !open { break } - this.logger.Print(entry + platform.LineSeparator()) + v.logger.Print(entry + platform.LineSeparator()) } } -func (this *FileLogWriter) Close() { - close(this.queue) - this.cancel.WaitForDone() - this.file.Close() +func (v *FileLogWriter) Close() { + close(v.queue) + v.cancel.WaitForDone() + v.file.Close() } func NewFileLogWriter(path string) (*FileLogWriter, error) { diff --git a/common/net/address.go b/common/net/address.go index 150ed9535..85e7e6c8c 100644 --- a/common/net/address.go +++ b/common/net/address.go @@ -20,25 +20,25 @@ const ( AddressFamilyDomain = AddressFamily(2) ) -func (this AddressFamily) Either(fs ...AddressFamily) bool { +func (v AddressFamily) Either(fs ...AddressFamily) bool { for _, f := range fs { - if this == f { + if v == f { return true } } return false } -func (this AddressFamily) IsIPv4() bool { - return this == AddressFamilyIPv4 +func (v AddressFamily) IsIPv4() bool { + return v == AddressFamilyIPv4 } -func (this AddressFamily) IsIPv6() bool { - return this == AddressFamilyIPv6 +func (v AddressFamily) IsIPv6() bool { + return v == AddressFamilyIPv6 } -func (this AddressFamily) IsDomain() bool { - return this == AddressFamilyDomain +func (v AddressFamily) IsDomain() bool { + return v == AddressFamilyDomain } // Address represents a network address to be communicated with. It may be an IP address or domain @@ -104,8 +104,8 @@ func (addr ipv4Address) Family() AddressFamily { return AddressFamilyIPv4 } -func (this ipv4Address) String() string { - return this.IP().String() +func (v ipv4Address) String() string { + return v.IP().String() } type ipv6Address [16]byte @@ -118,12 +118,12 @@ func (addr ipv6Address) Domain() string { panic("Calling Domain() on an IPv6Address.") } -func (this ipv6Address) Family() AddressFamily { +func (v ipv6Address) Family() AddressFamily { return AddressFamilyIPv6 } -func (this ipv6Address) String() string { - return "[" + this.IP().String() + "]" +func (v ipv6Address) String() string { + return "[" + v.IP().String() + "]" } type domainAddress string @@ -140,15 +140,15 @@ func (addr domainAddress) Family() AddressFamily { return AddressFamilyDomain } -func (this domainAddress) String() string { - return this.Domain() +func (v domainAddress) String() string { + return v.Domain() } -func (this *IPOrDomain) AsAddress() Address { - if this == nil { +func (v *IPOrDomain) AsAddress() Address { + if v == nil { return nil } - switch addr := this.Address.(type) { + switch addr := v.Address.(type) { case *IPOrDomain_Ip: return IPAddress(addr.Ip) case *IPOrDomain_Domain: diff --git a/common/net/destination.go b/common/net/destination.go index 450a27f81..4be6aaa6b 100644 --- a/common/net/destination.go +++ b/common/net/destination.go @@ -40,18 +40,18 @@ func UDPDestination(address Address, port Port) Destination { } } -func (this Destination) NetAddr() string { - return this.Address.String() + ":" + this.Port.String() +func (v Destination) NetAddr() string { + return v.Address.String() + ":" + v.Port.String() } -func (this Destination) String() string { - return this.Network.UrlPrefix() + ":" + this.NetAddr() +func (v Destination) String() string { + return v.Network.UrlPrefix() + ":" + v.NetAddr() } -func (this *Endpoint) AsDestination() Destination { +func (v *Endpoint) AsDestination() Destination { return Destination{ - Network: this.Network, - Address: this.Address.AsAddress(), - Port: Port(this.Port), + Network: v.Network, + Address: v.Address.AsAddress(), + Port: Port(v.Port), } } diff --git a/common/net/ipnet.go b/common/net/ipnet.go index de97e39f1..590329e74 100644 --- a/common/net/ipnet.go +++ b/common/net/ipnet.go @@ -35,32 +35,32 @@ func ipMaskToByte(mask net.IPMask) byte { return value } -func (this *IPNet) Add(ipNet *net.IPNet) { +func (v *IPNet) Add(ipNet *net.IPNet) { ipv4 := ipNet.IP.To4() if ipv4 == nil { // For now, we don't support IPv6 return } mask := ipMaskToByte(ipNet.Mask) - this.AddIP(ipv4, mask) + v.AddIP(ipv4, mask) } -func (this *IPNet) AddIP(ip []byte, mask byte) { +func (v *IPNet) AddIP(ip []byte, mask byte) { k := ipToUint32(ip) - existing, found := this.cache[k] + existing, found := v.cache[k] if !found || existing > mask { - this.cache[k] = mask + v.cache[k] = mask } } -func (this *IPNet) Contains(ip net.IP) bool { +func (v *IPNet) Contains(ip net.IP) bool { ipv4 := ip.To4() if ipv4 == nil { return false } originalValue := ipToUint32(ipv4) - if entry, found := this.cache[originalValue]; found { + if entry, found := v.cache[originalValue]; found { if entry == 32 { return true } @@ -71,7 +71,7 @@ func (this *IPNet) Contains(ip net.IP) bool { mask += 1 << uint32(32-maskbit) maskedValue := originalValue & mask - if entry, found := this.cache[maskedValue]; found { + if entry, found := v.cache[maskedValue]; found { if entry == maskbit { return true } @@ -80,8 +80,8 @@ func (this *IPNet) Contains(ip net.IP) bool { return false } -func (this *IPNet) IsEmpty() bool { - return len(this.cache) == 0 +func (v *IPNet) IsEmpty() bool { + return len(v.cache) == 0 } func init() { diff --git a/common/net/network.go b/common/net/network.go index 4afd61544..3c8bcd20d 100644 --- a/common/net/network.go +++ b/common/net/network.go @@ -22,14 +22,14 @@ func ParseNetwork(nwStr string) Network { } } -func (this Network) AsList() *NetworkList { +func (v Network) AsList() *NetworkList { return &NetworkList{ - Network: []Network{this}, + Network: []Network{v}, } } -func (this Network) SystemString() string { - switch this { +func (v Network) SystemString() string { + switch v { case Network_TCP, Network_RawTCP: return "tcp" case Network_UDP, Network_KCP: @@ -39,8 +39,8 @@ func (this Network) SystemString() string { } } -func (this Network) UrlPrefix() string { - switch this { +func (v Network) UrlPrefix() string { + switch v { case Network_TCP, Network_RawTCP: return "tcp" case Network_UDP: @@ -54,9 +54,9 @@ func (this Network) UrlPrefix() string { } } -// HashNetwork returns true if the given network is in this NetworkList. -func (this NetworkList) HasNetwork(network Network) bool { - for _, value := range this.Network { +// HashNetwork returns true if the given network is in v NetworkList. +func (v NetworkList) HasNetwork(network Network) bool { + for _, value := range v.Network { if string(value) == string(network) { return true } @@ -64,6 +64,6 @@ func (this NetworkList) HasNetwork(network Network) bool { return false } -func (this NetworkList) Get(idx int) Network { - return this.Network[idx] +func (v NetworkList) Get(idx int) Network { + return v.Network[idx] } diff --git a/common/net/port.go b/common/net/port.go index 3dbfe9853..185442cc1 100644 --- a/common/net/port.go +++ b/common/net/port.go @@ -40,30 +40,30 @@ func PortFromString(s string) (Port, error) { return PortFromInt(uint32(val)) } -// Value return the correspoding uint16 value of this Port. -func (this Port) Value() uint16 { - return uint16(this) +// Value return the correspoding uint16 value of v Port. +func (v Port) Value() uint16 { + return uint16(v) } -// Bytes returns the correspoding bytes of this Port, in big endian order. -func (this Port) Bytes(b []byte) []byte { - return serial.Uint16ToBytes(this.Value(), b) +// Bytes returns the correspoding bytes of v Port, in big endian order. +func (v Port) Bytes(b []byte) []byte { + return serial.Uint16ToBytes(v.Value(), b) } -// String returns the string presentation of this Port. -func (this Port) String() string { - return serial.Uint16ToString(this.Value()) +// String returns the string presentation of v Port. +func (v Port) String() string { + return serial.Uint16ToString(v.Value()) } -func (this PortRange) FromPort() Port { - return Port(this.From) +func (v PortRange) FromPort() Port { + return Port(v.From) } -func (this PortRange) ToPort() Port { - return Port(this.To) +func (v PortRange) ToPort() Port { + return Port(v.To) } -// Contains returns true if the given port is within the range of this PortRange. -func (this PortRange) Contains(port Port) bool { - return this.FromPort() <= port && port <= this.ToPort() +// Contains returns true if the given port is within the range of v PortRange. +func (v PortRange) Contains(port Port) bool { + return v.FromPort() <= port && port <= v.ToPort() } diff --git a/common/net/timed_io.go b/common/net/timed_io.go index 60e6bdbf8..a56127e17 100644 --- a/common/net/timed_io.go +++ b/common/net/timed_io.go @@ -60,11 +60,11 @@ type timedReaderWorker struct { connection net.Conn } -func (this *timedReaderWorker) Read(p []byte) (int, error) { - deadline := time.Duration(this.timeout) * time.Second - this.connection.SetReadDeadline(time.Now().Add(deadline)) - nBytes, err := this.connection.Read(p) - this.connection.SetReadDeadline(emptyTime) +func (v *timedReaderWorker) Read(p []byte) (int, error) { + deadline := time.Duration(v.timeout) * time.Second + v.connection.SetReadDeadline(time.Now().Add(deadline)) + nBytes, err := v.connection.Read(p) + v.connection.SetReadDeadline(emptyTime) return nBytes, err } @@ -72,6 +72,6 @@ type noOpReaderWorker struct { connection net.Conn } -func (this *noOpReaderWorker) Read(p []byte) (int, error) { - return this.connection.Read(p) +func (v *noOpReaderWorker) Read(p []byte) (int, error) { + return v.connection.Read(p) } diff --git a/common/predicate/predicate.go b/common/predicate/predicate.go index c6c2e3487..326ceba1f 100644 --- a/common/predicate/predicate.go +++ b/common/predicate/predicate.go @@ -2,12 +2,12 @@ package predicate type Predicate func() bool -func (this Predicate) And(predicate Predicate) Predicate { - return All(this, predicate) +func (v Predicate) And(predicate Predicate) Predicate { + return All(v, predicate) } -func (this Predicate) Or(predicate Predicate) Predicate { - return Any(this, predicate) +func (v Predicate) Or(predicate Predicate) Predicate { + return Any(v, predicate) } func All(predicates ...Predicate) Predicate { diff --git a/common/protocol/headers.go b/common/protocol/headers.go index 597f7256d..1c38c5df1 100644 --- a/common/protocol/headers.go +++ b/common/protocol/headers.go @@ -19,16 +19,16 @@ const ( RequestOptionConnectionReuse = RequestOption(0x02) ) -func (this RequestOption) Has(option RequestOption) bool { - return (this & option) == option +func (v RequestOption) Has(option RequestOption) bool { + return (v & option) == option } -func (this *RequestOption) Set(option RequestOption) { - *this = (*this | option) +func (v *RequestOption) Set(option RequestOption) { + *v = (*v | option) } -func (this *RequestOption) Clear(option RequestOption) { - *this = (*this & (^option)) +func (v *RequestOption) Clear(option RequestOption) { + *v = (*v & (^option)) } type RequestHeader struct { @@ -40,11 +40,11 @@ type RequestHeader struct { Port v2net.Port } -func (this *RequestHeader) Destination() v2net.Destination { - if this.Command == RequestCommandUDP { - return v2net.UDPDestination(this.Address, this.Port) +func (v *RequestHeader) Destination() v2net.Destination { + if v.Command == RequestCommandUDP { + return v2net.UDPDestination(v.Address, v.Port) } - return v2net.TCPDestination(this.Address, this.Port) + return v2net.TCPDestination(v.Address, v.Port) } type ResponseOption byte @@ -53,16 +53,16 @@ const ( ResponseOptionConnectionReuse = ResponseOption(1) ) -func (this *ResponseOption) Set(option ResponseOption) { - *this = (*this | option) +func (v *ResponseOption) Set(option ResponseOption) { + *v = (*v | option) } -func (this ResponseOption) Has(option ResponseOption) bool { - return (this | option) == option +func (v ResponseOption) Has(option ResponseOption) bool { + return (v | option) == option } -func (this *ResponseOption) Clear(option ResponseOption) { - *this = (*this & (^option)) +func (v *ResponseOption) Clear(option ResponseOption) { + *v = (*v & (^option)) } type ResponseCommand interface{} diff --git a/common/protocol/id.go b/common/protocol/id.go index be31b655d..9c74ce445 100644 --- a/common/protocol/id.go +++ b/common/protocol/id.go @@ -29,20 +29,20 @@ type ID struct { cmdKey [IDBytesLen]byte } -func (this *ID) Equals(another *ID) bool { - return this.uuid.Equals(another.uuid) +func (v *ID) Equals(another *ID) bool { + return v.uuid.Equals(another.uuid) } -func (this *ID) Bytes() []byte { - return this.uuid.Bytes() +func (v *ID) Bytes() []byte { + return v.uuid.Bytes() } -func (this *ID) String() string { - return this.uuid.String() +func (v *ID) String() string { + return v.uuid.String() } -func (this *ID) UUID() *uuid.UUID { - return this.uuid +func (v *ID) UUID() *uuid.UUID { + return v.uuid } func (v ID) CmdKey() []byte { diff --git a/common/protocol/server_picker.go b/common/protocol/server_picker.go index 7773bd014..8665843ba 100644 --- a/common/protocol/server_picker.go +++ b/common/protocol/server_picker.go @@ -13,32 +13,32 @@ func NewServerList() *ServerList { return &ServerList{} } -func (this *ServerList) AddServer(server *ServerSpec) { - this.Lock() - defer this.Unlock() +func (v *ServerList) AddServer(server *ServerSpec) { + v.Lock() + defer v.Unlock() - this.servers = append(this.servers, server) + v.servers = append(v.servers, server) } -func (this *ServerList) Size() uint32 { - this.RLock() - defer this.RUnlock() +func (v *ServerList) Size() uint32 { + v.RLock() + defer v.RUnlock() - return uint32(len(this.servers)) + return uint32(len(v.servers)) } -func (this *ServerList) GetServer(idx uint32) *ServerSpec { - this.RLock() - defer this.RUnlock() +func (v *ServerList) GetServer(idx uint32) *ServerSpec { + v.RLock() + defer v.RUnlock() for { - if idx >= uint32(len(this.servers)) { + if idx >= uint32(len(v.servers)) { return nil } - server := this.servers[idx] + server := v.servers[idx] if !server.IsValid() { - this.RemoveServer(idx) + v.RemoveServer(idx) continue } @@ -47,10 +47,10 @@ func (this *ServerList) GetServer(idx uint32) *ServerSpec { } // Private: Visible for testing. -func (this *ServerList) RemoveServer(idx uint32) { - n := len(this.servers) - this.servers[idx] = this.servers[n-1] - this.servers = this.servers[:n-1] +func (v *ServerList) RemoveServer(idx uint32) { + n := len(v.servers) + v.servers[idx] = v.servers[n-1] + v.servers = v.servers[:n-1] } type ServerPicker interface { @@ -70,21 +70,21 @@ func NewRoundRobinServerPicker(serverlist *ServerList) *RoundRobinServerPicker { } } -func (this *RoundRobinServerPicker) PickServer() *ServerSpec { - this.Lock() - defer this.Unlock() +func (v *RoundRobinServerPicker) PickServer() *ServerSpec { + v.Lock() + defer v.Unlock() - next := this.nextIndex - server := this.serverlist.GetServer(next) + next := v.nextIndex + server := v.serverlist.GetServer(next) if server == nil { next = 0 - server = this.serverlist.GetServer(0) + server = v.serverlist.GetServer(0) } next++ - if next >= this.serverlist.Size() { + if next >= v.serverlist.Size() { next = 0 } - this.nextIndex = next + v.nextIndex = next return server } diff --git a/common/protocol/server_spec.go b/common/protocol/server_spec.go index 138a566a1..d8444bf86 100644 --- a/common/protocol/server_spec.go +++ b/common/protocol/server_spec.go @@ -19,11 +19,11 @@ func AlwaysValid() ValidationStrategy { return AlwaysValidStrategy{} } -func (this AlwaysValidStrategy) IsValid() bool { +func (v AlwaysValidStrategy) IsValid() bool { return true } -func (this AlwaysValidStrategy) Invalidate() {} +func (v AlwaysValidStrategy) Invalidate() {} type TimeoutValidStrategy struct { until time.Time @@ -35,12 +35,12 @@ func BeforeTime(t time.Time) ValidationStrategy { } } -func (this *TimeoutValidStrategy) IsValid() bool { - return this.until.After(time.Now()) +func (v *TimeoutValidStrategy) IsValid() bool { + return v.until.After(time.Now()) } -func (this *TimeoutValidStrategy) Invalidate() { - this.until = time.Time{} +func (v *TimeoutValidStrategy) Invalidate() { + v.until = time.Time{} } type ServerSpec struct { @@ -63,19 +63,19 @@ func NewServerSpecFromPB(spec ServerEndpoint) *ServerSpec { return NewServerSpec(dest, AlwaysValid(), spec.User...) } -func (this *ServerSpec) Destination() v2net.Destination { - return this.dest +func (v *ServerSpec) Destination() v2net.Destination { + return v.dest } -func (this *ServerSpec) HasUser(user *User) bool { - this.RLock() - defer this.RUnlock() +func (v *ServerSpec) HasUser(user *User) bool { + v.RLock() + defer v.RUnlock() accountA, err := user.GetTypedAccount() if err != nil { return false } - for _, u := range this.users { + for _, u := range v.users { accountB, err := u.GetTypedAccount() if err == nil && accountA.Equals(accountB) { return true @@ -84,26 +84,26 @@ func (this *ServerSpec) HasUser(user *User) bool { return false } -func (this *ServerSpec) AddUser(user *User) { - if this.HasUser(user) { +func (v *ServerSpec) AddUser(user *User) { + if v.HasUser(user) { return } - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - this.users = append(this.users, user) + v.users = append(v.users, user) } -func (this *ServerSpec) PickUser() *User { - userCount := len(this.users) - return this.users[dice.Roll(userCount)] +func (v *ServerSpec) PickUser() *User { + userCount := len(v.users) + return v.users[dice.Roll(userCount)] } -func (this *ServerSpec) IsValid() bool { - return this.valid.IsValid() +func (v *ServerSpec) IsValid() bool { + return v.valid.IsValid() } -func (this *ServerSpec) Invalidate() { - this.valid.Invalidate() +func (v *ServerSpec) Invalidate() { + v.valid.Invalidate() } diff --git a/common/protocol/time.go b/common/protocol/time.go index c7156f632..10a585d2d 100644 --- a/common/protocol/time.go +++ b/common/protocol/time.go @@ -9,8 +9,8 @@ import ( type Timestamp int64 -func (this Timestamp) Bytes(b []byte) []byte { - return serial.Int64ToBytes(int64(this), b) +func (v Timestamp) Bytes(b []byte) []byte { + return serial.Int64ToBytes(int64(v), b) } type TimestampGenerator func() Timestamp diff --git a/common/protocol/user.go b/common/protocol/user.go index 91551d0e3..abc204468 100644 --- a/common/protocol/user.go +++ b/common/protocol/user.go @@ -11,12 +11,12 @@ var ( ErrUnknownAccountType = errors.New("Unknown account type.") ) -func (this *User) GetTypedAccount() (Account, error) { - if this.GetAccount() == nil { +func (v *User) GetTypedAccount() (Account, error) { + if v.GetAccount() == nil { return nil, ErrAccountMissing } - rawAccount, err := this.Account.GetInstance() + rawAccount, err := v.Account.GetInstance() if err != nil { return nil, err } @@ -26,14 +26,14 @@ func (this *User) GetTypedAccount() (Account, error) { if account, ok := rawAccount.(Account); ok { return account, nil } - return nil, errors.New("Unknown account type: " + this.Account.Type) + return nil, errors.New("Unknown account type: " + v.Account.Type) } -func (this *User) GetSettings() UserSettings { +func (v *User) GetSettings() UserSettings { settings := UserSettings{ PayloadReadTimeout: 120, } - if this.Level > 0 { + if v.Level > 0 { settings.PayloadReadTimeout = 0 } return settings diff --git a/common/signal/cancel.go b/common/signal/cancel.go index 53ad7fa85..2a46cdc82 100644 --- a/common/signal/cancel.go +++ b/common/signal/cancel.go @@ -17,18 +17,18 @@ func NewCloseSignal() *CancelSignal { } } -func (this *CancelSignal) WaitThread() { - this.done.Add(1) +func (v *CancelSignal) WaitThread() { + v.done.Add(1) } // Cancel signals the goroutine to stop. -func (this *CancelSignal) Cancel() { - close(this.cancel) +func (v *CancelSignal) Cancel() { + close(v.cancel) } -func (this *CancelSignal) Cancelled() bool { +func (v *CancelSignal) Cancelled() bool { select { - case <-this.cancel: + case <-v.cancel: return true default: return false @@ -36,16 +36,16 @@ func (this *CancelSignal) Cancelled() bool { } // WaitForCancel should be monitored by the goroutine for when to stop. -func (this *CancelSignal) WaitForCancel() <-chan struct{} { - return this.cancel +func (v *CancelSignal) WaitForCancel() <-chan struct{} { + return v.cancel } // FinishThread signals that current goroutine has finished. -func (this *CancelSignal) FinishThread() { - this.done.Done() +func (v *CancelSignal) FinishThread() { + v.done.Done() } // WaitForDone is used by caller to wait for the goroutine finishes. -func (this *CancelSignal) WaitForDone() { - this.done.Wait() +func (v *CancelSignal) WaitForDone() { + v.done.Wait() } diff --git a/common/uuid/uuid.go b/common/uuid/uuid.go index 4a9dccfce..77170d90b 100644 --- a/common/uuid/uuid.go +++ b/common/uuid/uuid.go @@ -17,35 +17,35 @@ var ( type UUID [16]byte // String returns the string representation of this UUID. -func (this *UUID) String() string { - return bytesToString(this.Bytes()) +func (v *UUID) String() string { + return bytesToString(v.Bytes()) } // Bytes returns the bytes representation of this UUID. -func (this *UUID) Bytes() []byte { - return this[:] +func (v *UUID) Bytes() []byte { + return v[:] } // Equals returns true if this UUID equals another UUID by value. -func (this *UUID) Equals(another *UUID) bool { - if this == nil && another == nil { +func (v *UUID) Equals(another *UUID) bool { + if v == nil && another == nil { return true } - if this == nil || another == nil { + if v == nil || another == nil { return false } - return bytes.Equal(this.Bytes(), another.Bytes()) + return bytes.Equal(v.Bytes(), another.Bytes()) } // Next generates a deterministic random UUID based on this UUID. -func (this *UUID) Next() *UUID { +func (v *UUID) Next() *UUID { md5hash := md5.New() - md5hash.Write(this.Bytes()) + md5hash.Write(v.Bytes()) md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")) newid := new(UUID) for { md5hash.Sum(newid[:0]) - if !newid.Equals(this) { + if !newid.Equals(v) { return newid } md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")) diff --git a/config.go b/config.go index a3d543ffd..cf0945161 100644 --- a/config.go +++ b/config.go @@ -5,51 +5,51 @@ import ( v2net "v2ray.com/core/common/net" ) -func (this *AllocationStrategyConcurrency) GetValue() uint32 { - if this == nil { +func (v *AllocationStrategyConcurrency) GetValue() uint32 { + if v == nil { return 3 } - return this.Value + return v.Value } -func (this *AllocationStrategyRefresh) GetValue() uint32 { - if this == nil { +func (v *AllocationStrategyRefresh) GetValue() uint32 { + if v == nil { return 5 } - return this.Value + return v.Value } -func (this *InboundConnectionConfig) GetAllocationStrategyValue() *AllocationStrategy { - if this.AllocationStrategy == nil { +func (v *InboundConnectionConfig) GetAllocationStrategyValue() *AllocationStrategy { + if v.AllocationStrategy == nil { return &AllocationStrategy{} } - return this.AllocationStrategy + return v.AllocationStrategy } -func (this *InboundConnectionConfig) GetListenOnValue() v2net.Address { - if this.GetListenOn() == nil { +func (v *InboundConnectionConfig) GetListenOnValue() v2net.Address { + if v.GetListenOn() == nil { return v2net.AnyIP } - return this.ListenOn.AsAddress() + return v.ListenOn.AsAddress() } -func (this *InboundConnectionConfig) GetTypedSettings() (interface{}, error) { - if this.GetSettings() == nil { +func (v *InboundConnectionConfig) GetTypedSettings() (interface{}, error) { + if v.GetSettings() == nil { return nil, common.ErrBadConfiguration } - return this.GetSettings().GetInstance() + return v.GetSettings().GetInstance() } -func (this *OutboundConnectionConfig) GetTypedSettings() (interface{}, error) { - if this.GetSettings() == nil { +func (v *OutboundConnectionConfig) GetTypedSettings() (interface{}, error) { + if v.GetSettings() == nil { return nil, common.ErrBadConfiguration } - return this.GetSettings().GetInstance() + return v.GetSettings().GetInstance() } -func (this *OutboundConnectionConfig) GetSendThroughValue() v2net.Address { - if this.GetSendThrough() == nil { +func (v *OutboundConnectionConfig) GetSendThroughValue() v2net.Address { + if v.GetSendThrough() == nil { return v2net.AnyIP } - return this.SendThrough.AsAddress() + return v.SendThrough.AsAddress() } diff --git a/inbound_detour_always.go b/inbound_detour_always.go index e1b7cc06f..2213aa66f 100644 --- a/inbound_detour_always.go +++ b/inbound_detour_always.go @@ -44,20 +44,20 @@ func NewInboundDetourHandlerAlways(space app.Space, config *InboundConnectionCon return handler, nil } -func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) { - ich := this.ich[dice.Roll(len(this.ich))] - return ich, int(this.config.GetAllocationStrategyValue().Refresh.GetValue()) +func (v *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) { + ich := v.ich[dice.Roll(len(v.ich))] + return ich, int(v.config.GetAllocationStrategyValue().Refresh.GetValue()) } -func (this *InboundDetourHandlerAlways) Close() { - for _, ich := range this.ich { +func (v *InboundDetourHandlerAlways) Close() { + for _, ich := range v.ich { ich.Close() } } // Starts the inbound connection handler. -func (this *InboundDetourHandlerAlways) Start() error { - for _, ich := range this.ich { +func (v *InboundDetourHandlerAlways) Start() error { + for _, ich := range v.ich { err := retry.ExponentialBackoff(10 /* times */, 200 /* ms */).On(func() error { err := ich.Start() if err != nil { diff --git a/inbound_detour_dynamic.go b/inbound_detour_dynamic.go index 05a588f6c..7740e677e 100644 --- a/inbound_detour_dynamic.go +++ b/inbound_detour_dynamic.go @@ -52,74 +52,74 @@ func NewInboundDetourHandlerDynamic(space app.Space, config *InboundConnectionCo return handler, nil } -func (this *InboundDetourHandlerDynamic) pickUnusedPort() v2net.Port { - delta := int(this.config.PortRange.To) - int(this.config.PortRange.From) + 1 +func (v *InboundDetourHandlerDynamic) pickUnusedPort() v2net.Port { + delta := int(v.config.PortRange.To) - int(v.config.PortRange.From) + 1 for { r := dice.Roll(delta) - port := this.config.PortRange.FromPort() + v2net.Port(r) - _, used := this.portsInUse[port] + port := v.config.PortRange.FromPort() + v2net.Port(r) + _, used := v.portsInUse[port] if !used { return port } } } -func (this *InboundDetourHandlerDynamic) GetConnectionHandler() (proxy.InboundHandler, int) { - this.RLock() - defer this.RUnlock() - ich := this.ichs[dice.Roll(len(this.ichs))] - until := int(this.config.GetAllocationStrategyValue().Refresh.GetValue()) - int((time.Now().Unix()-this.lastRefresh.Unix())/60/1000) +func (v *InboundDetourHandlerDynamic) GetConnectionHandler() (proxy.InboundHandler, int) { + v.RLock() + defer v.RUnlock() + ich := v.ichs[dice.Roll(len(v.ichs))] + until := int(v.config.GetAllocationStrategyValue().Refresh.GetValue()) - int((time.Now().Unix()-v.lastRefresh.Unix())/60/1000) if until < 0 { until = 0 } return ich, int(until) } -func (this *InboundDetourHandlerDynamic) Close() { - this.Lock() - defer this.Unlock() - for _, ich := range this.ichs { +func (v *InboundDetourHandlerDynamic) Close() { + v.Lock() + defer v.Unlock() + for _, ich := range v.ichs { ich.Close() } } -func (this *InboundDetourHandlerDynamic) RecyleHandles() { - if this.ich2Recyle != nil { - for _, ich := range this.ich2Recyle { +func (v *InboundDetourHandlerDynamic) RecyleHandles() { + if v.ich2Recyle != nil { + for _, ich := range v.ich2Recyle { if ich == nil { continue } port := ich.Port() ich.Close() - delete(this.portsInUse, port) + delete(v.portsInUse, port) } - this.ich2Recyle = nil + v.ich2Recyle = nil } } -func (this *InboundDetourHandlerDynamic) refresh() error { - this.lastRefresh = time.Now() +func (v *InboundDetourHandlerDynamic) refresh() error { + v.lastRefresh = time.Now() - config := this.config - this.ich2Recyle = this.ichs + config := v.config + v.ich2Recyle = v.ichs newIchs := make([]proxy.InboundHandler, config.GetAllocationStrategyValue().Concurrency.GetValue()) for idx := range newIchs { err := retry.Timed(5, 100).On(func() error { - port := this.pickUnusedPort() + port := v.pickUnusedPort() ichConfig, _ := config.GetTypedSettings() - ich, err := proxyregistry.CreateInboundHandler(config.Settings.Type, this.space, ichConfig, &proxy.InboundHandlerMeta{ + ich, err := proxyregistry.CreateInboundHandler(config.Settings.Type, v.space, ichConfig, &proxy.InboundHandlerMeta{ Address: config.GetListenOnValue(), Port: port, Tag: config.Tag, StreamSettings: config.StreamSettings}) if err != nil { - delete(this.portsInUse, port) + delete(v.portsInUse, port) return err } err = ich.Start() if err != nil { - delete(this.portsInUse, port) + delete(v.portsInUse, port) return err } - this.portsInUse[port] = true + v.portsInUse[port] = true newIchs[idx] = ich return nil }) @@ -129,15 +129,15 @@ func (this *InboundDetourHandlerDynamic) refresh() error { } } - this.Lock() - this.ichs = newIchs - this.Unlock() + v.Lock() + v.ichs = newIchs + v.Unlock() return nil } -func (this *InboundDetourHandlerDynamic) Start() error { - err := this.refresh() +func (v *InboundDetourHandlerDynamic) Start() error { + err := v.refresh() if err != nil { log.Error("Point: Failed to refresh dynamic allocations: ", err) return err @@ -145,9 +145,9 @@ func (this *InboundDetourHandlerDynamic) Start() error { go func() { for { - time.Sleep(time.Duration(this.config.GetAllocationStrategyValue().Refresh.GetValue())*time.Minute - 1) - this.RecyleHandles() - err := this.refresh() + time.Sleep(time.Duration(v.config.GetAllocationStrategyValue().Refresh.GetValue())*time.Minute - 1) + v.RecyleHandles() + err := v.refresh() if err != nil { log.Error("Point: Failed to refresh dynamic allocations: ", err) } diff --git a/proxy/blackhole/blackhole.go b/proxy/blackhole/blackhole.go index 24c6cc7a5..b176dad00 100644 --- a/proxy/blackhole/blackhole.go +++ b/proxy/blackhole/blackhole.go @@ -25,10 +25,10 @@ func NewBlackHole(space app.Space, config *Config, meta *proxy.OutboundHandlerMe }, nil } -func (this *BlackHole) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { +func (v *BlackHole) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { payload.Release() - this.response.WriteTo(ray.OutboundOutput()) + v.response.WriteTo(ray.OutboundOutput()) ray.OutboundOutput().Close() ray.OutboundInput().Release() @@ -38,12 +38,12 @@ func (this *BlackHole) Dispatch(destination v2net.Destination, payload *alloc.Bu type Factory struct{} -func (this *Factory) StreamCapability() v2net.NetworkList { +func (v *Factory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_RawTCP}, } } -func (this *Factory) Create(space app.Space, config interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { +func (v *Factory) Create(space app.Space, config interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { return NewBlackHole(space, config.(*Config), meta) } diff --git a/proxy/blackhole/config.go b/proxy/blackhole/config.go index aa96d6e00..b8804f0df 100644 --- a/proxy/blackhole/config.go +++ b/proxy/blackhole/config.go @@ -23,28 +23,28 @@ type ResponseConfig interface { WriteTo(v2io.Writer) } -func (this *NoneResponse) WriteTo(v2io.Writer) {} +func (v *NoneResponse) WriteTo(v2io.Writer) {} -func (this *NoneResponse) AsAny() *any.Any { - r, _ := ptypes.MarshalAny(this) +func (v *NoneResponse) AsAny() *any.Any { + r, _ := ptypes.MarshalAny(v) return r } -func (this *HTTPResponse) WriteTo(writer v2io.Writer) { +func (v *HTTPResponse) WriteTo(writer v2io.Writer) { writer.Write(alloc.NewLocalBuffer(512).Clear().AppendString(http403response)) } -func (this *HTTPResponse) AsAny() *any.Any { - r, _ := ptypes.MarshalAny(this) +func (v *HTTPResponse) AsAny() *any.Any { + r, _ := ptypes.MarshalAny(v) return r } -func (this *Config) GetInternalResponse() (ResponseConfig, error) { - if this.GetResponse() == nil { +func (v *Config) GetInternalResponse() (ResponseConfig, error) { + if v.GetResponse() == nil { return new(NoneResponse), nil } - config, err := this.GetResponse().GetInstance() + config, err := v.GetResponse().GetInstance() if err != nil { return nil, err } diff --git a/proxy/dokodemo/config.go b/proxy/dokodemo/config.go index 76847eb2b..45bf84ba8 100644 --- a/proxy/dokodemo/config.go +++ b/proxy/dokodemo/config.go @@ -4,8 +4,8 @@ import ( v2net "v2ray.com/core/common/net" ) -func (this *Config) GetPredefinedAddress() v2net.Address { - addr := this.Address.AsAddress() +func (v *Config) GetPredefinedAddress() v2net.Address { + addr := v.Address.AsAddress() if addr == nil { return nil } diff --git a/proxy/dokodemo/dokodemo.go b/proxy/dokodemo/dokodemo.go index 7f1187ec9..8a99e5714 100644 --- a/proxy/dokodemo/dokodemo.go +++ b/proxy/dokodemo/dokodemo.go @@ -48,40 +48,40 @@ func NewDokodemoDoor(config *Config, space app.Space, meta *proxy.InboundHandler return d } -func (this *DokodemoDoor) Port() v2net.Port { - return this.meta.Port +func (v *DokodemoDoor) Port() v2net.Port { + return v.meta.Port } -func (this *DokodemoDoor) Close() { - this.accepting = false - if this.tcpListener != nil { - this.tcpMutex.Lock() - this.tcpListener.Close() - this.tcpListener = nil - this.tcpMutex.Unlock() +func (v *DokodemoDoor) Close() { + v.accepting = false + if v.tcpListener != nil { + v.tcpMutex.Lock() + v.tcpListener.Close() + v.tcpListener = nil + v.tcpMutex.Unlock() } - if this.udpHub != nil { - this.udpMutex.Lock() - this.udpHub.Close() - this.udpHub = nil - this.udpMutex.Unlock() + if v.udpHub != nil { + v.udpMutex.Lock() + v.udpHub.Close() + v.udpHub = nil + v.udpMutex.Unlock() } } -func (this *DokodemoDoor) Start() error { - if this.accepting { +func (v *DokodemoDoor) Start() error { + if v.accepting { return nil } - this.accepting = true + v.accepting = true - if this.config.NetworkList.HasNetwork(v2net.Network_TCP) { - err := this.ListenTCP() + if v.config.NetworkList.HasNetwork(v2net.Network_TCP) { + err := v.ListenTCP() if err != nil { return err } } - if this.config.NetworkList.HasNetwork(v2net.Network_UDP) { - err := this.ListenUDP() + if v.config.NetworkList.HasNetwork(v2net.Network_UDP) { + err := v.ListenUDP() if err != nil { return err } @@ -89,71 +89,71 @@ func (this *DokodemoDoor) Start() error { return nil } -func (this *DokodemoDoor) ListenUDP() error { - this.udpServer = udp.NewUDPServer(this.packetDispatcher) +func (v *DokodemoDoor) ListenUDP() error { + v.udpServer = udp.NewUDPServer(v.packetDispatcher) udpHub, err := udp.ListenUDP( - this.meta.Address, this.meta.Port, udp.ListenOption{ - Callback: this.handleUDPPackets, - ReceiveOriginalDest: this.config.FollowRedirect, + v.meta.Address, v.meta.Port, udp.ListenOption{ + Callback: v.handleUDPPackets, + ReceiveOriginalDest: v.config.FollowRedirect, Concurrency: 2, }) if err != nil { - log.Error("Dokodemo failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("Dokodemo failed to listen on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.udpMutex.Lock() - this.udpHub = udpHub - this.udpMutex.Unlock() + v.udpMutex.Lock() + v.udpHub = udpHub + v.udpMutex.Unlock() return nil } -func (this *DokodemoDoor) handleUDPPackets(payload *alloc.Buffer, session *proxy.SessionInfo) { - if session.Destination.Network == v2net.Network_Unknown && this.address != nil && this.port > 0 { - session.Destination = v2net.UDPDestination(this.address, this.port) +func (v *DokodemoDoor) handleUDPPackets(payload *alloc.Buffer, session *proxy.SessionInfo) { + if session.Destination.Network == v2net.Network_Unknown && v.address != nil && v.port > 0 { + session.Destination = v2net.UDPDestination(v.address, v.port) } if session.Destination.Network == v2net.Network_Unknown { log.Info("Dokodemo: Unknown destination, stop forwarding...") return } - session.Inbound = this.meta - this.udpServer.Dispatch(session, payload, this.handleUDPResponse) + session.Inbound = v.meta + v.udpServer.Dispatch(session, payload, v.handleUDPResponse) } -func (this *DokodemoDoor) handleUDPResponse(dest v2net.Destination, payload *alloc.Buffer) { +func (v *DokodemoDoor) handleUDPResponse(dest v2net.Destination, payload *alloc.Buffer) { defer payload.Release() - this.udpMutex.RLock() - defer this.udpMutex.RUnlock() - if !this.accepting { + v.udpMutex.RLock() + defer v.udpMutex.RUnlock() + if !v.accepting { return } - this.udpHub.WriteTo(payload.Value, dest) + v.udpHub.WriteTo(payload.Value, dest) } -func (this *DokodemoDoor) ListenTCP() error { - tcpListener, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.HandleTCPConnection, this.meta.StreamSettings) +func (v *DokodemoDoor) ListenTCP() error { + tcpListener, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.HandleTCPConnection, v.meta.StreamSettings) if err != nil { - log.Error("Dokodemo: Failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("Dokodemo: Failed to listen on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.tcpMutex.Lock() - this.tcpListener = tcpListener - this.tcpMutex.Unlock() + v.tcpMutex.Lock() + v.tcpListener = tcpListener + v.tcpMutex.Unlock() return nil } -func (this *DokodemoDoor) HandleTCPConnection(conn internet.Connection) { +func (v *DokodemoDoor) HandleTCPConnection(conn internet.Connection) { defer conn.Close() var dest v2net.Destination - if this.config.FollowRedirect { + if v.config.FollowRedirect { originalDest := GetOriginalDestination(conn) if originalDest.Network != v2net.Network_Unknown { log.Info("Dokodemo: Following redirect to: ", originalDest) dest = originalDest } } - if dest.Network == v2net.Network_Unknown && this.address != nil && this.port > v2net.Port(0) { - dest = v2net.TCPDestination(this.address, this.port) + if dest.Network == v2net.Network_Unknown && v.address != nil && v.port > v2net.Port(0) { + dest = v2net.TCPDestination(v.address, v.port) } if dest.Network == v2net.Network_Unknown { @@ -162,16 +162,16 @@ func (this *DokodemoDoor) HandleTCPConnection(conn internet.Connection) { } log.Info("Dokodemo: Handling request to ", dest) - ray := this.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ + ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.DestinationFromAddr(conn.RemoteAddr()), Destination: dest, - Inbound: this.meta, + Inbound: v.meta, }) defer ray.InboundOutput().Release() var wg sync.WaitGroup - reader := v2net.NewTimeOutReader(this.config.Timeout, conn) + reader := v2net.NewTimeOutReader(v.config.Timeout, conn) defer reader.Release() wg.Add(1) @@ -202,13 +202,13 @@ func (this *DokodemoDoor) HandleTCPConnection(conn internet.Connection) { type Factory struct{} -func (this *Factory) StreamCapability() v2net.NetworkList { +func (v *Factory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_RawTCP}, } } -func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { +func (v *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { return NewDokodemoDoor(rawConfig.(*Config), space, meta), nil } diff --git a/proxy/freedom/freedom.go b/proxy/freedom/freedom.go index bf036eef8..982420a2d 100644 --- a/proxy/freedom/freedom.go +++ b/proxy/freedom/freedom.go @@ -45,12 +45,12 @@ func NewFreedomConnection(config *Config, space app.Space, meta *proxy.OutboundH } // Private: Visible for testing. -func (this *FreedomConnection) ResolveIP(destination v2net.Destination) v2net.Destination { +func (v *FreedomConnection) ResolveIP(destination v2net.Destination) v2net.Destination { if !destination.Address.Family().IsDomain() { return destination } - ips := this.dns.Get(destination.Address.Domain()) + ips := v.dns.Get(destination.Address.Domain()) if len(ips) == 0 { log.Info("Freedom: DNS returns nil answer. Keep domain as is.") return destination @@ -67,7 +67,7 @@ func (this *FreedomConnection) ResolveIP(destination v2net.Destination) v2net.De return newDest } -func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { +func (v *FreedomConnection) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { log.Info("Freedom: Opening connection to ", destination) defer payload.Release() @@ -75,11 +75,11 @@ func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload * defer ray.OutboundOutput().Close() var conn internet.Connection - if this.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() { - destination = this.ResolveIP(destination) + if v.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() { + destination = v.ResolveIP(destination) } err := retry.ExponentialBackoff(5, 100).On(func() error { - rawConn, err := internet.Dial(this.meta.Address, destination, this.meta.GetDialerOptions()) + rawConn, err := internet.Dial(v.meta.Address, destination, v.meta.GetDialerOptions()) if err != nil { return err } @@ -113,7 +113,7 @@ func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload * var reader io.Reader = conn - timeout := this.timeout + timeout := v.timeout if destination.Network == v2net.Network_UDP { timeout = 16 } @@ -133,13 +133,13 @@ func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload * type FreedomFactory struct{} -func (this *FreedomFactory) StreamCapability() v2net.NetworkList { +func (v *FreedomFactory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_RawTCP}, } } -func (this *FreedomFactory) Create(space app.Space, config interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { +func (v *FreedomFactory) Create(space app.Space, config interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { return NewFreedomConnection(config.(*Config), space, meta), nil } diff --git a/proxy/http/server.go b/proxy/http/server.go index 56fdc8081..4a5d19c0e 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -40,34 +40,34 @@ func NewServer(config *ServerConfig, packetDispatcher dispatcher.PacketDispatche } } -func (this *Server) Port() v2net.Port { - return this.meta.Port +func (v *Server) Port() v2net.Port { + return v.meta.Port } -func (this *Server) Close() { - this.accepting = false - if this.tcpListener != nil { - this.Lock() - this.tcpListener.Close() - this.tcpListener = nil - this.Unlock() +func (v *Server) Close() { + v.accepting = false + if v.tcpListener != nil { + v.Lock() + v.tcpListener.Close() + v.tcpListener = nil + v.Unlock() } } -func (this *Server) Start() error { - if this.accepting { +func (v *Server) Start() error { + if v.accepting { return nil } - tcpListener, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, this.meta.StreamSettings) + tcpListener, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.handleConnection, v.meta.StreamSettings) if err != nil { - log.Error("HTTP: Failed listen on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("HTTP: Failed listen on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.Lock() - this.tcpListener = tcpListener - this.Unlock() - this.accepting = true + v.Lock() + v.tcpListener = tcpListener + v.Unlock() + v.accepting = true return nil } @@ -94,9 +94,9 @@ func parseHost(rawHost string, defaultPort v2net.Port) (v2net.Destination, error return v2net.TCPDestination(v2net.DomainAddress(host), port), nil } -func (this *Server) handleConnection(conn internet.Connection) { +func (v *Server) handleConnection(conn internet.Connection) { defer conn.Close() - timedReader := v2net.NewTimeOutReader(this.config.Timeout, conn) + timedReader := v2net.NewTimeOutReader(v.config.Timeout, conn) reader := bufio.NewReaderSize(timedReader, 2048) request, err := http.ReadRequest(reader) @@ -124,16 +124,16 @@ func (this *Server) handleConnection(conn internet.Connection) { session := &proxy.SessionInfo{ Source: v2net.DestinationFromAddr(conn.RemoteAddr()), Destination: dest, - Inbound: this.meta, + Inbound: v.meta, } if strings.ToUpper(request.Method) == "CONNECT" { - this.handleConnect(request, session, reader, conn) + v.handleConnect(request, session, reader, conn) } else { - this.handlePlainHTTP(request, session, reader, conn) + v.handlePlainHTTP(request, session, reader, conn) } } -func (this *Server) handleConnect(request *http.Request, session *proxy.SessionInfo, reader io.Reader, writer io.Writer) { +func (v *Server) handleConnect(request *http.Request, session *proxy.SessionInfo, reader io.Reader, writer io.Writer) { response := &http.Response{ Status: "200 OK", StatusCode: 200, @@ -147,11 +147,11 @@ func (this *Server) handleConnect(request *http.Request, session *proxy.SessionI } response.Write(writer) - ray := this.packetDispatcher.DispatchToOutbound(session) - this.transport(reader, writer, ray) + ray := v.packetDispatcher.DispatchToOutbound(session) + v.transport(reader, writer, ray) } -func (this *Server) transport(input io.Reader, output io.Writer, ray ray.InboundRay) { +func (v *Server) transport(input io.Reader, output io.Writer, ray ray.InboundRay) { var wg sync.WaitGroup wg.Add(2) defer wg.Wait() @@ -204,7 +204,7 @@ func StripHopByHopHeaders(request *http.Request) { } } -func (this *Server) GenerateResponse(statusCode int, status string) *http.Response { +func (v *Server) GenerateResponse(statusCode int, status string) *http.Response { hdr := http.Header(make(map[string][]string)) hdr.Set("Connection", "close") return &http.Response{ @@ -220,9 +220,9 @@ func (this *Server) GenerateResponse(statusCode int, status string) *http.Respon } } -func (this *Server) handlePlainHTTP(request *http.Request, session *proxy.SessionInfo, reader *bufio.Reader, writer io.Writer) { +func (v *Server) handlePlainHTTP(request *http.Request, session *proxy.SessionInfo, reader *bufio.Reader, writer io.Writer) { if len(request.URL.Host) <= 0 { - response := this.GenerateResponse(400, "Bad Request") + response := v.GenerateResponse(400, "Bad Request") response.Write(writer) return @@ -231,7 +231,7 @@ func (this *Server) handlePlainHTTP(request *http.Request, session *proxy.Sessio request.Host = request.URL.Host StripHopByHopHeaders(request) - ray := this.packetDispatcher.DispatchToOutbound(session) + ray := v.packetDispatcher.DispatchToOutbound(session) defer ray.InboundInput().Close() defer ray.InboundOutput().Release() @@ -255,7 +255,7 @@ func (this *Server) handlePlainHTTP(request *http.Request, session *proxy.Sessio response, err := http.ReadResponse(responseReader, request) if err != nil { log.Warning("HTTP: Failed to read response: ", err) - response = this.GenerateResponse(503, "Service Unavailable") + response = v.GenerateResponse(503, "Service Unavailable") } responseWriter := v2io.NewBufferedWriter(writer) err = response.Write(responseWriter) @@ -270,13 +270,13 @@ func (this *Server) handlePlainHTTP(request *http.Request, session *proxy.Sessio type ServerFactory struct{} -func (this *ServerFactory) StreamCapability() v2net.NetworkList { +func (v *ServerFactory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_RawTCP}, } } -func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { +func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { if !space.HasApp(dispatcher.APP_ID) { return nil, common.ErrBadConfiguration } diff --git a/proxy/proxy.go b/proxy/proxy.go index af2a2fcc3..d9892b89f 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -38,10 +38,10 @@ type OutboundHandlerMeta struct { ProxySettings *internet.ProxyConfig } -func (this *OutboundHandlerMeta) GetDialerOptions() internet.DialerOptions { +func (v *OutboundHandlerMeta) GetDialerOptions() internet.DialerOptions { return internet.DialerOptions{ - Stream: this.StreamSettings, - Proxy: this.ProxySettings, + Stream: v.StreamSettings, + Proxy: v.ProxySettings, } } diff --git a/proxy/shadowsocks/client.go b/proxy/shadowsocks/client.go index da43c9270..f6b0b728f 100644 --- a/proxy/shadowsocks/client.go +++ b/proxy/shadowsocks/client.go @@ -33,7 +33,7 @@ func NewClient(config *ClientConfig, space app.Space, meta *proxy.OutboundHandle return client, nil } -func (this *Client) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { +func (v *Client) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { defer payload.Release() defer ray.OutboundInput().Release() defer ray.OutboundOutput().Close() @@ -44,10 +44,10 @@ func (this *Client) Dispatch(destination v2net.Destination, payload *alloc.Buffe var conn internet.Connection err := retry.ExponentialBackoff(5, 100).On(func() error { - server = this.serverPicker.PickServer() + server = v.serverPicker.PickServer() dest := server.Destination() dest.Network = network - rawConn, err := internet.Dial(this.meta.Address, dest, this.meta.GetDialerOptions()) + rawConn, err := internet.Dial(v.meta.Address, dest, v.meta.GetDialerOptions()) if err != nil { return err } @@ -164,12 +164,12 @@ func (this *Client) Dispatch(destination v2net.Destination, payload *alloc.Buffe type ClientFactory struct{} -func (this *ClientFactory) StreamCapability() v2net.NetworkList { +func (v *ClientFactory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_TCP, v2net.Network_RawTCP}, } } -func (this *ClientFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { +func (v *ClientFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { return NewClient(rawConfig.(*ClientConfig), space, meta) } diff --git a/proxy/shadowsocks/config.go b/proxy/shadowsocks/config.go index a6b3b1e00..468ce89ec 100644 --- a/proxy/shadowsocks/config.go +++ b/proxy/shadowsocks/config.go @@ -16,15 +16,15 @@ type ShadowsocksAccount struct { OneTimeAuth Account_OneTimeAuth } -func (this *ShadowsocksAccount) Equals(another protocol.Account) bool { +func (v *ShadowsocksAccount) Equals(another protocol.Account) bool { if account, ok := another.(*ShadowsocksAccount); ok { - return bytes.Equal(this.Key, account.Key) + return bytes.Equal(v.Key, account.Key) } return false } -func (this *Account) GetCipher() (Cipher, error) { - switch this.CipherType { +func (v *Account) GetCipher() (Cipher, error) { + switch v.CipherType { case CipherType_AES_128_CFB: return &AesCfb{KeyBytes: 16}, nil case CipherType_AES_256_CFB: @@ -38,24 +38,24 @@ func (this *Account) GetCipher() (Cipher, error) { } } -func (this *Account) AsAccount() (protocol.Account, error) { - cipher, err := this.GetCipher() +func (v *Account) AsAccount() (protocol.Account, error) { + cipher, err := v.GetCipher() if err != nil { return nil, err } return &ShadowsocksAccount{ Cipher: cipher, - Key: this.GetCipherKey(), - OneTimeAuth: this.Ota, + Key: v.GetCipherKey(), + OneTimeAuth: v.Ota, }, nil } -func (this *Account) GetCipherKey() []byte { - ct, err := this.GetCipher() +func (v *Account) GetCipherKey() []byte { + ct, err := v.GetCipher() if err != nil { return nil } - return PasswordToCipherKey(this.Password, ct.KeySize()) + return PasswordToCipherKey(v.Password, ct.KeySize()) } type Cipher interface { @@ -69,20 +69,20 @@ type AesCfb struct { KeyBytes int } -func (this *AesCfb) KeySize() int { - return this.KeyBytes +func (v *AesCfb) KeySize() int { + return v.KeyBytes } -func (this *AesCfb) IVSize() int { +func (v *AesCfb) IVSize() int { return 16 } -func (this *AesCfb) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) { +func (v *AesCfb) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) { stream := crypto.NewAesEncryptionStream(key, iv) return stream, nil } -func (this *AesCfb) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) { +func (v *AesCfb) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) { stream := crypto.NewAesDecryptionStream(key, iv) return stream, nil } @@ -91,19 +91,19 @@ type ChaCha20 struct { IVBytes int } -func (this *ChaCha20) KeySize() int { +func (v *ChaCha20) KeySize() int { return 32 } -func (this *ChaCha20) IVSize() int { - return this.IVBytes +func (v *ChaCha20) IVSize() int { + return v.IVBytes } -func (this *ChaCha20) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) { +func (v *ChaCha20) NewEncodingStream(key []byte, iv []byte) (cipher.Stream, error) { return crypto.NewChaCha20Stream(key, iv), nil } -func (this *ChaCha20) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) { +func (v *ChaCha20) NewDecodingStream(key []byte, iv []byte) (cipher.Stream, error) { return crypto.NewChaCha20Stream(key, iv), nil } diff --git a/proxy/shadowsocks/ota.go b/proxy/shadowsocks/ota.go index 3613d639f..65090d419 100644 --- a/proxy/shadowsocks/ota.go +++ b/proxy/shadowsocks/ota.go @@ -26,8 +26,8 @@ func NewAuthenticator(keygen KeyGenerator) *Authenticator { } } -func (this *Authenticator) Authenticate(auth []byte, data []byte) []byte { - hasher := hmac.New(sha1.New, this.key()) +func (v *Authenticator) Authenticate(auth []byte, data []byte) []byte { + hasher := hmac.New(sha1.New, v.key()) hasher.Write(data) res := hasher.Sum(nil) return append(auth, res[:AuthSize]...) @@ -65,14 +65,14 @@ func NewChunkReader(reader io.Reader, auth *Authenticator) *ChunkReader { } } -func (this *ChunkReader) Release() { - this.reader = nil - this.auth = nil +func (v *ChunkReader) Release() { + v.reader = nil + v.auth = nil } -func (this *ChunkReader) Read() (*alloc.Buffer, error) { +func (v *ChunkReader) Read() (*alloc.Buffer, error) { buffer := alloc.NewBuffer() - if _, err := io.ReadFull(this.reader, buffer.Value[:2]); err != nil { + if _, err := io.ReadFull(v.reader, buffer.Value[:2]); err != nil { buffer.Release() return nil, err } @@ -84,7 +84,7 @@ func (this *ChunkReader) Read() (*alloc.Buffer, error) { buffer.Release() buffer = alloc.NewLocalBuffer(int(length) + 128) } - if _, err := io.ReadFull(this.reader, buffer.Value[:length]); err != nil { + if _, err := io.ReadFull(v.reader, buffer.Value[:length]); err != nil { buffer.Release() return nil, err } @@ -93,7 +93,7 @@ func (this *ChunkReader) Read() (*alloc.Buffer, error) { authBytes := buffer.Value[:AuthSize] payload := buffer.Value[AuthSize:] - actualAuthBytes := this.auth.Authenticate(nil, payload) + actualAuthBytes := v.auth.Authenticate(nil, payload) if !bytes.Equal(authBytes, actualAuthBytes) { buffer.Release() return nil, errors.New("Shadowsocks|AuthenticationReader: Invalid auth.") @@ -115,16 +115,16 @@ func NewChunkWriter(writer io.Writer, auth *Authenticator) *ChunkWriter { } } -func (this *ChunkWriter) Release() { - this.writer = nil - this.auth = nil +func (v *ChunkWriter) Release() { + v.writer = nil + v.auth = nil } -func (this *ChunkWriter) Write(payload *alloc.Buffer) error { +func (v *ChunkWriter) Write(payload *alloc.Buffer) error { totalLength := payload.Len() payload.SliceBack(AuthSize) - this.auth.Authenticate(payload.Value[:0], payload.Value[AuthSize:]) + v.auth.Authenticate(payload.Value[:0], payload.Value[AuthSize:]) payload.PrependUint16(uint16(totalLength)) - _, err := this.writer.Write(payload.Bytes()) + _, err := v.writer.Write(payload.Bytes()) return err } diff --git a/proxy/shadowsocks/protocol.go b/proxy/shadowsocks/protocol.go index e868800f6..4c8d11419 100644 --- a/proxy/shadowsocks/protocol.go +++ b/proxy/shadowsocks/protocol.go @@ -364,15 +364,15 @@ type UDPReader struct { User *protocol.User } -func (this *UDPReader) Read() (*alloc.Buffer, error) { +func (v *UDPReader) Read() (*alloc.Buffer, error) { buffer := alloc.NewSmallBuffer() - nBytes, err := this.Reader.Read(buffer.Value) + nBytes, err := v.Reader.Read(buffer.Value) if err != nil { buffer.Release() return nil, err } buffer.Slice(0, nBytes) - _, payload, err := DecodeUDPPacket(this.User, buffer) + _, payload, err := DecodeUDPPacket(v.User, buffer) if err != nil { buffer.Release() return nil, err @@ -380,7 +380,7 @@ func (this *UDPReader) Read() (*alloc.Buffer, error) { return payload, nil } -func (this *UDPReader) Release() { +func (v *UDPReader) Release() { } type UDPWriter struct { @@ -388,16 +388,16 @@ type UDPWriter struct { Request *protocol.RequestHeader } -func (this *UDPWriter) Write(buffer *alloc.Buffer) error { - payload, err := EncodeUDPPacket(this.Request, buffer) +func (v *UDPWriter) Write(buffer *alloc.Buffer) error { + payload, err := EncodeUDPPacket(v.Request, buffer) if err != nil { return err } - _, err = this.Writer.Write(payload.Value) + _, err = v.Writer.Write(payload.Value) payload.Release() return err } -func (this *UDPWriter) Release() { +func (v *UDPWriter) Release() { } diff --git a/proxy/shadowsocks/server.go b/proxy/shadowsocks/server.go index c3069080e..92dd2f998 100644 --- a/proxy/shadowsocks/server.go +++ b/proxy/shadowsocks/server.go @@ -59,54 +59,54 @@ func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandler return s, nil } -func (this *Server) Port() v2net.Port { - return this.meta.Port +func (v *Server) Port() v2net.Port { + return v.meta.Port } -func (this *Server) Close() { - this.accepting = false +func (v *Server) Close() { + v.accepting = false // TODO: synchronization - if this.tcpHub != nil { - this.tcpHub.Close() - this.tcpHub = nil + if v.tcpHub != nil { + v.tcpHub.Close() + v.tcpHub = nil } - if this.udpHub != nil { - this.udpHub.Close() - this.udpHub = nil + if v.udpHub != nil { + v.udpHub.Close() + v.udpHub = nil } } -func (this *Server) Start() error { - if this.accepting { +func (v *Server) Start() error { + if v.accepting { return nil } - tcpHub, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.handleConnection, this.meta.StreamSettings) + tcpHub, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.handleConnection, v.meta.StreamSettings) if err != nil { - log.Error("Shadowsocks: Failed to listen TCP on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("Shadowsocks: Failed to listen TCP on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.tcpHub = tcpHub + v.tcpHub = tcpHub - if this.config.UdpEnabled { - this.udpServer = udp.NewUDPServer(this.packetDispatcher) - udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, udp.ListenOption{Callback: this.handlerUDPPayload}) + if v.config.UdpEnabled { + v.udpServer = udp.NewUDPServer(v.packetDispatcher) + udpHub, err := udp.ListenUDP(v.meta.Address, v.meta.Port, udp.ListenOption{Callback: v.handlerUDPPayload}) if err != nil { - log.Error("Shadowsocks: Failed to listen UDP on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("Shadowsocks: Failed to listen UDP on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.udpHub = udpHub + v.udpHub = udpHub } - this.accepting = true + v.accepting = true return nil } -func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { +func (v *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { source := session.Source - request, data, err := DecodeUDPPacket(this.user, payload) + request, data, err := DecodeUDPPacket(v.user, payload) if err != nil { log.Info("Shadowsocks|Server: Skipping invalid UDP packet from: ", source, ": ", err) log.Access(source, "", log.AccessRejected, err) @@ -114,13 +114,13 @@ func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.Sess return } - if request.Option.Has(RequestOptionOneTimeAuth) && this.account.OneTimeAuth == Account_Disabled { + if request.Option.Has(RequestOptionOneTimeAuth) && v.account.OneTimeAuth == Account_Disabled { log.Info("Shadowsocks|Server: Client payload enables OTA but server doesn't allow it.") payload.Release() return } - if !request.Option.Has(RequestOptionOneTimeAuth) && this.account.OneTimeAuth == Account_Enabled { + if !request.Option.Has(RequestOptionOneTimeAuth) && v.account.OneTimeAuth == Account_Enabled { log.Info("Shadowsocks|Server: Client payload disables OTA but server forces it.") payload.Release() return @@ -130,7 +130,7 @@ func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.Sess log.Access(source, dest, log.AccessAccepted, "") log.Info("Shadowsocks|Server: Tunnelling request to ", dest) - this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest, User: request.User, Inbound: this.meta}, data, func(destination v2net.Destination, payload *alloc.Buffer) { + v.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: dest, User: request.User, Inbound: v.meta}, data, func(destination v2net.Destination, payload *alloc.Buffer) { defer payload.Release() data, err := EncodeUDPPacket(request, payload) @@ -140,11 +140,11 @@ func (this *Server) handlerUDPPayload(payload *alloc.Buffer, session *proxy.Sess } defer data.Release() - this.udpHub.WriteTo(data.Value, source) + v.udpHub.WriteTo(data.Value, source) }) } -func (this *Server) handleConnection(conn internet.Connection) { +func (v *Server) handleConnection(conn internet.Connection) { defer conn.Close() conn.SetReusable(false) @@ -154,7 +154,7 @@ func (this *Server) handleConnection(conn internet.Connection) { bufferedReader := v2io.NewBufferedReader(timedReader) defer bufferedReader.Release() - request, bodyReader, err := ReadTCPSession(this.user, bufferedReader) + request, bodyReader, err := ReadTCPSession(v.user, bufferedReader) if err != nil { log.Access(conn.RemoteAddr(), "", log.AccessRejected, err) log.Info("Shadowsocks|Server: Failed to create request from: ", conn.RemoteAddr(), ": ", err) @@ -164,18 +164,18 @@ func (this *Server) handleConnection(conn internet.Connection) { bufferedReader.SetCached(false) - userSettings := this.user.GetSettings() + userSettings := v.user.GetSettings() timedReader.SetTimeOut(userSettings.PayloadReadTimeout) dest := request.Destination() log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "") log.Info("Shadowsocks|Server: Tunnelling request to ", dest) - ray := this.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ + ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.DestinationFromAddr(conn.RemoteAddr()), Destination: dest, User: request.User, - Inbound: this.meta, + Inbound: v.meta, }) defer ray.InboundOutput().Release() @@ -214,13 +214,13 @@ func (this *Server) handleConnection(conn internet.Connection) { type ServerFactory struct{} -func (this *ServerFactory) StreamCapability() v2net.NetworkList { +func (v *ServerFactory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_TCP, v2net.Network_RawTCP}, } } -func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { +func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { if !space.HasApp(dispatcher.APP_ID) { return nil, common.ErrBadConfiguration } diff --git a/proxy/socks/config.go b/proxy/socks/config.go index 98fc42fb5..cd0132201 100644 --- a/proxy/socks/config.go +++ b/proxy/socks/config.go @@ -8,39 +8,39 @@ import ( google_protobuf "github.com/golang/protobuf/ptypes/any" ) -func (this *Account) Equals(another protocol.Account) bool { +func (v *Account) Equals(another protocol.Account) bool { if account, ok := another.(*Account); ok { - return this.Username == account.Username + return v.Username == account.Username } return false } -func (this *Account) AsAccount() (protocol.Account, error) { - return this, nil +func (v *Account) AsAccount() (protocol.Account, error) { + return v, nil } func NewAccount() protocol.AsAccount { return &Account{} } -func (this *Account) AsAny() (*google_protobuf.Any, error) { - return ptypes.MarshalAny(this) +func (v *Account) AsAny() (*google_protobuf.Any, error) { + return ptypes.MarshalAny(v) } -func (this *ServerConfig) HasAccount(username, password string) bool { - if this.Accounts == nil { +func (v *ServerConfig) HasAccount(username, password string) bool { + if v.Accounts == nil { return false } - storedPassed, found := this.Accounts[username] + storedPassed, found := v.Accounts[username] if !found { return false } return storedPassed == password } -func (this *ServerConfig) GetNetAddress() v2net.Address { - if this.Address == nil { +func (v *ServerConfig) GetNetAddress() v2net.Address { + if v.Address == nil { return v2net.LocalHostIP } - return this.Address.AsAddress() + return v.Address.AsAddress() } diff --git a/proxy/socks/server.go b/proxy/socks/server.go index bcaa34056..ed960d986 100644 --- a/proxy/socks/server.go +++ b/proxy/socks/server.go @@ -55,56 +55,56 @@ func NewServer(config *ServerConfig, space app.Space, meta *proxy.InboundHandler } // Port implements InboundHandler.Port(). -func (this *Server) Port() v2net.Port { - return this.meta.Port +func (v *Server) Port() v2net.Port { + return v.meta.Port } // Close implements InboundHandler.Close(). -func (this *Server) Close() { - this.accepting = false - if this.tcpListener != nil { - this.tcpMutex.Lock() - this.tcpListener.Close() - this.tcpListener = nil - this.tcpMutex.Unlock() +func (v *Server) Close() { + v.accepting = false + if v.tcpListener != nil { + v.tcpMutex.Lock() + v.tcpListener.Close() + v.tcpListener = nil + v.tcpMutex.Unlock() } - if this.udpHub != nil { - this.udpMutex.Lock() - this.udpHub.Close() - this.udpHub = nil - this.udpMutex.Unlock() + if v.udpHub != nil { + v.udpMutex.Lock() + v.udpHub.Close() + v.udpHub = nil + v.udpMutex.Unlock() } } // Listen implements InboundHandler.Listen(). -func (this *Server) Start() error { - if this.accepting { +func (v *Server) Start() error { + if v.accepting { return nil } listener, err := internet.ListenTCP( - this.meta.Address, - this.meta.Port, - this.handleConnection, - this.meta.StreamSettings) + v.meta.Address, + v.meta.Port, + v.handleConnection, + v.meta.StreamSettings) if err != nil { - log.Error("Socks: failed to listen on ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("Socks: failed to listen on ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.accepting = true - this.tcpMutex.Lock() - this.tcpListener = listener - this.tcpMutex.Unlock() - if this.config.UdpEnabled { - this.listenUDP() + v.accepting = true + v.tcpMutex.Lock() + v.tcpListener = listener + v.tcpMutex.Unlock() + if v.config.UdpEnabled { + v.listenUDP() } return nil } -func (this *Server) handleConnection(connection internet.Connection) { +func (v *Server) handleConnection(connection internet.Connection) { defer connection.Close() - timedReader := v2net.NewTimeOutReader(this.config.Timeout, connection) + timedReader := v2net.NewTimeOutReader(v.config.Timeout, connection) reader := v2io.NewBufferedReader(timedReader) defer reader.Release() @@ -121,15 +121,15 @@ func (this *Server) handleConnection(connection internet.Connection) { clientAddr := v2net.DestinationFromAddr(connection.RemoteAddr()) if err != nil && err == protocol.Socks4Downgrade { - this.handleSocks4(clientAddr, reader, writer, auth4) + v.handleSocks4(clientAddr, reader, writer, auth4) } else { - this.handleSocks5(clientAddr, reader, writer, auth) + v.handleSocks5(clientAddr, reader, writer, auth) } } -func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error { +func (v *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks5AuthenticationRequest) error { expectedAuthMethod := protocol.AuthNotRequired - if this.config.AuthType == AuthType_PASSWORD { + if v.config.AuthType == AuthType_PASSWORD { expectedAuthMethod = protocol.AuthUserPass } @@ -152,14 +152,14 @@ func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.Buff log.Error("Socks: failed to write authentication: ", err) return err } - if this.config.AuthType == AuthType_PASSWORD { + if v.config.AuthType == AuthType_PASSWORD { upRequest, err := protocol.ReadUserPassRequest(reader) if err != nil { log.Warning("Socks: failed to read username and password: ", err) return err } status := byte(0) - if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) { + if !v.config.HasAccount(upRequest.Username(), upRequest.Password()) { status = byte(0xFF) } upResponse := protocol.NewSocks5UserPassResponse(status) @@ -182,8 +182,8 @@ func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.Buff return err } - if request.Command == protocol.CmdUdpAssociate && this.config.UdpEnabled { - return this.handleUDP(reader, writer) + if request.Command == protocol.CmdUdpAssociate && v.config.UdpEnabled { + return v.handleUDP(reader, writer) } if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate { @@ -222,20 +222,20 @@ func (this *Server) handleSocks5(clientAddr v2net.Destination, reader *v2io.Buff session := &proxy.SessionInfo{ Source: clientAddr, Destination: dest, - Inbound: this.meta, + Inbound: v.meta, } log.Info("Socks: TCP Connect request to ", dest) log.Access(clientAddr, dest, log.AccessAccepted, "") - this.transport(reader, writer, session) + v.transport(reader, writer, session) return nil } -func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error { +func (v *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) error { response := protocol.NewSocks5Response() response.Error = protocol.ErrorSuccess - udpAddr := this.udpAddress + udpAddr := v.udpAddress response.Port = udpAddr.Port switch udpAddr.Address.Family() { @@ -255,7 +255,7 @@ func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) err return err } - // The TCP connection closes after this method returns. We need to wait until + // The TCP connection closes after v method returns. We need to wait until // the client closes it. // TODO: get notified from UDP part <-time.After(5 * time.Minute) @@ -263,7 +263,7 @@ func (this *Server) handleUDP(reader io.Reader, writer *v2io.BufferedWriter) err return nil } -func (this *Server) handleSocks4(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error { +func (v *Server) handleSocks4(clientAddr v2net.Destination, reader *v2io.BufferedReader, writer *v2io.BufferedWriter, auth protocol.Socks4AuthenticationRequest) error { result := protocol.Socks4RequestGranted if auth.Command == protocol.CmdBind { result = protocol.Socks4RequestRejected @@ -285,15 +285,15 @@ func (this *Server) handleSocks4(clientAddr v2net.Destination, reader *v2io.Buff session := &proxy.SessionInfo{ Source: clientAddr, Destination: dest, - Inbound: this.meta, + Inbound: v.meta, } log.Access(clientAddr, dest, log.AccessAccepted, "") - this.transport(reader, writer, session) + v.transport(reader, writer, session) return nil } -func (this *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) { - ray := this.packetDispatcher.DispatchToOutbound(session) +func (v *Server) transport(reader io.Reader, writer io.Writer, session *proxy.SessionInfo) { + ray := v.packetDispatcher.DispatchToOutbound(session) input := ray.InboundInput() output := ray.InboundOutput() @@ -321,13 +321,13 @@ func (this *Server) transport(reader io.Reader, writer io.Writer, session *proxy type ServerFactory struct{} -func (this *ServerFactory) StreamCapability() v2net.NetworkList { +func (v *ServerFactory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_RawTCP}, } } -func (this *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { +func (v *ServerFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { return NewServer(rawConfig.(*ServerConfig), space, meta), nil } diff --git a/proxy/socks/server_udp.go b/proxy/socks/server_udp.go index 56f3de10a..ef83e9db2 100644 --- a/proxy/socks/server_udp.go +++ b/proxy/socks/server_udp.go @@ -9,21 +9,21 @@ import ( "v2ray.com/core/transport/internet/udp" ) -func (this *Server) listenUDP() error { - this.udpServer = udp.NewUDPServer(this.packetDispatcher) - udpHub, err := udp.ListenUDP(this.meta.Address, this.meta.Port, udp.ListenOption{Callback: this.handleUDPPayload}) +func (v *Server) listenUDP() error { + v.udpServer = udp.NewUDPServer(v.packetDispatcher) + udpHub, err := udp.ListenUDP(v.meta.Address, v.meta.Port, udp.ListenOption{Callback: v.handleUDPPayload}) if err != nil { - log.Error("Socks: Failed to listen on udp ", this.meta.Address, ":", this.meta.Port) + log.Error("Socks: Failed to listen on udp ", v.meta.Address, ":", v.meta.Port) return err } - this.udpMutex.Lock() - this.udpAddress = v2net.UDPDestination(this.config.GetNetAddress(), this.meta.Port) - this.udpHub = udpHub - this.udpMutex.Unlock() + v.udpMutex.Lock() + v.udpAddress = v2net.UDPDestination(v.config.GetNetAddress(), v.meta.Port) + v.udpHub = udpHub + v.udpMutex.Unlock() return nil } -func (this *Server) handleUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { +func (v *Server) handleUDPPayload(payload *alloc.Buffer, session *proxy.SessionInfo) { source := session.Source log.Info("Socks: Client UDP connection from ", source) request, err := protocol.ReadUDPRequest(payload.Value) @@ -46,7 +46,7 @@ func (this *Server) handleUDPPayload(payload *alloc.Buffer, session *proxy.Sessi log.Info("Socks: Send packet to ", request.Destination(), " with ", request.Data.Len(), " bytes") log.Access(source, request.Destination, log.AccessAccepted, "") - this.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: request.Destination(), Inbound: this.meta}, request.Data, func(destination v2net.Destination, payload *alloc.Buffer) { + v.udpServer.Dispatch(&proxy.SessionInfo{Source: source, Destination: request.Destination(), Inbound: v.meta}, request.Data, func(destination v2net.Destination, payload *alloc.Buffer) { response := &protocol.Socks5UDPRequest{ Fragment: 0, Address: request.Destination().Address, @@ -58,13 +58,13 @@ func (this *Server) handleUDPPayload(payload *alloc.Buffer, session *proxy.Sessi udpMessage := alloc.NewLocalBuffer(2048).Clear() response.Write(udpMessage) - this.udpMutex.RLock() - if !this.accepting { - this.udpMutex.RUnlock() + v.udpMutex.RLock() + if !v.accepting { + v.udpMutex.RUnlock() return } - nBytes, err := this.udpHub.WriteTo(udpMessage.Value, destination) - this.udpMutex.RUnlock() + nBytes, err := v.udpHub.WriteTo(udpMessage.Value, destination) + v.udpMutex.RUnlock() udpMessage.Release() response.Data.Release() if err != nil { diff --git a/proxy/testing/mocks/inboundhandler.go b/proxy/testing/mocks/inboundhandler.go index cd92c1508..948fcbf2d 100644 --- a/proxy/testing/mocks/inboundhandler.go +++ b/proxy/testing/mocks/inboundhandler.go @@ -18,20 +18,20 @@ type InboundConnectionHandler struct { ConnOutput io.Writer } -func (this *InboundConnectionHandler) Start() error { +func (v *InboundConnectionHandler) Start() error { return nil } -func (this *InboundConnectionHandler) Port() v2net.Port { - return this.ListeningPort +func (v *InboundConnectionHandler) Port() v2net.Port { + return v.ListeningPort } -func (this *InboundConnectionHandler) Close() { +func (v *InboundConnectionHandler) Close() { } -func (this *InboundConnectionHandler) Communicate(destination v2net.Destination) error { - ray := this.PacketDispatcher.DispatchToOutbound(&proxy.SessionInfo{ +func (v *InboundConnectionHandler) Communicate(destination v2net.Destination) error { + ray := v.PacketDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(0)), Destination: destination, Inbound: &proxy.InboundHandlerMeta{ @@ -49,7 +49,7 @@ func (this *InboundConnectionHandler) Communicate(destination v2net.Destination) writeFinish.Lock() go func() { - v2reader := v2io.NewAdaptiveReader(this.ConnInput) + v2reader := v2io.NewAdaptiveReader(v.ConnInput) defer v2reader.Release() v2io.Pipe(v2reader, input) @@ -58,7 +58,7 @@ func (this *InboundConnectionHandler) Communicate(destination v2net.Destination) }() go func() { - v2writer := v2io.NewAdaptiveWriter(this.ConnOutput) + v2writer := v2io.NewAdaptiveWriter(v.ConnOutput) defer v2writer.Release() v2io.Pipe(output, v2writer) diff --git a/proxy/testing/mocks/outboundhandler.go b/proxy/testing/mocks/outboundhandler.go index c1a6e7113..c02b7b0d8 100644 --- a/proxy/testing/mocks/outboundhandler.go +++ b/proxy/testing/mocks/outboundhandler.go @@ -18,13 +18,13 @@ type OutboundConnectionHandler struct { ConnOutput io.Writer } -func (this *OutboundConnectionHandler) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { +func (v *OutboundConnectionHandler) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { input := ray.OutboundInput() output := ray.OutboundOutput() - this.Destination = destination + v.Destination = destination if !payload.IsEmpty() { - this.ConnOutput.Write(payload.Value) + v.ConnOutput.Write(payload.Value) } payload.Release() @@ -33,7 +33,7 @@ func (this *OutboundConnectionHandler) Dispatch(destination v2net.Destination, p writeFinish.Lock() go func() { - v2writer := v2io.NewAdaptiveWriter(this.ConnOutput) + v2writer := v2io.NewAdaptiveWriter(v.ConnOutput) defer v2writer.Release() v2io.Pipe(input, v2writer) @@ -43,7 +43,7 @@ func (this *OutboundConnectionHandler) Dispatch(destination v2net.Destination, p writeFinish.Lock() - v2reader := v2io.NewAdaptiveReader(this.ConnInput) + v2reader := v2io.NewAdaptiveReader(v.ConnInput) defer v2reader.Release() v2io.Pipe(v2reader, output) @@ -52,6 +52,6 @@ func (this *OutboundConnectionHandler) Dispatch(destination v2net.Destination, p return nil } -func (this *OutboundConnectionHandler) Create(space app.Space, config interface{}, sendThrough v2net.Address) (proxy.OutboundHandler, error) { - return this, nil +func (v *OutboundConnectionHandler) Create(space app.Space, config interface{}, sendThrough v2net.Address) (proxy.OutboundHandler, error) { + return v, nil } diff --git a/proxy/vmess/account.go b/proxy/vmess/account.go index b2c406742..38dbef2cc 100644 --- a/proxy/vmess/account.go +++ b/proxy/vmess/account.go @@ -12,24 +12,24 @@ type InternalAccount struct { AlterIDs []*protocol.ID } -func (this *InternalAccount) AnyValidID() *protocol.ID { - if len(this.AlterIDs) == 0 { - return this.ID +func (v *InternalAccount) AnyValidID() *protocol.ID { + if len(v.AlterIDs) == 0 { + return v.ID } - return this.AlterIDs[dice.Roll(len(this.AlterIDs))] + return v.AlterIDs[dice.Roll(len(v.AlterIDs))] } -func (this *InternalAccount) Equals(account protocol.Account) bool { +func (v *InternalAccount) Equals(account protocol.Account) bool { vmessAccount, ok := account.(*InternalAccount) if !ok { return false } // TODO: handle AlterIds difference - return this.ID.Equals(vmessAccount.ID) + return v.ID.Equals(vmessAccount.ID) } -func (this *Account) AsAccount() (protocol.Account, error) { - id, err := uuid.ParseString(this.Id) +func (v *Account) AsAccount() (protocol.Account, error) { + id, err := uuid.ParseString(v.Id) if err != nil { log.Error("VMess: Failed to parse ID: ", err) return nil, err @@ -37,6 +37,6 @@ func (this *Account) AsAccount() (protocol.Account, error) { protoId := protocol.NewID(id) return &InternalAccount{ ID: protoId, - AlterIDs: protocol.NewAlterIDs(protoId, uint16(this.AlterId)), + AlterIDs: protocol.NewAlterIDs(protoId, uint16(v.AlterId)), }, nil } diff --git a/proxy/vmess/encoding/client.go b/proxy/vmess/encoding/client.go index 5c50febd0..160a1c153 100644 --- a/proxy/vmess/encoding/client.go +++ b/proxy/vmess/encoding/client.go @@ -49,22 +49,22 @@ func NewClientSession(idHash protocol.IDHash) *ClientSession { return session } -func (this *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) { +func (v *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) { timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)() account, err := header.User.GetTypedAccount() if err != nil { log.Error("VMess: Failed to get user account: ", err) return } - idHash := this.idHash(account.(*vmess.InternalAccount).AnyValidID().Bytes()) + idHash := v.idHash(account.(*vmess.InternalAccount).AnyValidID().Bytes()) idHash.Write(timestamp.Bytes(nil)) writer.Write(idHash.Sum(nil)) buffer := make([]byte, 0, 512) buffer = append(buffer, Version) - buffer = append(buffer, this.requestBodyIV...) - buffer = append(buffer, this.requestBodyKey...) - buffer = append(buffer, this.responseHeader, byte(header.Option), byte(0), byte(0), byte(header.Command)) + buffer = append(buffer, v.requestBodyIV...) + buffer = append(buffer, v.requestBodyKey...) + buffer = append(buffer, v.responseHeader, byte(header.Option), byte(0), byte(0), byte(header.Command)) buffer = header.Port.Bytes(buffer) switch header.Address.Family() { @@ -94,25 +94,25 @@ func (this *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, w return } -func (this *ClientSession) EncodeRequestBody(writer io.Writer) io.Writer { - aesStream := crypto.NewAesEncryptionStream(this.requestBodyKey, this.requestBodyIV) +func (v *ClientSession) EncodeRequestBody(writer io.Writer) io.Writer { + aesStream := crypto.NewAesEncryptionStream(v.requestBodyKey, v.requestBodyIV) return crypto.NewCryptionWriter(aesStream, writer) } -func (this *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) { - aesStream := crypto.NewAesDecryptionStream(this.responseBodyKey, this.responseBodyIV) - this.responseReader = crypto.NewCryptionReader(aesStream, reader) +func (v *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) { + aesStream := crypto.NewAesDecryptionStream(v.responseBodyKey, v.responseBodyIV) + v.responseReader = crypto.NewCryptionReader(aesStream, reader) buffer := make([]byte, 256) - _, err := io.ReadFull(this.responseReader, buffer[:4]) + _, err := io.ReadFull(v.responseReader, buffer[:4]) if err != nil { log.Info("Raw: Failed to read response header: ", err) return nil, err } - if buffer[0] != this.responseHeader { - return nil, fmt.Errorf("VMess|Client: Unexpected response header. Expecting %d but actually %d", this.responseHeader, buffer[0]) + if buffer[0] != v.responseHeader { + return nil, fmt.Errorf("VMess|Client: Unexpected response header. Expecting %d but actually %d", v.responseHeader, buffer[0]) } header := &protocol.ResponseHeader{ @@ -122,7 +122,7 @@ func (this *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Res if buffer[2] != 0 { cmdId := buffer[2] dataLen := int(buffer[3]) - _, err := io.ReadFull(this.responseReader, buffer[:dataLen]) + _, err := io.ReadFull(v.responseReader, buffer[:dataLen]) if err != nil { log.Info("Raw: Failed to read response command: ", err) return nil, err @@ -137,6 +137,6 @@ func (this *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Res return header, nil } -func (this *ClientSession) DecodeResponseBody(reader io.Reader) io.Reader { - return this.responseReader +func (v *ClientSession) DecodeResponseBody(reader io.Reader) io.Reader { + return v.responseReader } diff --git a/proxy/vmess/encoding/commands.go b/proxy/vmess/encoding/commands.go index ae79d8be8..e0c0b9121 100644 --- a/proxy/vmess/encoding/commands.go +++ b/proxy/vmess/encoding/commands.go @@ -79,7 +79,7 @@ type CommandFactory interface { type CommandSwitchAccountFactory struct { } -func (this *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { +func (v *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { cmd, ok := command.(*protocol.CommandSwitchAccount) if !ok { return ErrCommandTypeMismatch @@ -107,7 +107,7 @@ func (this *CommandSwitchAccountFactory) Marshal(command interface{}, writer io. return nil } -func (this *CommandSwitchAccountFactory) Unmarshal(data []byte) (interface{}, error) { +func (v *CommandSwitchAccountFactory) Unmarshal(data []byte) (interface{}, error) { cmd := new(protocol.CommandSwitchAccount) if len(data) == 0 { return nil, errors.New("VMess|SwitchAccountCommand: Insufficient length.") diff --git a/proxy/vmess/encoding/server.go b/proxy/vmess/encoding/server.go index 339732688..1556ef62c 100644 --- a/proxy/vmess/encoding/server.go +++ b/proxy/vmess/encoding/server.go @@ -32,16 +32,16 @@ func NewServerSession(validator protocol.UserValidator) *ServerSession { } // Release implements common.Releaseable. -func (this *ServerSession) Release() { - this.userValidator = nil - this.requestBodyIV = nil - this.requestBodyKey = nil - this.responseBodyIV = nil - this.responseBodyKey = nil - this.responseWriter = nil +func (v *ServerSession) Release() { + v.userValidator = nil + v.requestBodyIV = nil + v.requestBodyKey = nil + v.responseBodyIV = nil + v.responseBodyKey = nil + v.responseWriter = nil } -func (this *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) { +func (v *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) { buffer := make([]byte, 512) _, err := io.ReadFull(reader, buffer[:protocol.IDBytesLen]) @@ -50,7 +50,7 @@ func (this *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Requ return nil, io.EOF } - user, timestamp, valid := this.userValidator.Get(buffer[:protocol.IDBytesLen]) + user, timestamp, valid := v.userValidator.Get(buffer[:protocol.IDBytesLen]) if !valid { return nil, protocol.ErrInvalidUser } @@ -82,9 +82,9 @@ func (this *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Requ return nil, protocol.ErrInvalidVersion } - this.requestBodyIV = append([]byte(nil), buffer[1:17]...) // 16 bytes - this.requestBodyKey = append([]byte(nil), buffer[17:33]...) // 16 bytes - this.responseHeader = buffer[33] // 1 byte + v.requestBodyIV = append([]byte(nil), buffer[1:17]...) // 16 bytes + v.requestBodyKey = append([]byte(nil), buffer[17:33]...) // 16 bytes + v.responseHeader = buffer[33] // 1 byte request.Option = protocol.RequestOption(buffer[34]) // 1 byte + 2 bytes reserved request.Command = protocol.RequestCommand(buffer[37]) @@ -139,28 +139,28 @@ func (this *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Requ return request, nil } -func (this *ServerSession) DecodeRequestBody(reader io.Reader) io.Reader { - aesStream := crypto.NewAesDecryptionStream(this.requestBodyKey, this.requestBodyIV) +func (v *ServerSession) DecodeRequestBody(reader io.Reader) io.Reader { + aesStream := crypto.NewAesDecryptionStream(v.requestBodyKey, v.requestBodyIV) return crypto.NewCryptionReader(aesStream, reader) } -func (this *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) { - responseBodyKey := md5.Sum(this.requestBodyKey) - responseBodyIV := md5.Sum(this.requestBodyIV) - this.responseBodyKey = responseBodyKey[:] - this.responseBodyIV = responseBodyIV[:] +func (v *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) { + responseBodyKey := md5.Sum(v.requestBodyKey) + responseBodyIV := md5.Sum(v.requestBodyIV) + v.responseBodyKey = responseBodyKey[:] + v.responseBodyIV = responseBodyIV[:] - aesStream := crypto.NewAesEncryptionStream(this.responseBodyKey, this.responseBodyIV) + aesStream := crypto.NewAesEncryptionStream(v.responseBodyKey, v.responseBodyIV) encryptionWriter := crypto.NewCryptionWriter(aesStream, writer) - this.responseWriter = encryptionWriter + v.responseWriter = encryptionWriter - encryptionWriter.Write([]byte{this.responseHeader, byte(header.Option)}) + encryptionWriter.Write([]byte{v.responseHeader, byte(header.Option)}) err := MarshalCommand(header.Command, encryptionWriter) if err != nil { encryptionWriter.Write([]byte{0x00, 0x00}) } } -func (this *ServerSession) EncodeResponseBody(writer io.Writer) io.Writer { - return this.responseWriter +func (v *ServerSession) EncodeResponseBody(writer io.Writer) io.Writer { + return v.responseWriter } diff --git a/proxy/vmess/inbound/command.go b/proxy/vmess/inbound/command.go index f8c04d1ef..737cf5db6 100644 --- a/proxy/vmess/inbound/command.go +++ b/proxy/vmess/inbound/command.go @@ -6,11 +6,11 @@ import ( "v2ray.com/core/proxy/vmess" ) -func (this *VMessInboundHandler) generateCommand(request *protocol.RequestHeader) protocol.ResponseCommand { - if this.detours != nil { - tag := this.detours.To - if this.inboundHandlerManager != nil { - handler, availableMin := this.inboundHandlerManager.GetHandler(tag) +func (v *VMessInboundHandler) generateCommand(request *protocol.RequestHeader) protocol.ResponseCommand { + if v.detours != nil { + tag := v.detours.To + if v.inboundHandlerManager != nil { + handler, availableMin := v.inboundHandlerManager.GetHandler(tag) inboundHandler, ok := handler.(*VMessInboundHandler) if ok { if availableMin > 255 { diff --git a/proxy/vmess/inbound/config.go b/proxy/vmess/inbound/config.go index 7e1642f86..e7b6081a2 100644 --- a/proxy/vmess/inbound/config.go +++ b/proxy/vmess/inbound/config.go @@ -1,11 +1,11 @@ package inbound -func (this *Config) GetDefaultValue() *DefaultConfig { - if this.GetDefault() == nil { +func (v *Config) GetDefaultValue() *DefaultConfig { + if v.GetDefault() == nil { return &DefaultConfig{ AlterId: 32, Level: 0, } } - return this.Default + return v.Default } diff --git a/proxy/vmess/inbound/inbound.go b/proxy/vmess/inbound/inbound.go index ff5737f33..c2560d8cb 100644 --- a/proxy/vmess/inbound/inbound.go +++ b/proxy/vmess/inbound/inbound.go @@ -42,28 +42,28 @@ func NewUserByEmail(users []*protocol.User, config *DefaultConfig) *userByEmail } } -func (this *userByEmail) Get(email string) (*protocol.User, bool) { +func (v *userByEmail) Get(email string) (*protocol.User, bool) { var user *protocol.User var found bool - this.RLock() - user, found = this.cache[email] - this.RUnlock() + v.RLock() + user, found = v.cache[email] + v.RUnlock() if !found { - this.Lock() - user, found = this.cache[email] + v.Lock() + user, found = v.cache[email] if !found { account := &vmess.Account{ Id: uuid.New().String(), - AlterId: uint32(this.defaultAlterIDs), + AlterId: uint32(v.defaultAlterIDs), } user = &protocol.User{ - Level: this.defaultLevel, + Level: v.defaultLevel, Email: email, Account: loader.NewTypedSettings(account), } - this.cache[email] = user + v.cache[email] = user } - this.Unlock() + v.Unlock() } return user, found } @@ -81,58 +81,58 @@ type VMessInboundHandler struct { meta *proxy.InboundHandlerMeta } -func (this *VMessInboundHandler) Port() v2net.Port { - return this.meta.Port +func (v *VMessInboundHandler) Port() v2net.Port { + return v.meta.Port } -func (this *VMessInboundHandler) Close() { - this.accepting = false - if this.listener != nil { - this.Lock() - this.listener.Close() - this.listener = nil - this.clients.Release() - this.clients = nil - this.Unlock() +func (v *VMessInboundHandler) Close() { + v.accepting = false + if v.listener != nil { + v.Lock() + v.listener.Close() + v.listener = nil + v.clients.Release() + v.clients = nil + v.Unlock() } } -func (this *VMessInboundHandler) GetUser(email string) *protocol.User { - this.RLock() - defer this.RUnlock() +func (v *VMessInboundHandler) GetUser(email string) *protocol.User { + v.RLock() + defer v.RUnlock() - if !this.accepting { + if !v.accepting { return nil } - user, existing := this.usersByEmail.Get(email) + user, existing := v.usersByEmail.Get(email) if !existing { - this.clients.Add(user) + v.clients.Add(user) } return user } -func (this *VMessInboundHandler) Start() error { - if this.accepting { +func (v *VMessInboundHandler) Start() error { + if v.accepting { return nil } - tcpListener, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.HandleConnection, this.meta.StreamSettings) + tcpListener, err := internet.ListenTCP(v.meta.Address, v.meta.Port, v.HandleConnection, v.meta.StreamSettings) if err != nil { - log.Error("VMess|Inbound: Unable to listen tcp ", this.meta.Address, ":", this.meta.Port, ": ", err) + log.Error("VMess|Inbound: Unable to listen tcp ", v.meta.Address, ":", v.meta.Port, ": ", err) return err } - this.accepting = true - this.Lock() - this.listener = tcpListener - this.Unlock() + v.accepting = true + v.Lock() + v.listener = tcpListener + v.Unlock() return nil } -func (this *VMessInboundHandler) HandleConnection(connection internet.Connection) { +func (v *VMessInboundHandler) HandleConnection(connection internet.Connection) { defer connection.Close() - if !this.accepting { + if !v.accepting { return } @@ -142,16 +142,16 @@ func (this *VMessInboundHandler) HandleConnection(connection internet.Connection reader := v2io.NewBufferedReader(connReader) defer reader.Release() - this.RLock() - if !this.accepting { - this.RUnlock() + v.RLock() + if !v.accepting { + v.RUnlock() return } - session := encoding.NewServerSession(this.clients) + session := encoding.NewServerSession(v.clients) defer session.Release() request, err := session.DecodeRequestHeader(reader) - this.RUnlock() + v.RUnlock() if err != nil { if err != io.EOF { @@ -166,11 +166,11 @@ func (this *VMessInboundHandler) HandleConnection(connection internet.Connection connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse)) - ray := this.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ + ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{ Source: v2net.DestinationFromAddr(connection.RemoteAddr()), Destination: request.Destination(), User: request.User, - Inbound: this.meta, + Inbound: v.meta, }) input := ray.InboundInput() output := ray.InboundOutput() @@ -205,7 +205,7 @@ func (this *VMessInboundHandler) HandleConnection(connection internet.Connection defer writer.Release() response := &protocol.ResponseHeader{ - Command: this.generateCommand(request), + Command: v.generateCommand(request), } if connection.Reusable() { @@ -247,13 +247,13 @@ func (this *VMessInboundHandler) HandleConnection(connection internet.Connection type Factory struct{} -func (this *Factory) StreamCapability() v2net.NetworkList { +func (v *Factory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_TCP, v2net.Network_KCP, v2net.Network_WebSocket}, } } -func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { +func (v *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) { if !space.HasApp(dispatcher.APP_ID) { return nil, common.ErrBadConfiguration } diff --git a/proxy/vmess/io/reader.go b/proxy/vmess/io/reader.go index 4eeb36bb4..01943d1b1 100644 --- a/proxy/vmess/io/reader.go +++ b/proxy/vmess/io/reader.go @@ -22,12 +22,12 @@ func NewValidator(expectedAuth uint32) *Validator { } } -func (this *Validator) Consume(b []byte) { - this.actualAuth.Write(b) +func (v *Validator) Consume(b []byte) { + v.actualAuth.Write(b) } -func (this *Validator) Validate() bool { - return this.actualAuth.Sum32() == this.expectedAuth +func (v *Validator) Validate() bool { + return v.actualAuth.Sum32() == v.expectedAuth } type AuthChunkReader struct { @@ -44,73 +44,73 @@ func NewAuthChunkReader(reader io.Reader) *AuthChunkReader { } } -func (this *AuthChunkReader) Read() (*alloc.Buffer, error) { +func (v *AuthChunkReader) Read() (*alloc.Buffer, error) { var buffer *alloc.Buffer - if this.last != nil { - buffer = this.last - this.last = nil + if v.last != nil { + buffer = v.last + v.last = nil } else { buffer = alloc.NewBuffer().Clear() } - if this.chunkLength == -1 { + if v.chunkLength == -1 { for buffer.Len() < 6 { - _, err := buffer.FillFrom(this.reader) + _, err := buffer.FillFrom(v.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } length := serial.BytesToUint16(buffer.Value[:2]) - this.chunkLength = int(length) - 4 - this.validator = NewValidator(serial.BytesToUint32(buffer.Value[2:6])) + v.chunkLength = int(length) - 4 + v.validator = NewValidator(serial.BytesToUint32(buffer.Value[2:6])) buffer.SliceFrom(6) - if buffer.Len() < this.chunkLength && this.chunkLength <= 2048 { - _, err := buffer.FillFrom(this.reader) + if buffer.Len() < v.chunkLength && v.chunkLength <= 2048 { + _, err := buffer.FillFrom(v.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } - } else if buffer.Len() < this.chunkLength { - _, err := buffer.FillFrom(this.reader) + } else if buffer.Len() < v.chunkLength { + _, err := buffer.FillFrom(v.reader) if err != nil { buffer.Release() return nil, io.ErrUnexpectedEOF } } - if this.chunkLength == 0 { + if v.chunkLength == 0 { buffer.Release() return nil, io.EOF } - if buffer.Len() < this.chunkLength { - this.validator.Consume(buffer.Value) - this.chunkLength -= buffer.Len() + if buffer.Len() < v.chunkLength { + v.validator.Consume(buffer.Value) + v.chunkLength -= buffer.Len() } else { - this.validator.Consume(buffer.Value[:this.chunkLength]) - if !this.validator.Validate() { + v.validator.Consume(buffer.Value[:v.chunkLength]) + if !v.validator.Validate() { buffer.Release() return nil, errors.New("VMess|AuthChunkReader: Invalid auth.") } - leftLength := buffer.Len() - this.chunkLength + leftLength := buffer.Len() - v.chunkLength if leftLength > 0 { - this.last = alloc.NewBuffer().Clear() - this.last.Append(buffer.Value[this.chunkLength:]) - buffer.Slice(0, this.chunkLength) + v.last = alloc.NewBuffer().Clear() + v.last.Append(buffer.Value[v.chunkLength:]) + buffer.Slice(0, v.chunkLength) } - this.chunkLength = -1 - this.validator = nil + v.chunkLength = -1 + v.validator = nil } return buffer, nil } -func (this *AuthChunkReader) Release() { - this.reader = nil - this.last.Release() - this.last = nil - this.validator = nil +func (v *AuthChunkReader) Release() { + v.reader = nil + v.last.Release() + v.last = nil + v.validator = nil } diff --git a/proxy/vmess/io/writer.go b/proxy/vmess/io/writer.go index f24fea508..ffda61387 100644 --- a/proxy/vmess/io/writer.go +++ b/proxy/vmess/io/writer.go @@ -17,14 +17,14 @@ func NewAuthChunkWriter(writer v2io.Writer) *AuthChunkWriter { } } -func (this *AuthChunkWriter) Write(buffer *alloc.Buffer) error { +func (v *AuthChunkWriter) Write(buffer *alloc.Buffer) error { Authenticate(buffer) - return this.writer.Write(buffer) + return v.writer.Write(buffer) } -func (this *AuthChunkWriter) Release() { - this.writer.Release() - this.writer = nil +func (v *AuthChunkWriter) Release() { + v.writer.Release() + v.writer = nil } func Authenticate(buffer *alloc.Buffer) { diff --git a/proxy/vmess/outbound/command.go b/proxy/vmess/outbound/command.go index ef00fdecd..dd890e501 100644 --- a/proxy/vmess/outbound/command.go +++ b/proxy/vmess/outbound/command.go @@ -9,7 +9,7 @@ import ( "v2ray.com/core/proxy/vmess" ) -func (this *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) { +func (v *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitchAccount) { account := &vmess.Account{ Id: cmd.ID.String(), AlterId: uint32(cmd.AlterIds), @@ -22,16 +22,16 @@ func (this *VMessOutboundHandler) handleSwitchAccount(cmd *protocol.CommandSwitc } dest := v2net.TCPDestination(cmd.Host, cmd.Port) until := time.Now().Add(time.Duration(cmd.ValidMin) * time.Minute) - this.serverList.AddServer(protocol.NewServerSpec(dest, protocol.BeforeTime(until), user)) + v.serverList.AddServer(protocol.NewServerSpec(dest, protocol.BeforeTime(until), user)) } -func (this *VMessOutboundHandler) handleCommand(dest v2net.Destination, cmd protocol.ResponseCommand) { +func (v *VMessOutboundHandler) handleCommand(dest v2net.Destination, cmd protocol.ResponseCommand) { switch typedCommand := cmd.(type) { case *protocol.CommandSwitchAccount: if typedCommand.Host == nil { typedCommand.Host = dest.Address } - this.handleSwitchAccount(typedCommand) + v.handleSwitchAccount(typedCommand) default: } } diff --git a/proxy/vmess/outbound/outbound.go b/proxy/vmess/outbound/outbound.go index 3bbeacf47..720e30659 100644 --- a/proxy/vmess/outbound/outbound.go +++ b/proxy/vmess/outbound/outbound.go @@ -25,7 +25,7 @@ type VMessOutboundHandler struct { meta *proxy.OutboundHandlerMeta } -func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { +func (v *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error { defer ray.OutboundInput().Release() defer ray.OutboundOutput().Close() @@ -33,8 +33,8 @@ func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *al var conn internet.Connection err := retry.ExponentialBackoff(5, 100).On(func() error { - rec = this.serverPicker.PickServer() - rawConn, err := internet.Dial(this.meta.Address, rec.Destination(), this.meta.GetDialerOptions()) + rec = v.serverPicker.PickServer() + rawConn, err := internet.Dial(v.meta.Address, rec.Destination(), v.meta.GetDialerOptions()) if err != nil { return err } @@ -77,15 +77,15 @@ func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *al session := encoding.NewClientSession(protocol.DefaultIDHash) - go this.handleRequest(session, conn, request, payload, input, &requestFinish) - go this.handleResponse(session, conn, request, rec.Destination(), output, &responseFinish) + go v.handleRequest(session, conn, request, payload, input, &requestFinish) + go v.handleResponse(session, conn, request, rec.Destination(), output, &responseFinish) requestFinish.Lock() responseFinish.Lock() return nil } -func (this *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *alloc.Buffer, input v2io.Reader, finish *sync.Mutex) { +func (v *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *alloc.Buffer, input v2io.Reader, finish *sync.Mutex) { defer finish.Unlock() writer := v2io.NewBufferedWriter(conn) @@ -120,7 +120,7 @@ func (this *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, return } -func (this *VMessOutboundHandler) handleResponse(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output v2io.Writer, finish *sync.Mutex) { +func (v *VMessOutboundHandler) handleResponse(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output v2io.Writer, finish *sync.Mutex) { defer finish.Unlock() reader := v2io.NewBufferedReader(conn) @@ -132,7 +132,7 @@ func (this *VMessOutboundHandler) handleResponse(session *encoding.ClientSession log.Warning("VMess|Outbound: Failed to read response from ", request.Destination(), ": ", err) return } - go this.handleCommand(dest, header.Command) + go v.handleCommand(dest, header.Command) if !header.Option.Has(protocol.ResponseOptionConnectionReuse) { conn.SetReusable(false) @@ -158,13 +158,13 @@ func (this *VMessOutboundHandler) handleResponse(session *encoding.ClientSession type Factory struct{} -func (this *Factory) StreamCapability() v2net.NetworkList { +func (v *Factory) StreamCapability() v2net.NetworkList { return v2net.NetworkList{ Network: []v2net.Network{v2net.Network_TCP, v2net.Network_KCP, v2net.Network_WebSocket}, } } -func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { +func (v *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) { vOutConfig := rawConfig.(*Config) serverList := protocol.NewServerList() diff --git a/proxy/vmess/vmess.go b/proxy/vmess/vmess.go index 4d95c8881..cfeaaa4f4 100644 --- a/proxy/vmess/vmess.go +++ b/proxy/vmess/vmess.go @@ -53,33 +53,33 @@ func NewTimedUserValidator(hasher protocol.IDHash) protocol.UserValidator { return tus } -func (this *TimedUserValidator) Release() { - if !this.running { +func (v *TimedUserValidator) Release() { + if !v.running { return } - this.cancel.Cancel() - this.cancel.WaitForDone() + v.cancel.Cancel() + v.cancel.WaitForDone() - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - if !this.running { + if !v.running { return } - this.running = false - this.validUsers = nil - this.userHash = nil - this.ids = nil - this.hasher = nil - this.cancel = nil + v.running = false + v.validUsers = nil + v.userHash = nil + v.ids = nil + v.hasher = nil + v.cancel = nil } -func (this *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, idx int, entry *idEntry) { +func (v *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, idx int, entry *idEntry) { var hashValue [16]byte var hashValueRemoval [16]byte - idHash := this.hasher(entry.id.Bytes()) + idHash := v.hasher(entry.id.Bytes()) for entry.lastSec <= nowSec { idHash.Write(entry.lastSec.Bytes(nil)) idHash.Sum(hashValue[:0]) @@ -89,36 +89,36 @@ func (this *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, idx idHash.Sum(hashValueRemoval[:0]) idHash.Reset() - this.Lock() - this.userHash[hashValue] = &indexTimePair{idx, entry.lastSec} - delete(this.userHash, hashValueRemoval) - this.Unlock() + v.Lock() + v.userHash[hashValue] = &indexTimePair{idx, entry.lastSec} + delete(v.userHash, hashValueRemoval) + v.Unlock() entry.lastSec++ entry.lastSecRemoval++ } } -func (this *TimedUserValidator) updateUserHash(interval time.Duration) { - this.cancel.WaitThread() - defer this.cancel.FinishThread() +func (v *TimedUserValidator) updateUserHash(interval time.Duration) { + v.cancel.WaitThread() + defer v.cancel.FinishThread() for { select { case now := <-time.After(interval): nowSec := protocol.Timestamp(now.Unix() + cacheDurationSec) - for _, entry := range this.ids { - this.generateNewHashes(nowSec, entry.userIdx, entry) + for _, entry := range v.ids { + v.generateNewHashes(nowSec, entry.userIdx, entry) } - case <-this.cancel.WaitForCancel(): + case <-v.cancel.WaitForCancel(): return } } } -func (this *TimedUserValidator) Add(user *protocol.User) error { - idx := len(this.validUsers) - this.validUsers = append(this.validUsers, user) +func (v *TimedUserValidator) Add(user *protocol.User) error { + idx := len(v.validUsers) + v.validUsers = append(v.validUsers, user) rawAccount, err := user.GetTypedAccount() if err != nil { return err @@ -133,8 +133,8 @@ func (this *TimedUserValidator) Add(user *protocol.User) error { lastSec: protocol.Timestamp(nowSec - cacheDurationSec), lastSecRemoval: protocol.Timestamp(nowSec - cacheDurationSec*3), } - this.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry) - this.ids = append(this.ids, entry) + v.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry) + v.ids = append(v.ids, entry) for _, alterid := range account.AlterIDs { entry := &idEntry{ id: alterid, @@ -142,25 +142,25 @@ func (this *TimedUserValidator) Add(user *protocol.User) error { lastSec: protocol.Timestamp(nowSec - cacheDurationSec), lastSecRemoval: protocol.Timestamp(nowSec - cacheDurationSec*3), } - this.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry) - this.ids = append(this.ids, entry) + v.generateNewHashes(protocol.Timestamp(nowSec+cacheDurationSec), idx, entry) + v.ids = append(v.ids, entry) } return nil } -func (this *TimedUserValidator) Get(userHash []byte) (*protocol.User, protocol.Timestamp, bool) { - defer this.RUnlock() - this.RLock() +func (v *TimedUserValidator) Get(userHash []byte) (*protocol.User, protocol.Timestamp, bool) { + defer v.RUnlock() + v.RLock() - if !this.running { + if !v.running { return nil, 0, false } var fixedSizeHash [16]byte copy(fixedSizeHash[:], userHash) - pair, found := this.userHash[fixedSizeHash] + pair, found := v.userHash[fixedSizeHash] if found { - return this.validUsers[pair.index], pair.timeSec, true + return v.validUsers[pair.index], pair.timeSec, true } return nil, 0, false } diff --git a/testing/assert/address.go b/testing/assert/address.go index 7eb66ea19..b9ee2a186 100644 --- a/testing/assert/address.go +++ b/testing/assert/address.go @@ -4,11 +4,11 @@ import ( v2net "v2ray.com/core/common/net" ) -func (this *Assert) Address(value v2net.Address) *AddressSubject { +func (v *Assert) Address(value v2net.Address) *AddressSubject { return &AddressSubject{ Subject: Subject{ disp: value.String(), - a: this, + a: v, }, value: value, } diff --git a/testing/assert/assert.go b/testing/assert/assert.go index eaa5f682f..3e8a1849a 100644 --- a/testing/assert/assert.go +++ b/testing/assert/assert.go @@ -18,9 +18,9 @@ type Assert struct { t *testing.T } -func (this *Assert) Fail(message string) { +func (v *Assert) Fail(message string) { fmt.Println(decorate(message)) - this.t.Fail() + v.t.Fail() } func getCaller() (string, int) { diff --git a/testing/assert/bool.go b/testing/assert/bool.go index 070b8932a..bd777a7c5 100644 --- a/testing/assert/bool.go +++ b/testing/assert/bool.go @@ -5,11 +5,11 @@ import ( ) // Assert on a boolean variable. -func (this *Assert) Bool(value bool) *BoolSubject { +func (v *Assert) Bool(value bool) *BoolSubject { return &BoolSubject{ Subject: Subject{ disp: strconv.FormatBool(value), - a: this, + a: v, }, value: value, } diff --git a/testing/assert/byte.go b/testing/assert/byte.go index ac2504885..73813cb61 100644 --- a/testing/assert/byte.go +++ b/testing/assert/byte.go @@ -4,11 +4,11 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Byte(value byte) *ByteSubject { +func (v *Assert) Byte(value byte) *ByteSubject { return &ByteSubject{ Subject: Subject{ disp: serial.ByteToHexString(value), - a: this, + a: v, }, value: value, } diff --git a/testing/assert/bytes.go b/testing/assert/bytes.go index c791a2b5e..70f121f29 100644 --- a/testing/assert/bytes.go +++ b/testing/assert/bytes.go @@ -6,11 +6,11 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Bytes(value []byte) *BytesSubject { +func (v *Assert) Bytes(value []byte) *BytesSubject { return &BytesSubject{ Subject: Subject{ disp: serial.BytesToHexString(value), - a: this, + a: v, }, value: value, } diff --git a/testing/assert/destination.go b/testing/assert/destination.go index d6cdea766..0425654bd 100644 --- a/testing/assert/destination.go +++ b/testing/assert/destination.go @@ -4,11 +4,11 @@ import ( v2net "v2ray.com/core/common/net" ) -func (this *Assert) Destination(value v2net.Destination) *DestinationSubject { +func (v *Assert) Destination(value v2net.Destination) *DestinationSubject { return &DestinationSubject{ Subject: Subject{ disp: value.String(), - a: this, + a: v, }, value: value, } @@ -19,40 +19,40 @@ type DestinationSubject struct { value v2net.Destination } -func (this *DestinationSubject) IsTCP() { - if this.value.Network != v2net.Network_TCP { - this.Fail("is", "a TCP destination") +func (v *DestinationSubject) IsTCP() { + if v.value.Network != v2net.Network_TCP { + v.Fail("is", "a TCP destination") } } -func (this *DestinationSubject) IsNotTCP() { - if this.value.Network == v2net.Network_TCP { - this.Fail("is not", "a TCP destination") +func (v *DestinationSubject) IsNotTCP() { + if v.value.Network == v2net.Network_TCP { + v.Fail("is not", "a TCP destination") } } -func (this *DestinationSubject) IsUDP() { - if this.value.Network != v2net.Network_UDP { - this.Fail("is", "a UDP destination") +func (v *DestinationSubject) IsUDP() { + if v.value.Network != v2net.Network_UDP { + v.Fail("is", "a UDP destination") } } -func (this *DestinationSubject) IsNotUDP() { - if this.value.Network == v2net.Network_UDP { - this.Fail("is not", "a UDP destination") +func (v *DestinationSubject) IsNotUDP() { + if v.value.Network == v2net.Network_UDP { + v.Fail("is not", "a UDP destination") } } -func (this *DestinationSubject) EqualsString(another string) { - if this.value.String() != another { - this.Fail("not equals to string", another) +func (v *DestinationSubject) EqualsString(another string) { + if v.value.String() != another { + v.Fail("not equals to string", another) } } -func (this *DestinationSubject) HasAddress() *AddressSubject { - return this.a.Address(this.value.Address) +func (v *DestinationSubject) HasAddress() *AddressSubject { + return v.a.Address(v.value.Address) } -func (this *DestinationSubject) HasPort() *PortSubject { - return this.a.Port(this.value.Port) +func (v *DestinationSubject) HasPort() *PortSubject { + return v.a.Port(v.value.Port) } diff --git a/testing/assert/error.go b/testing/assert/error.go index 166abd6e0..3356db0e5 100644 --- a/testing/assert/error.go +++ b/testing/assert/error.go @@ -1,13 +1,13 @@ package assert -func (this *Assert) Error(value error) *ErrorSubject { +func (v *Assert) Error(value error) *ErrorSubject { valueStr := "" if value != nil { valueStr = value.Error() } return &ErrorSubject{ Subject: Subject{ - a: this, + a: v, disp: valueStr, }, value: value, diff --git a/testing/assert/int64.go b/testing/assert/int64.go index 8e5c73839..cf10ea6ce 100644 --- a/testing/assert/int64.go +++ b/testing/assert/int64.go @@ -4,10 +4,10 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Int64(value int64) *Int64Subject { +func (v *Assert) Int64(value int64) *Int64Subject { return &Int64Subject{ Subject: Subject{ - a: this, + a: v, disp: serial.Int64ToString(value), }, value: value, diff --git a/testing/assert/intsubject.go b/testing/assert/intsubject.go index 4d1017520..b688ff607 100644 --- a/testing/assert/intsubject.go +++ b/testing/assert/intsubject.go @@ -4,10 +4,10 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Int(value int) *IntSubject { +func (v *Assert) Int(value int) *IntSubject { return &IntSubject{ Subject: Subject{ - a: this, + a: v, disp: serial.IntToString(value), }, value: value, diff --git a/testing/assert/ip.go b/testing/assert/ip.go index 85dad1585..cf3982713 100644 --- a/testing/assert/ip.go +++ b/testing/assert/ip.go @@ -5,10 +5,10 @@ import ( "net" ) -func (this *Assert) IP(value net.IP) *IPSubject { +func (v *Assert) IP(value net.IP) *IPSubject { return &IPSubject{ Subject: Subject{ - a: this, + a: v, disp: value.String(), }, value: value, diff --git a/testing/assert/pointer.go b/testing/assert/pointer.go index 502d22041..c18e14b60 100644 --- a/testing/assert/pointer.go +++ b/testing/assert/pointer.go @@ -6,10 +6,10 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Pointer(value interface{}) *PointerSubject { +func (v *Assert) Pointer(value interface{}) *PointerSubject { return &PointerSubject{ Subject: Subject{ - a: this, + a: v, disp: serial.PointerToString(value), }, value: value, diff --git a/testing/assert/port.go b/testing/assert/port.go index a534eff27..5dd03a5d4 100644 --- a/testing/assert/port.go +++ b/testing/assert/port.go @@ -4,10 +4,10 @@ import ( v2net "v2ray.com/core/common/net" ) -func (this *Assert) Port(value v2net.Port) *PortSubject { +func (v *Assert) Port(value v2net.Port) *PortSubject { return &PortSubject{ Subject: Subject{ - a: this, + a: v, disp: value.String(), }, value: value, diff --git a/testing/assert/string.go b/testing/assert/string.go index 32a15efdf..9c3b0504e 100644 --- a/testing/assert/string.go +++ b/testing/assert/string.go @@ -4,10 +4,10 @@ import ( "strings" ) -func (this *Assert) String(value string) *StringSubject { +func (v *Assert) String(value string) *StringSubject { return &StringSubject{ Subject: Subject{ - a: this, + a: v, disp: value, }, value: value, diff --git a/testing/assert/uint16.go b/testing/assert/uint16.go index 806473ca4..9244e11b9 100644 --- a/testing/assert/uint16.go +++ b/testing/assert/uint16.go @@ -4,10 +4,10 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Uint16(value uint16) *Uint16Subject { +func (v *Assert) Uint16(value uint16) *Uint16Subject { return &Uint16Subject{ Subject: Subject{ - a: this, + a: v, disp: serial.Uint16ToString(value), }, value: value, diff --git a/testing/assert/uint32.go b/testing/assert/uint32.go index 61fb9e9fb..b2f18c0be 100644 --- a/testing/assert/uint32.go +++ b/testing/assert/uint32.go @@ -4,10 +4,10 @@ import ( "v2ray.com/core/common/serial" ) -func (this *Assert) Uint32(value uint32) *Uint32Subject { +func (v *Assert) Uint32(value uint32) *Uint32Subject { return &Uint32Subject{ Subject: Subject{ - a: this, + a: v, disp: serial.Uint32ToString(value), }, value: value, diff --git a/testing/servers/http/http.go b/testing/servers/http/http.go index 0d305c8fa..e90ef87a8 100644 --- a/testing/servers/http/http.go +++ b/testing/servers/http/http.go @@ -31,6 +31,6 @@ func (server *Server) Start() (v2net.Destination, error) { return v2net.TCPDestination(v2net.LocalHostIP, v2net.Port(server.Port)), nil } -func (this *Server) Close() { - this.accepting = false +func (v *Server) Close() { + v.accepting = false } diff --git a/testing/servers/tcp/tcp.go b/testing/servers/tcp/tcp.go index 2aabf9975..2ff8c02a6 100644 --- a/testing/servers/tcp/tcp.go +++ b/testing/servers/tcp/tcp.go @@ -60,7 +60,7 @@ func (server *Server) handleConnection(conn net.Conn) { conn.Close() } -func (this *Server) Close() { - this.accepting = false - this.listener.Close() +func (v *Server) Close() { + v.accepting = false + v.listener.Close() } diff --git a/tools/conf/blackhole.go b/tools/conf/blackhole.go index fdd5137b9..9178671ba 100644 --- a/tools/conf/blackhole.go +++ b/tools/conf/blackhole.go @@ -24,10 +24,10 @@ type BlackholeConfig struct { Response json.RawMessage `json:"response"` } -func (this *BlackholeConfig) Build() (*loader.TypedSettings, error) { +func (v *BlackholeConfig) Build() (*loader.TypedSettings, error) { config := new(blackhole.Config) - if this.Response != nil { - response, _, err := configLoader.Load(this.Response) + if v.Response != nil { + response, _, err := configLoader.Load(v.Response) if err != nil { return nil, errors.New("Blackhole: Failed to parse response config: " + err.Error()) } diff --git a/tools/conf/common.go b/tools/conf/common.go index f95ed53b8..2f309902e 100644 --- a/tools/conf/common.go +++ b/tools/conf/common.go @@ -17,21 +17,21 @@ func NewStringList(raw []string) *StringList { return &list } -func (this StringList) Len() int { - return len(this) +func (v StringList) Len() int { + return len(v) } -func (this *StringList) UnmarshalJSON(data []byte) error { +func (v *StringList) UnmarshalJSON(data []byte) error { var strarray []string if err := json.Unmarshal(data, &strarray); err == nil { - *this = *NewStringList(strarray) + *v = *NewStringList(strarray) return nil } var rawstr string if err := json.Unmarshal(data, &rawstr); err == nil { strlist := strings.Split(rawstr, ",") - *this = *NewStringList(strlist) + *v = *NewStringList(strlist) return nil } return errors.New("Unknown format of a string list: " + string(data)) @@ -41,45 +41,45 @@ type Address struct { v2net.Address } -func (this *Address) UnmarshalJSON(data []byte) error { +func (v *Address) UnmarshalJSON(data []byte) error { var rawStr string if err := json.Unmarshal(data, &rawStr); err != nil { return err } - this.Address = v2net.ParseAddress(rawStr) + v.Address = v2net.ParseAddress(rawStr) return nil } -func (this *Address) Build() *v2net.IPOrDomain { - if this.Family().IsDomain() { +func (v *Address) Build() *v2net.IPOrDomain { + if v.Family().IsDomain() { return &v2net.IPOrDomain{ Address: &v2net.IPOrDomain_Domain{ - Domain: this.Domain(), + Domain: v.Domain(), }, } } return &v2net.IPOrDomain{ Address: &v2net.IPOrDomain_Ip{ - Ip: []byte(this.IP()), + Ip: []byte(v.IP()), }, } } type Network string -func (this Network) Build() v2net.Network { - return v2net.ParseNetwork(string(this)) +func (v Network) Build() v2net.Network { + return v2net.ParseNetwork(string(v)) } type NetworkList []Network -func (this *NetworkList) UnmarshalJSON(data []byte) error { +func (v *NetworkList) UnmarshalJSON(data []byte) error { var strarray []Network if err := json.Unmarshal(data, &strarray); err == nil { nl := NetworkList(strarray) - *this = nl + *v = nl return nil } @@ -90,15 +90,15 @@ func (this *NetworkList) UnmarshalJSON(data []byte) error { for idx, network := range strlist { nl[idx] = Network(network) } - *this = nl + *v = nl return nil } return errors.New("Unknown format of a string list: " + string(data)) } -func (this *NetworkList) Build() *v2net.NetworkList { +func (v *NetworkList) Build() *v2net.NetworkList { list := new(v2net.NetworkList) - for _, network := range *this { + for _, network := range *v { list.Network = append(list.Network, network.Build()) } return list @@ -144,28 +144,28 @@ type PortRange struct { To uint32 } -func (this *PortRange) Build() *v2net.PortRange { +func (v *PortRange) Build() *v2net.PortRange { return &v2net.PortRange{ - From: this.From, - To: this.To, + From: v.From, + To: v.To, } } // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON -func (this *PortRange) UnmarshalJSON(data []byte) error { +func (v *PortRange) UnmarshalJSON(data []byte) error { port, err := parseIntPort(data) if err == nil { - this.From = uint32(port) - this.To = uint32(port) + v.From = uint32(port) + v.To = uint32(port) return nil } from, to, err := parseStringPort(data) if err == nil { - this.From = uint32(from) - this.To = uint32(to) - if this.From > this.To { - log.Error("Invalid port range ", this.From, " -> ", this.To) + v.From = uint32(from) + v.To = uint32(to) + if v.From > v.To { + log.Error("Invalid port range ", v.From, " -> ", v.To) return v2net.ErrInvalidPortRange } return nil @@ -180,9 +180,9 @@ type User struct { LevelByte byte `json:"level"` } -func (this *User) Build() *protocol.User { +func (v *User) Build() *protocol.User { return &protocol.User{ - Email: this.EmailString, - Level: uint32(this.LevelByte), + Email: v.EmailString, + Level: uint32(v.LevelByte), } } diff --git a/tools/conf/dns.go b/tools/conf/dns.go index 38280991f..50ebb9e3e 100644 --- a/tools/conf/dns.go +++ b/tools/conf/dns.go @@ -10,10 +10,10 @@ type DnsConfig struct { Hosts map[string]*Address `json:"hosts"` } -func (this *DnsConfig) Build() *dns.Config { +func (v *DnsConfig) Build() *dns.Config { config := new(dns.Config) - config.NameServers = make([]*v2net.Endpoint, len(this.Servers)) - for idx, server := range this.Servers { + config.NameServers = make([]*v2net.Endpoint, len(v.Servers)) + for idx, server := range v.Servers { config.NameServers[idx] = &v2net.Endpoint{ Network: v2net.Network_UDP, Address: server.Build(), @@ -21,9 +21,9 @@ func (this *DnsConfig) Build() *dns.Config { } } - if this.Hosts != nil { + if v.Hosts != nil { config.Hosts = make(map[string]*v2net.IPOrDomain) - for domain, ip := range this.Hosts { + for domain, ip := range v.Hosts { config.Hosts[domain] = ip.Build() } } diff --git a/tools/conf/dokodemo.go b/tools/conf/dokodemo.go index 156b18d23..b469e0972 100644 --- a/tools/conf/dokodemo.go +++ b/tools/conf/dokodemo.go @@ -13,14 +13,14 @@ type DokodemoConfig struct { Redirect bool `json:"followRedirect"` } -func (this *DokodemoConfig) Build() (*loader.TypedSettings, error) { +func (v *DokodemoConfig) Build() (*loader.TypedSettings, error) { config := new(dokodemo.Config) - if this.Host != nil { - config.Address = this.Host.Build() + if v.Host != nil { + config.Address = v.Host.Build() } - config.Port = uint32(this.PortValue) - config.NetworkList = this.NetworkList.Build() - config.Timeout = this.TimeoutValue - config.FollowRedirect = this.Redirect + config.Port = uint32(v.PortValue) + config.NetworkList = v.NetworkList.Build() + config.Timeout = v.TimeoutValue + config.FollowRedirect = v.Redirect return loader.NewTypedSettings(config), nil } diff --git a/tools/conf/freedom.go b/tools/conf/freedom.go index a5f23bbf8..d54e6c966 100644 --- a/tools/conf/freedom.go +++ b/tools/conf/freedom.go @@ -12,13 +12,13 @@ type FreedomConfig struct { Timeout uint32 `json:"timeout"` } -func (this *FreedomConfig) Build() (*loader.TypedSettings, error) { +func (v *FreedomConfig) Build() (*loader.TypedSettings, error) { config := new(freedom.Config) config.DomainStrategy = freedom.Config_AS_IS - domainStrategy := strings.ToLower(this.DomainStrategy) + domainStrategy := strings.ToLower(v.DomainStrategy) if domainStrategy == "useip" || domainStrategy == "use_ip" { config.DomainStrategy = freedom.Config_USE_IP } - config.Timeout = this.Timeout + config.Timeout = v.Timeout return loader.NewTypedSettings(config), nil } diff --git a/tools/conf/http.go b/tools/conf/http.go index edf5b4e98..944be624e 100644 --- a/tools/conf/http.go +++ b/tools/conf/http.go @@ -9,9 +9,9 @@ type HttpServerConfig struct { Timeout uint32 `json:"timeout"` } -func (this *HttpServerConfig) Build() (*loader.TypedSettings, error) { +func (v *HttpServerConfig) Build() (*loader.TypedSettings, error) { config := &http.ServerConfig{ - Timeout: this.Timeout, + Timeout: v.Timeout, } return loader.NewTypedSettings(config), nil diff --git a/tools/conf/loader.go b/tools/conf/loader.go index b6c7dbfc9..1ff5e461f 100644 --- a/tools/conf/loader.go +++ b/tools/conf/loader.go @@ -16,17 +16,17 @@ type ConfigCreator func() interface{} type ConfigCreatorCache map[string]ConfigCreator -func (this ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error { - if _, found := this[id]; found { +func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error { + if _, found := v[id]; found { return common.ErrDuplicatedName } - this[id] = creator + v[id] = creator return nil } -func (this ConfigCreatorCache) CreateConfig(id string) (interface{}, error) { - creator, found := this[id] +func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) { + creator, found := v[id] if !found { return nil, ErrUnknownConfigID } @@ -47,8 +47,8 @@ func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey strin } } -func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) { - creator, found := this.cache[id] +func (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) { + creator, found := v.cache[id] if !found { return nil, ErrUnknownConfigID } @@ -60,14 +60,14 @@ func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, er return config, nil } -func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) { +func (v *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) { var obj map[string]json.RawMessage if err := json.Unmarshal(raw, &obj); err != nil { return nil, "", err } - rawID, found := obj[this.idKey] + rawID, found := obj[v.idKey] if !found { - log.Error(this.idKey, " not found in JSON content.") + log.Error(v.idKey, " not found in JSON content.") return nil, "", common.ErrObjectNotFound } var id string @@ -75,15 +75,15 @@ func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) { return nil, "", err } rawConfig := json.RawMessage(raw) - if len(this.configKey) > 0 { - configValue, found := obj[this.configKey] + if len(v.configKey) > 0 { + configValue, found := obj[v.configKey] if !found { - log.Error(this.configKey, " not found in JSON content.") + log.Error(v.configKey, " not found in JSON content.") return nil, "", common.ErrObjectNotFound } rawConfig = configValue } - config, err := this.LoadWithID([]byte(rawConfig), id) + config, err := v.LoadWithID([]byte(rawConfig), id) if err != nil { return nil, id, err } diff --git a/tools/conf/log.go b/tools/conf/log.go index 07ee61c55..085214c21 100644 --- a/tools/conf/log.go +++ b/tools/conf/log.go @@ -12,8 +12,8 @@ type LogConfig struct { LogLevel string `json:"loglevel"` } -func (this *LogConfig) Build() *log.Config { - if this == nil { +func (v *LogConfig) Build() *log.Config { + if v == nil { return nil } config := &log.Config{ @@ -21,16 +21,16 @@ func (this *LogConfig) Build() *log.Config { AccessLogType: log.LogType_Console, } - if len(this.AccessLog) > 0 { - config.AccessLogPath = this.AccessLog + if len(v.AccessLog) > 0 { + config.AccessLogPath = v.AccessLog config.AccessLogType = log.LogType_File } - if len(this.ErrorLog) > 0 { - config.ErrorLogPath = this.ErrorLog + if len(v.ErrorLog) > 0 { + config.ErrorLogPath = v.ErrorLog config.ErrorLogType = log.LogType_File } - level := strings.ToLower(this.LogLevel) + level := strings.ToLower(v.LogLevel) switch level { case "debug": config.ErrorLogLevel = log.LogLevel_Debug diff --git a/tools/conf/router.go b/tools/conf/router.go index 3de96cb20..1a89f8937 100644 --- a/tools/conf/router.go +++ b/tools/conf/router.go @@ -23,13 +23,13 @@ type RouterConfig struct { Settings *RouterRulesConfig `json:"settings"` } -func (this *RouterConfig) Build() (*router.Config, error) { - if this.Settings == nil { +func (v *RouterConfig) Build() (*router.Config, error) { + if v.Settings == nil { return nil, errors.New("Router settings is not specified.") } config := new(router.Config) - settings := this.Settings + settings := v.Settings config.DomainStrategy = router.Config_AsIs config.Rule = make([]*router.RoutingRule, len(settings.RuleList)) domainStrategy := strings.ToLower(settings.DomainStrategy) diff --git a/tools/conf/shadowsocks.go b/tools/conf/shadowsocks.go index b1f66151e..d3360800f 100644 --- a/tools/conf/shadowsocks.go +++ b/tools/conf/shadowsocks.go @@ -18,25 +18,25 @@ type ShadowsocksServerConfig struct { OTA *bool `json:"ota"` } -func (this *ShadowsocksServerConfig) Build() (*loader.TypedSettings, error) { +func (v *ShadowsocksServerConfig) Build() (*loader.TypedSettings, error) { config := new(shadowsocks.ServerConfig) - config.UdpEnabled = this.UDP + config.UdpEnabled = v.UDP - if len(this.Password) == 0 { + if len(v.Password) == 0 { return nil, errors.New("Shadowsocks password is not specified.") } account := &shadowsocks.Account{ - Password: this.Password, + Password: v.Password, Ota: shadowsocks.Account_Auto, } - if this.OTA != nil { - if *this.OTA { + if v.OTA != nil { + if *v.OTA { account.Ota = shadowsocks.Account_Enabled } else { account.Ota = shadowsocks.Account_Disabled } } - cipher := strings.ToLower(this.Cipher) + cipher := strings.ToLower(v.Cipher) switch cipher { case "aes-256-cfb": account.CipherType = shadowsocks.CipherType_AES_256_CFB @@ -51,8 +51,8 @@ func (this *ShadowsocksServerConfig) Build() (*loader.TypedSettings, error) { } config.User = &protocol.User{ - Email: this.Email, - Level: uint32(this.Level), + Email: v.Email, + Level: uint32(v.Level), Account: loader.NewTypedSettings(account), } @@ -72,15 +72,15 @@ type ShadowsocksClientConfig struct { Servers []*ShadowsocksServerTarget `json:"servers"` } -func (this *ShadowsocksClientConfig) Build() (*loader.TypedSettings, error) { +func (v *ShadowsocksClientConfig) Build() (*loader.TypedSettings, error) { config := new(shadowsocks.ClientConfig) - if len(this.Servers) == 0 { + if len(v.Servers) == 0 { return nil, errors.New("0 Shadowsocks server configured.") } - serverSpecs := make([]*protocol.ServerEndpoint, len(this.Servers)) - for idx, server := range this.Servers { + serverSpecs := make([]*protocol.ServerEndpoint, len(v.Servers)) + for idx, server := range v.Servers { if server.Address == nil { return nil, errors.New("Shadowsocks server address is not set.") } diff --git a/tools/conf/socks.go b/tools/conf/socks.go index 4478b5c46..a46b20e96 100644 --- a/tools/conf/socks.go +++ b/tools/conf/socks.go @@ -14,10 +14,10 @@ type SocksAccount struct { Password string `json:"pass"` } -func (this *SocksAccount) Build() *socks.Account { +func (v *SocksAccount) Build() *socks.Account { return &socks.Account{ - Username: this.Username, - Password: this.Password, + Username: v.Username, + Password: v.Password, } } @@ -34,29 +34,29 @@ type SocksServerConfig struct { Timeout uint32 `json:"timeout"` } -func (this *SocksServerConfig) Build() (*loader.TypedSettings, error) { +func (v *SocksServerConfig) Build() (*loader.TypedSettings, error) { config := new(socks.ServerConfig) - if this.AuthMethod == AuthMethodNoAuth { + if v.AuthMethod == AuthMethodNoAuth { config.AuthType = socks.AuthType_NO_AUTH - } else if this.AuthMethod == AuthMethodUserPass { + } else if v.AuthMethod == AuthMethodUserPass { config.AuthType = socks.AuthType_PASSWORD } else { - return nil, errors.New("Unknown socks auth method: " + this.AuthMethod) + return nil, errors.New("Unknown socks auth method: " + v.AuthMethod) } - if len(this.Accounts) > 0 { - config.Accounts = make(map[string]string, len(this.Accounts)) - for _, account := range this.Accounts { + if len(v.Accounts) > 0 { + config.Accounts = make(map[string]string, len(v.Accounts)) + for _, account := range v.Accounts { config.Accounts[account.Username] = account.Password } } - config.UdpEnabled = this.UDP - if this.Host != nil { - config.Address = this.Host.Build() + config.UdpEnabled = v.UDP + if v.Host != nil { + config.Address = v.Host.Build() } - config.Timeout = this.Timeout + config.Timeout = v.Timeout return loader.NewTypedSettings(config), nil } @@ -69,10 +69,10 @@ type SocksClientConfig struct { Servers []*SocksRemoteConfig `json:"servers"` } -func (this *SocksClientConfig) Build() (*loader.TypedSettings, error) { +func (v *SocksClientConfig) Build() (*loader.TypedSettings, error) { config := new(socks.ClientConfig) - config.Server = make([]*protocol.ServerEndpoint, len(this.Servers)) - for idx, serverConfig := range this.Servers { + config.Server = make([]*protocol.ServerEndpoint, len(v.Servers)) + for idx, serverConfig := range v.Servers { server := &protocol.ServerEndpoint{ Address: serverConfig.Address.Build(), Port: uint32(serverConfig.Port), diff --git a/tools/conf/transport.go b/tools/conf/transport.go index 7a8089259..ea33bef79 100644 --- a/tools/conf/transport.go +++ b/tools/conf/transport.go @@ -14,11 +14,11 @@ type TransportConfig struct { WSConfig *WebSocketConfig `json:"wsSettings"` } -func (this *TransportConfig) Build() (*transport.Config, error) { +func (v *TransportConfig) Build() (*transport.Config, error) { config := new(transport.Config) - if this.TCPConfig != nil { - ts, err := this.TCPConfig.Build() + if v.TCPConfig != nil { + ts, err := v.TCPConfig.Build() if err != nil { return nil, errors.New("Failed to build TCP config: " + err.Error()) } @@ -28,8 +28,8 @@ func (this *TransportConfig) Build() (*transport.Config, error) { }) } - if this.KCPConfig != nil { - ts, err := this.KCPConfig.Build() + if v.KCPConfig != nil { + ts, err := v.KCPConfig.Build() if err != nil { return nil, errors.New("Failed to build KCP config: " + err.Error()) } @@ -39,8 +39,8 @@ func (this *TransportConfig) Build() (*transport.Config, error) { }) } - if this.WSConfig != nil { - ts, err := this.WSConfig.Build() + if v.WSConfig != nil { + ts, err := v.WSConfig.Build() if err != nil { return nil, errors.New("Failed to build WebSocket config: " + err.Error()) } diff --git a/tools/conf/transport_authenticators.go b/tools/conf/transport_authenticators.go index 60dc51101..48d67b614 100644 --- a/tools/conf/transport_authenticators.go +++ b/tools/conf/transport_authenticators.go @@ -41,7 +41,7 @@ type HTTPAuthenticatorRequest struct { Headers map[string]*StringList `json:"headers"` } -func (this *HTTPAuthenticatorRequest) Build() (*http.RequestConfig, error) { +func (v *HTTPAuthenticatorRequest) Build() (*http.RequestConfig, error) { config := &http.RequestConfig{ Uri: []string{"/"}, Header: []*http.Header{ @@ -71,21 +71,21 @@ func (this *HTTPAuthenticatorRequest) Build() (*http.RequestConfig, error) { }, } - if len(this.Version) > 0 { - config.Version = &http.Version{Value: this.Version} + if len(v.Version) > 0 { + config.Version = &http.Version{Value: v.Version} } - if len(this.Method) > 0 { - config.Method = &http.Method{Value: this.Method} + if len(v.Method) > 0 { + config.Method = &http.Method{Value: v.Method} } - if len(this.Path) > 0 { - config.Uri = append([]string(nil), (this.Path)...) + if len(v.Path) > 0 { + config.Uri = append([]string(nil), (v.Path)...) } - if len(this.Headers) > 0 { - config.Header = make([]*http.Header, 0, len(this.Headers)) - for key, value := range this.Headers { + if len(v.Headers) > 0 { + config.Header = make([]*http.Header, 0, len(v.Headers)) + for key, value := range v.Headers { if value == nil { return nil, errors.New("Empty HTTP header value: " + key) } @@ -106,7 +106,7 @@ type HTTPAuthenticatorResponse struct { Headers map[string]*StringList `json:"headers"` } -func (this *HTTPAuthenticatorResponse) Build() (*http.ResponseConfig, error) { +func (v *HTTPAuthenticatorResponse) Build() (*http.ResponseConfig, error) { config := &http.ResponseConfig{ Header: []*http.Header{ { @@ -128,26 +128,26 @@ func (this *HTTPAuthenticatorResponse) Build() (*http.ResponseConfig, error) { }, } - if len(this.Version) > 0 { - config.Version = &http.Version{Value: this.Version} + if len(v.Version) > 0 { + config.Version = &http.Version{Value: v.Version} } - if len(this.Status) > 0 || len(this.Reason) > 0 { + if len(v.Status) > 0 || len(v.Reason) > 0 { config.Status = &http.Status{ Code: "200", Reason: "OK", } - if len(this.Status) > 0 { - config.Status.Code = this.Status + if len(v.Status) > 0 { + config.Status.Code = v.Status } - if len(this.Reason) > 0 { - config.Status.Reason = this.Reason + if len(v.Reason) > 0 { + config.Status.Reason = v.Reason } } - if len(this.Headers) > 0 { - config.Header = make([]*http.Header, 0, len(this.Headers)) - for key, value := range this.Headers { + if len(v.Headers) > 0 { + config.Header = make([]*http.Header, 0, len(v.Headers)) + for key, value := range v.Headers { if value == nil { return nil, errors.New("Empty HTTP header value: " + key) } @@ -166,15 +166,15 @@ type HTTPAuthenticator struct { Response HTTPAuthenticatorResponse `json:"response"` } -func (this *HTTPAuthenticator) Build() (*loader.TypedSettings, error) { +func (v *HTTPAuthenticator) Build() (*loader.TypedSettings, error) { config := new(http.Config) - requestConfig, err := this.Request.Build() + requestConfig, err := v.Request.Build() if err != nil { return nil, err } config.Request = requestConfig - responseConfig, err := this.Response.Build() + responseConfig, err := v.Response.Build() if err != nil { return nil, err } diff --git a/tools/conf/transport_internet.go b/tools/conf/transport_internet.go index a3bf509ca..acc39a7d6 100644 --- a/tools/conf/transport_internet.go +++ b/tools/conf/transport_internet.go @@ -40,50 +40,50 @@ type KCPConfig struct { HeaderConfig json.RawMessage `json:"header"` } -func (this *KCPConfig) Build() (*loader.TypedSettings, error) { +func (v *KCPConfig) Build() (*loader.TypedSettings, error) { config := new(kcp.Config) - if this.Mtu != nil { - mtu := *this.Mtu + if v.Mtu != nil { + mtu := *v.Mtu if mtu < 576 || mtu > 1460 { return nil, fmt.Errorf("KCP|Config: Invalid MTU size: %d", mtu) } config.Mtu = &kcp.MTU{Value: mtu} } - if this.Tti != nil { - tti := *this.Tti + if v.Tti != nil { + tti := *v.Tti if tti < 10 || tti > 100 { return nil, fmt.Errorf("KCP|Config: Invalid TTI: %d", tti) } config.Tti = &kcp.TTI{Value: tti} } - if this.UpCap != nil { - config.UplinkCapacity = &kcp.UplinkCapacity{Value: *this.UpCap} + if v.UpCap != nil { + config.UplinkCapacity = &kcp.UplinkCapacity{Value: *v.UpCap} } - if this.DownCap != nil { - config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *this.DownCap} + if v.DownCap != nil { + config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *v.DownCap} } - if this.Congestion != nil { - config.Congestion = *this.Congestion + if v.Congestion != nil { + config.Congestion = *v.Congestion } - if this.ReadBufferSize != nil { - size := *this.ReadBufferSize + if v.ReadBufferSize != nil { + size := *v.ReadBufferSize if size > 0 { config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024} } else { config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024} } } - if this.WriteBufferSize != nil { - size := *this.WriteBufferSize + if v.WriteBufferSize != nil { + size := *v.WriteBufferSize if size > 0 { config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024} } else { config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024} } } - if len(this.HeaderConfig) > 0 { - headerConfig, _, err := kcpHeaderLoader.Load(this.HeaderConfig) + if len(v.HeaderConfig) > 0 { + headerConfig, _, err := kcpHeaderLoader.Load(v.HeaderConfig) if err != nil { return nil, errors.New("KCP|Config: Failed to parse header config: " + err.Error()) } @@ -102,15 +102,15 @@ type TCPConfig struct { HeaderConfig json.RawMessage `json:"header"` } -func (this *TCPConfig) Build() (*loader.TypedSettings, error) { +func (v *TCPConfig) Build() (*loader.TypedSettings, error) { config := new(tcp.Config) - if this.ConnectionReuse != nil { + if v.ConnectionReuse != nil { config.ConnectionReuse = &tcp.ConnectionReuse{ - Enable: *this.ConnectionReuse, + Enable: *v.ConnectionReuse, } } - if len(this.HeaderConfig) > 0 { - headerConfig, _, err := tcpHeaderLoader.Load(this.HeaderConfig) + if len(v.HeaderConfig) > 0 { + headerConfig, _, err := tcpHeaderLoader.Load(v.HeaderConfig) if err != nil { return nil, errors.New("TCP|Config: Failed to parse header config: " + err.Error()) } @@ -129,13 +129,13 @@ type WebSocketConfig struct { Path string `json:"Path"` } -func (this *WebSocketConfig) Build() (*loader.TypedSettings, error) { +func (v *WebSocketConfig) Build() (*loader.TypedSettings, error) { config := &ws.Config{ - Path: this.Path, + Path: v.Path, } - if this.ConnectionReuse != nil { + if v.ConnectionReuse != nil { config.ConnectionReuse = &ws.ConnectionReuse{ - Enable: *this.ConnectionReuse, + Enable: *v.ConnectionReuse, } } return loader.NewTypedSettings(config), nil @@ -150,10 +150,10 @@ type TLSConfig struct { Certs []*TLSCertConfig `json:"certificates"` } -func (this *TLSConfig) Build() (*loader.TypedSettings, error) { +func (v *TLSConfig) Build() (*loader.TypedSettings, error) { config := new(tls.Config) - config.Certificate = make([]*tls.Certificate, len(this.Certs)) - for idx, certConf := range this.Certs { + config.Certificate = make([]*tls.Certificate, len(v.Certs)) + for idx, certConf := range v.Certs { cert, err := ioutil.ReadFile(certConf.CertFile) if err != nil { return nil, errors.New("TLS: Failed to load certificate file: " + err.Error()) @@ -167,7 +167,7 @@ func (this *TLSConfig) Build() (*loader.TypedSettings, error) { Certificate: cert, } } - config.AllowInsecure = this.Insecure + config.AllowInsecure = v.Insecure return loader.NewTypedSettings(config), nil } @@ -180,15 +180,15 @@ type StreamConfig struct { WSSettings *WebSocketConfig `json:"wsSettings"` } -func (this *StreamConfig) Build() (*internet.StreamConfig, error) { +func (v *StreamConfig) Build() (*internet.StreamConfig, error) { config := &internet.StreamConfig{ Network: v2net.Network_RawTCP, } - if this.Network != nil { - config.Network = (*this.Network).Build() + if v.Network != nil { + config.Network = (*v.Network).Build() } - if strings.ToLower(this.Security) == "tls" { - tlsSettings := this.TLSSettings + if strings.ToLower(v.Security) == "tls" { + tlsSettings := v.TLSSettings if tlsSettings == nil { tlsSettings = &TLSConfig{} } @@ -198,8 +198,8 @@ func (this *StreamConfig) Build() (*internet.StreamConfig, error) { } config.SecuritySettings = append(config.SecuritySettings, ts) } - if this.TCPSettings != nil { - ts, err := this.TCPSettings.Build() + if v.TCPSettings != nil { + ts, err := v.TCPSettings.Build() if err != nil { return nil, errors.New("Failed to build TCP config: " + err.Error()) } @@ -208,8 +208,8 @@ func (this *StreamConfig) Build() (*internet.StreamConfig, error) { Settings: ts, }) } - if this.KCPSettings != nil { - ts, err := this.KCPSettings.Build() + if v.KCPSettings != nil { + ts, err := v.KCPSettings.Build() if err != nil { return nil, errors.New("Failed to build KCP config: " + err.Error()) } @@ -218,8 +218,8 @@ func (this *StreamConfig) Build() (*internet.StreamConfig, error) { Settings: ts, }) } - if this.WSSettings != nil { - ts, err := this.WSSettings.Build() + if v.WSSettings != nil { + ts, err := v.WSSettings.Build() if err != nil { return nil, errors.New("Failed to build WebSocket config: " + err.Error()) } @@ -235,11 +235,11 @@ type ProxyConfig struct { Tag string `json:"tag"` } -func (this *ProxyConfig) Build() (*internet.ProxyConfig, error) { - if len(this.Tag) == 0 { +func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) { + if len(v.Tag) == 0 { return nil, errors.New("Proxy tag is not set.") } return &internet.ProxyConfig{ - Tag: this.Tag, + Tag: v.Tag, }, nil } diff --git a/tools/conf/v2ray.go b/tools/conf/v2ray.go index 13f85c86e..0929531a5 100644 --- a/tools/conf/v2ray.go +++ b/tools/conf/v2ray.go @@ -38,28 +38,28 @@ type InboundConnectionConfig struct { Tag string `json:"tag"` } -func (this *InboundConnectionConfig) Build() (*core.InboundConnectionConfig, error) { +func (v *InboundConnectionConfig) Build() (*core.InboundConnectionConfig, error) { config := new(core.InboundConnectionConfig) config.PortRange = &v2net.PortRange{ - From: uint32(this.Port), - To: uint32(this.Port), + From: uint32(v.Port), + To: uint32(v.Port), } - if this.Listen != nil { - if this.Listen.Family().IsDomain() { - return nil, errors.New("Point: Unable to listen on domain address: " + this.Listen.Domain()) + if v.Listen != nil { + if v.Listen.Family().IsDomain() { + return nil, errors.New("Point: Unable to listen on domain address: " + v.Listen.Domain()) } - config.ListenOn = this.Listen.Build() + config.ListenOn = v.Listen.Build() } - if this.StreamSetting != nil { - ts, err := this.StreamSetting.Build() + if v.StreamSetting != nil { + ts, err := v.StreamSetting.Build() if err != nil { return nil, err } config.StreamSettings = ts } - config.AllowPassiveConnection = this.AllowPassive + config.AllowPassiveConnection = v.AllowPassive - jsonConfig, err := inboundConfigLoader.LoadWithID(this.Settings, this.Protocol) + jsonConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.New("Failed to load inbound config: " + err.Error()) } @@ -68,8 +68,8 @@ func (this *InboundConnectionConfig) Build() (*core.InboundConnectionConfig, err return nil, err } config.Settings = ts - if len(this.Tag) > 0 { - config.Tag = this.Tag + if len(v.Tag) > 0 { + config.Tag = v.Tag } return config, nil } @@ -83,9 +83,9 @@ type OutboundConnectionConfig struct { Tag string `json:"tag"` } -func (this *OutboundConnectionConfig) Build() (*core.OutboundConnectionConfig, error) { +func (v *OutboundConnectionConfig) Build() (*core.OutboundConnectionConfig, error) { config := new(core.OutboundConnectionConfig) - rawConfig, err := outboundConfigLoader.LoadWithID(this.Settings, this.Protocol) + rawConfig, err := outboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.New("Failed to parse outbound config: " + err.Error()) } @@ -95,29 +95,29 @@ func (this *OutboundConnectionConfig) Build() (*core.OutboundConnectionConfig, e } config.Settings = ts - if this.SendThrough != nil { - address := this.SendThrough + if v.SendThrough != nil { + address := v.SendThrough if address.Family().IsDomain() { return nil, errors.New("Point: Unable to send through: " + address.String()) } config.SendThrough = address.Build() } - if this.StreamSetting != nil { - ss, err := this.StreamSetting.Build() + if v.StreamSetting != nil { + ss, err := v.StreamSetting.Build() if err != nil { return nil, err } config.StreamSettings = ss } - if this.ProxySettings != nil { - ps, err := this.ProxySettings.Build() + if v.ProxySettings != nil { + ps, err := v.ProxySettings.Build() if err != nil { return nil, errors.New("Outbound: invalid proxy settings: " + err.Error()) } config.ProxySettings = ps } - if len(this.Tag) > 0 { - config.Tag = this.Tag + if len(v.Tag) > 0 { + config.Tag = v.Tag } return config, nil } @@ -128,9 +128,9 @@ type InboundDetourAllocationConfig struct { RefreshMin *uint32 `json:"refresh"` } -func (this *InboundDetourAllocationConfig) Build() (*core.AllocationStrategy, error) { +func (v *InboundDetourAllocationConfig) Build() (*core.AllocationStrategy, error) { config := new(core.AllocationStrategy) - switch strings.ToLower(this.Strategy) { + switch strings.ToLower(v.Strategy) { case "always": config.Type = core.AllocationStrategy_Always case "random": @@ -138,17 +138,17 @@ func (this *InboundDetourAllocationConfig) Build() (*core.AllocationStrategy, er case "external": config.Type = core.AllocationStrategy_External default: - return nil, errors.New("Unknown allocation strategy: " + this.Strategy) + return nil, errors.New("Unknown allocation strategy: " + v.Strategy) } - if this.Concurrency != nil { + if v.Concurrency != nil { config.Concurrency = &core.AllocationStrategyConcurrency{ - Value: *this.Concurrency, + Value: *v.Concurrency, } } - if this.RefreshMin != nil { + if v.RefreshMin != nil { config.Refresh = &core.AllocationStrategyRefresh{ - Value: *this.RefreshMin, + Value: *v.RefreshMin, } } @@ -166,37 +166,37 @@ type InboundDetourConfig struct { AllowPassive bool `json:"allowPassive"` } -func (this *InboundDetourConfig) Build() (*core.InboundConnectionConfig, error) { +func (v *InboundDetourConfig) Build() (*core.InboundConnectionConfig, error) { config := new(core.InboundConnectionConfig) - if this.PortRange == nil { + if v.PortRange == nil { return nil, errors.New("Point: Port range not specified in InboundDetour.") } - config.PortRange = this.PortRange.Build() + config.PortRange = v.PortRange.Build() - if this.ListenOn != nil { - if this.ListenOn.Family().IsDomain() { - return nil, errors.New("Point: Unable to listen on domain address: " + this.ListenOn.Domain()) + if v.ListenOn != nil { + if v.ListenOn.Family().IsDomain() { + return nil, errors.New("Point: Unable to listen on domain address: " + v.ListenOn.Domain()) } - config.ListenOn = this.ListenOn.Build() + config.ListenOn = v.ListenOn.Build() } - config.Tag = this.Tag - if this.Allocation != nil { - as, err := this.Allocation.Build() + config.Tag = v.Tag + if v.Allocation != nil { + as, err := v.Allocation.Build() if err != nil { return nil, err } config.AllocationStrategy = as } - if this.StreamSetting != nil { - ss, err := this.StreamSetting.Build() + if v.StreamSetting != nil { + ss, err := v.StreamSetting.Build() if err != nil { return nil, err } config.StreamSettings = ss } - config.AllowPassiveConnection = this.AllowPassive + config.AllowPassiveConnection = v.AllowPassive - rawConfig, err := inboundConfigLoader.LoadWithID(this.Settings, this.Protocol) + rawConfig, err := inboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.New("Failed to load inbound detour config: " + err.Error()) } @@ -217,27 +217,27 @@ type OutboundDetourConfig struct { ProxySettings *ProxyConfig `json:"proxySettings"` } -func (this *OutboundDetourConfig) Build() (*core.OutboundConnectionConfig, error) { +func (v *OutboundDetourConfig) Build() (*core.OutboundConnectionConfig, error) { config := new(core.OutboundConnectionConfig) - config.Tag = this.Tag + config.Tag = v.Tag - if this.SendThrough != nil { - address := this.SendThrough + if v.SendThrough != nil { + address := v.SendThrough if address.Family().IsDomain() { return nil, errors.New("Point: Unable to send through: " + address.String()) } config.SendThrough = address.Build() } - if this.StreamSetting != nil { - ss, err := this.StreamSetting.Build() + if v.StreamSetting != nil { + ss, err := v.StreamSetting.Build() if err != nil { return nil, err } config.StreamSettings = ss } - rawConfig, err := outboundConfigLoader.LoadWithID(this.Settings, this.Protocol) + rawConfig, err := outboundConfigLoader.LoadWithID(v.Settings, v.Protocol) if err != nil { return nil, errors.New("Failed to parse to outbound detour config: " + err.Error()) } @@ -246,8 +246,8 @@ func (this *OutboundDetourConfig) Build() (*core.OutboundConnectionConfig, error return nil, err } - if this.ProxySettings != nil { - ps, err := this.ProxySettings.Build() + if v.ProxySettings != nil { + ps, err := v.ProxySettings.Build() if err != nil { return nil, errors.New("OutboundDetour: invalid proxy settings: " + err.Error()) } @@ -269,48 +269,48 @@ type Config struct { Transport *TransportConfig `json:"transport"` } -func (this *Config) Build() (*core.Config, error) { +func (v *Config) Build() (*core.Config, error) { config := new(core.Config) - if this.LogConfig != nil { - config.Log = this.LogConfig.Build() + if v.LogConfig != nil { + config.Log = v.LogConfig.Build() } - if this.Transport != nil { - ts, err := this.Transport.Build() + if v.Transport != nil { + ts, err := v.Transport.Build() if err != nil { return nil, err } config.Transport = ts } - if this.RouterConfig != nil { - routerConfig, err := this.RouterConfig.Build() + if v.RouterConfig != nil { + routerConfig, err := v.RouterConfig.Build() if err != nil { return nil, err } config.App = append(config.App, loader.NewTypedSettings(routerConfig)) } - if this.DNSConfig != nil { - config.App = append(config.App, loader.NewTypedSettings(this.DNSConfig.Build())) + if v.DNSConfig != nil { + config.App = append(config.App, loader.NewTypedSettings(v.DNSConfig.Build())) } - if this.InboundConfig == nil { + if v.InboundConfig == nil { return nil, errors.New("No inbound config specified.") } - if this.InboundConfig.Port == 0 && this.Port > 0 { - this.InboundConfig.Port = this.Port + if v.InboundConfig.Port == 0 && v.Port > 0 { + v.InboundConfig.Port = v.Port } - ic, err := this.InboundConfig.Build() + ic, err := v.InboundConfig.Build() if err != nil { return nil, err } config.Inbound = append(config.Inbound, ic) - for _, rawInboundConfig := range this.InboundDetours { + for _, rawInboundConfig := range v.InboundDetours { ic, err := rawInboundConfig.Build() if err != nil { return nil, err @@ -318,13 +318,13 @@ func (this *Config) Build() (*core.Config, error) { config.Inbound = append(config.Inbound, ic) } - oc, err := this.OutboundConfig.Build() + oc, err := v.OutboundConfig.Build() if err != nil { return nil, err } config.Outbound = append(config.Outbound, oc) - for _, rawOutboundConfig := range this.OutboundDetours { + for _, rawOutboundConfig := range v.OutboundDetours { oc, err := rawOutboundConfig.Build() if err != nil { return nil, err diff --git a/tools/conf/vmess.go b/tools/conf/vmess.go index 79d957089..15f99aadd 100644 --- a/tools/conf/vmess.go +++ b/tools/conf/vmess.go @@ -18,10 +18,10 @@ type VMessAccount struct { AlterIds uint16 `json:"alterId"` } -func (this *VMessAccount) Build() *vmess.Account { +func (v *VMessAccount) Build() *vmess.Account { return &vmess.Account{ - Id: this.ID, - AlterId: uint32(this.AlterIds), + Id: v.ID, + AlterId: uint32(v.AlterIds), } } @@ -29,9 +29,9 @@ type VMessDetourConfig struct { ToTag string `json:"to"` } -func (this *VMessDetourConfig) Build() *inbound.DetourConfig { +func (v *VMessDetourConfig) Build() *inbound.DetourConfig { return &inbound.DetourConfig{ - To: this.ToTag, + To: v.ToTag, } } @@ -44,13 +44,13 @@ type VMessDefaultConfig struct { Level byte `json:"level"` } -func (this *VMessDefaultConfig) Build() *inbound.DefaultConfig { +func (v *VMessDefaultConfig) Build() *inbound.DefaultConfig { config := new(inbound.DefaultConfig) - config.AlterId = uint32(this.AlterIDs) + config.AlterId = uint32(v.AlterIDs) if config.AlterId == 0 { config.AlterId = 32 } - config.Level = uint32(this.Level) + config.Level = uint32(v.Level) return config } @@ -61,21 +61,21 @@ type VMessInboundConfig struct { DetourConfig *VMessDetourConfig `json:"detour"` } -func (this *VMessInboundConfig) Build() (*loader.TypedSettings, error) { +func (v *VMessInboundConfig) Build() (*loader.TypedSettings, error) { config := new(inbound.Config) - if this.Defaults != nil { - config.Default = this.Defaults.Build() + if v.Defaults != nil { + config.Default = v.Defaults.Build() } - if this.DetourConfig != nil { - config.Detour = this.DetourConfig.Build() - } else if this.Features != nil && this.Features.Detour != nil { - config.Detour = this.Features.Detour.Build() + if v.DetourConfig != nil { + config.Detour = v.DetourConfig.Build() + } else if v.Features != nil && v.Features.Detour != nil { + config.Detour = v.Features.Detour.Build() } - config.User = make([]*protocol.User, len(this.Users)) - for idx, rawData := range this.Users { + config.User = make([]*protocol.User, len(v.Users)) + for idx, rawData := range v.Users { user := new(protocol.User) if err := json.Unmarshal(rawData, user); err != nil { return nil, errors.New("VMess|Inbound: Invalid user: " + err.Error()) @@ -100,14 +100,14 @@ type VMessOutboundConfig struct { Receivers []*VMessOutboundTarget `json:"vnext"` } -func (this *VMessOutboundConfig) Build() (*loader.TypedSettings, error) { +func (v *VMessOutboundConfig) Build() (*loader.TypedSettings, error) { config := new(outbound.Config) - if len(this.Receivers) == 0 { + if len(v.Receivers) == 0 { return nil, errors.New("0 VMess receiver configured.") } - serverSpecs := make([]*protocol.ServerEndpoint, len(this.Receivers)) - for idx, rec := range this.Receivers { + serverSpecs := make([]*protocol.ServerEndpoint, len(v.Receivers)) + for idx, rec := range v.Receivers { if len(rec.Users) == 0 { return nil, errors.New("0 user configured for VMess outbound.") } diff --git a/transport/config.go b/transport/config.go index 7c5bfbcd7..74329a8e7 100644 --- a/transport/config.go +++ b/transport/config.go @@ -5,11 +5,11 @@ import ( ) // Apply applies this Config. -func (this *Config) Apply() error { - if this == nil { +func (v *Config) Apply() error { + if v == nil { return nil } - if err := internet.ApplyGlobalNetworkSettings(this.NetworkSettings); err != nil { + if err := internet.ApplyGlobalNetworkSettings(v.NetworkSettings); err != nil { return err } return nil diff --git a/transport/internet/authenticator.go b/transport/internet/authenticator.go index 8bef925c6..a9458db01 100644 --- a/transport/internet/authenticator.go +++ b/transport/internet/authenticator.go @@ -45,16 +45,16 @@ func NewAuthenticatorChain(auths ...Authenticator) Authenticator { } } -func (this *AuthenticatorChain) Overhead() int { +func (v *AuthenticatorChain) Overhead() int { total := 0 - for _, auth := range this.authenticators { + for _, auth := range v.authenticators { total += auth.Overhead() } return total } -func (this *AuthenticatorChain) Open(payload *alloc.Buffer) bool { - for _, auth := range this.authenticators { +func (v *AuthenticatorChain) Open(payload *alloc.Buffer) bool { + for _, auth := range v.authenticators { if !auth.Open(payload) { return false } @@ -62,9 +62,9 @@ func (this *AuthenticatorChain) Open(payload *alloc.Buffer) bool { return true } -func (this *AuthenticatorChain) Seal(payload *alloc.Buffer) { - for i := len(this.authenticators) - 1; i >= 0; i-- { - auth := this.authenticators[i] +func (v *AuthenticatorChain) Seal(payload *alloc.Buffer) { + for i := len(v.authenticators) - 1; i >= 0; i-- { + auth := v.authenticators[i] auth.Seal(payload) } } diff --git a/transport/internet/authenticators/http/config.go b/transport/internet/authenticators/http/config.go index 62a1a8c43..77f609db6 100644 --- a/transport/internet/authenticators/http/config.go +++ b/transport/internet/authenticators/http/config.go @@ -5,32 +5,32 @@ import ( "v2ray.com/core/common/dice" ) -func (this *Version) GetValue() string { - if this == nil { +func (v *Version) GetValue() string { + if v == nil { return "1.1" } - return this.Value + return v.Value } -func (this *Method) GetValue() string { - if this == nil { +func (v *Method) GetValue() string { + if v == nil { return "GET" } - return this.Value + return v.Value } -func (this *Status) GetCode() string { - if this == nil { +func (v *Status) GetCode() string { + if v == nil { return "200" } - return this.Code + return v.Code } -func (this *Status) GetReason() string { - if this == nil { +func (v *Status) GetReason() string { + if v == nil { return "OK" } - return this.Reason + return v.Reason } func pickString(arr []string) string { @@ -45,17 +45,17 @@ func pickString(arr []string) string { } } -func (this *RequestConfig) PickUri() string { - return pickString(this.Uri) +func (v *RequestConfig) PickUri() string { + return pickString(v.Uri) } -func (this *RequestConfig) PickHeaders() []string { - n := len(this.Header) +func (v *RequestConfig) PickHeaders() []string { + n := len(v.Header) if n == 0 { return nil } headers := make([]string, n) - for idx, headerConfig := range this.Header { + for idx, headerConfig := range v.Header { headerName := headerConfig.Name headerValue := pickString(headerConfig.Value) headers[idx] = headerName + ": " + headerValue @@ -63,13 +63,13 @@ func (this *RequestConfig) PickHeaders() []string { return headers } -func (this *RequestConfig) GetFullVersion() string { - return "HTTP/" + this.Version.GetValue() +func (v *RequestConfig) GetFullVersion() string { + return "HTTP/" + v.Version.GetValue() } -func (this *ResponseConfig) HasHeader(header string) bool { +func (v *ResponseConfig) HasHeader(header string) bool { cHeader := strings.ToLower(header) - for _, tHeader := range this.Header { + for _, tHeader := range v.Header { if strings.ToLower(tHeader.Name) == cHeader { return true } @@ -77,13 +77,13 @@ func (this *ResponseConfig) HasHeader(header string) bool { return false } -func (this *ResponseConfig) PickHeaders() []string { - n := len(this.Header) +func (v *ResponseConfig) PickHeaders() []string { + n := len(v.Header) if n == 0 { return nil } headers := make([]string, n) - for idx, headerConfig := range this.Header { + for idx, headerConfig := range v.Header { headerName := headerConfig.Name headerValue := pickString(headerConfig.Value) headers[idx] = headerName + ": " + headerValue @@ -91,6 +91,6 @@ func (this *ResponseConfig) PickHeaders() []string { return headers } -func (this *ResponseConfig) GetFullVersion() string { - return "HTTP/" + this.Version.GetValue() +func (v *ResponseConfig) GetFullVersion() string { + return "HTTP/" + v.Version.GetValue() } diff --git a/transport/internet/authenticators/http/http.go b/transport/internet/authenticators/http/http.go index 4817b5bc9..306aeb0f8 100644 --- a/transport/internet/authenticators/http/http.go +++ b/transport/internet/authenticators/http/http.go @@ -27,13 +27,13 @@ type Writer interface { type NoOpReader struct{} -func (this *NoOpReader) Read(io.Reader) (*alloc.Buffer, error) { +func (v *NoOpReader) Read(io.Reader) (*alloc.Buffer, error) { return nil, nil } type NoOpWriter struct{} -func (this *NoOpWriter) Write(io.Writer) error { +func (v *NoOpWriter) Write(io.Writer) error { return nil } @@ -73,13 +73,13 @@ func NewHeaderWriter(header *alloc.Buffer) *HeaderWriter { } } -func (this *HeaderWriter) Write(writer io.Writer) error { - if this.header == nil { +func (v *HeaderWriter) Write(writer io.Writer) error { + if v.header == nil { return nil } - _, err := writer.Write(this.header.Value) - this.header.Release() - this.header = nil + _, err := writer.Write(v.header.Value) + v.header.Release() + v.header = nil return err } @@ -99,47 +99,47 @@ func NewHttpConn(conn net.Conn, reader Reader, writer Writer) *HttpConn { } } -func (this *HttpConn) Read(b []byte) (int, error) { - if this.oneTimeReader != nil { - buffer, err := this.oneTimeReader.Read(this.Conn) +func (v *HttpConn) Read(b []byte) (int, error) { + if v.oneTimeReader != nil { + buffer, err := v.oneTimeReader.Read(v.Conn) if err != nil { return 0, err } - this.readBuffer = buffer - this.oneTimeReader = nil + v.readBuffer = buffer + v.oneTimeReader = nil } - if this.readBuffer.Len() > 0 { - nBytes, err := this.readBuffer.Read(b) - if nBytes == this.readBuffer.Len() { - this.readBuffer.Release() - this.readBuffer = nil + if v.readBuffer.Len() > 0 { + nBytes, err := v.readBuffer.Read(b) + if nBytes == v.readBuffer.Len() { + v.readBuffer.Release() + v.readBuffer = nil } return nBytes, err } - return this.Conn.Read(b) + return v.Conn.Read(b) } -func (this *HttpConn) Write(b []byte) (int, error) { - if this.oneTimeWriter != nil { - err := this.oneTimeWriter.Write(this.Conn) - this.oneTimeWriter = nil +func (v *HttpConn) Write(b []byte) (int, error) { + if v.oneTimeWriter != nil { + err := v.oneTimeWriter.Write(v.Conn) + v.oneTimeWriter = nil if err != nil { return 0, err } } - return this.Conn.Write(b) + return v.Conn.Write(b) } type HttpAuthenticator struct { config *Config } -func (this HttpAuthenticator) GetClientWriter() *HeaderWriter { +func (v HttpAuthenticator) GetClientWriter() *HeaderWriter { header := alloc.NewSmallBuffer().Clear() - config := this.config.Request + config := v.config.Request header.AppendString(config.Method.GetValue()).AppendString(" ").AppendString(config.PickUri()).AppendString(" ").AppendString(config.GetFullVersion()).AppendString(CRLF) headers := config.PickHeaders() @@ -152,9 +152,9 @@ func (this HttpAuthenticator) GetClientWriter() *HeaderWriter { } } -func (this HttpAuthenticator) GetServerWriter() *HeaderWriter { +func (v HttpAuthenticator) GetServerWriter() *HeaderWriter { header := alloc.NewSmallBuffer().Clear() - config := this.config.Response + config := v.config.Response header.AppendString(config.GetFullVersion()).AppendString(" ").AppendString(config.Status.GetCode()).AppendString(" ").AppendString(config.Status.GetReason()).AppendString(CRLF) headers := config.PickHeaders() @@ -170,27 +170,27 @@ func (this HttpAuthenticator) GetServerWriter() *HeaderWriter { } } -func (this HttpAuthenticator) Client(conn net.Conn) net.Conn { - if this.config.Request == nil && this.config.Response == nil { +func (v HttpAuthenticator) Client(conn net.Conn) net.Conn { + if v.config.Request == nil && v.config.Response == nil { return conn } var reader Reader = new(NoOpReader) - if this.config.Request != nil { + if v.config.Request != nil { reader = new(HeaderReader) } var writer Writer = new(NoOpWriter) - if this.config.Response != nil { - writer = this.GetClientWriter() + if v.config.Response != nil { + writer = v.GetClientWriter() } return NewHttpConn(conn, reader, writer) } -func (this HttpAuthenticator) Server(conn net.Conn) net.Conn { - if this.config.Request == nil && this.config.Response == nil { +func (v HttpAuthenticator) Server(conn net.Conn) net.Conn { + if v.config.Request == nil && v.config.Response == nil { return conn } - return NewHttpConn(conn, new(HeaderReader), this.GetServerWriter()) + return NewHttpConn(conn, new(HeaderReader), v.GetServerWriter()) } type HttpAuthenticatorFactory struct{} diff --git a/transport/internet/authenticators/noop/noop.go b/transport/internet/authenticators/noop/noop.go index da0cfcd40..9d9f46192 100644 --- a/transport/internet/authenticators/noop/noop.go +++ b/transport/internet/authenticators/noop/noop.go @@ -10,17 +10,17 @@ import ( type NoOpAuthenticator struct{} -func (this NoOpAuthenticator) Overhead() int { +func (v NoOpAuthenticator) Overhead() int { return 0 } -func (this NoOpAuthenticator) Open(payload *alloc.Buffer) bool { +func (v NoOpAuthenticator) Open(payload *alloc.Buffer) bool { return true } -func (this NoOpAuthenticator) Seal(payload *alloc.Buffer) {} +func (v NoOpAuthenticator) Seal(payload *alloc.Buffer) {} type NoOpAuthenticatorFactory struct{} -func (this NoOpAuthenticatorFactory) Create(config interface{}) internet.Authenticator { +func (v NoOpAuthenticatorFactory) Create(config interface{}) internet.Authenticator { return NoOpAuthenticator{} } diff --git a/transport/internet/authenticators/srtp/srtp.go b/transport/internet/authenticators/srtp/srtp.go index d35a9d2dd..6b463498e 100644 --- a/transport/internet/authenticators/srtp/srtp.go +++ b/transport/internet/authenticators/srtp/srtp.go @@ -13,25 +13,25 @@ type SRTP struct { number uint16 } -func (this *SRTP) Overhead() int { +func (v *SRTP) Overhead() int { return 4 } -func (this *SRTP) Open(payload *alloc.Buffer) bool { - payload.SliceFrom(this.Overhead()) +func (v *SRTP) Open(payload *alloc.Buffer) bool { + payload.SliceFrom(v.Overhead()) return true } -func (this *SRTP) Seal(payload *alloc.Buffer) { - this.number++ - payload.PrependUint16(this.number) - payload.PrependUint16(this.header) +func (v *SRTP) Seal(payload *alloc.Buffer) { + v.number++ + payload.PrependUint16(v.number) + payload.PrependUint16(v.header) } type SRTPFactory struct { } -func (this SRTPFactory) Create(rawSettings interface{}) internet.Authenticator { +func (v SRTPFactory) Create(rawSettings interface{}) internet.Authenticator { return &SRTP{ header: 0xB5E8, number: uint16(rand.Intn(65536)), diff --git a/transport/internet/authenticators/utp/utp.go b/transport/internet/authenticators/utp/utp.go index 3f62b5a1f..088749283 100644 --- a/transport/internet/authenticators/utp/utp.go +++ b/transport/internet/authenticators/utp/utp.go @@ -14,23 +14,23 @@ type UTP struct { connectionId uint16 } -func (this *UTP) Overhead() int { +func (v *UTP) Overhead() int { return 4 } -func (this *UTP) Open(payload *alloc.Buffer) bool { - payload.SliceFrom(this.Overhead()) +func (v *UTP) Open(payload *alloc.Buffer) bool { + payload.SliceFrom(v.Overhead()) return true } -func (this *UTP) Seal(payload *alloc.Buffer) { - payload.PrependUint16(this.connectionId) - payload.PrependBytes(this.header, this.extension) +func (v *UTP) Seal(payload *alloc.Buffer) { + payload.PrependUint16(v.connectionId) + payload.PrependBytes(v.header, v.extension) } type UTPFactory struct{} -func (this UTPFactory) Create(rawSettings interface{}) internet.Authenticator { +func (v UTPFactory) Create(rawSettings interface{}) internet.Authenticator { return &UTP{ header: 1, extension: 0, diff --git a/transport/internet/config.go b/transport/internet/config.go index 8ca30de31..228c2d2af 100644 --- a/transport/internet/config.go +++ b/transport/internet/config.go @@ -33,35 +33,35 @@ func CreateNetworkConfig(network v2net.Network) (interface{}, error) { return creator(), nil } -func (this *NetworkSettings) GetTypedSettings() (interface{}, error) { - return this.Settings.GetInstance() +func (v *NetworkSettings) GetTypedSettings() (interface{}, error) { + return v.Settings.GetInstance() } -func (this *StreamConfig) GetEffectiveNetworkSettings() (interface{}, error) { - for _, settings := range this.NetworkSettings { - if settings.Network == this.Network { +func (v *StreamConfig) GetEffectiveNetworkSettings() (interface{}, error) { + for _, settings := range v.NetworkSettings { + if settings.Network == v.Network { return settings.GetTypedSettings() } } for _, settings := range globalNetworkSettings { - if settings.Network == this.Network { + if settings.Network == v.Network { return settings.GetTypedSettings() } } - return CreateNetworkConfig(this.Network) + return CreateNetworkConfig(v.Network) } -func (this *StreamConfig) GetEffectiveSecuritySettings() (interface{}, error) { - for _, settings := range this.SecuritySettings { - if settings.Type == this.SecurityType { +func (v *StreamConfig) GetEffectiveSecuritySettings() (interface{}, error) { + for _, settings := range v.SecuritySettings { + if settings.Type == v.SecurityType { return settings.GetInstance() } } - return loader.GetInstance(this.SecurityType) + return loader.GetInstance(v.SecurityType) } -func (this *StreamConfig) HasSecuritySettings() bool { - return len(this.SecurityType) > 0 +func (v *StreamConfig) HasSecuritySettings() bool { + return len(v.SecurityType) > 0 } func ApplyGlobalNetworkSettings(settings []*NetworkSettings) error { @@ -69,6 +69,6 @@ func ApplyGlobalNetworkSettings(settings []*NetworkSettings) error { return nil } -func (this *ProxyConfig) HasTag() bool { - return this != nil && len(this.Tag) > 0 +func (v *ProxyConfig) HasTag() bool { + return v != nil && len(v.Tag) > 0 } diff --git a/transport/internet/kcp/config.go b/transport/internet/kcp/config.go index 293e34075..2e71098ca 100644 --- a/transport/internet/kcp/config.go +++ b/transport/internet/kcp/config.go @@ -5,57 +5,57 @@ import ( "v2ray.com/core/transport/internet" ) -func (this *MTU) GetValue() uint32 { - if this == nil { +func (v *MTU) GetValue() uint32 { + if v == nil { return 1350 } - return this.Value + return v.Value } -func (this *TTI) GetValue() uint32 { - if this == nil { +func (v *TTI) GetValue() uint32 { + if v == nil { return 50 } - return this.Value + return v.Value } -func (this *UplinkCapacity) GetValue() uint32 { - if this == nil { +func (v *UplinkCapacity) GetValue() uint32 { + if v == nil { return 5 } - return this.Value + return v.Value } -func (this *DownlinkCapacity) GetValue() uint32 { - if this == nil { +func (v *DownlinkCapacity) GetValue() uint32 { + if v == nil { return 20 } - return this.Value + return v.Value } -func (this *WriteBuffer) GetSize() uint32 { - if this == nil { +func (v *WriteBuffer) GetSize() uint32 { + if v == nil { return 1 * 1024 * 1024 } - return this.Size + return v.Size } -func (this *ReadBuffer) GetSize() uint32 { - if this == nil { +func (v *ReadBuffer) GetSize() uint32 { + if v == nil { return 1 * 1024 * 1024 } - return this.Size + return v.Size } -func (this *Config) GetAuthenticator() (internet.Authenticator, error) { +func (v *Config) GetAuthenticator() (internet.Authenticator, error) { auth := NewSimpleAuthenticator() - if this.HeaderConfig != nil { - rawConfig, err := this.HeaderConfig.GetInstance() + if v.HeaderConfig != nil { + rawConfig, err := v.HeaderConfig.GetInstance() if err != nil { return nil, err } - header, err := internet.CreateAuthenticator(this.HeaderConfig.Type, rawConfig) + header, err := internet.CreateAuthenticator(v.HeaderConfig.Type, rawConfig) if err != nil { return nil, err } @@ -64,28 +64,28 @@ func (this *Config) GetAuthenticator() (internet.Authenticator, error) { return auth, nil } -func (this *Config) GetSendingInFlightSize() uint32 { - size := this.UplinkCapacity.GetValue() * 1024 * 1024 / this.Mtu.GetValue() / (1000 / this.Tti.GetValue()) / 2 +func (v *Config) GetSendingInFlightSize() uint32 { + size := v.UplinkCapacity.GetValue() * 1024 * 1024 / v.Mtu.GetValue() / (1000 / v.Tti.GetValue()) / 2 if size < 8 { size = 8 } return size } -func (this *Config) GetSendingBufferSize() uint32 { - return this.WriteBuffer.GetSize() / this.Mtu.GetValue() +func (v *Config) GetSendingBufferSize() uint32 { + return v.WriteBuffer.GetSize() / v.Mtu.GetValue() } -func (this *Config) GetReceivingInFlightSize() uint32 { - size := this.DownlinkCapacity.GetValue() * 1024 * 1024 / this.Mtu.GetValue() / (1000 / this.Tti.GetValue()) / 2 +func (v *Config) GetReceivingInFlightSize() uint32 { + size := v.DownlinkCapacity.GetValue() * 1024 * 1024 / v.Mtu.GetValue() / (1000 / v.Tti.GetValue()) / 2 if size < 8 { size = 8 } return size } -func (this *Config) GetReceivingBufferSize() uint32 { - return this.ReadBuffer.GetSize() / this.Mtu.GetValue() +func (v *Config) GetReceivingBufferSize() uint32 { + return v.ReadBuffer.GetSize() / v.Mtu.GetValue() } func (o *ConnectionReuse) IsEnabled() bool { diff --git a/transport/internet/kcp/connection.go b/transport/internet/kcp/connection.go index ac7b20d04..ae8bbf642 100644 --- a/transport/internet/kcp/connection.go +++ b/transport/internet/kcp/connection.go @@ -22,9 +22,9 @@ var ( type State int32 -func (this State) Is(states ...State) bool { +func (v State) Is(states ...State) bool { for _, state := range states { - if this == state { + if v == state { return true } } @@ -58,66 +58,66 @@ type RoundTripInfo struct { updatedTimestamp uint32 } -func (this *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) { - this.Lock() - defer this.Unlock() +func (v *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) { + v.Lock() + defer v.Unlock() - if current-this.updatedTimestamp < 3000 { + if current-v.updatedTimestamp < 3000 { return } - this.updatedTimestamp = current - this.rto = rto + v.updatedTimestamp = current + v.rto = rto } -func (this *RoundTripInfo) Update(rtt uint32, current uint32) { +func (v *RoundTripInfo) Update(rtt uint32, current uint32) { if rtt > 0x7FFFFFFF { return } - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() // https://tools.ietf.org/html/rfc6298 - if this.srtt == 0 { - this.srtt = rtt - this.variation = rtt / 2 + if v.srtt == 0 { + v.srtt = rtt + v.variation = rtt / 2 } else { - delta := rtt - this.srtt - if this.srtt > rtt { - delta = this.srtt - rtt + delta := rtt - v.srtt + if v.srtt > rtt { + delta = v.srtt - rtt } - this.variation = (3*this.variation + delta) / 4 - this.srtt = (7*this.srtt + rtt) / 8 - if this.srtt < this.minRtt { - this.srtt = this.minRtt + v.variation = (3*v.variation + delta) / 4 + v.srtt = (7*v.srtt + rtt) / 8 + if v.srtt < v.minRtt { + v.srtt = v.minRtt } } var rto uint32 - if this.minRtt < 4*this.variation { - rto = this.srtt + 4*this.variation + if v.minRtt < 4*v.variation { + rto = v.srtt + 4*v.variation } else { - rto = this.srtt + this.variation + rto = v.srtt + v.variation } if rto > 10000 { rto = 10000 } - this.rto = rto * 5 / 4 - this.updatedTimestamp = current + v.rto = rto * 5 / 4 + v.updatedTimestamp = current } -func (this *RoundTripInfo) Timeout() uint32 { - this.RLock() - defer this.RUnlock() +func (v *RoundTripInfo) Timeout() uint32 { + v.RLock() + defer v.RUnlock() - return this.rto + return v.rto } -func (this *RoundTripInfo) SmoothedTime() uint32 { - this.RLock() - defer this.RUnlock() +func (v *RoundTripInfo) SmoothedTime() uint32 { + v.RLock() + defer v.RUnlock() - return this.srtt + return v.srtt } type Updater struct { @@ -140,21 +140,21 @@ func NewUpdater(interval uint32, shouldContinue predicate.Predicate, shouldTermi return u } -func (this *Updater) WakeUp() { +func (v *Updater) WakeUp() { select { - case this.notifier <- true: + case v.notifier <- true: default: } } -func (this *Updater) Run() { - for <-this.notifier { - if this.shouldTerminate() { +func (v *Updater) Run() { + for <-v.notifier { + if v.shouldTerminate() { return } - for this.shouldContinue() { - this.updateFunc() - time.Sleep(this.interval) + for v.shouldContinue() { + v.updateFunc() + time.Sleep(v.interval) } } } @@ -249,60 +249,60 @@ func NewConnection(conv uint16, sysConn SystemConnection, recycler internal.Conn return conn } -func (this *Connection) Elapsed() uint32 { - return uint32(nowMillisec() - this.since) +func (v *Connection) Elapsed() uint32 { + return uint32(nowMillisec() - v.since) } // Read implements the Conn Read method. -func (this *Connection) Read(b []byte) (int, error) { - if this == nil { +func (v *Connection) Read(b []byte) (int, error) { + if v == nil { return 0, io.EOF } for { - if this.State().Is(StateReadyToClose, StateTerminating, StateTerminated) { + if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) { return 0, io.EOF } - nBytes := this.receivingWorker.Read(b) + nBytes := v.receivingWorker.Read(b) if nBytes > 0 { return nBytes, nil } - if this.State() == StatePeerTerminating { + if v.State() == StatePeerTerminating { return 0, io.EOF } var timer *time.Timer - if !this.rd.IsZero() { - duration := this.rd.Sub(time.Now()) + if !v.rd.IsZero() { + duration := v.rd.Sub(time.Now()) if duration <= 0 { return 0, ErrIOTimeout } - timer = time.AfterFunc(duration, this.dataInputCond.Signal) + timer = time.AfterFunc(duration, v.dataInputCond.Signal) } - this.dataInputCond.L.Lock() - this.dataInputCond.Wait() - this.dataInputCond.L.Unlock() + v.dataInputCond.L.Lock() + v.dataInputCond.Wait() + v.dataInputCond.L.Unlock() if timer != nil { timer.Stop() } - if !this.rd.IsZero() && this.rd.Before(time.Now()) { + if !v.rd.IsZero() && v.rd.Before(time.Now()) { return 0, ErrIOTimeout } } } // Write implements the Conn Write method. -func (this *Connection) Write(b []byte) (int, error) { +func (v *Connection) Write(b []byte) (int, error) { totalWritten := 0 for { - if this == nil || this.State() != StateActive { + if v == nil || v.State() != StateActive { return totalWritten, io.ErrClosedPipe } - nBytes := this.sendingWorker.Push(b[totalWritten:]) - this.dataUpdater.WakeUp() + nBytes := v.sendingWorker.Push(b[totalWritten:]) + v.dataUpdater.WakeUp() if nBytes > 0 { totalWritten += nBytes if totalWritten == len(b) { @@ -311,179 +311,179 @@ func (this *Connection) Write(b []byte) (int, error) { } var timer *time.Timer - if !this.wd.IsZero() { - duration := this.wd.Sub(time.Now()) + if !v.wd.IsZero() { + duration := v.wd.Sub(time.Now()) if duration <= 0 { return totalWritten, ErrIOTimeout } - timer = time.AfterFunc(duration, this.dataOutputCond.Signal) + timer = time.AfterFunc(duration, v.dataOutputCond.Signal) } - this.dataOutputCond.L.Lock() - this.dataOutputCond.Wait() - this.dataOutputCond.L.Unlock() + v.dataOutputCond.L.Lock() + v.dataOutputCond.Wait() + v.dataOutputCond.L.Unlock() if timer != nil { timer.Stop() } - if !this.wd.IsZero() && this.wd.Before(time.Now()) { + if !v.wd.IsZero() && v.wd.Before(time.Now()) { return totalWritten, ErrIOTimeout } } } -func (this *Connection) SetState(state State) { - current := this.Elapsed() - atomic.StoreInt32((*int32)(&this.state), int32(state)) - atomic.StoreUint32(&this.stateBeginTime, current) - log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current) +func (v *Connection) SetState(state State) { + current := v.Elapsed() + atomic.StoreInt32((*int32)(&v.state), int32(state)) + atomic.StoreUint32(&v.stateBeginTime, current) + log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current) switch state { case StateReadyToClose: - this.receivingWorker.CloseRead() + v.receivingWorker.CloseRead() case StatePeerClosed: - this.sendingWorker.CloseWrite() + v.sendingWorker.CloseWrite() case StateTerminating: - this.receivingWorker.CloseRead() - this.sendingWorker.CloseWrite() - this.pingUpdater.interval = time.Second + v.receivingWorker.CloseRead() + v.sendingWorker.CloseWrite() + v.pingUpdater.interval = time.Second case StatePeerTerminating: - this.sendingWorker.CloseWrite() - this.pingUpdater.interval = time.Second + v.sendingWorker.CloseWrite() + v.pingUpdater.interval = time.Second case StateTerminated: - this.receivingWorker.CloseRead() - this.sendingWorker.CloseWrite() - this.pingUpdater.interval = time.Second - this.dataUpdater.WakeUp() - this.pingUpdater.WakeUp() - go this.Terminate() + v.receivingWorker.CloseRead() + v.sendingWorker.CloseWrite() + v.pingUpdater.interval = time.Second + v.dataUpdater.WakeUp() + v.pingUpdater.WakeUp() + go v.Terminate() } } // Close closes the connection. -func (this *Connection) Close() error { - if this == nil { +func (v *Connection) Close() error { + if v == nil { return ErrClosedConnection } - this.dataInputCond.Broadcast() - this.dataOutputCond.Broadcast() + v.dataInputCond.Broadcast() + v.dataOutputCond.Broadcast() - state := this.State() + state := v.State() if state.Is(StateReadyToClose, StateTerminating, StateTerminated) { return ErrClosedConnection } - log.Info("KCP|Connection: Closing connection to ", this.conn.RemoteAddr()) + log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr()) if state == StateActive { - this.SetState(StateReadyToClose) + v.SetState(StateReadyToClose) } if state == StatePeerClosed { - this.SetState(StateTerminating) + v.SetState(StateTerminating) } if state == StatePeerTerminating { - this.SetState(StateTerminated) + v.SetState(StateTerminated) } return nil } // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it. -func (this *Connection) LocalAddr() net.Addr { - if this == nil { +func (v *Connection) LocalAddr() net.Addr { + if v == nil { return nil } - return this.conn.LocalAddr() + return v.conn.LocalAddr() } // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it. -func (this *Connection) RemoteAddr() net.Addr { - if this == nil { +func (v *Connection) RemoteAddr() net.Addr { + if v == nil { return nil } - return this.conn.RemoteAddr() + return v.conn.RemoteAddr() } // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline. -func (this *Connection) SetDeadline(t time.Time) error { - if err := this.SetReadDeadline(t); err != nil { +func (v *Connection) SetDeadline(t time.Time) error { + if err := v.SetReadDeadline(t); err != nil { return err } - if err := this.SetWriteDeadline(t); err != nil { + if err := v.SetWriteDeadline(t); err != nil { return err } return nil } // SetReadDeadline implements the Conn SetReadDeadline method. -func (this *Connection) SetReadDeadline(t time.Time) error { - if this == nil || this.State() != StateActive { +func (v *Connection) SetReadDeadline(t time.Time) error { + if v == nil || v.State() != StateActive { return ErrClosedConnection } - this.rd = t + v.rd = t return nil } // SetWriteDeadline implements the Conn SetWriteDeadline method. -func (this *Connection) SetWriteDeadline(t time.Time) error { - if this == nil || this.State() != StateActive { +func (v *Connection) SetWriteDeadline(t time.Time) error { + if v == nil || v.State() != StateActive { return ErrClosedConnection } - this.wd = t + v.wd = t return nil } // kcp update, input loop -func (this *Connection) updateTask() { - this.flush() +func (v *Connection) updateTask() { + v.flush() } -func (this *Connection) Reusable() bool { - return this.Config.ConnectionReuse.IsEnabled() && this.reusable +func (v *Connection) Reusable() bool { + return v.Config.ConnectionReuse.IsEnabled() && v.reusable } -func (this *Connection) SetReusable(b bool) { - this.reusable = b +func (v *Connection) SetReusable(b bool) { + v.reusable = b } -func (this *Connection) Terminate() { - if this == nil { +func (v *Connection) Terminate() { + if v == nil { return } - log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr()) + log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr()) - //this.SetState(StateTerminated) - this.dataInputCond.Broadcast() - this.dataOutputCond.Broadcast() - if this.Config.ConnectionReuse.IsEnabled() && this.reusable { - this.connRecycler.Put(this.conn.Id(), this.conn) + //v.SetState(StateTerminated) + v.dataInputCond.Broadcast() + v.dataOutputCond.Broadcast() + if v.Config.ConnectionReuse.IsEnabled() && v.reusable { + v.connRecycler.Put(v.conn.Id(), v.conn) } else { - this.conn.Close() + v.conn.Close() } - this.sendingWorker.Release() - this.receivingWorker.Release() + v.sendingWorker.Release() + v.receivingWorker.Release() } -func (this *Connection) HandleOption(opt SegmentOption) { +func (v *Connection) HandleOption(opt SegmentOption) { if (opt & SegmentOptionClose) == SegmentOptionClose { - this.OnPeerClosed() + v.OnPeerClosed() } } -func (this *Connection) OnPeerClosed() { - state := this.State() +func (v *Connection) OnPeerClosed() { + state := v.State() if state == StateReadyToClose { - this.SetState(StateTerminating) + v.SetState(StateTerminating) } if state == StateActive { - this.SetState(StatePeerClosed) + v.SetState(StatePeerClosed) } } // Input when you received a low level packet (eg. UDP packet), call it -func (this *Connection) Input(data []byte) { - current := this.Elapsed() - atomic.StoreUint32(&this.lastIncomingTime, current) +func (v *Connection) Input(data []byte) { + current := v.Elapsed() + atomic.StoreUint32(&v.lastIncomingTime, current) var seg Segment for { @@ -491,101 +491,101 @@ func (this *Connection) Input(data []byte) { if seg == nil { break } - if seg.Conversation() != this.conv { + if seg.Conversation() != v.conv { return } switch seg := seg.(type) { case *DataSegment: - this.HandleOption(seg.Option) - this.receivingWorker.ProcessSegment(seg) - this.dataInputCond.Signal() - this.dataUpdater.WakeUp() + v.HandleOption(seg.Option) + v.receivingWorker.ProcessSegment(seg) + v.dataInputCond.Signal() + v.dataUpdater.WakeUp() case *AckSegment: - this.HandleOption(seg.Option) - this.sendingWorker.ProcessSegment(current, seg, this.roundTrip.Timeout()) - this.dataOutputCond.Signal() - this.dataUpdater.WakeUp() + v.HandleOption(seg.Option) + v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout()) + v.dataOutputCond.Signal() + v.dataUpdater.WakeUp() case *CmdOnlySegment: - this.HandleOption(seg.Option) + v.HandleOption(seg.Option) if seg.Command == CommandTerminate { - state := this.State() + state := v.State() if state == StateActive || state == StatePeerClosed { - this.SetState(StatePeerTerminating) + v.SetState(StatePeerTerminating) } else if state == StateReadyToClose { - this.SetState(StateTerminating) + v.SetState(StateTerminating) } else if state == StateTerminating { - this.SetState(StateTerminated) + v.SetState(StateTerminated) } } - this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext) - this.receivingWorker.ProcessSendingNext(seg.SendingNext) - this.roundTrip.UpdatePeerRTO(seg.PeerRTO, current) + v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext) + v.receivingWorker.ProcessSendingNext(seg.SendingNext) + v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current) seg.Release() default: } } } -func (this *Connection) flush() { - current := this.Elapsed() +func (v *Connection) flush() { + current := v.Elapsed() - if this.State() == StateTerminated { + if v.State() == StateTerminated { return } - if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 { - this.Close() + if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 { + v.Close() } - if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() { - this.SetState(StateTerminating) + if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() { + v.SetState(StateTerminating) } - if this.State() == StateTerminating { - log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.") - this.Ping(current, CommandTerminate) - this.output.Flush() + if v.State() == StateTerminating { + log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.") + v.Ping(current, CommandTerminate) + v.output.Flush() - if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 { - this.SetState(StateTerminated) + if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 { + v.SetState(StateTerminated) } return } - if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 { - this.SetState(StateTerminating) + if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 { + v.SetState(StateTerminating) } - if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 { - this.SetState(StateTerminating) + if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 { + v.SetState(StateTerminating) } // flush acknowledges - this.receivingWorker.Flush(current) - this.sendingWorker.Flush(current) + v.receivingWorker.Flush(current) + v.sendingWorker.Flush(current) - if current-atomic.LoadUint32(&this.lastPingTime) >= 3000 { - this.Ping(current, CommandPing) + if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 { + v.Ping(current, CommandPing) } // flash remain segments - this.output.Flush() + v.output.Flush() } -func (this *Connection) State() State { - return State(atomic.LoadInt32((*int32)(&this.state))) +func (v *Connection) State() State { + return State(atomic.LoadInt32((*int32)(&v.state))) } -func (this *Connection) Ping(current uint32, cmd Command) { +func (v *Connection) Ping(current uint32, cmd Command) { seg := NewCmdOnlySegment() - seg.Conv = this.conv + seg.Conv = v.conv seg.Command = cmd - seg.ReceivinNext = this.receivingWorker.nextNumber - seg.SendingNext = this.sendingWorker.firstUnacknowledged - seg.PeerRTO = this.roundTrip.Timeout() - if this.State() == StateReadyToClose { + seg.ReceivinNext = v.receivingWorker.nextNumber + seg.SendingNext = v.sendingWorker.firstUnacknowledged + seg.PeerRTO = v.roundTrip.Timeout() + if v.State() == StateReadyToClose { seg.Option = SegmentOptionClose } - this.output.Write(seg) - atomic.StoreUint32(&this.lastPingTime, current) + v.output.Write(seg) + atomic.StoreUint32(&v.lastPingTime, current) seg.Release() } diff --git a/transport/internet/kcp/crypt.go b/transport/internet/kcp/crypt.go index c586e7e3d..0bcf598b6 100644 --- a/transport/internet/kcp/crypt.go +++ b/transport/internet/kcp/crypt.go @@ -14,11 +14,11 @@ func NewSimpleAuthenticator() internet.Authenticator { return &SimpleAuthenticator{} } -func (this *SimpleAuthenticator) Overhead() int { +func (v *SimpleAuthenticator) Overhead() int { return 6 } -func (this *SimpleAuthenticator) Seal(buffer *alloc.Buffer) { +func (v *SimpleAuthenticator) Seal(buffer *alloc.Buffer) { buffer.PrependUint16(uint16(buffer.Len())) fnvHash := fnv.New32a() fnvHash.Write(buffer.Value) @@ -35,7 +35,7 @@ func (this *SimpleAuthenticator) Seal(buffer *alloc.Buffer) { } } -func (this *SimpleAuthenticator) Open(buffer *alloc.Buffer) bool { +func (v *SimpleAuthenticator) Open(buffer *alloc.Buffer) bool { len := buffer.Len() xtra := 4 - len%4 if xtra != 0 { diff --git a/transport/internet/kcp/kcp_test.go b/transport/internet/kcp/kcp_test.go index e4a3be16b..d013d2ee9 100644 --- a/transport/internet/kcp/kcp_test.go +++ b/transport/internet/kcp/kcp_test.go @@ -92,7 +92,7 @@ func TestDialAndListen(t *testing.T) { } wg.Wait() - time.Sleep(15 * time.Second) + time.Sleep(20 * time.Second) assert.Int(listerner.ActiveConnections()).Equals(0) listerner.Close() diff --git a/transport/internet/kcp/listener.go b/transport/internet/kcp/listener.go index b682c8a02..b52ea43c8 100644 --- a/transport/internet/kcp/listener.go +++ b/transport/internet/kcp/listener.go @@ -133,21 +133,21 @@ func NewListener(address v2net.Address, port v2net.Port, options internet.Listen return l, nil } -func (this *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInfo) { +func (v *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInfo) { defer payload.Release() src := session.Source - if valid := this.authenticator.Open(payload); !valid { + if valid := v.authenticator.Open(payload); !valid { log.Info("KCP|Listener: discarding invalid payload from ", src) return } - if !this.running { + if !v.running { return } - this.Lock() - defer this.Unlock() - if !this.running { + v.Lock() + defer v.Unlock() + if !v.running { return } if payload.Len() < 4 { @@ -160,7 +160,7 @@ func (this *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInf Port: src.Port, Conv: conv, } - conn, found := this.sessions[id] + conn, found := v.sessions[id] if !found { if cmd == CommandTerminate { @@ -168,16 +168,16 @@ func (this *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInf } writer := &Writer{ id: id, - hub: this.hub, + hub: v.hub, dest: src, - listener: this, + listener: v, } remoteAddr := &net.UDPAddr{ IP: src.Address.IP(), Port: int(src.Port), } - localAddr := this.hub.Addr() - auth, err := this.config.GetAuthenticator() + localAddr := v.hub.Addr() + auth, err := v.config.GetAuthenticator() if err != nil { log.Error("KCP|Listener: Failed to create authenticator: ", err) } @@ -187,43 +187,43 @@ func (this *Listener) OnReceive(payload *alloc.Buffer, session *proxy.SessionInf remote: remoteAddr, writer: writer, } - conn = NewConnection(conv, sConn, this, auth, this.config) + conn = NewConnection(conv, sConn, v, auth, v.config) select { - case this.awaitingConns <- conn: + case v.awaitingConns <- conn: case <-time.After(time.Second * 5): conn.Close() return } - this.sessions[id] = conn + v.sessions[id] = conn } conn.Input(payload.Value) } -func (this *Listener) Remove(id ConnectionId) { - if !this.running { +func (v *Listener) Remove(id ConnectionId) { + if !v.running { return } - this.Lock() - defer this.Unlock() - if !this.running { + v.Lock() + defer v.Unlock() + if !v.running { return } - delete(this.sessions, id) + delete(v.sessions, id) } // Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn. -func (this *Listener) Accept() (internet.Connection, error) { +func (v *Listener) Accept() (internet.Connection, error) { for { - if !this.running { + if !v.running { return nil, ErrClosedListener } select { - case conn, open := <-this.awaitingConns: + case conn, open := <-v.awaitingConns: if !open { break } - if this.tlsConfig != nil { - tlsConn := tls.Server(conn, this.tlsConfig) + if v.tlsConfig != nil { + tlsConn := tls.Server(conn, v.tlsConfig) return v2tls.NewConnection(tlsConn), nil } return conn, nil @@ -234,36 +234,36 @@ func (this *Listener) Accept() (internet.Connection, error) { } // Close stops listening on the UDP address. Already Accepted connections are not closed. -func (this *Listener) Close() error { - if !this.running { +func (v *Listener) Close() error { + if !v.running { return ErrClosedListener } - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - this.running = false - close(this.awaitingConns) - for _, conn := range this.sessions { + v.running = false + close(v.awaitingConns) + for _, conn := range v.sessions { go conn.Terminate() } - this.hub.Close() + v.hub.Close() return nil } -func (this *Listener) ActiveConnections() int { - this.Lock() - defer this.Unlock() +func (v *Listener) ActiveConnections() int { + v.Lock() + defer v.Unlock() - return len(this.sessions) + return len(v.sessions) } // Addr returns the listener's network address, The Addr returned is shared by all invocations of Addr, so do not modify it. -func (this *Listener) Addr() net.Addr { - return this.hub.Addr() +func (v *Listener) Addr() net.Addr { + return v.hub.Addr() } -func (this *Listener) Put(internal.ConnectionId, net.Conn) {} +func (v *Listener) Put(internal.ConnectionId, net.Conn) {} type Writer struct { id ConnectionId @@ -272,12 +272,12 @@ type Writer struct { listener *Listener } -func (this *Writer) Write(payload []byte) (int, error) { - return this.hub.WriteTo(payload, this.dest) +func (v *Writer) Write(payload []byte) (int, error) { + return v.hub.WriteTo(payload, v.dest) } -func (this *Writer) Close() error { - this.listener.Remove(this.id) +func (v *Writer) Close() error { + v.listener.Remove(v.id) return nil } diff --git a/transport/internet/kcp/output.go b/transport/internet/kcp/output.go index f1294f6a1..1d52a12f7 100644 --- a/transport/internet/kcp/output.go +++ b/transport/internet/kcp/output.go @@ -27,36 +27,36 @@ func NewSegmentWriter(writer *AuthenticationWriter) *BufferedSegmentWriter { } } -func (this *BufferedSegmentWriter) Write(seg Segment) { - this.Lock() - defer this.Unlock() +func (v *BufferedSegmentWriter) Write(seg Segment) { + v.Lock() + defer v.Unlock() nBytes := seg.ByteSize() - if uint32(this.buffer.Len()+nBytes) > this.mtu { - this.FlushWithoutLock() + if uint32(v.buffer.Len()+nBytes) > v.mtu { + v.FlushWithoutLock() } - if this.buffer == nil { - this.buffer = alloc.NewSmallBuffer().Clear() + if v.buffer == nil { + v.buffer = alloc.NewSmallBuffer().Clear() } - this.buffer.Value = seg.Bytes(this.buffer.Value) + v.buffer.Value = seg.Bytes(v.buffer.Value) } -func (this *BufferedSegmentWriter) FlushWithoutLock() { - this.writer.Write(this.buffer) - this.buffer = nil +func (v *BufferedSegmentWriter) FlushWithoutLock() { + v.writer.Write(v.buffer) + v.buffer = nil } -func (this *BufferedSegmentWriter) Flush() { - this.Lock() - defer this.Unlock() +func (v *BufferedSegmentWriter) Flush() { + v.Lock() + defer v.Unlock() - if this.buffer.Len() == 0 { + if v.buffer.Len() == 0 { return } - this.FlushWithoutLock() + v.FlushWithoutLock() } type AuthenticationWriter struct { @@ -65,16 +65,16 @@ type AuthenticationWriter struct { Config *Config } -func (this *AuthenticationWriter) Write(payload *alloc.Buffer) error { +func (v *AuthenticationWriter) Write(payload *alloc.Buffer) error { defer payload.Release() - this.Authenticator.Seal(payload) - _, err := this.Writer.Write(payload.Value) + v.Authenticator.Seal(payload) + _, err := v.Writer.Write(payload.Value) return err } -func (this *AuthenticationWriter) Release() {} +func (v *AuthenticationWriter) Release() {} -func (this *AuthenticationWriter) Mtu() uint32 { - return this.Config.Mtu.GetValue() - uint32(this.Authenticator.Overhead()) +func (v *AuthenticationWriter) Mtu() uint32 { + return v.Config.Mtu.GetValue() - uint32(v.Authenticator.Overhead()) } diff --git a/transport/internet/kcp/receiving.go b/transport/internet/kcp/receiving.go index 28d7aad62..824c7bd2e 100644 --- a/transport/internet/kcp/receiving.go +++ b/transport/internet/kcp/receiving.go @@ -20,38 +20,38 @@ func NewReceivingWindow(size uint32) *ReceivingWindow { } } -func (this *ReceivingWindow) Size() uint32 { - return this.size +func (v *ReceivingWindow) Size() uint32 { + return v.size } -func (this *ReceivingWindow) Position(idx uint32) uint32 { - return (idx + this.start) % this.size +func (v *ReceivingWindow) Position(idx uint32) uint32 { + return (idx + v.start) % v.size } -func (this *ReceivingWindow) Set(idx uint32, value *DataSegment) bool { - pos := this.Position(idx) - if this.list[pos] != nil { +func (v *ReceivingWindow) Set(idx uint32, value *DataSegment) bool { + pos := v.Position(idx) + if v.list[pos] != nil { return false } - this.list[pos] = value + v.list[pos] = value return true } -func (this *ReceivingWindow) Remove(idx uint32) *DataSegment { - pos := this.Position(idx) - e := this.list[pos] - this.list[pos] = nil +func (v *ReceivingWindow) Remove(idx uint32) *DataSegment { + pos := v.Position(idx) + e := v.list[pos] + v.list[pos] = nil return e } -func (this *ReceivingWindow) RemoveFirst() *DataSegment { - return this.Remove(0) +func (v *ReceivingWindow) RemoveFirst() *DataSegment { + return v.Remove(0) } -func (this *ReceivingWindow) Advance() { - this.start++ - if this.start == this.size { - this.start = 0 +func (v *ReceivingWindow) Advance() { + v.start++ + if v.start == v.size { + v.start = 0 } } @@ -71,48 +71,48 @@ func NewAckList(writer SegmentWriter) *AckList { } } -func (this *AckList) Add(number uint32, timestamp uint32) { - this.timestamps = append(this.timestamps, timestamp) - this.numbers = append(this.numbers, number) - this.nextFlush = append(this.nextFlush, 0) +func (v *AckList) Add(number uint32, timestamp uint32) { + v.timestamps = append(v.timestamps, timestamp) + v.numbers = append(v.numbers, number) + v.nextFlush = append(v.nextFlush, 0) } -func (this *AckList) Clear(una uint32) { +func (v *AckList) Clear(una uint32) { count := 0 - for i := 0; i < len(this.numbers); i++ { - if this.numbers[i] < una { + for i := 0; i < len(v.numbers); i++ { + if v.numbers[i] < una { continue } if i != count { - this.numbers[count] = this.numbers[i] - this.timestamps[count] = this.timestamps[i] - this.nextFlush[count] = this.nextFlush[i] + v.numbers[count] = v.numbers[i] + v.timestamps[count] = v.timestamps[i] + v.nextFlush[count] = v.nextFlush[i] } count++ } - if count < len(this.numbers) { - this.numbers = this.numbers[:count] - this.timestamps = this.timestamps[:count] - this.nextFlush = this.nextFlush[:count] + if count < len(v.numbers) { + v.numbers = v.numbers[:count] + v.timestamps = v.timestamps[:count] + v.nextFlush = v.nextFlush[:count] } } -func (this *AckList) Flush(current uint32, rto uint32) { +func (v *AckList) Flush(current uint32, rto uint32) { seg := NewAckSegment() - for i := 0; i < len(this.numbers) && !seg.IsFull(); i++ { - if this.nextFlush[i] > current { + for i := 0; i < len(v.numbers) && !seg.IsFull(); i++ { + if v.nextFlush[i] > current { continue } - seg.PutNumber(this.numbers[i]) - seg.PutTimestamp(this.timestamps[i]) + seg.PutNumber(v.numbers[i]) + seg.PutTimestamp(v.timestamps[i]) timeout := rto / 4 if timeout < 20 { timeout = 20 } - this.nextFlush[i] = current + timeout + v.nextFlush[i] = current + timeout } if seg.Count > 0 { - this.writer.Write(seg) + v.writer.Write(seg) seg.Release() } } @@ -137,63 +137,63 @@ func NewReceivingWorker(kcp *Connection) *ReceivingWorker { return worker } -func (this *ReceivingWorker) Release() { - this.leftOver.Release() +func (v *ReceivingWorker) Release() { + v.leftOver.Release() } -func (this *ReceivingWorker) ProcessSendingNext(number uint32) { - this.Lock() - defer this.Unlock() +func (v *ReceivingWorker) ProcessSendingNext(number uint32) { + v.Lock() + defer v.Unlock() - this.acklist.Clear(number) + v.acklist.Clear(number) } -func (this *ReceivingWorker) ProcessSegment(seg *DataSegment) { - this.Lock() - defer this.Unlock() +func (v *ReceivingWorker) ProcessSegment(seg *DataSegment) { + v.Lock() + defer v.Unlock() number := seg.Number - idx := number - this.nextNumber - if idx >= this.windowSize { + idx := number - v.nextNumber + if idx >= v.windowSize { return } - this.acklist.Clear(seg.SendingNext) - this.acklist.Add(number, seg.Timestamp) + v.acklist.Clear(seg.SendingNext) + v.acklist.Add(number, seg.Timestamp) - if !this.window.Set(idx, seg) { + if !v.window.Set(idx, seg) { seg.Release() } } -func (this *ReceivingWorker) Read(b []byte) int { - this.Lock() - defer this.Unlock() +func (v *ReceivingWorker) Read(b []byte) int { + v.Lock() + defer v.Unlock() total := 0 - if this.leftOver != nil { - nBytes := copy(b, this.leftOver.Value) - if nBytes < this.leftOver.Len() { - this.leftOver.SliceFrom(nBytes) + if v.leftOver != nil { + nBytes := copy(b, v.leftOver.Value) + if nBytes < v.leftOver.Len() { + v.leftOver.SliceFrom(nBytes) return nBytes } - this.leftOver.Release() - this.leftOver = nil + v.leftOver.Release() + v.leftOver = nil total += nBytes } for total < len(b) { - seg := this.window.RemoveFirst() + seg := v.window.RemoveFirst() if seg == nil { break } - this.window.Advance() - this.nextNumber++ + v.window.Advance() + v.nextNumber++ nBytes := copy(b[total:], seg.Data.Value) total += nBytes if nBytes < seg.Data.Len() { seg.Data.SliceFrom(nBytes) - this.leftOver = seg.Data + v.leftOver = seg.Data seg.Data = nil seg.Release() break @@ -203,27 +203,27 @@ func (this *ReceivingWorker) Read(b []byte) int { return total } -func (this *ReceivingWorker) Flush(current uint32) { - this.Lock() - defer this.Unlock() +func (v *ReceivingWorker) Flush(current uint32) { + v.Lock() + defer v.Unlock() - this.acklist.Flush(current, this.conn.roundTrip.Timeout()) + v.acklist.Flush(current, v.conn.roundTrip.Timeout()) } -func (this *ReceivingWorker) Write(seg Segment) { +func (v *ReceivingWorker) Write(seg Segment) { ackSeg := seg.(*AckSegment) - ackSeg.Conv = this.conn.conv - ackSeg.ReceivingNext = this.nextNumber - ackSeg.ReceivingWindow = this.nextNumber + this.windowSize - if this.conn.state == StateReadyToClose { + ackSeg.Conv = v.conn.conv + ackSeg.ReceivingNext = v.nextNumber + ackSeg.ReceivingWindow = v.nextNumber + v.windowSize + if v.conn.state == StateReadyToClose { ackSeg.Option = SegmentOptionClose } - this.conn.output.Write(ackSeg) + v.conn.output.Write(ackSeg) } -func (this *ReceivingWorker) CloseRead() { +func (v *ReceivingWorker) CloseRead() { } -func (this *ReceivingWorker) UpdateNecessary() bool { - return len(this.acklist.numbers) > 0 +func (v *ReceivingWorker) UpdateNecessary() bool { + return len(v.acklist.numbers) > 0 } diff --git a/transport/internet/kcp/segment.go b/transport/internet/kcp/segment.go index 19ab60047..208a66e28 100644 --- a/transport/internet/kcp/segment.go +++ b/transport/internet/kcp/segment.go @@ -49,35 +49,35 @@ func NewDataSegment() *DataSegment { return new(DataSegment) } -func (this *DataSegment) Conversation() uint16 { - return this.Conv +func (v *DataSegment) Conversation() uint16 { + return v.Conv } -func (this *DataSegment) SetData(b []byte) { - if this.Data == nil { - this.Data = alloc.NewSmallBuffer() +func (v *DataSegment) SetData(b []byte) { + if v.Data == nil { + v.Data = alloc.NewSmallBuffer() } - this.Data.Clear().Append(b) + v.Data.Clear().Append(b) } -func (this *DataSegment) Bytes(b []byte) []byte { - b = serial.Uint16ToBytes(this.Conv, b) - b = append(b, byte(CommandData), byte(this.Option)) - b = serial.Uint32ToBytes(this.Timestamp, b) - b = serial.Uint32ToBytes(this.Number, b) - b = serial.Uint32ToBytes(this.SendingNext, b) - b = serial.Uint16ToBytes(uint16(this.Data.Len()), b) - b = append(b, this.Data.Value...) +func (v *DataSegment) Bytes(b []byte) []byte { + b = serial.Uint16ToBytes(v.Conv, b) + b = append(b, byte(CommandData), byte(v.Option)) + b = serial.Uint32ToBytes(v.Timestamp, b) + b = serial.Uint32ToBytes(v.Number, b) + b = serial.Uint32ToBytes(v.SendingNext, b) + b = serial.Uint16ToBytes(uint16(v.Data.Len()), b) + b = append(b, v.Data.Value...) return b } -func (this *DataSegment) ByteSize() int { - return 2 + 1 + 1 + 4 + 4 + 4 + 2 + this.Data.Len() +func (v *DataSegment) ByteSize() int { + return 2 + 1 + 1 + 4 + 4 + 4 + 2 + v.Data.Len() } -func (this *DataSegment) Release() { - this.Data.Release() - this.Data = nil +func (v *DataSegment) Release() { + v.Data.Release() + v.Data = nil } type AckSegment struct { @@ -94,44 +94,44 @@ func NewAckSegment() *AckSegment { return new(AckSegment) } -func (this *AckSegment) Conversation() uint16 { - return this.Conv +func (v *AckSegment) Conversation() uint16 { + return v.Conv } -func (this *AckSegment) PutTimestamp(timestamp uint32) { - if timestamp-this.Timestamp < 0x7FFFFFFF { - this.Timestamp = timestamp +func (v *AckSegment) PutTimestamp(timestamp uint32) { + if timestamp-v.Timestamp < 0x7FFFFFFF { + v.Timestamp = timestamp } } -func (this *AckSegment) PutNumber(number uint32) { - this.Count++ - this.NumberList = append(this.NumberList, number) +func (v *AckSegment) PutNumber(number uint32) { + v.Count++ + v.NumberList = append(v.NumberList, number) } -func (this *AckSegment) IsFull() bool { - return this.Count == 128 +func (v *AckSegment) IsFull() bool { + return v.Count == 128 } -func (this *AckSegment) ByteSize() int { - return 2 + 1 + 1 + 4 + 4 + 4 + 1 + int(this.Count)*4 +func (v *AckSegment) ByteSize() int { + return 2 + 1 + 1 + 4 + 4 + 4 + 1 + int(v.Count)*4 } -func (this *AckSegment) Bytes(b []byte) []byte { - b = serial.Uint16ToBytes(this.Conv, b) - b = append(b, byte(CommandACK), byte(this.Option)) - b = serial.Uint32ToBytes(this.ReceivingWindow, b) - b = serial.Uint32ToBytes(this.ReceivingNext, b) - b = serial.Uint32ToBytes(this.Timestamp, b) - b = append(b, this.Count) - for i := byte(0); i < this.Count; i++ { - b = serial.Uint32ToBytes(this.NumberList[i], b) +func (v *AckSegment) Bytes(b []byte) []byte { + b = serial.Uint16ToBytes(v.Conv, b) + b = append(b, byte(CommandACK), byte(v.Option)) + b = serial.Uint32ToBytes(v.ReceivingWindow, b) + b = serial.Uint32ToBytes(v.ReceivingNext, b) + b = serial.Uint32ToBytes(v.Timestamp, b) + b = append(b, v.Count) + for i := byte(0); i < v.Count; i++ { + b = serial.Uint32ToBytes(v.NumberList[i], b) } return b } -func (this *AckSegment) Release() { - this.NumberList = nil +func (v *AckSegment) Release() { + v.NumberList = nil } type CmdOnlySegment struct { @@ -147,24 +147,24 @@ func NewCmdOnlySegment() *CmdOnlySegment { return new(CmdOnlySegment) } -func (this *CmdOnlySegment) Conversation() uint16 { - return this.Conv +func (v *CmdOnlySegment) Conversation() uint16 { + return v.Conv } -func (this *CmdOnlySegment) ByteSize() int { +func (v *CmdOnlySegment) ByteSize() int { return 2 + 1 + 1 + 4 + 4 + 4 } -func (this *CmdOnlySegment) Bytes(b []byte) []byte { - b = serial.Uint16ToBytes(this.Conv, b) - b = append(b, byte(this.Command), byte(this.Option)) - b = serial.Uint32ToBytes(this.SendingNext, b) - b = serial.Uint32ToBytes(this.ReceivinNext, b) - b = serial.Uint32ToBytes(this.PeerRTO, b) +func (v *CmdOnlySegment) Bytes(b []byte) []byte { + b = serial.Uint16ToBytes(v.Conv, b) + b = append(b, byte(v.Command), byte(v.Option)) + b = serial.Uint32ToBytes(v.SendingNext, b) + b = serial.Uint32ToBytes(v.ReceivinNext, b) + b = serial.Uint32ToBytes(v.PeerRTO, b) return b } -func (this *CmdOnlySegment) Release() { +func (v *CmdOnlySegment) Release() { } func ReadSegment(buf []byte) (Segment, []byte) { diff --git a/transport/internet/kcp/sending.go b/transport/internet/kcp/sending.go index 646cca2e2..60d36c84c 100644 --- a/transport/internet/kcp/sending.go +++ b/transport/internet/kcp/sending.go @@ -36,93 +36,93 @@ func NewSendingWindow(size uint32, writer SegmentWriter, onPacketLoss func(uint3 return window } -func (this *SendingWindow) Release() { - if this == nil { +func (v *SendingWindow) Release() { + if v == nil { return } - for _, seg := range this.data { + for _, seg := range v.data { seg.Release() } } -func (this *SendingWindow) Len() int { - return int(this.len) +func (v *SendingWindow) Len() int { + return int(v.len) } -func (this *SendingWindow) IsEmpty() bool { - return this.len == 0 +func (v *SendingWindow) IsEmpty() bool { + return v.len == 0 } -func (this *SendingWindow) Size() uint32 { - return this.cap +func (v *SendingWindow) Size() uint32 { + return v.cap } -func (this *SendingWindow) IsFull() bool { - return this.len == this.cap +func (v *SendingWindow) IsFull() bool { + return v.len == v.cap } -func (this *SendingWindow) Push(number uint32, data []byte) { - pos := (this.start + this.len) % this.cap - this.data[pos].SetData(data) - this.data[pos].Number = number - this.data[pos].timeout = 0 - this.data[pos].transmit = 0 - this.inuse[pos] = true - if this.len > 0 { - this.next[this.last] = pos - this.prev[pos] = this.last +func (v *SendingWindow) Push(number uint32, data []byte) { + pos := (v.start + v.len) % v.cap + v.data[pos].SetData(data) + v.data[pos].Number = number + v.data[pos].timeout = 0 + v.data[pos].transmit = 0 + v.inuse[pos] = true + if v.len > 0 { + v.next[v.last] = pos + v.prev[pos] = v.last } - this.last = pos - this.len++ + v.last = pos + v.len++ } -func (this *SendingWindow) FirstNumber() uint32 { - return this.data[this.start].Number +func (v *SendingWindow) FirstNumber() uint32 { + return v.data[v.start].Number } -func (this *SendingWindow) Clear(una uint32) { - for !this.IsEmpty() && this.data[this.start].Number < una { - this.Remove(0) +func (v *SendingWindow) Clear(una uint32) { + for !v.IsEmpty() && v.data[v.start].Number < una { + v.Remove(0) } } -func (this *SendingWindow) Remove(idx uint32) bool { - if this.len == 0 { +func (v *SendingWindow) Remove(idx uint32) bool { + if v.len == 0 { return false } - pos := (this.start + idx) % this.cap - if !this.inuse[pos] { + pos := (v.start + idx) % v.cap + if !v.inuse[pos] { return false } - this.inuse[pos] = false - this.totalInFlightSize-- - if pos == this.start && pos == this.last { - this.len = 0 - this.start = 0 - this.last = 0 - } else if pos == this.start { - delta := this.next[pos] - this.start - if this.next[pos] < this.start { - delta = this.next[pos] + this.cap - this.start + v.inuse[pos] = false + v.totalInFlightSize-- + if pos == v.start && pos == v.last { + v.len = 0 + v.start = 0 + v.last = 0 + } else if pos == v.start { + delta := v.next[pos] - v.start + if v.next[pos] < v.start { + delta = v.next[pos] + v.cap - v.start } - this.start = this.next[pos] - this.len -= delta - } else if pos == this.last { - this.last = this.prev[pos] + v.start = v.next[pos] + v.len -= delta + } else if pos == v.last { + v.last = v.prev[pos] } else { - this.next[this.prev[pos]] = this.next[pos] - this.prev[this.next[pos]] = this.prev[pos] + v.next[v.prev[pos]] = v.next[pos] + v.prev[v.next[pos]] = v.prev[pos] } return true } -func (this *SendingWindow) HandleFastAck(number uint32, rto uint32) { - if this.IsEmpty() { +func (v *SendingWindow) HandleFastAck(number uint32, rto uint32) { + if v.IsEmpty() { return } - this.Visit(func(seg *DataSegment) bool { + v.Visit(func(seg *DataSegment) bool { if number == seg.Number || number-seg.Number > 0x7FFFFFFF { return false } @@ -134,29 +134,29 @@ func (this *SendingWindow) HandleFastAck(number uint32, rto uint32) { }) } -func (this *SendingWindow) Visit(visitor func(seg *DataSegment) bool) { - for i := this.start; ; i = this.next[i] { - if !visitor(&this.data[i]) || i == this.last { +func (v *SendingWindow) Visit(visitor func(seg *DataSegment) bool) { + for i := v.start; ; i = v.next[i] { + if !visitor(&v.data[i]) || i == v.last { break } } } -func (this *SendingWindow) Flush(current uint32, rto uint32, maxInFlightSize uint32) { - if this.IsEmpty() { +func (v *SendingWindow) Flush(current uint32, rto uint32, maxInFlightSize uint32) { + if v.IsEmpty() { return } var lost uint32 var inFlightSize uint32 - this.Visit(func(segment *DataSegment) bool { + v.Visit(func(segment *DataSegment) bool { if current-segment.timeout >= 0x7FFFFFFF { return true } if segment.transmit == 0 { // First time - this.totalInFlightSize++ + v.totalInFlightSize++ } else { lost++ } @@ -164,7 +164,7 @@ func (this *SendingWindow) Flush(current uint32, rto uint32, maxInFlightSize uin segment.Timestamp = current segment.transmit++ - this.writer.Write(segment) + v.writer.Write(segment) inFlightSize++ if inFlightSize >= maxInFlightSize { return false @@ -172,9 +172,9 @@ func (this *SendingWindow) Flush(current uint32, rto uint32, maxInFlightSize uin return true }) - if this.onPacketLoss != nil && inFlightSize > 0 && this.totalInFlightSize != 0 { - rate := lost * 100 / this.totalInFlightSize - this.onPacketLoss(rate) + if v.onPacketLoss != nil && inFlightSize > 0 && v.totalInFlightSize != 0 { + rate := lost * 100 / v.totalInFlightSize + v.onPacketLoss(rate) } } @@ -201,66 +201,66 @@ func NewSendingWorker(kcp *Connection) *SendingWorker { return worker } -func (this *SendingWorker) Release() { - this.window.Release() +func (v *SendingWorker) Release() { + v.window.Release() } -func (this *SendingWorker) ProcessReceivingNext(nextNumber uint32) { - this.Lock() - defer this.Unlock() +func (v *SendingWorker) ProcessReceivingNext(nextNumber uint32) { + v.Lock() + defer v.Unlock() - this.ProcessReceivingNextWithoutLock(nextNumber) + v.ProcessReceivingNextWithoutLock(nextNumber) } -func (this *SendingWorker) ProcessReceivingNextWithoutLock(nextNumber uint32) { - this.window.Clear(nextNumber) - this.FindFirstUnacknowledged() +func (v *SendingWorker) ProcessReceivingNextWithoutLock(nextNumber uint32) { + v.window.Clear(nextNumber) + v.FindFirstUnacknowledged() } // Private: Visible for testing. -func (this *SendingWorker) FindFirstUnacknowledged() { - first := this.firstUnacknowledged - if !this.window.IsEmpty() { - this.firstUnacknowledged = this.window.FirstNumber() +func (v *SendingWorker) FindFirstUnacknowledged() { + first := v.firstUnacknowledged + if !v.window.IsEmpty() { + v.firstUnacknowledged = v.window.FirstNumber() } else { - this.firstUnacknowledged = this.nextNumber + v.firstUnacknowledged = v.nextNumber } - if first != this.firstUnacknowledged { - this.firstUnacknowledgedUpdated = true + if first != v.firstUnacknowledged { + v.firstUnacknowledgedUpdated = true } } // Private: Visible for testing. -func (this *SendingWorker) ProcessAck(number uint32) bool { - // number < this.firstUnacknowledged || number >= this.nextNumber - if number-this.firstUnacknowledged > 0x7FFFFFFF || number-this.nextNumber < 0x7FFFFFFF { +func (v *SendingWorker) ProcessAck(number uint32) bool { + // number < v.firstUnacknowledged || number >= v.nextNumber + if number-v.firstUnacknowledged > 0x7FFFFFFF || number-v.nextNumber < 0x7FFFFFFF { return false } - removed := this.window.Remove(number - this.firstUnacknowledged) + removed := v.window.Remove(number - v.firstUnacknowledged) if removed { - this.FindFirstUnacknowledged() + v.FindFirstUnacknowledged() } return removed } -func (this *SendingWorker) ProcessSegment(current uint32, seg *AckSegment, rto uint32) { +func (v *SendingWorker) ProcessSegment(current uint32, seg *AckSegment, rto uint32) { defer seg.Release() - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - if this.remoteNextNumber < seg.ReceivingWindow { - this.remoteNextNumber = seg.ReceivingWindow + if v.remoteNextNumber < seg.ReceivingWindow { + v.remoteNextNumber = seg.ReceivingWindow } - this.ProcessReceivingNextWithoutLock(seg.ReceivingNext) + v.ProcessReceivingNextWithoutLock(seg.ReceivingNext) var maxack uint32 var maxackRemoved bool for i := 0; i < int(seg.Count); i++ { number := seg.NumberList[i] - removed := this.ProcessAck(number) + removed := v.ProcessAck(number) if maxack < number { maxack = number maxackRemoved = removed @@ -268,27 +268,27 @@ func (this *SendingWorker) ProcessSegment(current uint32, seg *AckSegment, rto u } if maxackRemoved { - this.window.HandleFastAck(maxack, rto) + v.window.HandleFastAck(maxack, rto) if current-seg.Timestamp < 10000 { - this.conn.roundTrip.Update(current-seg.Timestamp, current) + v.conn.roundTrip.Update(current-seg.Timestamp, current) } } } -func (this *SendingWorker) Push(b []byte) int { +func (v *SendingWorker) Push(b []byte) int { nBytes := 0 - this.Lock() - defer this.Unlock() + v.Lock() + defer v.Unlock() - for len(b) > 0 && !this.window.IsFull() { + for len(b) > 0 && !v.window.IsFull() { var size int - if len(b) > int(this.conn.mss) { - size = int(this.conn.mss) + if len(b) > int(v.conn.mss) { + size = int(v.conn.mss) } else { size = len(b) } - this.window.Push(this.nextNumber, b[:size]) - this.nextNumber++ + v.window.Push(v.nextNumber, b[:size]) + v.nextNumber++ b = b[size:] nBytes += size } @@ -296,72 +296,72 @@ func (this *SendingWorker) Push(b []byte) int { } // Private: Visible for testing. -func (this *SendingWorker) Write(seg Segment) { +func (v *SendingWorker) Write(seg Segment) { dataSeg := seg.(*DataSegment) - dataSeg.Conv = this.conn.conv - dataSeg.SendingNext = this.firstUnacknowledged + dataSeg.Conv = v.conn.conv + dataSeg.SendingNext = v.firstUnacknowledged dataSeg.Option = 0 - if this.conn.State() == StateReadyToClose { + if v.conn.State() == StateReadyToClose { dataSeg.Option = SegmentOptionClose } - this.conn.output.Write(dataSeg) + v.conn.output.Write(dataSeg) } -func (this *SendingWorker) OnPacketLoss(lossRate uint32) { - if !this.conn.Config.Congestion || this.conn.roundTrip.Timeout() == 0 { +func (v *SendingWorker) OnPacketLoss(lossRate uint32) { + if !v.conn.Config.Congestion || v.conn.roundTrip.Timeout() == 0 { return } if lossRate >= 15 { - this.controlWindow = 3 * this.controlWindow / 4 + v.controlWindow = 3 * v.controlWindow / 4 } else if lossRate <= 5 { - this.controlWindow += this.controlWindow / 4 + v.controlWindow += v.controlWindow / 4 } - if this.controlWindow < 16 { - this.controlWindow = 16 + if v.controlWindow < 16 { + v.controlWindow = 16 } - if this.controlWindow > 2*this.conn.Config.GetSendingInFlightSize() { - this.controlWindow = 2 * this.conn.Config.GetSendingInFlightSize() + if v.controlWindow > 2*v.conn.Config.GetSendingInFlightSize() { + v.controlWindow = 2 * v.conn.Config.GetSendingInFlightSize() } } -func (this *SendingWorker) Flush(current uint32) { - this.Lock() - defer this.Unlock() +func (v *SendingWorker) Flush(current uint32) { + v.Lock() + defer v.Unlock() - cwnd := this.firstUnacknowledged + this.conn.Config.GetSendingInFlightSize() - if cwnd > this.remoteNextNumber { - cwnd = this.remoteNextNumber + cwnd := v.firstUnacknowledged + v.conn.Config.GetSendingInFlightSize() + if cwnd > v.remoteNextNumber { + cwnd = v.remoteNextNumber } - if this.conn.Config.Congestion && cwnd > this.firstUnacknowledged+this.controlWindow { - cwnd = this.firstUnacknowledged + this.controlWindow + if v.conn.Config.Congestion && cwnd > v.firstUnacknowledged+v.controlWindow { + cwnd = v.firstUnacknowledged + v.controlWindow } - if !this.window.IsEmpty() { - this.window.Flush(current, this.conn.roundTrip.Timeout(), cwnd) - } else if this.firstUnacknowledgedUpdated { - this.conn.Ping(current, CommandPing) + if !v.window.IsEmpty() { + v.window.Flush(current, v.conn.roundTrip.Timeout(), cwnd) + } else if v.firstUnacknowledgedUpdated { + v.conn.Ping(current, CommandPing) } - this.firstUnacknowledgedUpdated = false + v.firstUnacknowledgedUpdated = false } -func (this *SendingWorker) CloseWrite() { - this.Lock() - defer this.Unlock() +func (v *SendingWorker) CloseWrite() { + v.Lock() + defer v.Unlock() - this.window.Clear(0xFFFFFFFF) + v.window.Clear(0xFFFFFFFF) } -func (this *SendingWorker) IsEmpty() bool { - this.RLock() - defer this.RUnlock() +func (v *SendingWorker) IsEmpty() bool { + v.RLock() + defer v.RUnlock() - return this.window.IsEmpty() + return v.window.IsEmpty() } -func (this *SendingWorker) UpdateNecessary() bool { - return !this.IsEmpty() +func (v *SendingWorker) UpdateNecessary() bool { + return !v.IsEmpty() } diff --git a/transport/internet/system_dialer.go b/transport/internet/system_dialer.go index 2710c6a59..9427bde80 100644 --- a/transport/internet/system_dialer.go +++ b/transport/internet/system_dialer.go @@ -18,7 +18,7 @@ type SystemDialer interface { type DefaultSystemDialer struct { } -func (this *DefaultSystemDialer) Dial(src v2net.Address, dest v2net.Destination) (net.Conn, error) { +func (v *DefaultSystemDialer) Dial(src v2net.Address, dest v2net.Destination) (net.Conn, error) { dialer := &net.Dialer{ Timeout: time.Second * 60, DualStack: true, @@ -55,8 +55,8 @@ func WithAdapter(dialer SystemDialerAdapter) SystemDialer { } } -func (this *SimpleSystemDialer) Dial(src v2net.Address, dest v2net.Destination) (net.Conn, error) { - return this.adapter.Dial(dest.Network.SystemString(), dest.NetAddr()) +func (v *SimpleSystemDialer) Dial(src v2net.Address, dest v2net.Destination) (net.Conn, error) { + return v.adapter.Dial(dest.Network.SystemString(), dest.NetAddr()) } // UseAlternativeSystemDialer replaces the current system dialer with a given one. diff --git a/transport/internet/tcp/config.go b/transport/internet/tcp/config.go index 124bea2ed..0f2eb8b4e 100644 --- a/transport/internet/tcp/config.go +++ b/transport/internet/tcp/config.go @@ -5,11 +5,11 @@ import ( "v2ray.com/core/transport/internet" ) -func (this *ConnectionReuse) IsEnabled() bool { - if this == nil { +func (v *ConnectionReuse) IsEnabled() bool { + if v == nil { return true } - return this.Enable + return v.Enable } func init() { diff --git a/transport/internet/tcp/connection.go b/transport/internet/tcp/connection.go index 4e52b20bc..ab8a887f8 100644 --- a/transport/internet/tcp/connection.go +++ b/transport/internet/tcp/connection.go @@ -16,14 +16,14 @@ type RawConnection struct { net.TCPConn } -func (this *RawConnection) Reusable() bool { +func (v *RawConnection) Reusable() bool { return false } -func (this *RawConnection) SetReusable(b bool) {} +func (v *RawConnection) SetReusable(b bool) {} -func (this *RawConnection) SysFd() (int, error) { - return internal.GetSysFd(&this.TCPConn) +func (v *RawConnection) SysFd() (int, error) { + return internal.GetSysFd(&v.TCPConn) } type Connection struct { @@ -44,65 +44,65 @@ func NewConnection(id internal.ConnectionId, conn net.Conn, manager ConnectionMa } } -func (this *Connection) Read(b []byte) (int, error) { - if this == nil || this.conn == nil { +func (v *Connection) Read(b []byte) (int, error) { + if v == nil || v.conn == nil { return 0, io.EOF } - return this.conn.Read(b) + return v.conn.Read(b) } -func (this *Connection) Write(b []byte) (int, error) { - if this == nil || this.conn == nil { +func (v *Connection) Write(b []byte) (int, error) { + if v == nil || v.conn == nil { return 0, io.ErrClosedPipe } - return this.conn.Write(b) + return v.conn.Write(b) } -func (this *Connection) Close() error { - if this == nil || this.conn == nil { +func (v *Connection) Close() error { + if v == nil || v.conn == nil { return io.ErrClosedPipe } - if this.Reusable() { - this.listener.Put(this.id, this.conn) + if v.Reusable() { + v.listener.Put(v.id, v.conn) return nil } - err := this.conn.Close() - this.conn = nil + err := v.conn.Close() + v.conn = nil return err } -func (this *Connection) LocalAddr() net.Addr { - return this.conn.LocalAddr() +func (v *Connection) LocalAddr() net.Addr { + return v.conn.LocalAddr() } -func (this *Connection) RemoteAddr() net.Addr { - return this.conn.RemoteAddr() +func (v *Connection) RemoteAddr() net.Addr { + return v.conn.RemoteAddr() } -func (this *Connection) SetDeadline(t time.Time) error { - return this.conn.SetDeadline(t) +func (v *Connection) SetDeadline(t time.Time) error { + return v.conn.SetDeadline(t) } -func (this *Connection) SetReadDeadline(t time.Time) error { - return this.conn.SetReadDeadline(t) +func (v *Connection) SetReadDeadline(t time.Time) error { + return v.conn.SetReadDeadline(t) } -func (this *Connection) SetWriteDeadline(t time.Time) error { - return this.conn.SetWriteDeadline(t) +func (v *Connection) SetWriteDeadline(t time.Time) error { + return v.conn.SetWriteDeadline(t) } -func (this *Connection) SetReusable(reusable bool) { - if !this.config.ConnectionReuse.IsEnabled() { +func (v *Connection) SetReusable(reusable bool) { + if !v.config.ConnectionReuse.IsEnabled() { return } - this.reusable = reusable + v.reusable = reusable } -func (this *Connection) Reusable() bool { - return this.reusable +func (v *Connection) Reusable() bool { + return v.reusable } -func (this *Connection) SysFd() (int, error) { - return internal.GetSysFd(this.conn) +func (v *Connection) SysFd() (int, error) { + return internal.GetSysFd(v.conn) } diff --git a/transport/internet/tcp/hub.go b/transport/internet/tcp/hub.go index 663510136..f61d5212a 100644 --- a/transport/internet/tcp/hub.go +++ b/transport/internet/tcp/hub.go @@ -79,10 +79,10 @@ func ListenTCP(address v2net.Address, port v2net.Port, options internet.ListenOp return l, nil } -func (this *TCPListener) Accept() (internet.Connection, error) { - for this.acccepting { +func (v *TCPListener) Accept() (internet.Connection, error) { + for v.acccepting { select { - case connErr, open := <-this.awaitingConns: + case connErr, open := <-v.awaitingConns: if !open { return nil, ErrClosedListener } @@ -90,29 +90,29 @@ func (this *TCPListener) Accept() (internet.Connection, error) { return nil, connErr.err } conn := connErr.conn - return NewConnection(internal.ConnectionId{}, conn, this, this.config), nil + return NewConnection(internal.ConnectionId{}, conn, v, v.config), nil case <-time.After(time.Second * 2): } } return nil, ErrClosedListener } -func (this *TCPListener) KeepAccepting() { - for this.acccepting { - conn, err := this.listener.Accept() - this.Lock() - if !this.acccepting { - this.Unlock() +func (v *TCPListener) KeepAccepting() { + for v.acccepting { + conn, err := v.listener.Accept() + v.Lock() + if !v.acccepting { + v.Unlock() break } - if this.tlsConfig != nil { - conn = tls.Server(conn, this.tlsConfig) + if v.tlsConfig != nil { + conn = tls.Server(conn, v.tlsConfig) } - if this.authConfig != nil { - conn = this.authConfig.Server(conn) + if v.authConfig != nil { + conn = v.authConfig.Server(conn) } select { - case this.awaitingConns <- &ConnectionWithError{ + case v.awaitingConns <- &ConnectionWithError{ conn: conn, err: err, }: @@ -122,34 +122,34 @@ func (this *TCPListener) KeepAccepting() { } } - this.Unlock() + v.Unlock() } } -func (this *TCPListener) Put(id internal.ConnectionId, conn net.Conn) { - this.Lock() - defer this.Unlock() - if !this.acccepting { +func (v *TCPListener) Put(id internal.ConnectionId, conn net.Conn) { + v.Lock() + defer v.Unlock() + if !v.acccepting { return } select { - case this.awaitingConns <- &ConnectionWithError{conn: conn}: + case v.awaitingConns <- &ConnectionWithError{conn: conn}: default: conn.Close() } } -func (this *TCPListener) Addr() net.Addr { - return this.listener.Addr() +func (v *TCPListener) Addr() net.Addr { + return v.listener.Addr() } -func (this *TCPListener) Close() error { - this.Lock() - defer this.Unlock() - this.acccepting = false - this.listener.Close() - close(this.awaitingConns) - for connErr := range this.awaitingConns { +func (v *TCPListener) Close() error { + v.Lock() + defer v.Unlock() + v.acccepting = false + v.listener.Close() + close(v.awaitingConns) + for connErr := range v.awaitingConns { if connErr.conn != nil { go connErr.conn.Close() } @@ -162,8 +162,8 @@ type RawTCPListener struct { listener *net.TCPListener } -func (this *RawTCPListener) Accept() (internet.Connection, error) { - conn, err := this.listener.AcceptTCP() +func (v *RawTCPListener) Accept() (internet.Connection, error) { + conn, err := v.listener.AcceptTCP() if err != nil { return nil, err } @@ -172,13 +172,13 @@ func (this *RawTCPListener) Accept() (internet.Connection, error) { }, nil } -func (this *RawTCPListener) Addr() net.Addr { - return this.listener.Addr() +func (v *RawTCPListener) Addr() net.Addr { + return v.listener.Addr() } -func (this *RawTCPListener) Close() error { - this.accepting = false - this.listener.Close() +func (v *RawTCPListener) Close() error { + v.accepting = false + v.listener.Close() return nil } diff --git a/transport/internet/tcp_hub.go b/transport/internet/tcp_hub.go index 413134767..6dbff3bf0 100644 --- a/transport/internet/tcp_hub.go +++ b/transport/internet/tcp_hub.go @@ -71,22 +71,22 @@ func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandle return hub, nil } -func (this *TCPHub) Close() { - this.accepting = false - this.listener.Close() +func (v *TCPHub) Close() { + v.accepting = false + v.listener.Close() } -func (this *TCPHub) start() { - this.accepting = true - for this.accepting { +func (v *TCPHub) start() { + v.accepting = true + for v.accepting { var newConn Connection err := retry.ExponentialBackoff(10, 200).On(func() error { - if !this.accepting { + if !v.accepting { return nil } - conn, err := this.listener.Accept() + conn, err := v.listener.Accept() if err != nil { - if this.accepting { + if v.accepting { log.Warning("Internet|Listener: Failed to accept new TCP connection: ", err) } return err @@ -95,7 +95,7 @@ func (this *TCPHub) start() { return nil }) if err == nil && newConn != nil { - go this.connCallback(newConn) + go v.connCallback(newConn) } } } diff --git a/transport/internet/tls/config.go b/transport/internet/tls/config.go index e40b2e9b5..254588a2a 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -10,9 +10,9 @@ var ( globalSessionCache = tls.NewLRUClientSessionCache(128) ) -func (this *Config) BuildCertificates() []tls.Certificate { - certs := make([]tls.Certificate, 0, len(this.Certificate)) - for _, entry := range this.Certificate { +func (v *Config) BuildCertificates() []tls.Certificate { + certs := make([]tls.Certificate, 0, len(v.Certificate)) + for _, entry := range v.Certificate { keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key) if err != nil { log.Warning("TLS: ignoring invalid X509 key pair: ", err) @@ -23,16 +23,16 @@ func (this *Config) BuildCertificates() []tls.Certificate { return certs } -func (this *Config) GetTLSConfig() *tls.Config { +func (v *Config) GetTLSConfig() *tls.Config { config := &tls.Config{ ClientSessionCache: globalSessionCache, } - if this == nil { + if v == nil { return config } - config.InsecureSkipVerify = this.AllowInsecure - config.Certificates = this.BuildCertificates() + config.InsecureSkipVerify = v.AllowInsecure + config.Certificates = v.BuildCertificates() config.BuildNameToCertificate() return config diff --git a/transport/internet/tls/connection.go b/transport/internet/tls/connection.go index f46249149..39fcd48bb 100644 --- a/transport/internet/tls/connection.go +++ b/transport/internet/tls/connection.go @@ -8,11 +8,11 @@ type Connection struct { *tls.Conn } -func (this *Connection) Reusable() bool { +func (v *Connection) Reusable() bool { return false } -func (this *Connection) SetReusable(bool) {} +func (v *Connection) SetReusable(bool) {} func NewConnection(conn *tls.Conn) *Connection { return &Connection{ diff --git a/transport/internet/udp/connection.go b/transport/internet/udp/connection.go index a2b64599a..2a25fae1a 100644 --- a/transport/internet/udp/connection.go +++ b/transport/internet/udp/connection.go @@ -10,11 +10,11 @@ type Connection struct { net.UDPConn } -func (this *Connection) Reusable() bool { +func (v *Connection) Reusable() bool { return false } -func (this *Connection) SetReusable(b bool) {} +func (v *Connection) SetReusable(b bool) {} func init() { internet.UDPDialer = func(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) { diff --git a/transport/internet/udp/hub.go b/transport/internet/udp/hub.go index d44b39c00..2a1783779 100644 --- a/transport/internet/udp/hub.go +++ b/transport/internet/udp/hub.go @@ -37,15 +37,15 @@ func NewUDPPayloadQueue(option ListenOption) *UDPPayloadQueue { return queue } -func (this *UDPPayloadQueue) Enqueue(payload UDPPayload) { - size := len(this.queue) +func (v *UDPPayloadQueue) Enqueue(payload UDPPayload) { + size := len(v.queue) idx := 0 if size > 1 { idx = dice.Roll(size) } for i := 0; i < size; i++ { select { - case this.queue[idx%size] <- payload: + case v.queue[idx%size] <- payload: return default: idx++ @@ -53,14 +53,14 @@ func (this *UDPPayloadQueue) Enqueue(payload UDPPayload) { } } -func (this *UDPPayloadQueue) Dequeue(queue <-chan UDPPayload) { +func (v *UDPPayloadQueue) Dequeue(queue <-chan UDPPayload) { for payload := range queue { - this.callback(payload.payload, payload.session) + v.callback(payload.payload, payload.session) } } -func (this *UDPPayloadQueue) Close() { - for _, queue := range this.queue { +func (v *UDPPayloadQueue) Close() { + for _, queue := range v.queue { close(queue) } } @@ -112,31 +112,31 @@ func ListenUDP(address v2net.Address, port v2net.Port, option ListenOption) (*UD return hub, nil } -func (this *UDPHub) Close() { - this.Lock() - defer this.Unlock() +func (v *UDPHub) Close() { + v.Lock() + defer v.Unlock() - this.cancel.Cancel() - this.conn.Close() - this.cancel.WaitForDone() - this.queue.Close() + v.cancel.Cancel() + v.conn.Close() + v.cancel.WaitForDone() + v.queue.Close() } -func (this *UDPHub) WriteTo(payload []byte, dest v2net.Destination) (int, error) { - return this.conn.WriteToUDP(payload, &net.UDPAddr{ +func (v *UDPHub) WriteTo(payload []byte, dest v2net.Destination) (int, error) { + return v.conn.WriteToUDP(payload, &net.UDPAddr{ IP: dest.Address.IP(), Port: int(dest.Port), }) } -func (this *UDPHub) start() { - this.cancel.WaitThread() - defer this.cancel.FinishThread() +func (v *UDPHub) start() { + v.cancel.WaitThread() + defer v.cancel.FinishThread() oobBytes := make([]byte, 256) - for this.Running() { + for v.Running() { buffer := alloc.NewSmallBuffer() - nBytes, noob, _, addr, err := ReadUDPMsg(this.conn, buffer.Value, oobBytes) + nBytes, noob, _, addr, err := ReadUDPMsg(v.conn, buffer.Value, oobBytes) if err != nil { log.Info("UDP|Hub: Failed to read UDP msg: ", err) buffer.Release() @@ -146,26 +146,26 @@ func (this *UDPHub) start() { session := new(proxy.SessionInfo) session.Source = v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port)) - if this.option.ReceiveOriginalDest && noob > 0 { + if v.option.ReceiveOriginalDest && noob > 0 { session.Destination = RetrieveOriginalDest(oobBytes[:noob]) } - this.queue.Enqueue(UDPPayload{ + v.queue.Enqueue(UDPPayload{ payload: buffer, session: session, }) } } -func (this *UDPHub) Running() bool { - return !this.cancel.Cancelled() +func (v *UDPHub) Running() bool { + return !v.cancel.Cancelled() } -// Connection return the net.Conn underneath this hub. +// Connection return the net.Conn underneath v hub. // Private: Visible for testing only -func (this *UDPHub) Connection() net.Conn { - return this.conn +func (v *UDPHub) Connection() net.Conn { + return v.conn } -func (this *UDPHub) Addr() net.Addr { - return this.conn.LocalAddr() +func (v *UDPHub) Addr() net.Addr { + return v.conn.LocalAddr() } diff --git a/transport/internet/udp/udp_server.go b/transport/internet/udp/udp_server.go index 219900af1..febfe44ac 100644 --- a/transport/internet/udp/udp_server.go +++ b/transport/internet/udp/udp_server.go @@ -33,63 +33,63 @@ func NewTimedInboundRay(name string, inboundRay ray.InboundRay, server *UDPServe return r } -func (this *TimedInboundRay) Monitor() { +func (v *TimedInboundRay) Monitor() { for { time.Sleep(time.Second * 16) select { - case <-this.accessed: + case <-v.accessed: default: // Ray not accessed for a while, assuming communication is dead. - this.RLock() - if this.server == nil { - this.RUnlock() + v.RLock() + if v.server == nil { + v.RUnlock() return } - this.server.RemoveRay(this.name) - this.RUnlock() - this.Release() + v.server.RemoveRay(v.name) + v.RUnlock() + v.Release() return } } } -func (this *TimedInboundRay) InboundInput() ray.OutputStream { - this.RLock() - defer this.RUnlock() - if this.inboundRay == nil { +func (v *TimedInboundRay) InboundInput() ray.OutputStream { + v.RLock() + defer v.RUnlock() + if v.inboundRay == nil { return nil } select { - case this.accessed <- true: + case v.accessed <- true: default: } - return this.inboundRay.InboundInput() + return v.inboundRay.InboundInput() } -func (this *TimedInboundRay) InboundOutput() ray.InputStream { - this.RLock() - defer this.RUnlock() - if this.inboundRay == nil { +func (v *TimedInboundRay) InboundOutput() ray.InputStream { + v.RLock() + defer v.RUnlock() + if v.inboundRay == nil { return nil } select { - case this.accessed <- true: + case v.accessed <- true: default: } - return this.inboundRay.InboundOutput() + return v.inboundRay.InboundOutput() } -func (this *TimedInboundRay) Release() { - log.Debug("UDP Server: Releasing TimedInboundRay: ", this.name) - this.Lock() - defer this.Unlock() - if this.server == nil { +func (v *TimedInboundRay) Release() { + log.Debug("UDP Server: Releasing TimedInboundRay: ", v.name) + v.Lock() + defer v.Unlock() + if v.server == nil { return } - this.server = nil - this.inboundRay.InboundInput().Close() - this.inboundRay.InboundOutput().Release() - this.inboundRay = nil + v.server = nil + v.inboundRay.InboundInput().Close() + v.inboundRay.InboundOutput().Release() + v.inboundRay = nil } type UDPServer struct { @@ -105,17 +105,17 @@ func NewUDPServer(packetDispatcher dispatcher.PacketDispatcher) *UDPServer { } } -func (this *UDPServer) RemoveRay(name string) { - this.Lock() - defer this.Unlock() - delete(this.conns, name) +func (v *UDPServer) RemoveRay(name string) { + v.Lock() + defer v.Unlock() + delete(v.conns, name) } -func (this *UDPServer) locateExistingAndDispatch(name string, payload *alloc.Buffer) bool { +func (v *UDPServer) locateExistingAndDispatch(name string, payload *alloc.Buffer) bool { log.Debug("UDP Server: Locating existing connection for ", name) - this.RLock() - defer this.RUnlock() - if entry, found := this.conns[name]; found { + v.RLock() + defer v.RUnlock() + if entry, found := v.conns[name]; found { outputStream := entry.InboundInput() if outputStream == nil { return false @@ -130,32 +130,32 @@ func (this *UDPServer) locateExistingAndDispatch(name string, payload *alloc.Buf return false } -func (this *UDPServer) Dispatch(session *proxy.SessionInfo, payload *alloc.Buffer, callback UDPResponseCallback) { +func (v *UDPServer) Dispatch(session *proxy.SessionInfo, payload *alloc.Buffer, callback UDPResponseCallback) { source := session.Source destination := session.Destination // TODO: Add user to destString destString := source.String() + "-" + destination.String() log.Debug("UDP Server: Dispatch request: ", destString) - if this.locateExistingAndDispatch(destString, payload) { + if v.locateExistingAndDispatch(destString, payload) { return } log.Info("UDP Server: establishing new connection for ", destString) - inboundRay := this.packetDispatcher.DispatchToOutbound(session) - timedInboundRay := NewTimedInboundRay(destString, inboundRay, this) + inboundRay := v.packetDispatcher.DispatchToOutbound(session) + timedInboundRay := NewTimedInboundRay(destString, inboundRay, v) outputStream := timedInboundRay.InboundInput() if outputStream != nil { outputStream.Write(payload) } - this.Lock() - this.conns[destString] = timedInboundRay - this.Unlock() - go this.handleConnection(timedInboundRay, source, callback) + v.Lock() + v.conns[destString] = timedInboundRay + v.Unlock() + go v.handleConnection(timedInboundRay, source, callback) } -func (this *UDPServer) handleConnection(inboundRay *TimedInboundRay, source v2net.Destination, callback UDPResponseCallback) { +func (v *UDPServer) handleConnection(inboundRay *TimedInboundRay, source v2net.Destination, callback UDPResponseCallback) { for { inputStream := inboundRay.InboundOutput() if inputStream == nil { diff --git a/transport/internet/ws/config.go b/transport/internet/ws/config.go index 859cb93cd..660e9e3f9 100644 --- a/transport/internet/ws/config.go +++ b/transport/internet/ws/config.go @@ -5,11 +5,11 @@ import ( "v2ray.com/core/transport/internet" ) -func (this *ConnectionReuse) IsEnabled() bool { - if this == nil { +func (v *ConnectionReuse) IsEnabled() bool { + if v == nil { return false } - return this.Enable + return v.Enable } func init() { diff --git a/transport/internet/ws/connection.go b/transport/internet/ws/connection.go index 55163e530..069596e24 100644 --- a/transport/internet/ws/connection.go +++ b/transport/internet/ws/connection.go @@ -33,67 +33,67 @@ func NewConnection(dest string, conn *wsconn, manager ConnectionManager, config } } -func (this *Connection) Read(b []byte) (int, error) { - if this == nil || this.conn == nil { +func (v *Connection) Read(b []byte) (int, error) { + if v == nil || v.conn == nil { return 0, io.EOF } - return this.conn.Read(b) + return v.conn.Read(b) } -func (this *Connection) Write(b []byte) (int, error) { - if this == nil || this.conn == nil { +func (v *Connection) Write(b []byte) (int, error) { + if v == nil || v.conn == nil { return 0, io.ErrClosedPipe } - return this.conn.Write(b) + return v.conn.Write(b) } -func (this *Connection) Close() error { - if this == nil || this.conn == nil { +func (v *Connection) Close() error { + if v == nil || v.conn == nil { return io.ErrClosedPipe } - if this.Reusable() { - this.listener.Recycle(this.dest, this.conn) + if v.Reusable() { + v.listener.Recycle(v.dest, v.conn) return nil } - err := this.conn.Close() - this.conn = nil + err := v.conn.Close() + v.conn = nil return err } -func (this *Connection) LocalAddr() net.Addr { - return this.conn.LocalAddr() +func (v *Connection) LocalAddr() net.Addr { + return v.conn.LocalAddr() } -func (this *Connection) RemoteAddr() net.Addr { - return this.conn.RemoteAddr() +func (v *Connection) RemoteAddr() net.Addr { + return v.conn.RemoteAddr() } -func (this *Connection) SetDeadline(t time.Time) error { - return this.conn.SetDeadline(t) +func (v *Connection) SetDeadline(t time.Time) error { + return v.conn.SetDeadline(t) } -func (this *Connection) SetReadDeadline(t time.Time) error { - return this.conn.SetReadDeadline(t) +func (v *Connection) SetReadDeadline(t time.Time) error { + return v.conn.SetReadDeadline(t) } -func (this *Connection) SetWriteDeadline(t time.Time) error { - return this.conn.SetWriteDeadline(t) +func (v *Connection) SetWriteDeadline(t time.Time) error { + return v.conn.SetWriteDeadline(t) } -func (this *Connection) SetReusable(reusable bool) { - if !this.config.ConnectionReuse.IsEnabled() { +func (v *Connection) SetReusable(reusable bool) { + if !v.config.ConnectionReuse.IsEnabled() { return } - this.reusable = reusable + v.reusable = reusable } -func (this *Connection) Reusable() bool { - return this.reusable +func (v *Connection) Reusable() bool { + return v.reusable } -func (this *Connection) SysFd() (int, error) { - return getSysFd(this.conn) +func (v *Connection) SysFd() (int, error) { + return getSysFd(v.conn) } func getSysFd(conn net.Conn) (int, error) { diff --git a/transport/internet/ws/connection_cache.go b/transport/internet/ws/connection_cache.go index f53a27bbb..db253acb8 100644 --- a/transport/internet/ws/connection_cache.go +++ b/transport/internet/ws/connection_cache.go @@ -14,8 +14,8 @@ type AwaitingConnection struct { expire time.Time } -func (this *AwaitingConnection) Expired() bool { - return this.expire.Before(time.Now()) +func (v *AwaitingConnection) Expired() bool { + return v.expire.Before(time.Now()) } type ConnectionCache struct { @@ -30,13 +30,13 @@ func NewConnectionCache() *ConnectionCache { } } -func (this *ConnectionCache) Cleanup() { - defer this.cleanupOnce.Reset() +func (v *ConnectionCache) Cleanup() { + defer v.cleanupOnce.Reset() - for len(this.cache) > 0 { + for len(v.cache) > 0 { time.Sleep(time.Second * 7) - this.Lock() - for key, value := range this.cache { + v.Lock() + for key, value := range v.cache { size := len(value) changed := false for i := 0; i < size; { @@ -54,16 +54,16 @@ func (this *ConnectionCache) Cleanup() { value[i] = nil } value = value[:size] - this.cache[key] = value + v.cache[key] = value } } - this.Unlock() + v.Unlock() } } -func (this *ConnectionCache) Recycle(dest string, conn *wsconn) { - this.Lock() - defer this.Unlock() +func (v *ConnectionCache) Recycle(dest string, conn *wsconn) { + v.Lock() + defer v.Unlock() aconn := &AwaitingConnection{ conn: conn, @@ -71,15 +71,15 @@ func (this *ConnectionCache) Recycle(dest string, conn *wsconn) { } var list []*AwaitingConnection - if val, found := this.cache[dest]; found { + if val, found := v.cache[dest]; found { val = append(val, aconn) list = val } else { list = []*AwaitingConnection{aconn} } - this.cache[dest] = list + v.cache[dest] = list - go this.cleanupOnce.Do(this.Cleanup) + go v.cleanupOnce.Do(v.Cleanup) } func FindFirstValid(list []*AwaitingConnection) int { @@ -92,23 +92,23 @@ func FindFirstValid(list []*AwaitingConnection) int { return -1 } -func (this *ConnectionCache) Get(dest string) net.Conn { - this.Lock() - defer this.Unlock() +func (v *ConnectionCache) Get(dest string) net.Conn { + v.Lock() + defer v.Unlock() - list, found := this.cache[dest] + list, found := v.cache[dest] if !found { return nil } firstValid := FindFirstValid(list) if firstValid == -1 { - delete(this.cache, dest) + delete(v.cache, dest) return nil } res := list[firstValid].conn list = list[firstValid+1:] - this.cache[dest] = list + v.cache[dest] = list log.Debug("WS:Conn Cache used.") return res } diff --git a/transport/internet/ws/hub.go b/transport/internet/ws/hub.go index 91b9c3cf3..e8eda5ac1 100644 --- a/transport/internet/ws/hub.go +++ b/transport/internet/ws/hub.go @@ -145,49 +145,49 @@ func (wsl *WSListener) converttovws(w http.ResponseWriter, r *http.Request) (*ws return wrapedConn, nil } -func (this *WSListener) Accept() (internet.Connection, error) { - for this.acccepting { +func (v *WSListener) Accept() (internet.Connection, error) { + for v.acccepting { select { - case connErr, open := <-this.awaitingConns: + case connErr, open := <-v.awaitingConns: if !open { return nil, ErrClosedListener } if connErr.err != nil { return nil, connErr.err } - return NewConnection("", connErr.conn.(*wsconn), this, this.config), nil + return NewConnection("", connErr.conn.(*wsconn), v, v.config), nil case <-time.After(time.Second * 2): } } return nil, ErrClosedListener } -func (this *WSListener) Recycle(dest string, conn *wsconn) { - this.Lock() - defer this.Unlock() - if !this.acccepting { +func (v *WSListener) Recycle(dest string, conn *wsconn) { + v.Lock() + defer v.Unlock() + if !v.acccepting { return } select { - case this.awaitingConns <- &ConnectionWithError{conn: conn}: + case v.awaitingConns <- &ConnectionWithError{conn: conn}: default: conn.Close() } } -func (this *WSListener) Addr() net.Addr { +func (v *WSListener) Addr() net.Addr { return nil } -func (this *WSListener) Close() error { - this.Lock() - defer this.Unlock() - this.acccepting = false +func (v *WSListener) Close() error { + v.Lock() + defer v.Unlock() + v.acccepting = false - this.listener.Stop() + v.listener.Stop() - close(this.awaitingConns) - for connErr := range this.awaitingConns { + close(v.awaitingConns) + for connErr := range v.awaitingConns { if connErr.conn != nil { go connErr.conn.Close() } diff --git a/transport/ray/direct.go b/transport/ray/direct.go index 719b9e4f6..2594e7d88 100644 --- a/transport/ray/direct.go +++ b/transport/ray/direct.go @@ -25,20 +25,20 @@ type directRay struct { Output *Stream } -func (this *directRay) OutboundInput() InputStream { - return this.Input +func (v *directRay) OutboundInput() InputStream { + return v.Input } -func (this *directRay) OutboundOutput() OutputStream { - return this.Output +func (v *directRay) OutboundOutput() OutputStream { + return v.Output } -func (this *directRay) InboundInput() OutputStream { - return this.Input +func (v *directRay) InboundInput() OutputStream { + return v.Input } -func (this *directRay) InboundOutput() InputStream { - return this.Output +func (v *directRay) InboundOutput() InputStream { + return v.Output } type Stream struct { @@ -53,17 +53,17 @@ func NewStream() *Stream { } } -func (this *Stream) Read() (*alloc.Buffer, error) { - if this.buffer == nil { +func (v *Stream) Read() (*alloc.Buffer, error) { + if v.buffer == nil { return nil, io.EOF } - this.access.RLock() - if this.buffer == nil { - this.access.RUnlock() + v.access.RLock() + if v.buffer == nil { + v.access.RUnlock() return nil, io.EOF } - channel := this.buffer - this.access.RUnlock() + channel := v.buffer + v.access.RUnlock() result, open := <-channel if !open { return nil, io.EOF @@ -71,9 +71,9 @@ func (this *Stream) Read() (*alloc.Buffer, error) { return result, nil } -func (this *Stream) Write(data *alloc.Buffer) error { - for !this.closed { - err := this.TryWriteOnce(data) +func (v *Stream) Write(data *alloc.Buffer) error { + for !v.closed { + err := v.TryWriteOnce(data) if err != io.ErrNoProgress { return err } @@ -81,45 +81,45 @@ func (this *Stream) Write(data *alloc.Buffer) error { return io.ErrClosedPipe } -func (this *Stream) TryWriteOnce(data *alloc.Buffer) error { - this.access.RLock() - defer this.access.RUnlock() - if this.closed { +func (v *Stream) TryWriteOnce(data *alloc.Buffer) error { + v.access.RLock() + defer v.access.RUnlock() + if v.closed { return io.ErrClosedPipe } select { - case this.buffer <- data: + case v.buffer <- data: return nil case <-time.After(2 * time.Second): return io.ErrNoProgress } } -func (this *Stream) Close() { - if this.closed { +func (v *Stream) Close() { + if v.closed { return } - this.access.Lock() - defer this.access.Unlock() - if this.closed { + v.access.Lock() + defer v.access.Unlock() + if v.closed { return } - this.closed = true - close(this.buffer) + v.closed = true + close(v.buffer) } -func (this *Stream) Release() { - if this.buffer == nil { +func (v *Stream) Release() { + if v.buffer == nil { return } - this.Close() - this.access.Lock() - defer this.access.Unlock() - if this.buffer == nil { + v.Close() + v.access.Lock() + defer v.access.Unlock() + if v.buffer == nil { return } - for data := range this.buffer { + for data := range v.buffer { data.Release() } - this.buffer = nil + v.buffer = nil } diff --git a/v2ray.go b/v2ray.go index f39664aaa..fd84c5439 100644 --- a/v2ray.go +++ b/v2ray.go @@ -142,16 +142,16 @@ func NewPoint(pConfig *Config) (*Point, error) { return vpoint, nil } -func (this *Point) Close() { - for _, inbound := range this.inboundHandlers { +func (v *Point) Close() { + for _, inbound := range v.inboundHandlers { inbound.Close() } } // Start starts the Point server, and return any error during the process. // In the case of any errors, the state of the server is unpredicatable. -func (this *Point) Start() error { - for _, inbound := range this.inboundHandlers { +func (v *Point) Start() error { + for _, inbound := range v.inboundHandlers { err := inbound.Start() if err != nil { return err @@ -162,8 +162,8 @@ func (this *Point) Start() error { return nil } -func (this *Point) GetHandler(tag string) (proxy.InboundHandler, int) { - handler, found := this.taggedInboundHandlers[tag] +func (v *Point) GetHandler(tag string) (proxy.InboundHandler, int) { + handler, found := v.taggedInboundHandlers[tag] if !found { log.Warning("V2Ray: Unable to find an inbound handler with tag: ", tag) return nil, 0 @@ -171,6 +171,6 @@ func (this *Point) GetHandler(tag string) (proxy.InboundHandler, int) { return handler.GetConnectionHandler() } -func (this *Point) Release() { +func (v *Point) Release() { }