1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00
v2fly/proxy/dokodemo/dokodemo.go
2017-04-07 21:54:40 +02:00

110 lines
2.8 KiB
Go

package dokodemo
import (
"context"
"runtime"
"time"
"v2ray.com/core/app"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/common/signal"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/internet"
)
type DokodemoDoor struct {
config *Config
address net.Address
port net.Port
}
func New(ctx context.Context, config *Config) (*DokodemoDoor, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("Dokodemo: No space in context.")
}
if config.NetworkList == nil || config.NetworkList.Size() == 0 {
return nil, errors.New("DokodemoDoor: No network specified.")
}
d := &DokodemoDoor{
config: config,
address: config.GetPredefinedAddress(),
port: net.Port(config.Port),
}
return d, nil
}
func (d *DokodemoDoor) Network() net.NetworkList {
return *(d.config.NetworkList)
}
func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher dispatcher.Interface) error {
log.Trace(errors.New("Dokodemo: processing connection from: ", conn.RemoteAddr()).AtDebug())
dest := net.Destination{
Network: network,
Address: d.address,
Port: d.port,
}
if d.config.FollowRedirect {
if origDest, ok := proxy.OriginalTargetFromContext(ctx); ok {
dest = origDest
}
}
if !dest.IsValid() || dest.Address == nil {
return errors.New("unable to get destination").Path("Proxy", "Dokodemo")
}
timeout := time.Second * time.Duration(d.config.Timeout)
if timeout == 0 {
timeout = time.Minute * 2
}
ctx, timer := signal.CancelAfterInactivity(ctx, timeout)
inboundRay, err := dispatcher.Dispatch(ctx, dest)
if err != nil {
return err
}
requestDone := signal.ExecuteAsync(func() error {
defer inboundRay.InboundInput().Close()
chunkReader := buf.NewReader(conn)
if err := buf.PipeUntilEOF(timer, chunkReader, inboundRay.InboundInput()); err != nil {
return errors.New("failed to transport request").Base(err).Path("Proxy", "Dokodemo")
}
return nil
})
responseDone := signal.ExecuteAsync(func() error {
v2writer := buf.NewWriter(conn)
if err := buf.PipeUntilEOF(timer, inboundRay.InboundOutput(), v2writer); err != nil {
return errors.New("failed to transport response").Base(err).Path("Proxy", "Dokodemo")
}
return nil
})
if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
inboundRay.InboundInput().CloseError()
inboundRay.InboundOutput().CloseError()
return errors.New("connection ends").Base(err).Path("Proxy", "Dokodemo")
}
runtime.KeepAlive(timer)
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}