Browse Source

rename 'this'

Darien Raymond 9 years ago
parent
commit
f95c322677
100 changed files with 1317 additions and 1317 deletions
  1. 11 11
      app/dispatcher/impl/default.go
  2. 3 3
      app/dispatcher/testing/dispatcher.go
  3. 30 30
      app/dns/nameserver.go
  4. 14 14
      app/dns/server.go
  5. 26 26
      app/proxy/proxy.go
  6. 18 18
      app/proxyman/proxyman.go
  7. 32 32
      app/router/condition.go
  8. 17 17
      app/router/config.go
  9. 12 12
      app/router/router.go
  10. 19 19
      app/router/routing_table.go
  11. 13 13
      app/space.go
  12. 14 14
      common/crypto/io.go
  13. 22 22
      common/io/buffered_reader.go
  14. 38 38
      common/io/buffered_writer.go
  15. 10 10
      common/io/chain_writer.go
  16. 23 23
      common/io/chan_reader.go
  17. 5 5
      common/io/reader.go
  18. 4 4
      common/io/writer.go
  19. 7 7
      common/loader/type.go
  20. 8 8
      common/log/config.go
  21. 14 14
      common/log/internal/log_entry.go
  22. 16 16
      common/log/internal/log_writer.go
  23. 18 18
      common/net/address.go
  24. 8 8
      common/net/destination.go
  25. 10 10
      common/net/ipnet.go
  26. 11 11
      common/net/network.go
  27. 16 16
      common/net/port.go
  28. 7 7
      common/net/timed_io.go
  29. 4 4
      common/predicate/predicate.go
  30. 16 16
      common/protocol/headers.go
  31. 8 8
      common/protocol/id.go
  32. 26 26
      common/protocol/server_picker.go
  33. 24 24
      common/protocol/server_spec.go
  34. 2 2
      common/protocol/time.go
  35. 6 6
      common/protocol/user.go
  36. 12 12
      common/signal/cancel.go
  37. 11 11
      common/uuid/uuid.go
  38. 21 21
      config.go
  39. 7 7
      inbound_detour_always.go
  40. 35 35
      inbound_detour_dynamic.go
  41. 4 4
      proxy/blackhole/blackhole.go
  42. 9 9
      proxy/blackhole/config.go
  43. 2 2
      proxy/dokodemo/config.go
  44. 55 55
      proxy/dokodemo/dokodemo.go
  45. 9 9
      proxy/freedom/freedom.go
  46. 33 33
      proxy/http/server.go
  47. 3 3
      proxy/proxy.go
  48. 5 5
      proxy/shadowsocks/client.go
  49. 21 21
      proxy/shadowsocks/config.go
  50. 15 15
      proxy/shadowsocks/ota.go
  51. 8 8
      proxy/shadowsocks/protocol.go
  52. 34 34
      proxy/shadowsocks/server.go
  53. 12 12
      proxy/socks/config.go
  54. 49 49
      proxy/socks/server.go
  55. 15 15
      proxy/socks/server_udp.go
  56. 8 8
      proxy/testing/mocks/inboundhandler.go
  57. 7 7
      proxy/testing/mocks/outboundhandler.go
  58. 9 9
      proxy/vmess/account.go
  59. 16 16
      proxy/vmess/encoding/client.go
  60. 2 2
      proxy/vmess/encoding/commands.go
  61. 24 24
      proxy/vmess/encoding/server.go
  62. 5 5
      proxy/vmess/inbound/command.go
  63. 3 3
      proxy/vmess/inbound/config.go
  64. 47 47
      proxy/vmess/inbound/inbound.go
  65. 33 33
      proxy/vmess/io/reader.go
  66. 5 5
      proxy/vmess/io/writer.go
  67. 4 4
      proxy/vmess/outbound/command.go
  68. 10 10
      proxy/vmess/outbound/outbound.go
  69. 38 38
      proxy/vmess/vmess.go
  70. 2 2
      testing/assert/address.go
  71. 2 2
      testing/assert/assert.go
  72. 2 2
      testing/assert/bool.go
  73. 2 2
      testing/assert/byte.go
  74. 2 2
      testing/assert/bytes.go
  75. 21 21
      testing/assert/destination.go
  76. 2 2
      testing/assert/error.go
  77. 2 2
      testing/assert/int64.go
  78. 2 2
      testing/assert/intsubject.go
  79. 2 2
      testing/assert/ip.go
  80. 2 2
      testing/assert/pointer.go
  81. 2 2
      testing/assert/port.go
  82. 2 2
      testing/assert/string.go
  83. 2 2
      testing/assert/uint16.go
  84. 2 2
      testing/assert/uint32.go
  85. 2 2
      testing/servers/http/http.go
  86. 3 3
      testing/servers/tcp/tcp.go
  87. 3 3
      tools/conf/blackhole.go
  88. 31 31
      tools/conf/common.go
  89. 5 5
      tools/conf/dns.go
  90. 7 7
      tools/conf/dokodemo.go
  91. 3 3
      tools/conf/freedom.go
  92. 2 2
      tools/conf/http.go
  93. 14 14
      tools/conf/loader.go
  94. 7 7
      tools/conf/log.go
  95. 3 3
      tools/conf/router.go
  96. 13 13
      tools/conf/shadowsocks.go
  97. 17 17
      tools/conf/socks.go
  98. 7 7
      tools/conf/transport.go
  99. 24 24
      tools/conf/transport_authenticators.go
  100. 44 44
      tools/conf/transport_internet.go

