forked from nabla-c0d3/multcprelay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcprelay.py
186 lines (151 loc) · 5.89 KB
/
tcprelay.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
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# tcprelay.py - TCP connection relay for usbmuxd
#
# Copyright (C) 2009 Hector Martin "marcan" <[email protected]>
#
# 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 2 or version 3.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# @2020 Modified by ptcong to support multiple devices and multiple ports per device
import usbmux
import SocketServer
import select
from optparse import OptionParser
import sys
import traceback
import time
class SocketRelay(object):
def __init__(self, a, b, maxBuffer=65535):
self.a = a
self.b = b
self.atob = ""
self.btoa = ""
self.maxBuffer = maxBuffer
def handle(self):
while True:
rlist = []
wlist = []
xlist = [self.a, self.b]
if self.atob:
wlist.append(self.b)
if self.btoa:
wlist.append(self.a)
if len(self.atob) < self.maxBuffer:
rlist.append(self.a)
if len(self.btoa) < self.maxBuffer:
rlist.append(self.b)
rlo, wlo, xlo = select.select(rlist, wlist, xlist)
if xlo:
return
if self.a in wlo:
n = self.a.send(self.btoa)
self.btoa = self.btoa[n:]
if self.b in wlo:
n = self.b.send(self.atob)
self.atob = self.atob[n:]
if self.a in rlo:
s = self.a.recv(self.maxBuffer - len(self.atob))
if not s:
return
self.atob += s
if self.b in rlo:
s = self.b.recv(self.maxBuffer - len(self.btoa))
if not s:
return
self.btoa += s
# print "Relay iter: %8d atob, %8d btoa, lists: %r %r %r"%(len(self.atob), len(self.btoa), rlo, wlo, xlo)
class TCPRelay(SocketServer.BaseRequestHandler):
def handle(self):
def show_msg(msg):
print "{0} ### {1}".format(self.server.server_address[1], msg)
show_msg("Incoming connection to local port {0}:{1}".format(self.server.server_address[0], self.server.server_address[1]))
show_msg("Waiting for device {0}:{1}".format(self.server.deviceUDID, self.server.remotePort))
device = None
if self.server.deviceUDID is None:
device = mux.devices[0]
else:
for dev in mux.devices:
if dev.serial == self.server.deviceUDID:
device = dev
break
if not device:
self.request.close()
mux.process(0.1)
return
try:
show_msg("Connecting to device {0}:{1}".format(device.serial, self.server.remotePort))
dsock = mux.connect(device, self.server.remotePort)
lsock = self.request
show_msg("Connection established, relaying data")
try:
fwd = SocketRelay(dsock, lsock, self.server.bufferSize * 1024)
fwd.handle()
finally:
dsock.close()
lsock.close()
show_msg("Connection closed")
except KeyboardInterrupt:
quit()
except:
pass
mux.process(0.1)
class TCPServer(SocketServer.TCPServer):
allow_reuse_address = True
class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer):
pass
parser = OptionParser(usage="usage: %prog [OPTIONS] [Lhost:]Lport::deviceUDID:Rport [[Lhost:]Lport::deviceUDID:Rport] ...")
parser.add_option("-t", "--threaded", dest='threaded', action='store_true', default=True,
help="use threading to handle multiple connections at once")
parser.add_option("-b", "--bufsize", dest='bufsize', action='store', metavar='KILOBYTES', type='int', default=128,
help="specify buffer size for socket forwarding")
parser.add_option("-s", "--socket", dest='sockpath', action='store', metavar='PATH', type='str', default=None,
help="specify the path of the usbmuxd socket")
options, args = parser.parse_args()
serverClass = ThreadedTCPServer if options.threaded else TCPServer
if len(args) == 0:
parser.print_help()
sys.exit(1)
ports = []
for arg in args:
try:
localPort, remotePort = arg.split("::")
localHost, localPort = localPort.split(":") if len(localPort.split(":")) > 1 else ("localhost", localPort)
deviceUDID, remotePort = remotePort.split(":") if len(remotePort.split(":")) > 1 else (None, remotePort)
ports.append((localHost, int(localPort), deviceUDID, int(remotePort)))
except:
parser.print_help()
sys.exit(1)
servers = []
for localHost, localPort, deviceUDID, remotePort in ports:
print "Forwarding {0}:{1} ==> {2}:{3}".format(localHost, localPort, deviceUDID, remotePort)
server = serverClass((localHost, localPort), TCPRelay)
server.deviceUDID = deviceUDID
server.remotePort = remotePort
server.bufferSize = options.bufsize
servers.append(server)
mux = usbmux.USBMux(options.sockpath)
for i in range(1, len(ports)):
mux.process(0.1)
alive = True
while alive:
try:
rl, wl, xl = select.select(servers, [], [])
for server in rl:
server.handle_request()
except KeyboardInterrupt:
quit()
except:
traceback.print_exc()
alive = False