-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpinhole.py
82 lines (73 loc) · 2.18 KB
/
pinhole.py
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
import sys, socket, time, threading, icmp
LOGGING = True
loglock = threading.Lock()
def log(s, *a):
if LOGGING:
loglock.acquire()
try:
print '%s:%s' % (time.ctime(), (s % a))
sys.stdout.flush()
finally:
loglock.release()
class PipeThread(threading.Thread):
pipes = []
pipeslock = threading.Lock()
def __init__(self, source, sink):
threading.Thread.__init__(self)
self.source = source
self.sink = sink
log('Creating new pipe thread %s ( %s -> %s )', \
self, source.getpeername(), sink.getpeername())
self.pipeslock.acquire()
try: self.pipes.append(self)
finally: self.pipeslock.release()
self.pipeslock.acquire()
try: pipes_now = len(self.pipes)
finally: self.pipeslock.release()
log('%s pipes now active', pipes_now)
def run(self):
while True:
try:
data = self.source.recv(1024)
if not data: break
self.sink.send(data)
except:
break
log('%s terminateing', self)
self.pipeslock.acquire()
try: self.pipes.append(self)
finally: self.pipeslock.release()
self.pipeslock.acquire()
try: pipes_left = len(self.pipes)
finally: self.pipeslock.release()
log('%s pipes still active', pipes_left)
class Pinhole(threading.Thread):
def __init__(self, port, newhost, newport):
threading.Thread.__init__(self)
log('Redirecting: localhost: %s -> %s:%s', port, newhost, newport)
self.newhost = newhost
self.newport = newport
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('', port))
self.sock.listen(5)
def run(self):
while True:
newsock, address = self.sock.accept()
log('Creating new session for %s:%s', *address)
fwd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fwd.connect((self.newhost, self.newport))
PipeThread(newsock, fwd).start()
PipeThread(fwd, newsock).start()
if __name__ == '__main__':
print 'Starting Pinhole port forwarder/redirector'
import sys
try:
port = int(sys.argv[1])
newhost = sys.argv[2]
try: newport = int(sys.argv[3])
except IndexError: newport = port
except (ValueError, IndexError):
print 'Usage: %s port newhost [newhost]' % sys.argv[0]
sys.exit(1)
sys.stdout = open('pinhole.log', 'w')
Pinhole(port, newhost, newport).start()