forked from stb-tester/stb-tester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathirnetbox-proxy
executable file
·316 lines (267 loc) · 11.7 KB
/
irnetbox-proxy
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
#!/usr/bin/env python2.7
# -*- python -*-
"""A network proxy for the RedRat irNetBox MK-III infra-red emitter.
Unlike the real irNetBox hardware, this proxy accepts multiple simultaneous
TCP connections from different clients. This proxy maintains a single TCP
connection to the irNetBox, and multiplexes incoming client connections onto
this single connection.
Copyright 2013 YouView TV Ltd.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/stb-tester/stb-tester/blob/master/LICENSE for details).
Based on the irNetBox protocol specification:
http://www.redrat.co.uk/products/IRNetBox_Comms-V3.X.pdf
Usage
-----
```
$ irnetbox-proxy <irNetBox address>
```
OR
```
$ irnetbox-proxy -vv \
--listen-port 10001 --listen-address 127.0.0.1 \
<irNetBox address> 10001
> Listening for connections on 127.0.0.1:10001
```
Features
--------
- Session multiplexing: irnetbox-proxy dynamically maps Asyncronous Sequence
IDs on the fly, meaning that multiple clients can use the same Sequence ID
concurrently, and the irnet box will continue to work. Both the command
acknowledgement, and the subsequent Async complete message are always routed
to the correct client.
- On/Off management: irnetbox-proxy will silently accept the on and off
messages (5 and 6). A standard ACK response is returned to the client, but the
command is never sent to the device. This allows multiple scripts to try to
turn off the device while other devices use it. irnetbox-proxy issues the ON
command when it connects, and issues an OFF command when it is stopped.
"""
import argparse
import cStringIO as StringIO
import itertools
import select
import socket
import struct
import sys
import traceback
def safe_recv(sock, num):
in_buffer = StringIO.StringIO()
while num:
packet = sock.recv(num)
if packet == '':
raise SocketClosed(sock)
in_buffer.write(packet)
num -= len(packet)
return in_buffer.getvalue()
class SocketClosed(Exception):
@property
def socket(self):
return self.message
class StopRunning(BaseException):
pass
class IRNetBoxProxy(object):
MESSAGE_HEADER = struct.Struct(">cHB")
RESPONSE_HEADER = struct.Struct(">HB")
SEQUENCE_ID = struct.Struct(">H")
MESSAGE_MARKER = "#"
ASYNC_COMMAND = 0x30
ASYNC_COMPLETE = 0x31
ACK_NACK_INDEX = 3
POWER_ON = 0x05
POWER_OFF = 0x06
IGNORED_COMMANDS = frozenset((POWER_ON, POWER_OFF))
USIZE_MAX = 65535
def __init__(self, irnet_address, irnet_port=10001,
listen_address="0.0.0.0", listen_port=10001,
verbosity=0):
self.irnet_addr = (irnet_address, irnet_port)
self.listen_addr = (listen_address, listen_port)
self.verbosity = verbosity
self.counter = itertools.count()
self.async_commands = {}
self.listen_sock = None
self.irnet_sock = None
self.read_sockets = {}
def make_id(self):
command_id = None
while command_id is None or command_id in self.async_commands:
command_id = self.counter.next()
if command_id > self.USIZE_MAX:
self.counter = itertools.count()
return self.make_id()
return command_id
def replace_sequence_id(self, data, new_id, little_endian=False):
sequence_id_format = struct.Struct(
("<" if little_endian else ">") + "H")
return sequence_id_format.pack(new_id) + data[sequence_id_format.size:]
def get_message_from_irnet(self, expect_sync_response=True):
header_data = safe_recv(self.irnet_sock, self.RESPONSE_HEADER.size)
response_len, response_type = self.RESPONSE_HEADER.unpack(header_data)
data = safe_recv(self.irnet_sock, response_len)
if response_type == self.ASYNC_COMPLETE:
self.handle_async_response(header_data, data)
if expect_sync_response:
return self.get_message_from_irnet(True)
else:
return
elif response_type == self.ASYNC_COMMAND:
# Sequence number in the response message is defined as big-endian
# in sections 5.1 and 6.1.2 of the protocol specification v3.0,
# but due to a known bug it is little-endian.
new_id, = struct.unpack_from("<H", data)
_, old_id = self.async_commands[new_id]
data = self.replace_sequence_id(data, old_id, little_endian=True)
if not data[self.ACK_NACK_INDEX]:
# The async command request failed, remove record
del self.async_commands[new_id]
return response_type, header_data, data
def handle_async_response(self, header, data):
try:
new_id, = self.SEQUENCE_ID.unpack_from(data)
if new_id not in self.async_commands:
self.warn("Sequence ID not recognised: %r" % (new_id, ))
return
sock, old_id = self.async_commands[new_id]
data = self.replace_sequence_id(data, old_id)
sock.sendall(header + data)
except Exception, e: # pylint: disable=W0703
self.error(e, "Error sending async complete command", fatal=False)
if new_id in self.async_commands:
del self.async_commands[new_id]
def get_message_from_client(self, sock):
header = safe_recv(sock, self.MESSAGE_HEADER.size)
marker, message_len, message_type = self.MESSAGE_HEADER.unpack(header)
if marker == "q":
raise StopRunning()
elif marker != self.MESSAGE_MARKER:
raise ValueError("Invalid message from client")
data = safe_recv(sock, message_len)
if message_type == self.ASYNC_COMMAND:
old_id, = self.SEQUENCE_ID.unpack_from(data)
new_id = self.make_id()
self.async_commands[new_id] = (sock, old_id)
data = self.replace_sequence_id(data, new_id)
return message_type, header, data
def send_management_command(self, message_type):
message = self.MESSAGE_HEADER.pack(self.MESSAGE_MARKER, 0, message_type)
self.irnet_sock.sendall(message)
response_type, _, _ = self.get_message_from_irnet(True) # pylint: disable=W0633,C0301
assert response_type == message_type
def accept_client(self):
new_client, (addr, _) = self.listen_sock.accept()
self.info("Accepted connection from %s" % (addr,))
# pylint: disable=E1101
self.read_sockets[new_client.fileno()] = new_client
def read_client_command(self, sock):
try:
message_type, header, message = self.get_message_from_client(sock)
if message_type in self.IGNORED_COMMANDS:
response_header = self.RESPONSE_HEADER.pack(0, message_type)
response = ""
else:
self.irnet_sock.sendall(header + message)
_, response_header, response = self.get_message_from_irnet(True) # pylint: disable=W0633,C0301
sock.sendall(response_header + response)
except Exception, e: # pylint: disable=W0703
del self.read_sockets[sock.fileno()]
sock.close()
if isinstance(e, SocketClosed) and e.socket is sock: # pylint:disable=no-member
self.info("Client connection closed")
else:
self.error(e, "Error reading from client. Connection closed",
fatal=False)
def info(self, data):
if self.verbosity > 1:
print data
def warn(self, data):
if self.verbosity > 0:
sys.stderr.write("Warning: %s\n" % (data, ))
def error(self, exception, data, fatal=True):
if self.verbosity > 0:
traceback.print_exc(exception)
sys.stderr.write("%s\n" % (data, ))
if fatal:
sys.exit(1)
def connect(self):
try:
self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listen_sock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
self.listen_sock.bind(self.listen_addr)
self.listen_sock.listen(5)
except Exception, e: # pylint: disable=W0703
self.error(e, "Could not bind to local address")
try:
self.irnet_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.irnet_sock.connect(self.irnet_addr)
except Exception, e: # pylint: disable=W0703
self.error(e, "Could not connect to irNetBox.")
self.read_sockets = {
self.listen_sock.fileno(): self.listen_sock,
self.irnet_sock.fileno(): self.irnet_sock
}
def run(self):
self.connect()
try:
self.send_management_command(self.POWER_ON)
except Exception, e: # pylint: disable=W0703
self.error(
e, "Connected to irNetBox, but could not send power on command")
self.info("Listening for connections on %s:%s" % self.listen_addr)
try:
while True:
to_read = self.read_sockets.keys()
ready_to_read, _, _ = select.select(to_read, [], [])
for socket_fd in ready_to_read:
sock = self.read_sockets[socket_fd]
if sock is self.listen_sock:
self.accept_client()
elif sock is self.irnet_sock:
self.get_message_from_irnet(False)
else:
self.read_client_command(sock)
finally:
try:
self.send_management_command(self.POWER_OFF)
except Exception, e: # pylint: disable=W0703
self.error(e, "Could not turn irNetBox off", fatal=False)
for sock in self.read_sockets.viewvalues():
try:
sock.close()
except: # pylint: disable=W0702
pass
def parse_args(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description="""
Network proxy for the RedRat irNetBox MK-III infra-red emitter.
Unlike the real irNetBox hardware, this proxy accepts multiple
simultaneous TCP connections from different clients (and forwards
the client requests on to the irNetBox over a single connection).""")
parser.add_argument('-v', '--verbose', action="count", default=0,
help='Specify once to enable warnings, twice for'
'informational messages')
parser.add_argument('-l', '--listen-address', default="0.0.0.0",
help='IP address to listen on [%(default)s]')
parser.add_argument('-p', '--listen-port', type=int, default=10001,
help='Port to listen on [%(default)s]')
parser.add_argument('irnetbox_address', help='IRNetBox address')
parser.add_argument('irnetbox_port', type=int, default=10001, nargs='?',
help='IRNetBox port [%(default)s]')
options = parser.parse_args(args)
options.error = parser.error
return options
def main():
options = parse_args()
proxy = IRNetBoxProxy(irnet_address=options.irnetbox_address,
irnet_port=options.irnetbox_port,
listen_address=options.listen_address,
listen_port=options.listen_port,
verbosity=options.verbose)
try:
proxy.run()
except (KeyboardInterrupt, StopRunning), e:
proxy.error(e, "Stopped")
except Exception, e: # pylint:disable=W0703
proxy.error(e, "irNetProxy encountered an error")
if __name__ == "__main__":
sys.exit(main())