This commit is contained in:
Darien Raymond 2017-04-23 19:16:56 +02:00
parent cea6e28634
commit 59a1e2d736
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
10 changed files with 104 additions and 100 deletions

View File

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

View File

@ -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())

View File

@ -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):

View File

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

View File

@ -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) {

View File

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

View File

@ -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))

View File

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

View File

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

View File

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