-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
225 lines (200 loc) · 5.58 KB
/
proxy.go
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package masque
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"sync/atomic"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/quic-go/quic-go/quicvarint"
"github.com/dunglas/httpsfv"
"github.com/yosida95/uritemplate/v3"
)
const (
requestProtocol = "connect-udp"
capsuleHeader = "Capsule-Protocol"
)
const (
uriTemplateTargetHost = "target_host"
uriTemplateTargetPort = "target_port"
)
var capsuleProtocolHeaderValue string
func init() {
v, err := httpsfv.Marshal(httpsfv.NewItem(1))
if err != nil {
panic(fmt.Sprintf("failed to marshal capsule protocol header value: %v", err))
}
capsuleProtocolHeaderValue = v
}
type proxyEntry struct {
str http3.Stream
conn *net.UDPConn
}
type Proxy struct {
http3.Server
// Template is the URI template that clients will use to configure this UDP proxy.
Template *uritemplate.Template
// Allow determines if a proxying request from a client is allowed to proceed.
// It is called after the requested target address has been resolved.
Allow func(context.Context, *net.UDPAddr) bool
// DialTarget is called when the proxy needs to open a new UDP socket to the target server.
// It must return a connected UDP socket.
// TODO(#3): support unconnected sockets.
DialTarget func(*net.UDPAddr) (*net.UDPConn, error)
closed atomic.Bool
mx sync.Mutex
refCount sync.WaitGroup // counter for the Go routines spawned in Upgrade
conns map[proxyEntry]struct{}
}
func (s *Proxy) Upgrade(w http.ResponseWriter, r *http.Request) error {
if s.closed.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
}
s.refCount.Add(1)
defer s.refCount.Done()
if r.Method != http.MethodConnect {
w.WriteHeader(http.StatusMethodNotAllowed)
return fmt.Errorf("expected CONNECT request, got %s", r.Method)
}
if r.Proto != requestProtocol {
w.WriteHeader(http.StatusNotImplemented)
return fmt.Errorf("unexpected protocol: %s", r.Proto)
}
// TODO: check :authority
capsuleHeaderValues, ok := r.Header[capsuleHeader]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("missing Capsule-Protocol header")
}
item, err := httpsfv.UnmarshalItem(capsuleHeaderValues)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("invalid capsule header value: %s", r.Header[capsuleHeader])
}
if v, ok := item.Value.(int64); !ok || v != 1 {
w.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("incorrect capsule header value: %d", v)
}
match := s.Template.Match(r.URL.String())
targetHostEncoded := match.Get(uriTemplateTargetHost).String()
targetPortStr := match.Get(uriTemplateTargetPort).String()
if targetHostEncoded == "" || targetPortStr == "" {
w.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("expected target_host and target_port")
}
targetHost, err := url.QueryUnescape(targetHostEncoded)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("failed to decode target_host: %w", err)
}
targetPort, err := strconv.Atoi(targetPortStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return errors.New("failed to decode target_port")
}
w.Header().Set(capsuleHeader, capsuleProtocolHeaderValue)
dst := fmt.Sprintf("%s:%d", targetHost, targetPort)
addr, err := net.ResolveUDPAddr("udp", dst)
if err != nil {
// TODO: set proxy-status header (might want to use structured headers)
w.WriteHeader(http.StatusGatewayTimeout)
}
if s.Allow != nil && !s.Allow(r.Context(), addr) {
w.WriteHeader(http.StatusForbidden)
return errors.New("forbidden")
}
var conn *net.UDPConn
if s.DialTarget == nil {
conn, err = net.DialUDP("udp", nil, addr)
} else {
conn, err = s.DialTarget(addr)
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err
}
str := w.(http3.HTTPStreamer).HTTPStream()
s.mx.Lock()
if s.closed.Load() {
str.CancelRead(quic.StreamErrorCode(http3.ErrCodeNoError))
str.Close()
conn.Close()
w.WriteHeader(http.StatusServiceUnavailable)
}
if s.conns == nil {
s.conns = make(map[proxyEntry]struct{})
}
s.conns[proxyEntry{str: str, conn: conn}] = struct{}{}
s.refCount.Add(3)
s.mx.Unlock()
go func() {
defer s.refCount.Done()
if err := s.proxyConnSend(conn, str); err != nil {
log.Printf("proxying send side to %s failed: %v", conn.RemoteAddr(), err)
}
str.Close()
conn.Close()
}()
go func() {
defer s.refCount.Done()
if err := s.proxyConnReceive(conn, str); err != nil && !s.closed.Load() {
log.Printf("proxying receive side to %s failed: %v", conn.RemoteAddr(), err)
}
str.Close()
conn.Close()
}()
go func() {
defer s.refCount.Done()
// discard all capsules sent on the request stream
if err := skipCapsules(quicvarint.NewReader(str)); err == io.EOF {
log.Printf("reading from request stream failed: %v", err)
}
str.Close()
conn.Close()
}()
return nil
}
func (s *Proxy) proxyConnSend(conn *net.UDPConn, str http3.Stream) error {
for {
data, err := str.ReceiveDatagram(context.Background())
if err != nil {
return err
}
if _, err := conn.Write(data); err != nil {
return err
}
}
}
func (s *Proxy) proxyConnReceive(conn *net.UDPConn, str http3.Stream) error {
b := make([]byte, 1500)
for {
n, err := conn.Read(b)
if err != nil {
return err
}
if err := str.SendDatagram(b[:n]); err != nil {
return err
}
}
}
func (s *Proxy) Close() error {
s.closed.Store(true)
err := s.Server.Close()
s.mx.Lock()
for entry := range s.conns {
entry.str.CancelRead(quic.StreamErrorCode(http3.ErrCodeNoError))
entry.str.Close()
entry.conn.Close()
}
s.conns = nil
s.mx.Unlock()
s.refCount.Wait()
return err
}