summaryrefslogtreecommitdiff
path: root/pkg/server/hook/proxy.go
blob: 8c3de7b3b3becfa5930a6d9683972f663111cd26 (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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package hook

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"regexp"
	"tunnel/pkg/server/env"
	"tunnel/pkg/server/opts"
	"tunnel/pkg/server/queue"
)

var addrRe = regexp.MustCompile("^[0-9a-zA-Z-.]+:[0-9]+$")

var errBadHttpResponse = errors.New("bad HTTP response")

type proxyHook struct {
	addr string
}

type proxy struct {
	addr string
	ok   chan struct{}
	fail chan struct{}
}

func (p *proxy) Send(rq, wq queue.Q) error {
	request := fmt.Sprintf("CONNECT %s HTTP/1.0\r\n\r\n", p.addr)
	wq <- []byte(request)

	select {
	case <-p.fail:
		return nil
	case <-p.ok:
	}

	return queue.Copy(rq, wq)
}

func parseProxyResponse(s string) error {
	var version string
	var code int
	var desc string

	if _, err := fmt.Sscanf(s, "%s %d %s", &version, &code, &desc); err != nil {
		return errBadHttpResponse
	}

	if version != "HTTP/1.0" && version != "HTTP/1.1" {
		return errBadHttpResponse
	}

	if code != 200 {
		return fmt.Errorf("connect failed: %d %s", code, desc)
	}

	return nil
}

func (p *proxy) Recv(rq, wq queue.Q) (err error) {
	defer func() {
		if err != nil {
			close(p.fail)
		}
	}()

	s := bufio.NewScanner(rq.Reader())

	var resp bool

	for s.Scan() {
		line := s.Text()

		if !resp {
			if err := parseProxyResponse(line); err != nil {
				return err
			}
			resp = true
			continue
		}

		if line == "" {
			break
		}
	}

	if err := s.Err(); err != nil {
		return err
	} else if !resp {
		return io.ErrUnexpectedEOF
	}

	close(p.ok)

	return queue.Copy(rq, wq)
}

func (h *proxyHook) Open(env.Env) (interface{}, error) {
	p := &proxy{
		addr: h.addr,
		ok:   make(chan struct{}),
		fail: make(chan struct{}),
	}

	return p, nil
}

func newProxyHook(opts opts.Opts, env env.Env) (hook, error) {
	h := &proxyHook{}

	if addr, ok := opts["addr"]; !ok {
		return nil, errors.New("proxy: missing addr")
	} else if !addrRe.MatchString(addr) {
		return nil, errors.New("proxy: invalid addr")
	} else {
		h.addr = addr
	}

	return h, nil
}

func init() {
	register("proxy", newProxyHook)
}