summaryrefslogtreecommitdiff
path: root/pkg/server/socket/socket.go
blob: 62ce5cfa63b2734e5e0a8d1207b602552bb6dc31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package socket

import (
	"errors"
	"fmt"
	"log"
	"net"
	"strings"
	"sync"
	"tunnel/pkg/server/env"
	"tunnel/pkg/server/opts"
	"tunnel/pkg/server/queue"
)

var ErrAlreadyClosed = errors.New("already closed")

type Conn interface {
	Send(wq queue.Q) error
	Recv(rq queue.Q) error
	Close() error
}

type S interface {
	Open(env env.Env) (Conn, error)
	Close()
}

type Single interface {
	Single()
}

type conn struct {
	net.Conn

	desc string
	info string

	once sync.Once
}

func newConn(cn net.Conn, desc, info string) *conn {
	c := &conn{Conn: cn, desc: desc, info: info}
	return c
}

func (c *conn) Send(wq queue.Q) error {
	return queue.IoCopy(c, wq.Writer())
}

func (c *conn) Recv(rq queue.Q) error {
	return queue.IoCopy(rq.Reader(), c)
}

func (c *conn) String() string {
	return c.info
}

func (c *conn) Close() error {
	err := ErrAlreadyClosed

	c.once.Do(func() {
		log.Println("close", c.desc)
		err = c.Conn.Close()
	})

	return err
}

func New(desc string) (S, error) {
	base, opts := opts.Parse(desc)
	args := strings.SplitN(base, "/", 2)

	var proto string
	var addr string

	if len(args) < 2 {
		addr = args[0]
	} else {
		proto, addr = args[0], args[1]
	}

	if proto == "" {
		proto = "tcp"
	}

	switch addr {
	case "loop":
		return newLoopSocket()
	case "proxy":
		return newProxySocket(proto)
	case "":
		return nil, fmt.Errorf("bad socket '%s'", desc)
	}

	if proto == "tun" {
		return newTunSocket(addr)
	}

	if opts.Bool("listen") {
		return newListenSocket(proto, addr, opts)
	}

	if opts.Bool("defer") {
		return newDeferSocket(proto, addr)
	}

	return newDialSocket(proto, addr)
}