+ 11 - 11
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.")

+ 3 - 3
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
 }

+ 30 - 30
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() {

+ 14 - 14
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
 }
 

+ 26 - 26
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) {
 
 }

+ 18 - 18
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
 }

+ 32 - 32
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
 		}

+ 17 - 17
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 {

+ 12 - 12
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

+ 19 - 19
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
 	}

+ 13 - 13
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
 }

+ 14 - 14
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
 }

+ 22 - 22
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)
 }

+ 38 - 38
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
 }

+ 10 - 10
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()
 }

+ 23 - 23
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
 }

+ 5 - 5
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
 }

+ 4 - 4
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
 }

+ 7 - 7
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

+ 8 - 8
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

+ 14 - 14
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)}, " ")
 }

+ 16 - 16
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) {

+ 18 - 18
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:

+ 8 - 8
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),
 	}
 }

+ 10 - 10
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() {

+ 11 - 11
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]
 }

+ 16 - 16
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()
 }

+ 7 - 7
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)
 }

+ 4 - 4
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 {

+ 16 - 16
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{}

+ 8 - 8
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 {

+ 26 - 26
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
 }

+ 24 - 24
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()
 }

+ 2 - 2
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

+ 6 - 6
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

+ 12 - 12
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()
 }

+ 11 - 11
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"))

+ 21 - 21
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()
 }

+ 7 - 7
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 {

+ 35 - 35
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)
 			}

+ 4 - 4
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)
 }

+ 9 - 9
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
 	}

+ 2 - 2
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
 	}

+ 55 - 55
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
 }
 

+ 9 - 9
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
 }
 

+ 33 - 33
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
 	}

+ 3 - 3
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,
 	}
 }
 

+ 5 - 5
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)
 }

+ 21 - 21
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
 }
 

+ 15 - 15
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
 }

+ 8 - 8
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() {
 
 }

+ 34 - 34
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
 	}

+ 12 - 12
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()
 }

+ 49 - 49
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
 }
 

+ 15 - 15
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 {

+ 8 - 8
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)

+ 7 - 7
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
 }

+ 9 - 9
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
 }

+ 16 - 16
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
 }

+ 2 - 2
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.")

+ 24 - 24
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
 }

+ 5 - 5
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 {

+ 3 - 3
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
 }

+ 47 - 47
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
 	}

+ 33 - 33
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
 }

+ 5 - 5
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) {

+ 4 - 4
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:
 	}
 }

+ 10 - 10
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()

+ 38 - 38
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
 }

+ 2 - 2
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,
 	}

+ 2 - 2
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) {

+ 2 - 2
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,
 	}

+ 2 - 2
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,
 	}

+ 2 - 2
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,
 	}

+ 21 - 21
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)
 }

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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,

+ 2 - 2
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
 }

+ 3 - 3
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()
 }

+ 3 - 3
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())
 		}

+ 31 - 31
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),
 	}
 }

+ 5 - 5
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()
 		}
 	}

+ 7 - 7
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
 }

+ 3 - 3
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
 }

+ 2 - 2
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

+ 14 - 14
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
 	}

+ 7 - 7
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

+ 3 - 3
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)

+ 13 - 13
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.")
 		}

+ 17 - 17
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),

+ 7 - 7
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())
 		}

+ 24 - 24
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
 	}

+ 44 - 44
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
 }

Some files were not shown because too many files changed in this diff