From 59a1e2d7363fbe4f0d74f29b2e77e3902f2e6a3c Mon Sep 17 00:00:00 2001 From: Darien Raymond Date: Sun, 23 Apr 2017 19:16:56 +0200 Subject: [PATCH] refactor --- app/dispatcher/impl/default.go | 10 ++++----- app/dns/config.go | 4 ++-- app/dns/server/server.go | 23 ++++++++++---------- app/log/internal/log_entry.go | 8 +++---- app/log/internal/log_writer.go | 32 +++++++++++++-------------- app/proxyman/outbound/outbound.go | 30 +++++++++++++------------- app/router/router.go | 20 ++++++++--------- app/space.go | 26 +++++++++++----------- common/buf/buffered_writer.go | 36 +++++++++++++++---------------- common/buf/multi_buffer.go | 15 +++++++++---- 10 files changed, 104 insertions(+), 100 deletions(-) diff --git a/app/dispatcher/impl/default.go b/app/dispatcher/impl/default.go index f66a38d29..608249d00 100644 --- a/app/dispatcher/impl/default.go +++ b/app/dispatcher/impl/default.go @@ -48,17 +48,17 @@ func (DefaultDispatcher) Interface() interface{} { return (*dispatcher.Interface)(nil) } -func (v *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) { - dispatcher := v.ohm.GetDefaultHandler() +func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) { + dispatcher := d.ohm.GetDefaultHandler() if !destination.IsValid() { panic("Dispatcher: Invalid destination.") } ctx = proxy.ContextWithTarget(ctx, destination) - if v.router != nil { - if tag, err := v.router.TakeDetour(ctx); err == nil { - if handler := v.ohm.GetHandler(tag); handler != nil { + if d.router != nil { + if tag, err := d.router.TakeDetour(ctx); err == nil { + if handler := d.ohm.GetHandler(tag); handler != nil { log.Trace(newError("taking detour [", tag, "] for [", destination, "]")) dispatcher = handler } else { diff --git a/app/dns/config.go b/app/dns/config.go index 0195d1ad7..c01c54a1e 100644 --- a/app/dns/config.go +++ b/app/dns/config.go @@ -6,9 +6,9 @@ import ( "v2ray.com/core/app/log" ) -func (v *Config) GetInternalHosts() map[string]net.IP { +func (c *Config) GetInternalHosts() map[string]net.IP { hosts := make(map[string]net.IP) - for domain, ipOrDomain := range v.GetHosts() { + for domain, ipOrDomain := range c.GetHosts() { address := ipOrDomain.AsAddress() if address.Family().IsDomain() { log.Trace(newError("ignoring domain address in static hosts: ", address.Domain()).AtWarning()) diff --git a/app/dns/server/server.go b/app/dns/server/server.go index 093c47241..8a44fe147 100644 --- a/app/dns/server/server.go +++ b/app/dns/server/server.go @@ -80,40 +80,39 @@ func (*CacheServer) Start() error { func (*CacheServer) Close() {} -// Private: Visible for testing. -func (v *CacheServer) GetCached(domain string) []net.IP { - v.RLock() - defer v.RUnlock() +func (s *CacheServer) GetCached(domain string) []net.IP { + s.RLock() + defer s.RUnlock() - if record, found := v.records[domain]; found && record.A.Expire.After(time.Now()) { + if record, found := s.records[domain]; found && record.A.Expire.After(time.Now()) { return record.A.IPs } return nil } -func (v *CacheServer) Get(domain string) []net.IP { - if ip, found := v.hosts[domain]; found { +func (s *CacheServer) Get(domain string) []net.IP { + if ip, found := s.hosts[domain]; found { return []net.IP{ip} } domain = dnsmsg.Fqdn(domain) - ips := v.GetCached(domain) + ips := s.GetCached(domain) if ips != nil { return ips } - for _, server := range v.servers { + for _, server := range s.servers { response := server.QueryA(domain) select { case a, open := <-response: if !open || a == nil { continue } - v.Lock() - v.records[domain] = &DomainRecord{ + s.Lock() + s.records[domain] = &DomainRecord{ A: a, } - v.Unlock() + s.Unlock() log.Trace(newError("returning ", len(a.IPs), " IPs for domain ", domain).AtDebug()) return a.IPs case <-time.After(QueryTimeout): diff --git a/app/log/internal/log_entry.go b/app/log/internal/log_entry.go index a07d52f06..26381ac2a 100644 --- a/app/log/internal/log_entry.go +++ b/app/log/internal/log_entry.go @@ -16,8 +16,8 @@ type ErrorLog struct { Error error } -func (v *ErrorLog) String() string { - return v.Prefix + v.Error.Error() +func (l *ErrorLog) String() string { + return l.Prefix + l.Error.Error() } type AccessLog struct { @@ -27,6 +27,6 @@ type AccessLog struct { Reason interface{} } -func (v *AccessLog) String() string { - return strings.Join([]string{serial.ToString(v.From), v.Status, serial.ToString(v.To), serial.ToString(v.Reason)}, " ") +func (l *AccessLog) String() string { + return strings.Join([]string{serial.ToString(l.From), l.Status, serial.ToString(l.To), serial.ToString(l.Reason)}, " ") } diff --git a/app/log/internal/log_writer.go b/app/log/internal/log_writer.go index 2f61931ec..8b59226b9 100644 --- a/app/log/internal/log_writer.go +++ b/app/log/internal/log_writer.go @@ -16,10 +16,9 @@ type LogWriter interface { type NoOpLogWriter struct { } -func (v *NoOpLogWriter) Log(entry LogEntry) {} +func (*NoOpLogWriter) Log(entry LogEntry) {} -func (v *NoOpLogWriter) Close() { -} +func (*NoOpLogWriter) Close() {} type StdOutLogWriter struct { logger *log.Logger @@ -31,11 +30,11 @@ func NewStdOutLogWriter() LogWriter { } } -func (v *StdOutLogWriter) Log(log LogEntry) { - v.logger.Print(log.String() + platform.LineSeparator()) +func (w *StdOutLogWriter) Log(log LogEntry) { + w.logger.Print(log.String() + platform.LineSeparator()) } -func (v *StdOutLogWriter) Close() {} +func (*StdOutLogWriter) Close() {} type FileLogWriter struct { queue chan string @@ -45,31 +44,30 @@ type FileLogWriter struct { cancel context.CancelFunc } -func (v *FileLogWriter) Log(log LogEntry) { +func (w *FileLogWriter) Log(log LogEntry) { select { - case <-v.ctx.Done(): + case <-w.ctx.Done(): return - case v.queue <- log.String(): + case w.queue <- log.String(): default: // We don't expect this to happen, but don't want to block main thread as well. } } -func (v *FileLogWriter) run(ctx context.Context) { -L: +func (w *FileLogWriter) run(ctx context.Context) { for { select { case <-ctx.Done(): - break L - case entry := <-v.queue: - v.logger.Print(entry + platform.LineSeparator()) + w.file.Close() + return + case entry := <-w.queue: + w.logger.Print(entry + platform.LineSeparator()) } } - v.file.Close() } -func (v *FileLogWriter) Close() { - v.cancel() +func (w *FileLogWriter) Close() { + w.cancel() } func NewFileLogWriter(path string) (*FileLogWriter, error) { diff --git a/app/proxyman/outbound/outbound.go b/app/proxyman/outbound/outbound.go index a44d3074a..9460242c3 100644 --- a/app/proxyman/outbound/outbound.go +++ b/app/proxyman/outbound/outbound.go @@ -35,38 +35,38 @@ func (*Manager) Start() error { return nil } // Close implements Application.Close func (*Manager) Close() {} -func (v *Manager) GetDefaultHandler() proxyman.OutboundHandler { - v.RLock() - defer v.RUnlock() - if v.defaultHandler == nil { +func (m *Manager) GetDefaultHandler() proxyman.OutboundHandler { + m.RLock() + defer m.RUnlock() + if m.defaultHandler == nil { return nil } - return v.defaultHandler + return m.defaultHandler } -func (v *Manager) GetHandler(tag string) proxyman.OutboundHandler { - v.RLock() - defer v.RUnlock() - if handler, found := v.taggedHandler[tag]; found { +func (m *Manager) GetHandler(tag string) proxyman.OutboundHandler { + m.RLock() + defer m.RUnlock() + if handler, found := m.taggedHandler[tag]; found { return handler } return nil } -func (v *Manager) AddHandler(ctx context.Context, config *proxyman.OutboundHandlerConfig) error { - v.Lock() - defer v.Unlock() +func (m *Manager) AddHandler(ctx context.Context, config *proxyman.OutboundHandlerConfig) error { + m.Lock() + defer m.Unlock() handler, err := NewHandler(ctx, config) if err != nil { return err } - if v.defaultHandler == nil { - v.defaultHandler = handler + if m.defaultHandler == nil { + m.defaultHandler = handler } if len(config.Tag) > 0 { - v.taggedHandler[config.Tag] = handler + m.taggedHandler[config.Tag] = handler } return nil diff --git a/app/router/router.go b/app/router/router.go index 93f191528..15837e97a 100644 --- a/app/router/router.go +++ b/app/router/router.go @@ -52,8 +52,8 @@ func NewRouter(ctx context.Context, config *Config) (*Router, error) { return r, nil } -func (v *Router) resolveIP(dest net.Destination) []net.Address { - ips := v.dnsServer.Get(dest.Address.Domain()) +func (r *Router) resolveIP(dest net.Destination) []net.Address { + ips := r.dnsServer.Get(dest.Address.Domain()) if len(ips) == 0 { return nil } @@ -64,8 +64,8 @@ func (v *Router) resolveIP(dest net.Destination) []net.Address { return dests } -func (v *Router) TakeDetour(ctx context.Context) (string, error) { - for _, rule := range v.rules { +func (r *Router) TakeDetour(ctx context.Context) (string, error) { + for _, rule := range r.rules { if rule.Apply(ctx) { return rule.Tag, nil } @@ -76,12 +76,12 @@ func (v *Router) TakeDetour(ctx context.Context) (string, error) { return "", ErrNoRuleApplicable } - if v.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() { + if r.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() { log.Trace(newError("looking up IP for ", dest)) - ipDests := v.resolveIP(dest) + ipDests := r.resolveIP(dest) if ipDests != nil { ctx = proxy.ContextWithResolveIPs(ctx, ipDests) - for _, rule := range v.rules { + for _, rule := range r.rules { if rule.Apply(ctx) { return rule.Tag, nil } @@ -92,15 +92,15 @@ func (v *Router) TakeDetour(ctx context.Context) (string, error) { return "", ErrNoRuleApplicable } -func (Router) Interface() interface{} { +func (*Router) Interface() interface{} { return (*Router)(nil) } -func (Router) Start() error { +func (*Router) Start() error { return nil } -func (Router) Close() {} +func (*Router) Close() {} func FromSpace(space app.Space) *Router { app := space.GetApplication((*Router)(nil)) diff --git a/app/space.go b/app/space.go index fafcedd99..09629b697 100644 --- a/app/space.go +++ b/app/space.go @@ -52,39 +52,39 @@ func NewSpace() Space { } } -func (v *spaceImpl) OnInitialize(f InitializationCallback) { - if v.initialized { +func (s *spaceImpl) OnInitialize(f InitializationCallback) { + if s.initialized { f() } else { - v.appInit = append(v.appInit, f) + s.appInit = append(s.appInit, f) } } -func (v *spaceImpl) Initialize() error { - for _, f := range v.appInit { +func (s *spaceImpl) Initialize() error { + for _, f := range s.appInit { if err := f(); err != nil { return err } } - v.appInit = nil - v.initialized = true + s.appInit = nil + s.initialized = true return nil } -func (v *spaceImpl) GetApplication(appInterface interface{}) Application { - if v == nil { +func (s *spaceImpl) GetApplication(appInterface interface{}) Application { + if s == nil { return nil } appType := reflect.TypeOf(appInterface) - return v.cache[appType] + return s.cache[appType] } -func (v *spaceImpl) AddApplication(app Application) error { - if v == nil { +func (s *spaceImpl) AddApplication(app Application) error { + if s == nil { return newError("nil space").AtError() } appType := reflect.TypeOf(app.Interface()) - v.cache[appType] = app + s.cache[appType] = app return nil } diff --git a/common/buf/buffered_writer.go b/common/buf/buffered_writer.go index 196e6a399..6faed0dbd 100644 --- a/common/buf/buffered_writer.go +++ b/common/buf/buffered_writer.go @@ -20,20 +20,20 @@ func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter { } // Write implements io.Writer. -func (v *BufferedWriter) Write(b []byte) (int, error) { - if !v.buffered || v.buffer == nil { - return v.writer.Write(b) +func (w *BufferedWriter) Write(b []byte) (int, error) { + if !w.buffered || w.buffer == nil { + return w.writer.Write(b) } - nBytes, err := v.buffer.Write(b) + nBytes, err := w.buffer.Write(b) if err != nil { return 0, err } - if v.buffer.IsFull() { - if err := v.Flush(); err != nil { + if w.buffer.IsFull() { + if err := w.Flush(); err != nil { return 0, err } if nBytes < len(b) { - if _, err := v.writer.Write(b[nBytes:]); err != nil { + if _, err := w.writer.Write(b[nBytes:]); err != nil { return nBytes, err } } @@ -42,28 +42,28 @@ func (v *BufferedWriter) Write(b []byte) (int, error) { } // Flush writes all buffered content into underlying writer, if any. -func (v *BufferedWriter) Flush() error { - defer v.buffer.Clear() - for !v.buffer.IsEmpty() { - nBytes, err := v.writer.Write(v.buffer.Bytes()) +func (w *BufferedWriter) Flush() error { + defer w.buffer.Clear() + for !w.buffer.IsEmpty() { + nBytes, err := w.writer.Write(w.buffer.Bytes()) if err != nil { return err } - v.buffer.SliceFrom(nBytes) + w.buffer.SliceFrom(nBytes) } return nil } // IsBuffered returns true if this BufferedWriter holds a buffer. -func (v *BufferedWriter) IsBuffered() bool { - return v.buffered +func (w *BufferedWriter) IsBuffered() bool { + return w.buffered } // SetBuffered controls whether the BufferedWriter holds a buffer for writing. If not buffered, any write() calls into underlying writer directly. -func (v *BufferedWriter) SetBuffered(cached bool) error { - v.buffered = cached - if !cached && !v.buffer.IsEmpty() { - return v.Flush() +func (w *BufferedWriter) SetBuffered(cached bool) error { + w.buffered = cached + if !cached && !w.buffer.IsEmpty() { + return w.Flush() } return nil } diff --git a/common/buf/multi_buffer.go b/common/buf/multi_buffer.go index 5c11c8305..1562685d1 100644 --- a/common/buf/multi_buffer.go +++ b/common/buf/multi_buffer.go @@ -10,22 +10,25 @@ type MultiBufferReader interface { ReadMultiBuffer() (MultiBuffer, error) } +// MultiBuffer is a list of Buffers. The order of Buffer matters. type MultiBuffer []*Buffer +// NewMultiBuffer creates a new MultiBuffer instance. func NewMultiBuffer() MultiBuffer { return MultiBuffer(make([]*Buffer, 0, 128)) } +// NewMultiBufferValue wraps a list of Buffers into MultiBuffer. func NewMultiBufferValue(b ...*Buffer) MultiBuffer { return MultiBuffer(b) } -func (b *MultiBuffer) Append(buf *Buffer) { - *b = append(*b, buf) +func (mb *MultiBuffer) Append(buf *Buffer) { + *mb = append(*mb, buf) } -func (b *MultiBuffer) AppendMulti(mb MultiBuffer) { - *b = append(*b, mb...) +func (mb *MultiBuffer) AppendMulti(buf MultiBuffer) { + *mb = append(*mb, buf...) } func (mb *MultiBuffer) Read(b []byte) (int, error) { @@ -46,6 +49,7 @@ func (mb *MultiBuffer) Read(b []byte) (int, error) { return totalBytes, nil } +// Len returns the total number of bytes in the MultiBuffer. func (mb MultiBuffer) Len() int { size := 0 for _, b := range mb { @@ -54,6 +58,7 @@ func (mb MultiBuffer) Len() int { return size } +// IsEmpty return true if the MultiBuffer has no content. func (mb MultiBuffer) IsEmpty() bool { for _, b := range mb { if !b.IsEmpty() { @@ -63,6 +68,7 @@ func (mb MultiBuffer) IsEmpty() bool { return true } +// Release releases all Buffers in the MultiBuffer. func (mb MultiBuffer) Release() { for i, b := range mb { b.Release() @@ -70,6 +76,7 @@ func (mb MultiBuffer) Release() { } } +// ToNetBuffers converts this MultiBuffer to net.Buffers. The return net.Buffers points to the same content of the MultiBuffer. func (mb MultiBuffer) ToNetBuffers() net.Buffers { bs := make([][]byte, len(mb)) for i, b := range mb {