本文整理汇总了Golang中v2ray/com/core/transport/internet.Connection类的典型用法代码示例。如果您正苦于以下问题:Golang Connection类的具体用法?Golang Connection怎么用?Golang Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Process
func (s *Server) Process(ctx context.Context, network v2net.Network, conn internet.Connection) error {
conn.SetReusable(false)
timedReader := v2net.NewTimeOutReader(s.config.Timeout, conn)
reader := bufio.OriginalReaderSize(timedReader, 2048)
request, err := http.ReadRequest(reader)
if err != nil {
if errors.Cause(err) != io.EOF {
log.Warning("HTTP: Failed to read http request: ", err)
}
return err
}
log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
defaultPort := v2net.Port(80)
if strings.ToLower(request.URL.Scheme) == "https" {
defaultPort = v2net.Port(443)
}
host := request.Host
if len(host) == 0 {
host = request.URL.Host
}
dest, err := parseHost(host, defaultPort)
if err != nil {
log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
return err
}
log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
ctx = proxy.ContextWithDestination(ctx, dest)
if strings.ToUpper(request.Method) == "CONNECT" {
return s.handleConnect(ctx, request, reader, conn)
} else {
return s.handlePlainHTTP(ctx, request, reader, conn)
}
}
示例2: handleConnection
func (v *Server) handleConnection(connection internet.Connection) {
defer connection.Close()
timedReader := v2net.NewTimeOutReader(v.config.Timeout, connection)
reader := bufio.NewReader(timedReader)
defer reader.Release()
writer := bufio.NewWriter(connection)
defer writer.Release()
auth, auth4, err := protocol.ReadAuthentication(reader)
if err != nil && errors.Cause(err) != protocol.Socks4Downgrade {
if errors.Cause(err) != io.EOF {
log.Warning("Socks: failed to read authentication: ", err)
}
return
}
clientAddr := v2net.DestinationFromAddr(connection.RemoteAddr())
if err != nil && err == protocol.Socks4Downgrade {
v.handleSocks4(clientAddr, reader, writer, auth4)
} else {
v.handleSocks5(clientAddr, reader, writer, auth)
}
}
示例3: Dispatch
func (this *FreedomConnection) Dispatch(destination v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error {
log.Info("Freedom: Opening connection to ", destination)
defer payload.Release()
defer ray.OutboundInput().Release()
defer ray.OutboundOutput().Close()
var conn internet.Connection
if this.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
destination = this.ResolveIP(destination)
}
err := retry.ExponentialBackoff(5, 100).On(func() error {
rawConn, err := internet.Dial(this.meta.Address, destination, this.meta.GetDialerOptions())
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
log.Warning("Freedom: Failed to open connection to ", destination, ": ", err)
return err
}
defer conn.Close()
input := ray.OutboundInput()
output := ray.OutboundOutput()
if !payload.IsEmpty() {
conn.Write(payload.Value)
}
go func() {
v2writer := v2io.NewAdaptiveWriter(conn)
defer v2writer.Release()
v2io.Pipe(input, v2writer)
if tcpConn, ok := conn.(*tcp.RawConnection); ok {
tcpConn.CloseWrite()
}
}()
var reader io.Reader = conn
timeout := this.timeout
if destination.Network == v2net.Network_UDP {
timeout = 16
}
if timeout > 0 {
reader = v2net.NewTimeOutReader(timeout /* seconds */, conn)
}
v2reader := v2io.NewAdaptiveReader(reader)
v2io.Pipe(v2reader, output)
v2reader.Release()
ray.OutboundOutput().Close()
return nil
}
示例4: HandleTCPConnection
func (v *DokodemoDoor) HandleTCPConnection(conn internet.Connection) {
defer conn.Close()
var dest v2net.Destination
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 && v.address != nil && v.port > v2net.Port(0) {
dest = v2net.TCPDestination(v.address, v.port)
}
if dest.Network == v2net.Network_Unknown {
log.Info("Dokodemo: Unknown destination, stop forwarding...")
return
}
log.Info("Dokodemo: Handling request to ", dest)
ray := v.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
Destination: dest,
Inbound: v.meta,
})
defer ray.InboundOutput().Release()
var wg sync.WaitGroup
reader := v2net.NewTimeOutReader(v.config.Timeout, conn)
defer reader.Release()
wg.Add(1)
go func() {
v2reader := buf.NewReader(reader)
defer v2reader.Release()
if err := buf.PipeUntilEOF(v2reader, ray.InboundInput()); err != nil {
log.Info("Dokodemo: Failed to transport all TCP request: ", err)
}
wg.Done()
ray.InboundInput().Close()
}()
wg.Add(1)
go func() {
v2writer := buf.NewWriter(conn)
defer v2writer.Release()
if err := buf.PipeUntilEOF(ray.InboundOutput(), v2writer); err != nil {
log.Info("Dokodemo: Failed to transport all TCP response: ", err)
}
wg.Done()
}()
wg.Wait()
}
示例5: HandleTCPConnection
func (this *DokodemoDoor) HandleTCPConnection(conn internet.Connection) {
defer conn.Close()
var dest v2net.Destination
if this.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 {
log.Info("Dokodemo: Unknown destination, stop forwarding...")
return
}
log.Info("Dokodemo: Handling request to ", dest)
ray := this.packetDispatcher.DispatchToOutbound(&proxy.SessionInfo{
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
Destination: dest,
Inbound: this.meta,
})
defer ray.InboundOutput().Release()
var wg sync.WaitGroup
reader := v2net.NewTimeOutReader(this.config.Timeout, conn)
defer reader.Release()
wg.Add(1)
go func() {
v2reader := v2io.NewAdaptiveReader(reader)
defer v2reader.Release()
v2io.Pipe(v2reader, ray.InboundInput())
wg.Done()
ray.InboundInput().Close()
}()
wg.Add(1)
go func() {
v2writer := v2io.NewAdaptiveWriter(conn)
defer v2writer.Release()
v2io.Pipe(ray.InboundOutput(), v2writer)
wg.Done()
}()
wg.Wait()
}
示例6: handlerUDPPayload
func (v *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection) error {
source := proxy.SourceFromContext(ctx)
reader := buf.NewReader(conn)
for {
payload, err := reader.Read()
if err != nil {
break
}
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)
payload.Release()
continue
}
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()
continue
}
if !request.Option.Has(RequestOptionOneTimeAuth) && v.account.OneTimeAuth == Account_Enabled {
log.Info("Shadowsocks|Server: Client payload disables OTA but server forces it.")
payload.Release()
continue
}
dest := request.Destination()
log.Access(source, dest, log.AccessAccepted, "")
log.Info("Shadowsocks|Server: Tunnelling request to ", dest)
ctx = protocol.ContextWithUser(ctx, request.User)
v.udpServer.Dispatch(ctx, dest, data, func(payload *buf.Buffer) {
defer payload.Release()
data, err := EncodeUDPPacket(request, payload)
if err != nil {
log.Warning("Shadowsocks|Server: Failed to encode UDP packet: ", err)
return
}
defer data.Release()
conn.Write(data.Bytes())
})
}
return nil
}
示例7: callback
func (w *tcpWorker) callback(conn internet.Connection) {
ctx, cancel := context.WithCancel(w.ctx)
if w.recvOrigDest {
dest := tcp.GetOriginalDestination(conn)
if dest.IsValid() {
ctx = proxy.ContextWithOriginalDestination(ctx, dest)
}
}
if len(w.tag) > 0 {
ctx = proxy.ContextWithInboundTag(ctx, w.tag)
}
ctx = proxy.ContextWithAllowPassiveConnection(ctx, w.allowPassiveConn)
ctx = proxy.ContextWithInboundDestination(ctx, v2net.TCPDestination(w.address, w.port))
w.proxy.Process(ctx, v2net.Network_TCP, conn)
cancel()
conn.Close()
}
示例8: Dispatch
func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *alloc.Buffer, ray ray.OutboundRay) error {
defer ray.OutboundInput().Release()
defer ray.OutboundOutput().Close()
var rec *protocol.ServerSpec
var conn internet.Connection
err := retry.Timed(5, 100).On(func() error {
rec = this.serverPicker.PickServer()
rawConn, err := internet.Dial(this.meta.Address, rec.Destination(), this.meta.StreamSettings)
if err != nil {
return err
}
conn = rawConn
return nil
})
if err != nil {
log.Error("VMess|Outbound: Failed to find an available destination:", err)
return err
}
log.Info("VMess|Outbound: Tunneling request to ", target, " via ", rec.Destination())
command := protocol.RequestCommandTCP
if target.IsUDP() {
command = protocol.RequestCommandUDP
}
request := &protocol.RequestHeader{
Version: encoding.Version,
User: rec.PickUser(),
Command: command,
Address: target.Address(),
Port: target.Port(),
Option: protocol.RequestOptionChunkStream,
}
defer conn.Close()
conn.SetReusable(true)
if conn.Reusable() { // Conn reuse may be disabled on transportation layer
request.Option.Set(protocol.RequestOptionConnectionReuse)
}
input := ray.OutboundInput()
output := ray.OutboundOutput()
var requestFinish, responseFinish sync.Mutex
requestFinish.Lock()
responseFinish.Lock()
session := encoding.NewClientSession(protocol.DefaultIDHash)
go this.handleRequest(session, conn, request, payload, input, &requestFinish)
go this.handleResponse(session, conn, request, rec.Destination(), output, &responseFinish)
requestFinish.Lock()
responseFinish.Lock()
return nil
}
示例9: Process
func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection) error {
log.Debug("Dokodemo: processing connection from: ", conn.RemoteAddr())
conn.SetReusable(false)
ctx = proxy.ContextWithDestination(ctx, net.Destination{
Network: network,
Address: d.address,
Port: d.port,
})
inboundRay := d.packetDispatcher.DispatchToOutbound(ctx)
requestDone := signal.ExecuteAsync(func() error {
defer inboundRay.InboundInput().Close()
timedReader := net.NewTimeOutReader(d.config.Timeout, conn)
chunkReader := buf.NewReader(timedReader)
if err := buf.PipeUntilEOF(chunkReader, inboundRay.InboundInput()); err != nil {
log.Info("Dokodemo: Failed to transport request: ", err)
return err
}
return nil
})
responseDone := signal.ExecuteAsync(func() error {
v2writer := buf.NewWriter(conn)
if err := buf.PipeUntilEOF(inboundRay.InboundOutput(), v2writer); err != nil {
log.Info("Dokodemo: Failed to transport response: ", err)
return err
}
return nil
})
if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
inboundRay.InboundInput().CloseError()
inboundRay.InboundOutput().CloseError()
log.Info("Dokodemo: Connection ends with ", err)
return err
}
return nil
}
示例10: handleRequest
func (v *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *buf.Buffer, input buf.Reader, finish *sync.Mutex) {
defer finish.Unlock()
writer := bufio.NewWriter(conn)
defer writer.Release()
session.EncodeRequestHeader(request, writer)
bodyWriter := session.EncodeRequestBody(request, writer)
defer bodyWriter.Release()
if !payload.IsEmpty() {
if err := bodyWriter.Write(payload); err != nil {
log.Info("VMess|Outbound: Failed to write payload. Disabling connection reuse.", err)
conn.SetReusable(false)
}
payload.Release()
}
writer.SetCached(false)
if err := buf.PipeUntilEOF(input, bodyWriter); err != nil {
conn.SetReusable(false)
}
if request.Option.Has(protocol.RequestOptionChunkStream) {
err := bodyWriter.Write(buf.NewLocal(8))
if err != nil {
conn.SetReusable(false)
}
}
return
}
示例11: handleResponse
func (v *VMessOutboundHandler) handleResponse(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output buf.Writer, finish *sync.Mutex) {
defer finish.Unlock()
reader := bufio.NewReader(conn)
defer reader.Release()
header, err := session.DecodeResponseHeader(reader)
if err != nil {
conn.SetReusable(false)
log.Warning("VMess|Outbound: Failed to read response from ", request.Destination(), ": ", err)
return
}
v.handleCommand(dest, header.Command)
conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse))
reader.SetCached(false)
bodyReader := session.DecodeResponseBody(request, reader)
defer bodyReader.Release()
if err := buf.PipeUntilEOF(bodyReader, output); err != nil {
conn.SetReusable(false)
}
return
}
示例12: handleRequest
func (this *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)
defer writer.Release()
session.EncodeRequestHeader(request, writer)
bodyWriter := session.EncodeRequestBody(writer)
var streamWriter v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
if request.Option.Has(protocol.RequestOptionChunkStream) {
streamWriter = vmessio.NewAuthChunkWriter(streamWriter)
}
if !payload.IsEmpty() {
if err := streamWriter.Write(payload); err != nil {
conn.SetReusable(false)
}
}
writer.SetCached(false)
err := v2io.Pipe(input, streamWriter)
if err != io.EOF {
conn.SetReusable(false)
}
if request.Option.Has(protocol.RequestOptionChunkStream) {
err := streamWriter.Write(alloc.NewLocalBuffer(32).Clear())
if err != nil {
conn.SetReusable(false)
}
}
streamWriter.Release()
return
}
示例13: handleUDPPayload
func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection) error {
source := proxy.SourceFromContext(ctx)
log.Info("Socks|Server: Client UDP connection from ", source)
reader := buf.NewReader(conn)
for {
payload, err := reader.Read()
if err != nil {
return err
}
request, data, err := DecodeUDPPacket(payload.Bytes())
if err != nil {
log.Info("Socks|Server: Failed to parse UDP request: ", err)
continue
}
if len(data) == 0 {
continue
}
log.Info("Socks: Send packet to ", request.Destination(), " with ", len(data), " bytes")
log.Access(source, request.Destination, log.AccessAccepted, "")
dataBuf := buf.NewSmall()
dataBuf.Append(data)
v.udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
defer payload.Release()
log.Info("Socks|Server: Writing back UDP response with ", payload.Len(), " bytes")
udpMessage := EncodeUDPPacket(request, payload.Bytes())
defer udpMessage.Release()
conn.Write(udpMessage.Bytes())
})
}
}
示例14: processTCP
func (s *Server) processTCP(ctx context.Context, conn internet.Connection) error {
conn.SetReusable(false)
timedReader := net.NewTimeOutReader(16 /* seconds, for handshake */, conn)
reader := bufio.NewReader(timedReader)
inboundDest := proxy.InboundDestinationFromContext(ctx)
session := &ServerSession{
config: s.config,
port: inboundDest.Port,
}
source := proxy.SourceFromContext(ctx)
request, err := session.Handshake(reader, conn)
if err != nil {
log.Access(source, "", log.AccessRejected, err)
log.Info("Socks|Server: Failed to read request: ", err)
return err
}
if request.Command == protocol.RequestCommandTCP {
dest := request.Destination()
log.Info("Socks|Server: TCP Connect request to ", dest)
log.Access(source, dest, log.AccessAccepted, "")
timedReader.SetTimeOut(s.config.Timeout)
ctx = proxy.ContextWithDestination(ctx, dest)
return s.transport(ctx, reader, conn)
}
if request.Command == protocol.RequestCommandUDP {
return s.handleUDP()
}
return nil
}
示例15: handleConnection
func (this *Server) handleConnection(conn internet.Connection) {
defer conn.Close()
timedReader := v2net.NewTimeOutReader(this.config.Timeout, conn)
reader := bufio.NewReaderSize(timedReader, 2048)
request, err := http.ReadRequest(reader)
if err != nil {
if err != io.EOF {
log.Warning("HTTP: Failed to read http request: ", err)
}
return
}
log.Info("HTTP: Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
defaultPort := v2net.Port(80)
if strings.ToLower(request.URL.Scheme) == "https" {
defaultPort = v2net.Port(443)
}
host := request.Host
if len(host) == 0 {
host = request.URL.Host
}
dest, err := parseHost(host, defaultPort)
if err != nil {
log.Warning("HTTP: Malformed proxy host (", host, "): ", err)
return
}
log.Access(conn.RemoteAddr(), request.URL, log.AccessAccepted, "")
session := &proxy.SessionInfo{
Source: v2net.DestinationFromAddr(conn.RemoteAddr()),
Destination: dest,
Inbound: this.meta,
}
if strings.ToUpper(request.Method) == "CONNECT" {
this.handleConnect(request, session, reader, conn)
} else {
this.handlePlainHTTP(request, session, reader, conn)
}
}