2018-02-05 17:38:24 -05:00
|
|
|
package commander
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
2018-02-08 09:39:46 -05:00
|
|
|
"sync"
|
2018-02-05 17:38:24 -05:00
|
|
|
|
|
|
|
"v2ray.com/core/common/signal"
|
|
|
|
"v2ray.com/core/transport/ray"
|
|
|
|
)
|
|
|
|
|
|
|
|
type OutboundListener struct {
|
|
|
|
buffer chan net.Conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *OutboundListener) add(conn net.Conn) {
|
|
|
|
select {
|
|
|
|
case l.buffer <- conn:
|
|
|
|
default:
|
|
|
|
conn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *OutboundListener) Accept() (net.Conn, error) {
|
|
|
|
c, open := <-l.buffer
|
|
|
|
if !open {
|
|
|
|
return nil, newError("listener closed")
|
|
|
|
}
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *OutboundListener) Close() error {
|
|
|
|
close(l.buffer)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *OutboundListener) Addr() net.Addr {
|
|
|
|
return &net.TCPAddr{
|
|
|
|
IP: net.IP{0, 0, 0, 0},
|
|
|
|
Port: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type CommanderOutbound struct {
|
|
|
|
tag string
|
|
|
|
listener *OutboundListener
|
2018-02-08 09:39:46 -05:00
|
|
|
access sync.RWMutex
|
|
|
|
closed bool
|
2018-02-05 17:38:24 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (co *CommanderOutbound) Dispatch(ctx context.Context, r ray.OutboundRay) {
|
2018-02-08 09:39:46 -05:00
|
|
|
co.access.RLock()
|
|
|
|
|
|
|
|
if co.closed {
|
|
|
|
r.OutboundInput().CloseError()
|
|
|
|
r.OutboundOutput().CloseError()
|
|
|
|
co.access.RUnlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-02-05 17:38:24 -05:00
|
|
|
closeSignal := signal.NewNotifier()
|
|
|
|
c := ray.NewConnection(r.OutboundInput(), r.OutboundOutput(), ray.ConnCloseSignal(closeSignal))
|
|
|
|
co.listener.add(c)
|
2018-02-08 09:39:46 -05:00
|
|
|
co.access.RUnlock()
|
2018-02-05 17:38:24 -05:00
|
|
|
<-closeSignal.Wait()
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (co *CommanderOutbound) Tag() string {
|
|
|
|
return co.tag
|
|
|
|
}
|
|
|
|
|
|
|
|
func (co *CommanderOutbound) Start() error {
|
2018-02-08 09:39:46 -05:00
|
|
|
co.access.Lock()
|
|
|
|
co.closed = false
|
|
|
|
co.access.Unlock()
|
2018-02-05 17:38:24 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-02-08 09:39:46 -05:00
|
|
|
func (co *CommanderOutbound) Close() error {
|
|
|
|
co.access.Lock()
|
|
|
|
co.closed = true
|
|
|
|
co.listener.Close()
|
|
|
|
co.access.Unlock()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|