-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmux.go
258 lines (211 loc) · 5.2 KB
/
mux.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// HLMUX
//
// Copyright (C) 2022 hlpkg-dev
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
package hlmux
import (
"context"
"encoding/binary"
"fmt"
"log"
"net"
"runtime"
"strings"
"sync"
"time"
)
func makeUDPAddrKey(addr *net.UDPAddr) uint64 {
key := make([]byte, 8)
copy(key, addr.IP.To4())
binary.BigEndian.PutUint16(key[4:], uint16(addr.Port))
return binary.BigEndian.Uint64(key)
}
func tokenize(data string) []string {
return strings.Split(data, " ")
}
type HandlerFunc func(*Conn)
type HandlersChain []HandlerFunc
type Mux struct {
timeout time.Duration
defaultUpstream *net.UDPAddr
conns map[uint64]*Conn
connsRWLock sync.RWMutex
stop chan bool
getchallengeChains HandlersChain
logger *log.Logger
workers int
}
func NewMux(upstream *net.UDPAddr) *Mux {
return &Mux{
timeout: 30 * time.Second,
defaultUpstream: upstream,
conns: make(map[uint64]*Conn),
getchallengeChains: make(HandlersChain, 0),
workers: runtime.NumCPU(),
}
}
func (mux *Mux) SetWorkers(n int) {
mux.workers = n
}
func (mux *Mux) SetTimeout(timeout time.Duration) {
mux.timeout = timeout
}
func (mux *Mux) SetDefaultUpstream(upstream *net.UDPAddr) {
mux.defaultUpstream = upstream
}
func (mux *Mux) FindConnectionByClient(client *net.UDPAddr) *Conn {
mux.connsRWLock.RLock()
defer mux.connsRWLock.RUnlock()
if conn, ok := mux.conns[makeUDPAddrKey(client)]; ok {
return conn
}
return nil
}
func (mux *Mux) Connections() []*Conn {
ret := make([]*Conn, 0)
mux.connsRWLock.RLock()
defer mux.connsRWLock.RUnlock()
for _, conn := range mux.conns {
ret = append(ret, conn)
}
return ret
}
func (mux *Mux) OnGetChallenge(handlers ...HandlerFunc) {
mux.getchallengeChains = append(mux.getchallengeChains, handlers...)
}
func (mux *Mux) delete(client *net.UDPAddr) {
mux.connsRWLock.Lock()
delete(mux.conns, makeUDPAddrKey(client))
mux.connsRWLock.Unlock()
log.Printf("delete client %v's connection", client)
}
func (mux *Mux) setConnection(client *net.UDPAddr, conn *Conn) {
mux.connsRWLock.Lock()
mux.conns[makeUDPAddrKey(client)] = conn
mux.connsRWLock.Unlock()
}
func (mux *Mux) SetLogger(logger *log.Logger) {
mux.logger = logger
}
func (mux *Mux) process(listener *net.UDPConn) error {
data := make([]byte, 1500)
n, client, err := listener.ReadFromUDP(data)
if err != nil {
return err
}
r := NewReader(data[:n])
peeked, err := r.PeekUint32()
if err != nil {
return err
}
conn := mux.FindConnectionByClient(client)
if conn == nil {
conn = &Conn{
timeout: mux.timeout,
client: client,
nextUpstream: mux.defaultUpstream,
}
mux.setConnection(client, conn)
if err := conn.applyNextUpstream(); err != nil {
return fmt.Errorf("cannot connect to upstream: %v", err)
}
go func() {
if err := conn.RunForward(listener); err != nil {
mux.delete(client)
}
}()
}
connectionless := false
if peeked == 0xffffffff {
connectionless = true
// connectionless packets
// eats 0xffffffff at the very beginning
r.ReadUint32()
// tokenize the incoming line (argv[0], argv[1], ...)
line, _ := r.ReadString('\n')
tokens := tokenize(line)
switch tokens[0] {
case "getchallenge":
for _, handler := range mux.getchallengeChains {
handler(conn)
}
default:
// do nothing
}
} else {
seq, _ := r.ReadUint32()
ack, _ := r.ReadUint32()
seqReliable := seq>>31 != 0
ackReliable := ack>>31 != 0
fragmented := seq&(1<<30) != 0
// TODO: ...
_ = seqReliable
_ = ackReliable
_ = fragmented
// r.Unmunge2(seq & 0xff)
// data, _ := io.ReadAll(r)
}
if connectionless && conn.shouldUpdate() {
conn.Stop()
}
if conn != nil {
if connectionless {
log.Printf("client %v write to upstream %v: %v", client, conn.Upstream(), string(data[:n]))
}
if err := conn.Write(data[:n]); err != nil {
conn.Stop()
}
}
return nil
}
func (mux *Mux) Run(address string) error {
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return fmt.Errorf("cannot resolve addr: %v", err)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return fmt.Errorf("cannot listen: %v", err)
}
defer conn.Close()
wg := &sync.WaitGroup{}
ctx, cancel := context.WithCancel(context.Background())
wg.Add(mux.workers)
for i := 0; i < mux.workers; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case <-mux.stop:
cancel()
return
default:
err := mux.process(conn)
if err != nil {
log.Printf("process error: %v", err)
}
}
}
}()
}
wg.Wait()
cancel()
return nil
}
func (mux *Mux) Stop() {
mux.stop <- true
}