-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
384 lines (338 loc) · 8.82 KB
/
main.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"runtime"
"sync"
"time"
)
const (
socksVersion = 5
authNone = 0
authUsernamePasswd = 2
authNoAccept = 0xFF
cmdConnect = 1
addrIPv4 = 1
addrDomain = 3
addrIPv6 = 4
)
var (
Users = map[string]string{}
TrafficUsage = map[string]int64{}
trafficMutex = sync.Mutex{}
trafficSaverRWMutex = sync.RWMutex{}
usersFile = "users.json"
trafficFile = "traffic.json"
)
type countingConn struct {
conn net.Conn
user string
rBytes int64
wBytes int64
}
func (c *countingConn) Read(b []byte) (int, error) {
n, err := c.conn.Read(b)
trafficMutex.Lock()
c.rBytes += int64(n)
TrafficUsage[c.user] += int64(n)
trafficMutex.Unlock()
return n, err
}
func (c *countingConn) Write(b []byte) (int, error) {
n, err := c.conn.Write(b)
trafficMutex.Lock()
c.wBytes += int64(n)
TrafficUsage[c.user] += int64(n)
trafficMutex.Unlock()
return n, err
}
func (c *countingConn) Close() error {
return c.conn.Close()
}
func loadUsers() {
file, err := ioutil.ReadFile(usersFile)
if err != nil {
if os.IsNotExist(err) {
log.Println("No users file found, starting with an empty user list")
return
}
log.Fatalf("Failed to read users file: %v", err)
}
if err := json.Unmarshal(file, &Users); err != nil {
log.Fatalf("Failed to unmarshal users: %v", err)
}
}
func saveUsers() {
file, err := json.MarshalIndent(Users, "", " ")
if err != nil {
log.Fatalf("Failed to marshal users: %v", err)
}
if err := ioutil.WriteFile(usersFile, file, 0600); err != nil {
log.Fatalf("Failed to write users file: %v", err)
}
}
func loadTraffic() {
trafficSaverRWMutex.RLock()
defer trafficSaverRWMutex.RUnlock()
file, err := ioutil.ReadFile(trafficFile)
if err != nil {
if os.IsNotExist(err) {
log.Println("No traffic file found, starting with an empty traffic record")
return
}
log.Fatalf("Failed to read traffic file: %v", err)
}
if err := json.Unmarshal(file, &TrafficUsage); err != nil {
log.Fatalf("Failed to unmarshal traffic: %v", err)
}
}
func saveTraffic() {
trafficSaverRWMutex.Lock()
defer trafficSaverRWMutex.Unlock()
file, err := json.MarshalIndent(TrafficUsage, "", " ")
if err != nil {
log.Fatalf("Failed to marshal traffic: %v", err)
}
if err := ioutil.WriteFile(trafficFile, file, 0600); err != nil {
log.Fatalf("Failed to write traffic file: %v", err)
}
}
func addUser(username, password string) {
Users[username] = password
saveUsers()
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// buf := make([]byte, 32768)
buf := make([]byte, 1024*1024)
// buf := []byte
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
log.Println("Failed to read version and nMethods:", err)
return
}
nMethods := int(buf[1])
if _, err := io.ReadFull(conn, buf[:nMethods]); err != nil {
log.Println("Failed to read methods:", err)
return
}
supported := false
for _, method := range buf[:nMethods] {
if method == authUsernamePasswd {
supported = true
break
}
}
if !supported {
conn.Write([]byte{socksVersion, authNoAccept})
return
}
conn.Write([]byte{socksVersion, authUsernamePasswd})
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
log.Println("Failed to read auth version and username length:", err)
return
}
usernameLen := int(buf[1])
if _, err := io.ReadFull(conn, buf[:usernameLen]); err != nil {
log.Println("Failed to read username:", err)
return
}
username := string(buf[:usernameLen])
if _, err := io.ReadFull(conn, buf[:1]); err != nil {
log.Println("Failed to read password length:", err)
return
}
passwordLen := int(buf[0])
if _, err := io.ReadFull(conn, buf[:passwordLen]); err != nil {
log.Println("Failed to read password:", err)
return
}
password := string(buf[:passwordLen])
if userPassword, ok := Users[username]; !ok || userPassword != password {
conn.Write([]byte{1, 1}) // Authentication failed
return
}
conn.Write([]byte{1, 0}) // Authentication successful
countingConn := &countingConn{conn: conn, user: username}
defer countingConn.Close()
if _, err := io.ReadFull(countingConn, buf[:4]); err != nil {
log.Println("Failed to read request header:", err)
return
}
if buf[1] != cmdConnect {
log.Println("Unsupported command:", buf[1])
countingConn.Write([]byte{socksVersion, 7})
return
}
var addr string
switch buf[3] {
case addrIPv4:
if _, err := io.ReadFull(countingConn, buf[:4]); err != nil {
log.Println("Failed to read IPv4 address:", err)
return
}
addr = net.IP(buf[:4]).String()
fmt.Printf("IPv4 address: %s\n", addr)
case addrDomain:
if _, err := io.ReadFull(countingConn, buf[:1]); err != nil {
log.Println("Failed to read domain length:", err)
return
}
domainLen := int(buf[0])
if _, err := io.ReadFull(countingConn, buf[:domainLen]); err != nil {
log.Println("Failed to read domain name:", err)
return
}
addr = string(buf[:domainLen])
fmt.Printf("Domain name: %s\n", addr)
case addrIPv6:
if _, err := io.ReadFull(countingConn, buf[:16]); err != nil {
log.Println("Failed to read IPv6 address:", err)
return
}
addr = net.IP(buf[:16]).String()
fmt.Printf("IPv6 address: %s\n", addr)
default:
log.Println("Unsupported address type:", buf[3])
countingConn.Write([]byte{socksVersion, 8})
return
}
if _, err := io.ReadFull(countingConn, buf[:2]); err != nil {
log.Println("Failed to read port:", err)
return
}
port := int(buf[0])<<8 | int(buf[1])
addr = net.JoinHostPort(addr, fmt.Sprintf("%d", port))
targetConn, err := net.Dial("tcp", addr)
if err != nil {
log.Println("Failed to connect to target:", err)
countingConn.Write([]byte{socksVersion, 5})
return
}
defer targetConn.Close()
countingConn.Write([]byte{socksVersion, 0, 0, addrIPv4, 0, 0, 0, 0, 0, 0})
// ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// defer cancel()
// var once sync.Once
closeConns := func() {
// once.Do(func() {
countingConn.Close()
targetConn.Close()
// })
}
// errCh := make(chan error, 1)
go func() {
// defer closeConns()
defer closeConns()
_, err := io.CopyBuffer(targetConn, countingConn, buf)
if err != nil {
log.Println("Error copying from countingConn to targetConn:", err)
}
// io.Copy(targetConn, countingConn)
// io.wri
// n, readErr := targetConn.Read(buf)
// if n > 0 {
// _, writeErr := countingConn.Write(buf[:n])
// if writeErr != nil {
// // Handling write error
// fmt.Println("Error writing to targetConn:", writeErr)
// return
// }
// }
// if readErr != nil {
// if readErr != io.EOF {
// // Handling read error
// fmt.Println("Error reading from countingConn:", readErr)
// }
// return
// }
}()
func() {
defer closeConns()
_, err := io.CopyBuffer(countingConn, targetConn, buf)
if err != nil {
log.Println("Error copying from targetConn to countingConn:", err)
}
// _, _ = io.Copy(countingConn, targetConn)
// n, readErr := targetConn.Read(buf)
// if n > 0 {
// _, writeErr := countingConn.Write(buf[:n])
// if writeErr != nil {
// // Handling write error
// fmt.Println("Error writing to targetConn:", writeErr)
// return
// }
// }
// if readErr != nil {
// if readErr != io.EOF {
// // Handling read error
// fmt.Println("Error reading from countingConn:", readErr)
// }
// return
// }
// errCh <- err
}()
// io.Copy(countingConn, targetConn)
// select {
// case <-ctx.Done():
// log.Println("Connection timed out")
// closeConns()
// case err := <-errCh:
// if err != nil && err != io.EOF {
// log.Println("Connection error:", err)
// }
// closeConns()
// }
saveTraffic()
}
func main() {
if len(os.Args) > 1 {
switch os.Args[1] {
case "adduser":
if len(os.Args) != 4 {
fmt.Println("Usage: go run main.go adduser <username> <password> after build you can use ./main adduser <username> <password>")
return
}
loadUsers()
addUser(os.Args[2], os.Args[3])
fmt.Println("User added successfully")
return
case "showtraffic":
loadTraffic()
for user, traffic := range TrafficUsage {
fmt.Printf("User: %s, Traffic: %d bytes\n", user, traffic)
}
return
}
}
loadUsers()
loadTraffic()
listener, err := net.Listen("tcp", ":1080")
if err != nil {
log.Fatalf("Failed to bind to port 1080: %v", err)
}
defer listener.Close()
go func() {
for {
fmt.Printf("Active Goroutines: %d\n", runtime.NumGoroutine())
time.Sleep(5 * time.Second)
}
}()
log.Println("SOCKS5 server listening on port 1080")
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed to accept connection:", err)
if ne, ok := err.(net.Error); ok && ne.Temporary() {
continue
}
log.Fatalf("Permanent error accepting connection: %v", err)
return
}
go handleConnection(conn)
}
}