-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.nim
More file actions
40 lines (37 loc) · 1.09 KB
/
Copy pathproxy.nim
File metadata and controls
40 lines (37 loc) · 1.09 KB
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
from posix import usleep
import sockets, selectors, parseutils, socks
proc pipe(a, b: Socket): bool =
var
buff = ""
len = a.recvAsync(buff, 20000)
if len > 0:
var sent = b.sendAsync buff
while sent < len:
sent += b.sendAsync buff[sent..len]
else:
return false
return true
proc proxy*(req: SocksProxyRequest) =
var
destsock = socket()
selector = newSelector()
events = {EvRead}
sourceKey: SelectorKey
sourceKey = selector.register(req.client.getFD, events, nil)
selector.register(destsock.getFD, events, nil)
destsock.connect req.destaddr, req.destport
# make sure sockets are non-blocking
req.client.setBlocking false
destsock.setBlocking false
block pump:
while true:
var info = selector.select(-1)
for ready in info:
if EvRead in ready.events:
if ready.key == sourceKey:
if not pipe(req.client, destsock):
break pump
elif not pipe(destsock, req.client):
break pump
# sleep for a short time to avoid high cpu for streaming connections
discard usleep 200