1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-10-31 00:08:08 -04:00
v2fly/transport/internet/tcp_hub.go

95 lines
2.1 KiB
Go
Raw Normal View History

2016-06-14 16:54:08 -04:00
package internet
import (
2016-07-10 09:27:58 -04:00
"crypto/tls"
2016-06-14 16:54:08 -04:00
"errors"
"net"
"sync"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
2016-07-10 09:27:58 -04:00
v2tls "github.com/v2ray/v2ray-core/transport/internet/tls"
2016-06-14 16:54:08 -04:00
)
var (
2016-06-27 02:53:35 -04:00
ErrClosedConnection = errors.New("Connection already closed.")
2016-06-14 16:54:08 -04:00
KCPListenFunc ListenFunc
TCPListenFunc ListenFunc
RawTCPListenFunc ListenFunc
)
type ListenFunc func(address v2net.Address, port v2net.Port) (Listener, error)
type Listener interface {
Accept() (Connection, error)
Close() error
Addr() net.Addr
}
type TCPHub struct {
sync.Mutex
listener Listener
connCallback ConnectionHandler
accepting bool
2016-07-10 09:27:58 -04:00
tlsConfig *tls.Config
2016-06-14 16:54:08 -04:00
}
func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandler, settings *StreamSettings) (*TCPHub, error) {
var listener Listener
var err error
2016-06-14 19:08:03 -04:00
switch {
case settings.IsCapableOf(StreamConnectionTypeTCP):
2016-06-14 16:54:08 -04:00
listener, err = TCPListenFunc(address, port)
2016-06-14 19:08:03 -04:00
case settings.IsCapableOf(StreamConnectionTypeKCP):
listener, err = KCPListenFunc(address, port)
case settings.IsCapableOf(StreamConnectionTypeRawTCP):
2016-06-14 16:54:08 -04:00
listener, err = RawTCPListenFunc(address, port)
2016-06-14 19:08:03 -04:00
default:
2016-06-17 12:03:31 -04:00
log.Error("Internet|Listener: Unknown stream type: ", settings.Type)
2016-06-14 19:08:03 -04:00
err = ErrUnsupportedStreamType
2016-06-14 16:54:08 -04:00
}
if err != nil {
2016-06-17 12:03:31 -04:00
log.Warning("Internet|Listener: Failed to listen on ", address, ":", port)
2016-06-14 16:54:08 -04:00
return nil, err
}
2016-07-10 09:27:58 -04:00
var tlsConfig *tls.Config
if settings.Security == StreamSecurityTypeTLS {
tlsConfig = settings.TLSSettings.GetTLSConfig()
}
2016-06-14 16:54:08 -04:00
hub := &TCPHub{
listener: listener,
connCallback: callback,
2016-07-10 09:27:58 -04:00
tlsConfig: tlsConfig,
2016-06-14 16:54:08 -04:00
}
go hub.start()
return hub, nil
}
func (this *TCPHub) Close() {
this.accepting = false
this.listener.Close()
}
func (this *TCPHub) start() {
this.accepting = true
for this.accepting {
conn, err := this.listener.Accept()
if err != nil {
if this.accepting {
2016-06-17 12:03:31 -04:00
log.Warning("Internet|Listener: Failed to accept new TCP connection: ", err)
2016-06-14 16:54:08 -04:00
}
continue
}
2016-07-10 09:27:58 -04:00
if this.tlsConfig != nil {
tlsConn := tls.Server(conn, this.tlsConfig)
conn = v2tls.NewConnection(tlsConn)
}
2016-06-14 16:54:08 -04:00
go this.connCallback(conn)
}
}