-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathslingbox_server.py
executable file
·1702 lines (1553 loc) · 66.3 KB
/
slingbox_server.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import sys
import os
import socket
import sys
import time
import select
import queue
import re
import subprocess
from threading import Thread, get_ident
import platform
import datetime
import traceback
import ipaddress
from struct import pack, unpack, calcsize
from configparser import ConfigParser
from ctypes import *
import mimetypes
version='4.01'
def encipher(v, k):
y = c_uint32(v[0])
z = c_uint32(v[1])
sum = c_uint32(0)
delta = 0x61C88647
n = 32
w = [0,0]
while(n>0):
sum.value -= delta
y.value += ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
z.value += ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
n -= 1
w[0] = y.value
w[1] = z.value
return w
def decipher(v, k):
y = c_uint32(v[0])
z = c_uint32(v[1])
sum = c_uint32(0xc6ef3720)
delta = 0x9e3779b9
n = 32
w = [0,0]
while(n>0):
z.value -= ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
y.value -= ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
sum.value -= delta
n -= 1
w[0] = y.value
w[1] = z.value
return w
def Crypt( data, key ):
bytes = b''
info = [int.from_bytes(data[i:i+4],byteorder='little') for i in range(0, len(data), 4)]
for i in range(0, len(info), 2):
chunk = [info[i], info[i+1]]
ciphertext = encipher(chunk, key)
bytes = bytes + ciphertext[0].to_bytes(4, byteorder='little') + ciphertext[1].to_bytes(4, byteorder='little')
return bytes
def Decrypt( data, key ):
bytes = b''
info = [int.from_bytes(data[i:i+4],byteorder='little') for i in range(0, len(data), 4)]
for i in range(0, len(info), 2):
chunk = [info[i], info[i+1]]
cleartext = decipher(chunk, key)
bytes = bytes + cleartext[0].to_bytes(4, byteorder='little') + cleartext[1].to_bytes(4, byteorder='little')
return bytes
def ts(res=-3):
return '%s ' % datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S.%f").rstrip('0')[:res]
def pbuf(s):
s = ''.join('{:02x} '.format(x) for x in s).upper()
cnt = 0
out = ''
for i in range(0, len(s), 48):
ss = s[i:i+48].strip()
# print( "%06d" % (cnt,), ss )
out = out + "%06d " % (cnt,) + ss + '\r\n'
cnt += 16
return out
productIdDict ={
"UNKNOWN": "Slingbox",
0: "Classic",
1: "PRO",
2: "Classic",
3: "AV",
4: "TUNER",
5: "Classic",
6: "Sling MODEM",
7: "SOLO",
8: "PRO-HD",
9: "922",
12: "HDS-600RS",
13: "120",
14: "Sling Adapter",
17: "350",
18: "500",
32: "M1",
19762: "M2"
}
def ip4_addresses():
ips = []
interfaces = netifaces.interfaces()
for interface in interfaces:
addresses = netifaces.ifaddresses(interface)
for address in addresses:
info = addresses[address][0]
if 'broadcast' in info:
ips.append((info['addr'],info['broadcast'], interface))
return ips
def find_slingbox_info(name):
try:
import netifaces
except:
print('ERROR. Cannot scan local network for slingboxes\nBecause the "netifaces" python modules has not been installed')
return []
boxes = []
query = [0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
ip = ''
port = 0
print(name, 'No valid slingbox ip info found in config.ini')
for local_ip, broadcast, interface in ip4_addresses():
if local_ip == '127.0.0.1': continue
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(2)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
try:
s.bind((local_ip, 0))
except Exception as e:
# print('Error binding socket to send broadcast', e )
continue
print(name,'Finding Slingboxes on local network. My IP Info = ', local_ip)
s.sendto( bytearray(query), (broadcast, 5004 ))
while True:
try:
msg, source = s.recvfrom(128)
# print('MSG', len(msg), source, pbuf(msg))
if len(msg) == 124 :
port = msg[121] * 256 + msg[120]
net_name = ''
for char in msg[ 56:120]:
if char != 0: net_name = net_name + chr(char)
finderid = ''.join('{:02x}'.format(x) for x in msg[40:56])
pid = msg[38] * 256 + msg[39]
if pid in productIdDict.keys(): pname = productIdDict[pid]
else: pname = 'Unknown slingbox type'
print( name, 'Found at', source[0], port, '"', net_name, '"',
'FinderID', finderid.upper(), 'ProductID', pname)
boxes.append((source[0], port, name, pid))
except Exception as e:
# print(e, traceback.print_exc())
break
return boxes
def closeconn( s ):
if s :
# print('Closing Connection')
try:
s.shutdown(socket.SHUT_RDWR)
except: pass
s.close()
return None
def find_max_buffer_size( opt ):
size = 1024*1024*8
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while size > 0 :
try:
# print( 'trying', size )
sock.setsockopt(socket.SOL_SOCKET, opt, size )
break
except :
size = size - (1024*1024)
continue
if size < 1024*1024*8 :
print('Warning TCP buffering might not be sufficent for reliable streaming')
return size
def streamer(maxstreams, config_fn, section_name, box_name, streamer_q, server_port):
global streamer_qs, stati, num_streams
smode = 0x2000 # basic cipher mode,
sid = 0
seq = 0
tbd = 0
dco = b''
bco = 0
bts = 0
s_ctl = None
stream = None
dbuf = None
skey = None
stat = 0
rccode = 0
streams = []
stream_header = None
max_recv_tcp_buffer = find_max_buffer_size(socket.SO_RCVBUF)
def new_key( sid, rand, challange ):
def bits2bytes(bits):
def abyte( b ):
n = 0
for abit in b[::-1]:
n = (n << 1) + abit
return n
ba = bytearray()
for i in range(0,len(bits), 8 ):
ba.append(abyte(bits[i:i+8]))
return ba
def xor( b1, b2 ):
br = bytearray()
l = len(b2)
for i in range(0,l):
br.append( b1[i] ^ b2[i])
return br + b1[l:]
def dynk( rand, sid, a, b ): # hash function for dynamic key
def p(ba): # make string from bits
z = ord('0')
out = ''
for b in ba : out = out + chr(z+b)
return out
def bytes2bits( buf ):
t = ''
for b in buf:
t = t + '{:08b}'.format(b)[::-1]
ba = bytearray()
for c in t:
ba.append( ord(c) & 1 )
return ba
#******************************
t = bytes2bits(rand)
s = bytes2bits(pack('H', sid ))
td = [a, b]
v = bytearray()
for i in range(1,17):
r = i * td[((sid >> (i - 1)) & 1)]
z = t[r:] + t[0:r]
t = xor(z,s)
v = xor(t, v)
return v
# rand = bytearray.fromhex('feedfacedeadbeef1111222233334444')
# c = bytearray.fromhex( challange )
my_key = xor( dynk(rand, sid, 2, 3), dynk(challange, sid, -1, -4))
# print( 'SKEY', pbuf(bits2bytes(my_key)) )
return list(unpack('IIII', bits2bytes(my_key)))
def futf16(in_str):
out_str = ''
for c in in_str: out_str = out_str + c + chr(0)
return bytes(out_str, 'utf-8')
def sling_cmd( opcode, data, msg_type=0x0101 ):
nonlocal sid, seq, s_ctl, dbuf, skey, stat, smode
parity = 0
if smode == 0x8000 :
for x in data:
parity ^= x
# print( 'Sending to Slingbox ', hex(opcode), hex(parity), '\r\n')
seq += 1
try:
cmd = pack("<HHHHH 6x HH 4x H 6x", msg_type, sid, opcode, 0, seq, len(data), smode, parity) + Crypt(data, skey)
s_ctl.sendall( cmd )
except Exception as e:
print(name, 'Error Sending Command', e, hex(msg_type), sid, hex(opcode), seq, len(data), hex(smode), hex(parity))
return False
if opcode == 0x66 : return True
try:
response = s_ctl.recv(32)
if len(response) == 32:
sid, stat, dlen = unpack("2x H 8x H 2x H", response[0:18] ) # "x2 v x8 v x2 v", $hbuf);
# print( 'Sent to Slingbox ', hex(opcode), hex(parity), hex(len(data)))
# print( 'Received from Slingbox', sid, hex(stat), dlen )
# print('RESP', pbuf(response))
if opcode == 0x68 : return # ignore logout errors
if stat & stat != 0x0d & stat != 0x13 :
print( "cmd:", hex(opcode), "err:", hex(stat), dlen )
if dlen > 0 :
in_buf = s_ctl.recv( 512 )
dbuf = Decrypt(in_buf, skey)
# print('DBUF', hex(opcode), pbuf(dbuf))
return True
else: return False
except Exception as e:
print(name, 'Error Getting Response', e, hex(msg_type), sid, hex(opcode), seq)
return False
def sling_open(addr, connection_type):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, max_recv_tcp_buffer)
s.settimeout(10)
print('Connecting...', addr, connection_type )
s.connect(addr)
s.sendall(str.encode('GET /stream.asf HTTP/1.1\r\nAccept: */*\r\nPragma: Sling-Connection-Type=%s, Session-Id=%d\r\n\r\n' % (connection_type, sid)))
return s
def SetVideoParameters(resolution, FrameRate, VideoBandwidth, VideoSmoothness, IframeRate, AudioBitRate ):
rand = bytearray.fromhex('feedfacedeadbeef1111222233334444') # 'random' challenge
print('VideoParameters: Resolution=',resolution, 'FrameRate=', FrameRate,
'VideoBandwidth=', VideoBandwidth, 'VideoSmoothness=', VideoSmoothness,
'IframeRate=', IframeRate, 'AudioBitRate=', AudioBitRate)
sling_cmd(0xb5, pack("11I 16s 2I 92x",
0xff,
0xff,
resolution, # Screen Size
1,
(IframeRate << 24 ) + (FrameRate << 16) + VideoBandwidth,
0x10001 + (VideoSmoothness << 8), #Video Smoothness
3, #fixed
1, #fixed
AudioBitRate,
# 3,
0x4f,
1,
rand,
0x1012020,
1)); # set stream params
if stat != 0:
print(name, 'Slingbox returned error trying to set video parameters')
print('Please validate parameters.')
return False
return True
def start_slingbox_session(streams):
nonlocal stream_header, sid, seq, s_ctl, dbuf, skey, stat, smode
global stati, num_streams
skey = [0xBCDEAAAA,0x87FBBBBA,0x7CCCCFFA,0xDDDDAABC]
# print('skey', skey )
smode = 0x2000 # basic cipher mode,
sid = seq = 0 # no session ID, seq 0
print(name, 'Opening Control stream', hex(smode), sid, seq)
s_ctl = sling_open(sling_net_address, 'Control') # open control connection to SB
if not sling_cmd(0x67, pack('I 32s 32s 132x', 0, futf16('admin'), futf16(password))): # log in to SB
print(name, 'Slingbox did not respond to login request. Please reset Slingbox and try again. NOT a factory reset')
return (s_ctl, None)
if stat != 0:
if stat == 0x2:
print(name,'Error Starting Session. Check your admin password in config.ini file!')
elif stat == 0x2b:
print(name,'Error Starting Session. Slingbox might be Bricked')
else:
print(name,'Unknown Error Starting Session. Can''t Continue.')
return s_ctl, None
rand = bytearray.fromhex('feedfacedeadbeef1111222233334444') # 'random' challenge
sling_cmd(0xc6, pack('I 16s 36x', 1, rand)) # setup dynamic key on SB
if stat != 0:
print(name,'Error Starting Session. Check your admin password in config.ini file!')
return s_ctl, None
skey = new_key(sid, rand, dbuf[0:16])
# print('New Key ', skey)
smode = 0x8000 # use dynamic key from now on
sling_cmd(0x7e, pack("I I", 1, 0)) # stream control
retries = 0
while stat and retries < 3:
retries += 1
print(name,'Box in use! Kicking off other user.' )
stati[server_port] = name + ' Slingbox in Use! Cannot start session, kicking off other user..'
sling_cmd(0x93, pack('32s 32s 8x', futf16('admin'), futf16(password)))
time.sleep(1)
sling_cmd(0x6a, pack("I 172x", 1)); # unk fn
sling_cmd(0x7e, pack("I I", 1, 0)) # stream control
if stat:
print(name, 'Cannot kick off other user, not starting session.')
print( 'If this error persists, consider rebooting your slingbox')
return (s_ctl, None)
## Select input
if VideoSource :
print(name,'Selecting Video Source', VideoSource)
source = int(VideoSource)
sling_cmd(0x85, pack('4h', source, 0, 0, 0 ))
if stat != 0 :
print('Error trying to set VideoSource. Please make sure the supplied value is valid for your slingbox model')
return ( s_ctl, None )
try:
sling_cmd( 0x86, pack("h 254x", 0x0400 + source )) # Get Key Codes
if len(dbuf) > 1 :
i = 1
codes = []
while dbuf[i] != 0 and i < len(dbuf):
codes.append(dbuf[i])
i += 1
codes.sort()
if codes :
print(name, 'Keycodes=', codes)
elif not ( Solo and source == 0):
print( name, 'Warning: No remote keys configured, using correct VideoSource?')
except:
Print('Error retreiving Keycodes. If this error persists consider rebooting your slingbox')
return (s_ctl,None)
sling_cmd(0xa6, pack("10h 76x", 0x1cf, 0, 0x40, 0x10, 0x5000, 0x180, 1, 0x1e, 0, 0x3d))
if not SetVideoParameters(resolution, FrameRate, VideoBandwidth, VideoSmoothness, IframeRate, AudioBitRate ) :
return (s_ctl,None)
stream = sling_open(sling_net_address, 'Stream')
first_buffer = bytearray(stream.recv(pksize, socket.MSG_PEEK))
magic = bytearray(u'Slingbox'.encode('utf-16le'))
idx = first_buffer.find(magic)
if idx > 0:
sourceid = bytearray(16)
# print('Fixup Media', name, section_name)
source_name = name
if source_name == 'SLINGBOX' : source_name = 'Slingbox'
sourceid[:len(source_name)*2] = bytearray(source_name[0:8].encode('utf-16le'))
first_buffer[idx:idx+16]= sourceid
# print( 'FIRST', type(first_buffer), pbuf(first_buffer))
h264_header = b'\x36\x26\xb2\x75\x8e\x66\xcf\x11\xa6\xd9\x00\xaa\x00\x62\xce\x6c'
h264_header_pos = first_buffer.find( h264_header ) + 50
# print( 'h246_header_pos', h264_header_pos, len( first_buffer ))
if Solo:
tbd = 0
audio_header = b'\x91\x07\xDC\xB7\xB7\xA9\xCF\x11\x8E\xE6\x00\xC0\x0C\x20\x53\x65\x72'
audio_header_pos = first_buffer.find( audio_header ) + 0x60 # find audio hdr
first_buffer[audio_header_pos:audio_header_pos+10] = pack("H 8x", 0x9012)
if SB240:
tbd = 0
audio_header = b'\xA1\xDC\xAB\x8C\x47\xA9\xCF\x11\x8E\xE6\x00\xC0\x0C\x20\x53\x65\x68'
audio_header_pos = first_buffer.find( audio_header ) + 0x60 # find audio hdr
first_buffer[audio_header_pos:audio_header_pos+10] = pack("H 8x", 0x9012)
stream_header = first_buffer[0:h264_header_pos]
#print( 'SH', type(stream_header), pbuf(stream_header))
print(name,'Stream started at', ts(), len(stream_header), len(first_buffer[h264_header_pos:]))
for s in streams :
try:
s.sendall(stream_header)
except:
print(name, 'ERROR: Media Player closed connection immediately after receiving 200 OK')
return (s_ctl, None )
# flush header from socket
stream.recv(h264_header_pos)
return s_ctl, stream
def parse_cmd(msg):
# print('Q',msg)
if msg[0] == 0x00 :
return msg[1:].decode('utf-8').split('=')
else:
return 'IR', msg
def check_ip( sling_net_address, retry_count ):
print( name, 'Checking for slingbox at', sling_net_address, retry_count)
cnt = 0
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect(sling_net_address)
print(name, sling_net_address, 'OK')
closeconn(s)
return True
except Exception as e:
closeconn(s)
time.sleep(1)
cnt += 1
if not cnt % 10 : print( name, 'Still waiting for', sling_net_address )
if retry_count == -1 : continue #Forever
if cnt < retry_count: continue
else:
print(name, 'Error connecting to ', sling_net_address)
closeconn(s)
return False
def public_ip(ip):
if ip == '' : return False
if ip.startswith('192.168.'): return False
if ip.startswith('10.'): return False
if ip.startswith('127.0.'): return False
if ip.startswith('172.') :
second_octet = int(ip.split('.')[1])
if second_octet > 15 and second_octet < 33 : return False
return True
def start_streaming_connection(ip):
global num_streams
if public_ip(ip) :
if num_streams == maxstreams :
print( 'Max remote streams', maxstreams, 'reached. Ignoring new streaming request')
return False
num_streams = num_streams + 1
print('Starting remote stream', num_streams )
return True
def close_streaming_connection(s):
global num_streams
if s :
if public_ip(stream_clients[s]) :
num_streams = num_streams - 1
print( num_streams, 'active remote connections')
del stream_clients[s]
streams.remove(s)
return closeconn(s)
return None
def closecontrol(s):
if s :
print( name, 'Logging Out')
try:
if Solo: sling_cmd( 0x68, b'')
except: pass
return closeconn(s)
################## START of Streamer Execution
print('Streamer Running: ', maxstreams, config_fn, section_name, box_name, server_port, max_recv_tcp_buffer)
OK = b'HTTP/1.0 200 OK\r\nContent-type: application/octet-stream\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n'
ERROR =b'HTTP/1.0 503 ERROR\r\nContent-type: application/octet-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n'
stream_clients = {}
cp = ConfigParser()
cp.read(config_fn)
slinginfo = cp[section_name]
slingip = slinginfo.get('ipaddress', '' )
slingport = int(slinginfo.get('port', '5201'))
name = slinginfo.get('name', box_name )
finderid = slinginfo.get('finderid', '' )
if finderid :
# sanity checks
finderid = finderid.strip().upper().split(':')
ext_port = -1
if len(finderid) == 2:
try:
ext_port = int(finderid[1], 10)
if ext_port > 65535: raise
except:
print(name, 'ERROR: Finderid External Port must be between 0-65535')
ext_port = -1
else:
ext_port = server_port
if ext_port != -1:
try:
if (len(finderid[0]) == 32) and int(finderid[0],16):
finderids[ finderid[0]] = ext_port
else : print(name, 'ERROR: Invalid Finderid length. Must be 32 characters', finderid)
except: print(name, 'ERROR: Finderid must only contain hexadecimal characters', finderid)
bts = bco = runt = 0
boxes = []
sling_net_address = (slingip, slingport)
if not check_ip(sling_net_address, int(slinginfo.get('ConnectRetries', '0' ))):
if not public_ip(sling_net_address[0]):
time.sleep(1)
boxes = find_slingbox_info(name)
for box in boxes:
# print('checking', slingip, 'box', box)
if box[0] == slingip:
print(name, 'Found matching IP Address', slingip, 'will use this box, check port number in your config file' )
boxes = [box]
break
if len(boxes) > 1:
print("""Found more than one slingbox on the local network.
Please select the one you want to use and update the config file accordingly.
\n%s Giving up. Sorry..""" % name)
return
if len(boxes) == 1:
slingip = boxes[0][0]
slingport = boxes[0][1]
sling_net_address = (slingip, slingport)
if not boxes:
msg = "Can't find a slingbox on network. Please make sure it's plugged in and connected. Check config.ini"
for port in stati.keys():
stati[port] = msg
print(name, msg)
time.sleep(5)
print( name, 'Giving up. Sorry...')
return
def readnbytes(sock, n):
# print( 'Reading', n )
buff = b''
try:
while n > 0:
b = sock.recv(n)
if len(b) == 0:
return b # peer socket has received a SH_WR shutdown
buff += b
n -= len(b)
except Exception as e:
print(name, 'Error Reading video stream')
buff = b''
return buff
def process_solo_msg( msg, sock ):
def cs( mybuf ):
sum = 0
for byte in mybuf:
sum = sum + byte
return sum
nonlocal tbd, dco, bco, pc, bts, stream_header
# if resolution == 0 : return msg
# print('MSG', pbuf(msg[0:16]))
msg = bytearray( msg )
pmode = unpack(">I", msg[0:4])[0]
pad, pktt, pcnt = unpack("<x I I 2x B", msg[4:16])
header = b''
# print('pmode..', pc, hex(pmode), pad, pktt, pcnt)
if ( pmode & 0xFFFFFFFE ) != 0x82000018 :
magic = bytes(u'Slingbox'.encode('utf-16le'))
# print('MAGIC', magic)
if magic in msg:
print(ts(), name, 'Solo/ProHD Input Video Format Changed. Stream Restarted')
return b'Restart'
off = 16
if pmode == 0x82000018 :
off = 15
pcnt = 1
p = 0
while p < (pcnt & 63) :
# print( "loop", p, off, pcnt & 63);
fmt = "<B x I x I 4x H"
if off > 2983 : break
sn, objoff, objsiz, length = unpack(fmt, msg[off:off+17]);
off += 17
if not pmode & 1 :
off -= 2
length = 2970 - pad
if ( sn == 0x82 or (sn & 63 == 1 )) :
if objoff == 0 : tbd = objsiz & ~15
bts = (bco + length ) & 15
cbd = (bco + length) & ~15
if (cbd):
# print( 'SN', sn, off, tbd, bts, objsiz, objoff, cbd, bco )
if (bco):
# print('Decrypting', bco, off, cbd)
buf = Decrypt(dco + msg[off:off + (cbd - bco)], skey);
dco = buf[0:bco] # fix data carried over
msg[off:off+(cbd - bco)] = buf[bco:] # fix current packet
bco = 0;
else:
# print('DEcrypting', off, cbd, len(msg), pbuf(msg[off:off+cbd]))
buf = Decrypt(msg[off:off+cbd], skey) # decrypt
# print('DEcrypted', pbuf(buf))
msg[off:off+cbd] = buf
tbd -= cbd
if tbd == 0 : bts = 0
if sn == 0x82 and objoff == 0:
break
off += length
# print('off', off, length, pad)
p += 1
# print $out $dco if $dco ne '';
msg = dco + msg
bco = bts
if bco > 0 :
dco = msg[-bts:]
msg = msg[0:-bts]
# print('DCO', bts, pbuf(dco)[7:-2])
else:
dco = b''
return header + msg
def SendKeycode( key, rccode ):
print('sending key', key, rccode )
if '.' in key:
code,chan,subchan = key.split('.')
chan = int(chan)
cmd = bytearray(8)
cmd[0] = int(code)
cmd[1] = 0
cmd[2] = 0
cmd[3] = 0
cmd[4] = chan & 255
cmd[5] = chan >> 8
cmd[6] = int(subchan)
cmd[7] = 0
sling_cmd(0x89, cmd + pack('8x'), msg_type=0x0101)
else:
cmd = bytearray(4)
cmd[0] = int(key)
cmd[1] = 0
cmd[2] = 0
cmd[3] = rccode
sling_cmd(0x87, cmd + pack('467x 4h', cmd[3], 0, 0, 0), msg_type=0x0101)
def send_start_channel( channel, rccode ):
if channel :
if channel != '0':
print(ts(), name, 'Sending Start Channel', channel)
if '+' in channel:
print('Split', channel.split('+'))
for keycode in channel.split('+'):
if keycode : SendKeycode(keycode, rccode)
elif '.' in channel:
SendKeycode( '2.' + channel, 0 )
else:
digits2buttons = ['18','9','10','11','12','13','14','15','16','17']
for digit in channel:
if digit in '0123456789' :
SendKeycode( digits2buttons[int(digit)], rccode)
return None
def parse_stream( header ):
bits = header.split(':')
return ( bits[0]+':'+bits[1], bits[2] )
def RemoteLocked(sender_ip):
if RemoteLock and sender_ip != 'Server' and (sender_ip != primary_stream_client):
print(name, 'Ignoring IR request from', sender_ip, 'Remote Locked by', primary_stream_client )
return True
else: return False
print(name, 'Using slingbox at ', sling_net_address)
while True:
stream_header = None
streams = []
# Wait for first stream request to arrive
cp = ConfigParser()
cp.read(config_fn)
slinginfo = cp[section_name]
name = slinginfo.get('name', box_name).strip()
my_num_streams = 0
my_max_streams = int(slinginfo.get('maxstreams', '10'))
print('Streamer: ', name, 'Waiting for first stream, flushing any IR requests that arrive while not connected to slingbox')
#if box_name == '/' : stati_key = '/'
#else: stati_key = '/'+ box_name
stati[box_name] = 'Waiting for first client. Slingbox at ' + str(sling_net_address)
while True:
cmd, value = parse_cmd(streamer_q.get())
if cmd == 'STREAM': break
client_addr, channel = parse_stream(value)
client_socket = (streamer_q.get()) ## Get the socket to stream on
if not start_streaming_connection(client_addr):
client_socket = closeconn(client_socket)
continue
my_num_streams = 1
cp.read(config_fn)
slinginfo = cp[section_name]
name = slinginfo.get('name', box_name).strip()
sbtype = slinginfo.get('sbtype', "350/500").strip()
# print('DiscoveredSolo', DiscoveredSolo)
if len(boxes) == 1 :
box_type = boxes[0][3]
Solo = box_type < 9
SB240 = box_type == 3
sbtype = productIdDict[box_type]
else:
Solo = 'Solo' in sbtype or 'Pro' in sbtype
SB240 = '240' in sbtype or 'AV' in sbtype
# print('Is Solo', Solo)
password = slinginfo.get('password', 'admin').strip()
if password.upper().startswith('E1:'):
print( name, 'Using encrypted password:', password)
pw = password.upper().replace('E1:', '').strip()
try:
pw_bytes = bytearray.fromhex(pw)
clear = Decrypt(pw_bytes, [0xBCDEAAAA,0x87FBBBBA,0x7CCCCFFA,0xDDDDAABC])
except Exception as e:
print('Bad E1: Password cannot decrypt. Missing/bad characters?', len(pw), e, traceback.print_exc())
return (closeconn(s_ctl), None)
eos = clear.find(b'\x00\x00')
if eos > 0:
password = clear[0:-2:2].decode("utf-8")
else:
print('name, Bad E1: Password Missing characters')
continue
resolution = int(slinginfo.get('Resolution', 12 ))
if resolution < 0 or resolution > 16 :
print(name, 'Invalid Resolution', resolution, 'Defaulting to 640x480')
resolution = 5;
FrameRate = int(slinginfo.get('FrameRate', 30 ))
VideoBandwidth = int(slinginfo.get('VideoBandwidth', 2000 ))
VideoSmoothness = int(slinginfo.get('VideoSmoothness', 63 ))
IframeRate = int(slinginfo.get('IframeRate', 5 ))
AudioBitRate = int(slinginfo.get('AudioBitRate', 64 ))
VideoSource = slinginfo.get('VideoSource', '' )
if channel == '0': StartChannel = slinginfo.get('StartChannel', '' )
else: StartChannel = channel
RemoteLock = slinginfo.get('RemoteLock', '')
if box_name in remotes.keys(): rccode = remotes[box_name][1][2]
if Solo :
if resolution : pksize = 3000
else: pksize = 1636
else: pksize = 3072
print( '\r\nSlinginfo ', sbtype, resolution, FrameRate, slingip, slingport, pksize, my_max_streams, password )
print(name, 'Starting Stream for ', client_addr)
stream_clients[client_socket] = client_addr
primary_stream_client = client_addr.split(':')[0]
streams.append(client_socket)
try:
client_socket.sendall(OK)
s_ctl, stream = start_slingbox_session(streams)
except Exception as e:
print(name, 'Badness starting slingbox session ', e, traceback.print_exc())
continue
if s_ctl and stream :
stati[box_name] = box_name + ' Streaming %d clients. Resolution=%d' % (len(streams), resolution )
pc = 0
stream.settimeout(15)
tick = lasttick = laststatus = lastkeepalive = last_remote_command_time = startchanneltime = time.time()
if not Solo : StartChannel = send_start_channel(StartChannel, rccode)
while streams:
msg = readnbytes(stream, pksize)
if Solo and len(msg) > 0:
try:
msg = process_solo_msg( msg, stream )
except Exception as e:
print(name, 'Error Processing Solo Message. Stopping', e, traceback.print_exc())
break
if len(msg) < 10:
if len(msg) == 0 :
print(ts(), name, 'Bad or Corrupted Solo message')
# Restart
break
if len(msg) == 0 :
print(ts(), name, 'Stream Stopped Unexpectly. Kicked Off?')
break
pc += 1
for stream_socket in streams:
try:
sent = stream_socket.send(msg)
except Exception as e:
if stream_socket in stream_clients.keys():
print(ts(), name, 'Stream Terminated for ', stream_clients[stream_socket])
close_streaming_connection(stream_socket)
else:
print(ts(), name, 'Stream Terminated', e, traceback.print_exc())
streams.remove(stream_socket)
my_num_streams = my_num_streams - 1
continue
msg = b''
if (not streamer_q.empty()):
cmd, data = parse_cmd(streamer_q.get())
print( name, 'Got Streamer Control Message', cmd )
if cmd == 'STREAM' :
new_stream = streamer_q.get()
#print(new_stream)
if my_num_streams == my_max_streams :
print( name, 'Max streams', my_max_streams, 'for this slingbox has been reached. Not starting connection')
new_stream.sendall(ERROR)
new_stream = closeconn(new_stream)
elif not start_streaming_connection(data) :
print(name, 'Video Stream Startup Error')
new_stream.sendall(ERROR)
new_steam = closeconn(new_stream)
else:
my_num_streams = my_num_streams + 1
new_stream.sendall(OK)
stream_clients[new_stream], channel = parse_stream(data)
new_stream.sendall(stream_header)
print( name, 'New Stream Starting', channel)
if channel != '0':
if not RemoteLock : StartChannel = channel
else: print( name, 'RemoteLocked, ignoring channel request')
streams.append(new_stream)
elif cmd == 'ProHD':
channel, sender_ip = data.split(':')
print(ts(), name, 'got ProHD', channel, sender_ip)
stream_ip = primary_stream_client
if not RemoteLocked(sender_ip):
SendKeycode( channel, rccode)
elif cmd == 'IR':
print('IR', data)
for key in data:
sender_ip = key[1:].decode('utf-8')
stream_ip = primary_stream_client
if not RemoteLocked( sender_ip ):
print(ts(), name,'Sending IR keycode', key[0], rccode, 'for', sender_ip)
SendKeycode(str(key[0]), rccode )
curtime = time.time()
if curtime - tick > 0.5: # Only check stuff every
tick = curtime
if curtime - lasttick > 10.0:
print('.', end='')
#print( stati_key, box_name )
stati[box_name] = box_name + ' Streaming %d clients. Resolution=%d Packets=%d' % (len(streams), resolution, pc)
lasttick = curtime
sys.stdout.flush()
if curtime - laststatus > 90.0 :
print(ts()[0:20].replace(' ', ''), name, '%d Clients.' % len(streams), end='')
for c in stream_clients.values(): print( c, end=' ')
print('')
laststatus = curtime
sys.stdout.flush()
if curtime - lastkeepalive > 10.0 :
# print('Sending Keep Alive' )
sling_cmd(0x66, '') # send a keepalive
lastkeepalive = curtime
socket_ready, _, _ = select.select([s_ctl], [], [], 0.0 )
if socket_ready : s_ctl.recv(8192)
if StartChannel :
if curtime - startchanneltime > 10.0 :
StartChannel = send_start_channel(StartChannel, rccode)
### No More Streams OR input stream stopped
print(name, 'Shutting down connections')
s_ctl = closecontrol(s_ctl)
for s in streams : close_streaming_connection(s)
streams = []
stream_clients = {}
my_num_streams = 0
else:
print(name,'ERROR: Slingbox session startup failed.')
if s_ctl : s_ctl = closecontrol(s_ctl)
if stream :
stream = close_streaming_connection(stream)
client_socket.sendall(ERROR)
else:
if public_ip(client_addr.split(':')[0]) :
num_streams = num_streams - 1
print( num_streams, 'active remote connections')
client_socket = closeconn(client_socket)
my_num_streams = 0
print(name, 'Streamer Exiting.. should never get here')
s_ctl = closecontrol(s_ctl)
stream = close_streaming_connection(stream)
client_socket = closeconn(client_socket)
def remote_control_stream( connection, client, request, server_port):
def fix_host(request):
start_host = request.find('Host:')
start_port = request.find(':', start_host + 5 )+1
end_port = request.find('\r\n', start_host)
# print('Fixing', start_port, end_port, request[0:start_port] + str(server_port) + request[end_port:])
return bytes(request[0:start_port] + str(server_port) + '\r\nFrom:%s'%client[0] + request[end_port:], 'utf-8')
http_port = server_port + 1
# print('\r\nStarting remote control stream handler for ', str(client), 'to port', http_port)
remote_control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_control_socket.connect(('127.0.0.1', http_port )) ## Send Packets to Flask
print('Remote Control Connected')
# print('GOT', request )
request = fix_host(request)
remote_control_socket.sendall(request)
sockets = [remote_control_socket, connection]
POST = 'POST'.encode('utf-8')
GET = 'GET'.encode('utf-8')
while True:
# print('Waiting for data')
read_sockets, _, _ = select.select(sockets, [], [])
for sock in read_sockets:
try: data = sock.recv(32768)