forked from lgladdy/SkyRemote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skyRemote.py
1741 lines (1548 loc) · 51.1 KB
/
skyRemote.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
# Based on Craig Heffner's Miranda - http://code.google.com/p/miranda-upnp/
# Licensed under GPL v3
try:
import sys,os
from socket import *
from urllib2 import URLError, HTTPError
from platform import system as thisSystem
import xml.dom.minidom as minidom
import IN,urllib,urllib2
import readline,time
import pickle
import struct
import base64
import re
import getopt
except Exception,e:
print 'Unmet dependency:',e
sys.exit(1)
#Most of the cmdCompleter class was originally written by John Kenyan
#It serves to tab-complete commands inside the program's shell
class cmdCompleter:
def __init__(self,commands):
self.commands = commands
#Traverses the list of available commands
def traverse(self,tokens,tree):
retVal = []
#If there are no commands, or no user input, return null
if tree is None or len(tokens) == 0:
return []
#If there is only one word, only auto-complete the primary commands
elif len(tokens) == 1:
retVal = [x+' ' for x in tree if x.startswith(tokens[0])]
#Else auto-complete for the sub-commands
elif tokens[0] in tree.keys():
retVal = self.traverse(tokens[1:],tree[tokens[0]])
return retVal
#Returns a list of possible commands that match the partial command that the user has entered
def complete(self,text,state):
try:
tokens = readline.get_line_buffer().split()
if not tokens or readline.get_line_buffer()[-1] == ' ':
tokens.append('')
results = self.traverse(tokens,self.commands) + [None]
return results[state]
except:
return
#UPNP class for getting, sending and parsing SSDP/SOAP XML data (among other things...)
class upnp:
ip = False
port = False
completer = False
msearchHeaders = {
'MAN' : '"ssdp:discover"',
'MX' : '2'
}
DEFAULT_IP = "239.255.255.250"
DEFAULT_PORT = 1900
UPNP_VERSION = '1.0'
MAX_RECV = 8192
HTTP_HEADERS = []
ENUM_HOSTS = {}
VERBOSE = False
UNIQ = False
DEBUG = False
LOG_FILE = False
IFACE = None
STARS = '****************************************************************'
csock = False
ssock = False
def __init__(self,ip,port,iface,appCommands):
if appCommands:
self.completer = cmdCompleter(appCommands)
if self.initSockets(ip,port,iface) == False:
print 'UPNP class initialization failed!'
print 'Bye!'
sys.exit(1)
else:
self.soapEnd = re.compile('<\/.*:envelope>')
#Initialize default sockets
def initSockets(self,ip,port,iface):
if self.csock:
self.csock.close()
if self.ssock:
self.ssock.close()
if iface != None:
self.IFACE = iface
if not ip:
ip = self.DEFAULT_IP
if not port:
port = self.DEFAULT_PORT
self.port = port
self.ip = ip
try:
#This is needed to join a multicast group
self.mreq = struct.pack("4sl",inet_aton(ip),INADDR_ANY)
#Set up client socket
self.csock = socket(AF_INET,SOCK_DGRAM)
self.csock.setsockopt(IPPROTO_IP,IP_MULTICAST_TTL,2)
#Set up server socket
self.ssock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)
self.ssock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
#Only bind to this interface
if self.IFACE != None:
print '\nBinding to interface',self.IFACE,'...\n'
self.ssock.setsockopt(SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len(self.IFACE)+1,), self.IFACE))
self.csock.setsockopt(SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len(self.IFACE)+1,), self.IFACE))
try:
self.ssock.bind(('',self.port))
except Exception, e:
print "WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port,e)
try:
self.ssock.setsockopt(IPPROTO_IP,IP_ADD_MEMBERSHIP,self.mreq)
except Exception, e:
print 'WARNING: Failed to join multicast group:',e
except Exception, e:
print "Failed to initialize UPNP sockets:",e
return False
return True
#Clean up file/socket descriptors
def cleanup(self):
if self.LOG_FILE != False:
self.LOG_FILE.close()
self.csock.close()
self.ssock.close()
#Send network data
def send(self,data,socket):
#By default, use the client socket that's part of this class
if socket == False:
socket = self.csock
try:
socket.sendto(data,(self.ip,self.port))
return True
except Exception, e:
print "SendTo method failed for %s:%d : %s" % (self.ip,self.port,e)
return False
#Listen for network data
def listen(self,size,socket):
if socket == False:
socket = self.ssock
try:
return socket.recv(size)
except:
return False
#Create new UDP socket on ip, bound to port
def createNewListener(self,ip,port):
try:
newsock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)
newsock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
newsock.bind((ip,port))
return newsock
except:
return False
#Return the class's primary server socket
def listener(self):
return self.ssock
#Return the class's primary client socket
def sender(self):
return self.csock
#Parse a URL, return the host and the page
def parseURL(self,url):
delim = '://'
host = False
page = False
#Split the host and page
try:
(host,page) = url.split(delim)[1].split('/',1)
page = '/' + page
except:
#If '://' is not in the url, then it's not a full URL, so assume that it's just a relative path
page = url
return (host,page)
#Pull the name of the device type from a device type string
#The device type string looks like: 'urn:schemas-upnp-org:device:WANDevice:1'
def parseDeviceTypeName(self,string):
delim1 = 'device:'
delim2 = ':'
if delim1 in string and not string.endswith(delim1):
return string.split(delim1)[1].split(delim2,1)[0]
return False
#Pull the name of the service type from a service type string
#The service type string looks like: 'urn:schemas-upnp-org:service:Layer3Forwarding:1'
def parseServiceTypeName(self,string):
delim1 = 'service:'
delim2 = ':'
if delim1 in string and not string.endswith(delim1):
return string.split(delim1)[1].split(delim2,1)[0]
return False
#Pull the header info for the specified HTTP header - case insensitive
def parseHeader(self,data,header):
delimiter = "%s:" % header
defaultRet = False
lowerDelim = delimiter.lower()
dataArray = data.split("\r\n")
#Loop through each line of the headers
for line in dataArray:
lowerLine = line.lower()
#Does this line start with the header we're looking for?
if lowerLine.startswith(lowerDelim):
try:
return line.split(':',1)[1].strip()
except:
print "Failure parsing header data for %s" % header
return defaultRet
#Extract the contents of a single XML tag from the data
def extractSingleTag(self,data,tag):
startTag = "<%s" % tag
endTag = "</%s>" % tag
try:
tmp = data.split(startTag)[1]
index = tmp.find('>')
if index != -1:
index += 1
return tmp[index:].split(endTag)[0].strip()
except:
pass
return None
#Parses SSDP notify and reply packets, and populates the ENUM_HOSTS dict
def parseSSDPInfo(self,data,showUniq,verbose):
hostFound = False
foundLocation = False
messageType = False
xmlFile = False
host = False
page = False
upnpType = None
knownHeaders = {
'NOTIFY' : 'notification',
'HTTP/1.1 200 OK' : 'reply'
}
#Use the class defaults if these aren't specified
if showUniq == False:
showUniq = self.UNIQ
if verbose == False:
verbose = self.VERBOSE
#Is the SSDP packet a notification, a reply, or neither?
for text,messageType in knownHeaders.iteritems():
if data.upper().startswith(text):
break
else:
messageType = False
#If this is a notification or a reply message...
if messageType != False:
#Get the host name and location of it's main UPNP XML file
xmlFile = self.parseHeader(data,"LOCATION")
upnpType = self.parseHeader(data,"SERVER")
(host,page) = self.parseURL(xmlFile)
if upnpType.find('SKY') == -1:
return False
#Update xmlFile to be description0.xml. Sky has two service points, and for now we only support the SkyPlay endpoint
xmlFile = "http://"+host+"/description0.xml"
#Sanity check to make sure we got all the info we need
if xmlFile == False or host == False or page == False:
print 'ERROR parsing recieved header:'
print self.STARS
print data
print self.STARS
print ''
return False
#Get the protocol in use (i.e., http, https, etc)
protocol = xmlFile.split('://')[0]+'://'
#Check if we've seen this host before; add to the list of hosts if:
# 1. This is a new host
# 2. We've already seen this host, but the uniq hosts setting is disabled
for hostID,hostInfo in self.ENUM_HOSTS.iteritems():
if hostInfo['name'] == host:
hostFound = True
if self.UNIQ:
return False
if (hostFound and not self.UNIQ) or not hostFound:
#Get the new host's index number and create an entry in ENUM_HOSTS
index = len(self.ENUM_HOSTS)
self.ENUM_HOSTS[index] = {
'name' : host,
'dataComplete' : False,
'proto' : protocol,
'xmlFile' : xmlFile,
'serverType' : None,
'upnpServer' : upnpType,
'deviceList' : {}
}
#Be sure to update the command completer so we can tab complete through this host's data structure
self.updateCmdCompleter(self.ENUM_HOSTS)
#Print out some basic device info
print "Found a Sky Box at "+host[:-6]
return "complete"
#Send GET request for a UPNP XML file
def getXML(self,url):
headers = {
'USER-AGENT':'SKY_skyplus',
'CONTENT-TYPE':'text/xml; charset="utf-8"'
}
try:
#Use urllib2 for the request, it's awesome
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req)
output = response.read()
headers = response.info()
return (headers,output)
except Exception, e:
print "Request for '%s' failed: %s" % (url,e)
return (False,False)
#Send SOAP request
def sendSOAP(self,hostName,serviceType,controlURL,actionName,actionArguments):
argList = ''
soapResponse = ''
if '://' in controlURL:
urlArray = controlURL.split('/',3)
if len(urlArray) < 4:
controlURL = '/'
else:
controlURL = '/' + urlArray[3]
soapRequest = 'POST %s HTTP/1.1\r\n' % controlURL
#Check if a port number was specified in the host name; default is port 80
if ':' in hostName:
hostNameArray = hostName.split(':')
host = hostNameArray[0]
try:
port = int(hostNameArray[1])
except:
print 'Invalid port specified for host connection:',hostName[1]
return False
else:
host = hostName
port = 80
#Create a string containing all of the SOAP action's arguments and values
for arg,(val,dt) in actionArguments.iteritems():
argList += '<%s>%s</%s>' % (arg,val,arg)
#Create the SOAP request
soapBody = '<?xml version="1.0" encoding="utf-8"?>'\
'<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'\
'<s:Body>'\
'<u:%s xmlns:u="%s">'\
'%s'\
'</u:%s>'\
'</s:Body>'\
'</s:Envelope>' % (actionName,serviceType,argList,actionName)
actualServiceType = serviceType[:-2] + "2:2"
#Specify the headers to send with the request
headers = {
'Host':hostName[:-6],
'Content-Length':len(soapBody),
'Content-Type':'text/xml; charset="utf-8"',
'User-Agent':'SKY_skyplus',
'SOAPACTION':'"%s#%s"' % (actualServiceType,actionName),
'connection':'close'
}
#Generate the final payload
for head,value in headers.iteritems():
soapRequest += '%s: %s\r\n' % (head,value)
soapRequest += '\r\n%s' % soapBody
#Send data and go into recieve loop
try:
sock = socket(AF_INET,SOCK_STREAM)
sock.connect((host,port))
sock.send(soapRequest)
while True:
data = sock.recv(self.MAX_RECV)
if not data:
break
else:
soapResponse += data
if self.soapEnd.search(soapResponse.lower()) != None:
break
sock.close()
(header,body) = soapResponse.split('\r\n\r\n',1)
if not header.upper().startswith('HTTP/1.1 200'):
print 'SOAP request failed with error code:',header.split('\r\n')[0].split(' ',1)[1]
errorMsg = self.extractSingleTag(body,'errorDescription')
if errorMsg:
print 'SOAP error message:',errorMsg
return False
else:
return body
except Exception, e:
print 'Caught socket exception:',e
sock.close()
return False
except KeyboardInterrupt:
sock.close()
return False
#Display all info for a given host
def showCompleteHostInfo(self,index,fp):
na = 'N/A'
serviceKeys = ['controlURL','eventSubURL','serviceId','SCPDURL','fullName']
if fp == False:
fp = sys.stdout
if index < 0 or index >= len(self.ENUM_HOSTS):
fp.write('Specified host does not exist...\n')
return
try:
hostInfo = self.ENUM_HOSTS[index]
if hostInfo['dataComplete'] == False:
print "Cannot show all host info because we don't have it all yet. Try running 'host info %d' first...\n" % index
fp.write('Host name: %s\n' % hostInfo['name'])
fp.write('UPNP XML File: %s\n\n' % hostInfo['xmlFile'])
fp.write('\nDevice information:\n')
for deviceName,deviceStruct in hostInfo['deviceList'].iteritems():
fp.write('\tDevice Name: %s\n' % deviceName)
for serviceName,serviceStruct in deviceStruct['services'].iteritems():
fp.write('\t\tService Name: %s\n' % serviceName)
for key in serviceKeys:
fp.write('\t\t\t%s: %s\n' % (key,serviceStruct[key]))
fp.write('\t\t\tServiceActions:\n')
for actionName,actionStruct in serviceStruct['actions'].iteritems():
fp.write('\t\t\t\t%s\n' % actionName)
for argName,argStruct in actionStruct['arguments'].iteritems():
fp.write('\t\t\t\t\t%s \n' % argName)
for key,val in argStruct.iteritems():
if key == 'relatedStateVariable':
fp.write('\t\t\t\t\t\t%s:\n' % val)
for k,v in serviceStruct['serviceStateVariables'][val].iteritems():
fp.write('\t\t\t\t\t\t\t%s: %s\n' % (k,v))
else:
fp.write('\t\t\t\t\t\t%s: %s\n' % (key,val))
except Exception, e:
print 'Caught exception while showing host info:',e
#Wrapper function...
def getHostInfo(self,xmlData,xmlHeaders,index):
if self.ENUM_HOSTS[index]['dataComplete'] == True:
return
if index >= 0 and index < len(self.ENUM_HOSTS):
try:
xmlRoot = minidom.parseString(xmlData)
self.parseDeviceInfo(xmlRoot,index)
self.ENUM_HOSTS[index]['serverType'] = xmlHeaders.getheader('Server')
self.ENUM_HOSTS[index]['dataComplete'] = True
return True
except Exception, e:
print 'Caught exception while getting host info:',e
return False
#Parse device info from the retrieved XML file
def parseDeviceInfo(self,xmlRoot,index):
deviceEntryPointer = False
devTag = "device"
deviceType = "deviceType"
deviceListEntries = "deviceList"
deviceTags = ["friendlyName","modelDescription","modelName","modelNumber","modelURL","presentationURL","UDN","UPC","manufacturer","manufacturerURL"]
#Find all device entries listed in the XML file
for device in xmlRoot.getElementsByTagName(devTag):
try:
#Get the deviceType string
deviceTypeName = str(device.getElementsByTagName(deviceType)[0].childNodes[0].data)
except:
continue
#Pull out the action device name from the deviceType string
deviceDisplayName = self.parseDeviceTypeName(deviceTypeName)
if not deviceDisplayName:
continue
#Create a new device entry for this host in the ENUM_HOSTS structure
deviceEntryPointer = self.ENUM_HOSTS[index][deviceListEntries][deviceDisplayName] = {}
deviceEntryPointer['fullName'] = deviceTypeName
#Parse out all the device tags for that device
for tag in deviceTags:
try:
deviceEntryPointer[tag] = str(device.getElementsByTagName(tag)[0].childNodes[0].data)
except Exception, e:
if self.VERBOSE:
print 'Device',deviceEntryPointer['fullName'],'does not have a',tag
continue
#Get a list of all services for this device listing
self.parseServiceList(device,deviceEntryPointer,index)
return
#Parse the list of services specified in the XML file
def parseServiceList(self,xmlRoot,device,index):
serviceEntryPointer = False
dictName = "services"
serviceListTag = "serviceList"
serviceTag = "service"
serviceNameTag = "serviceType"
serviceTags = ["serviceId","controlURL","eventSubURL","SCPDURL"]
try:
device[dictName] = {}
#Get a list of all services offered by this device
for service in xmlRoot.getElementsByTagName(serviceListTag)[0].getElementsByTagName(serviceTag):
#Get the full service descriptor
serviceName = str(service.getElementsByTagName(serviceNameTag)[0].childNodes[0].data)
#Get the service name from the service descriptor string
serviceDisplayName = self.parseServiceTypeName(serviceName)
if not serviceDisplayName:
continue
#Create new service entry for the device in ENUM_HOSTS
serviceEntryPointer = device[dictName][serviceDisplayName] = {}
serviceEntryPointer['fullName'] = serviceName
#Get all of the required service info and add it to ENUM_HOSTS
for tag in serviceTags:
serviceEntryPointer[tag] = str(service.getElementsByTagName(tag)[0].childNodes[0].data)
#Get specific service info about this service
self.parseServiceInfo(serviceEntryPointer,index)
except Exception, e:
print 'Caught exception while parsing device service list:',e
#Parse details about each service (arguements, variables, etc)
def parseServiceInfo(self,service,index):
argIndex = 0
argTags = ['direction','relatedStateVariable']
actionList = 'actionList'
actionTag = 'action'
nameTag = 'name'
argumentList = 'argumentList'
argumentTag = 'argument'
#Get the full path to the service's XML file
xmlFile = self.ENUM_HOSTS[index]['proto'] + self.ENUM_HOSTS[index]['name']
if not xmlFile.endswith('/') and not service['SCPDURL'].startswith('/'):
xmlFile += '/'
if self.ENUM_HOSTS[index]['proto'] in service['SCPDURL']:
xmlFile = service['SCPDURL']
else:
xmlFile += service['SCPDURL']
service['actions'] = {}
#Get the XML file that describes this service
(xmlHeaders,xmlData) = self.getXML(xmlFile)
if not xmlData:
print 'Failed to retrieve service descriptor located at:',xmlFile
return False
try:
xmlRoot = minidom.parseString(xmlData)
#Get a list of actions for this service
try:
actionList = xmlRoot.getElementsByTagName(actionList)[0]
except:
print 'Failed to retrieve action list for service %s!' % service['fullName']
return False
actions = actionList.getElementsByTagName(actionTag)
if actions == []:
print 'Failed to retrieve actions from service actions list for service %s!' % service['fullName']
return False
#Parse all actions in the service's action list
for action in actions:
#Get the action's name
try:
actionName = str(action.getElementsByTagName(nameTag)[0].childNodes[0].data).strip()
except:
print 'Failed to obtain service action name (%s)!' % service['fullName']
continue
#Add the action to the ENUM_HOSTS dictonary
service['actions'][actionName] = {}
service['actions'][actionName]['arguments'] = {}
#Parse all of the action's arguments
try:
argList = action.getElementsByTagName(argumentList)[0]
except:
#Some actions may take no arguments, so continue without raising an error here...
continue
#Get all the arguments in this action's argument list
arguments = argList.getElementsByTagName(argumentTag)
if arguments == []:
if self.VERBOSE:
print 'Action',actionName,'has no arguments!'
continue
#Loop through the action's arguments, appending them to the ENUM_HOSTS dictionary
for argument in arguments:
try:
argName = str(argument.getElementsByTagName(nameTag)[0].childNodes[0].data)
except:
print 'Failed to get argument name for',actionName
continue
service['actions'][actionName]['arguments'][argName] = {}
#Get each required argument tag value and add them to ENUM_HOSTS
for tag in argTags:
try:
service['actions'][actionName]['arguments'][argName][tag] = str(argument.getElementsByTagName(tag)[0].childNodes[0].data)
except:
print 'Failed to find tag %s for argument %s!' % (tag,argName)
continue
#Parse all of the state variables for this service
self.parseServiceStateVars(xmlRoot,service)
except Exception, e:
print 'Caught exception while parsing Service info for service %s: %s' % (service['fullName'],str(e))
return False
return True
#Get info about a service's state variables
def parseServiceStateVars(self,xmlRoot,servicePointer):
na = 'N/A'
varVals = ['sendEvents','dataType','defaultValue','allowedValues']
serviceStateTable = 'serviceStateTable'
stateVariable = 'stateVariable'
nameTag = 'name'
dataType = 'dataType'
sendEvents = 'sendEvents'
allowedValueList = 'allowedValueList'
allowedValue = 'allowedValue'
allowedValueRange = 'allowedValueRange'
minimum = 'minimum'
maximum = 'maximum'
#Create the serviceStateVariables entry for this service in ENUM_HOSTS
servicePointer['serviceStateVariables'] = {}
#Get a list of all state variables associated with this service
try:
stateVars = xmlRoot.getElementsByTagName(serviceStateTable)[0].getElementsByTagName(stateVariable)
except:
#Don't necessarily want to throw an error here, as there may be no service state variables
return False
#Loop through all state variables
for var in stateVars:
for tag in varVals:
#Get variable name
try:
varName = str(var.getElementsByTagName(nameTag)[0].childNodes[0].data)
except:
print 'Failed to get service state variable name for service %s!' % servicePointer['fullName']
continue
servicePointer['serviceStateVariables'][varName] = {}
try:
servicePointer['serviceStateVariables'][varName]['dataType'] = str(var.getElementsByTagName(dataType)[0].childNodes[0].data)
except:
servicePointer['serviceStateVariables'][varName]['dataType'] = na
try:
servicePointer['serviceStateVariables'][varName]['sendEvents'] = str(var.getElementsByTagName(sendEvents)[0].childNodes[0].data)
except:
servicePointer['serviceStateVariables'][varName]['sendEvents'] = na
servicePointer['serviceStateVariables'][varName][allowedValueList] = []
#Get a list of allowed values for this variable
try:
vals = var.getElementsByTagName(allowedValueList)[0].getElementsByTagName(allowedValue)
except:
pass
else:
#Add the list of allowed values to the ENUM_HOSTS dictionary
for val in vals:
servicePointer['serviceStateVariables'][varName][allowedValueList].append(str(val.childNodes[0].data))
#Get allowed value range for this variable
try:
valList = var.getElementsByTagName(allowedValueRange)[0]
except:
pass
else:
#Add the max and min values to the ENUM_HOSTS dictionary
servicePointer['serviceStateVariables'][varName][allowedValueRange] = []
try:
servicePointer['serviceStateVariables'][varName][allowedValueRange].append(str(valList.getElementsByTagName(minimum)[0].childNodes[0].data))
servicePointer['serviceStateVariables'][varName][allowedValueRange].append(str(valList.getElementsByTagName(maximum)[0].childNodes[0].data))
except:
pass
return True
#Update the command completer
def updateCmdCompleter(self,struct):
indexOnlyList = {
'host' : ['get','details','summary'],
'save' : ['info']
}
hostCommand = 'host'
subCommandList = ['info']
sendCommand = 'send'
try:
structPtr = {}
topLevelKeys = {}
for key,val in struct.iteritems():
structPtr[str(key)] = val
topLevelKeys[str(key)] = None
#Update the subCommandList
for subcmd in subCommandList:
self.completer.commands[hostCommand][subcmd] = None
self.completer.commands[hostCommand][subcmd] = structPtr
#Update the indexOnlyList
for cmd,data in indexOnlyList.iteritems():
for subcmd in data:
self.completer.commands[cmd][subcmd] = topLevelKeys
#This is for updating the sendCommand key
structPtr = {}
for hostIndex,hostData in struct.iteritems():
host = str(hostIndex)
structPtr[host] = {}
if hostData.has_key('deviceList'):
for device,deviceData in hostData['deviceList'].iteritems():
structPtr[host][device] = {}
if deviceData.has_key('services'):
for service,serviceData in deviceData['services'].iteritems():
structPtr[host][device][service] = {}
if serviceData.has_key('actions'):
for action,actionData in serviceData['actions'].iteritems():
structPtr[host][device][service][action] = None
self.completer.commands[hostCommand][sendCommand] = structPtr
except Exception,e:
print "Error updating command completer structure; some command completion features might not work..."
return
################## Action Functions ######################
#These functions handle user commands from the shell
#Actively search for UPNP devices
def msearch(argc,argv,hp):
defaultST = "upnp:rootdevice"
#Fix coda "
st = "schemas-upnp-org"
myip = ''
lport = hp.port
if argc >= 3:
if argc == 4:
st = argv[1]
searchType = argv[2]
searchName = argv[3]
else:
searchType = argv[1]
searchName = argv[2]
st = "urn:%s:%s:%s:%s" % (st,searchType,searchName,hp.UPNP_VERSION.split('.')[0])
else:
st = defaultST
#Build the request
request = "M-SEARCH * HTTP/1.1\r\n"\
"HOST:%s:%d\r\n"\
"ST:%s\r\n" % (hp.ip,hp.port,st)
for header,value in hp.msearchHeaders.iteritems():
request += header + ':' + value + "\r\n"
request += "\r\n"
print "Entering discovery mode for '%s', Ctl+C to stop..." % st
print ''
#Have to create a new socket since replies will be sent directly to our IP, not the multicast IP
server = hp.createNewListener(myip,lport)
if server == False:
print 'Failed to bind port %d' % lport
return
hp.send(request,server)
while True:
try:
hp.parseSSDPInfo(hp.listen(1024,server),False,False)
except Exception, e:
print 'Discover mode halted...'
break
#Passively listen for UPNP NOTIFY packets
def pcap(argc,argv,hp):
print 'Waiting for Sky+HD Box. This may take up to 30 seconds...'
search = True
while search:
try:
result = hp.parseSSDPInfo(hp.listen(1024,False),False,False)
if result == 'complete':
search = False
except Exception, e:
print "Search halted..."
break
#Manipulate M-SEARCH header values
def head(argc,argv,hp):
if argc >= 2:
action = argv[1]
#Show current headers
if action == 'show':
for header,value in hp.msearchHeaders.iteritems():
print header,':',value
return
#Delete the specified header
elif action == 'del':
if argc == 3:
header = argv[2]
if hp.msearchHeaders.has_key(header):
del hp.msearchHeaders[header]
print '%s removed from header list' % header
return
else:
print '%s is not in the current header list' % header
return
#Create/set a headers
elif action == 'set':
if argc == 4:
header = argv[2]
value = argv[3]
hp.msearchHeaders[header] = value
print "Added header: '%s:%s" % (header,value)
return
showHelp(argv[0])
#Manipulate application settings
def seti(argc,argv,hp):
if argc >= 2:
action = argv[1]
if action == 'uniq':
hp.UNIQ = toggleVal(hp.UNIQ)
print "Show unique hosts set to: %s" % hp.UNIQ
return
elif action == 'debug':
hp.DEBUG = toggleVal(hp.DEBUG)
print "Debug mode set to: %s" % hp.DEBUG
return
elif action == 'verbose':
hp.VERBOSE = toggleVal(hp.VERBOSE)
print "Verbose mode set to: %s" % hp.VERBOSE
return
elif action == 'version':
if argc == 3:
hp.UPNP_VERSION = argv[2]
print 'UPNP version set to: %s' % hp.UPNP_VERSION
else:
showHelp(argv[0])
return
elif action == 'iface':
if argc == 3:
hp.IFACE = argv[2]
print 'Interface set to %s, re-binding sockets...' % hp.IFACE
if hp.initSockets(hp.ip,hp.port,hp.IFACE):
print 'Interface change successful!'
else:
print 'Failed to bind new interface - are you sure you have root privilages??'
hp.IFACE = None
return
elif action == 'socket':
if argc == 3:
try:
(ip,port) = argv[2].split(':')
port = int(port)
hp.ip = ip
hp.port = port
hp.cleanup()
if hp.initSockets(ip,port,hp.IFACE) == False:
print "Setting new socket %s:%d failed!" % (ip,port)
else:
print "Using new socket: %s:%d" % (ip,port)
except Exception, e:
print 'Caught exception setting new socket:',e
return
elif action == 'show':
print 'Multicast IP: ',hp.ip
print 'Multicast Port: ',hp.port
print 'Network Interface: ',hp.IFACE
print 'Number of known hosts: ',len(hp.ENUM_HOSTS)
print 'UPNP Version: ',hp.UPNP_VERSION
print 'Debug mode: ',hp.DEBUG
print 'Verbose mode: ',hp.VERBOSE
print 'Show only unique hosts:',hp.UNIQ
print 'Using log file: ',hp.LOG_FILE
return
showHelp(argv[0])
return
#Host command. It's kind of big.
def host(argc,argv,hp):
indexList = []
indexError = "Host index out of range. Try the 'host list' command to get a list of known hosts"
if argc >= 2:
action = argv[1]
if action == 'list':
if len(hp.ENUM_HOSTS) == 0:
print "No known hosts - try running the 'msearch' or 'pcap' commands"
return
for index,hostInfo in hp.ENUM_HOSTS.iteritems():
print "\t[%d] %s" % (index,hostInfo['name'])
return
elif action == 'details':
hostInfo = False
if argc == 3:
try:
index = int(argv[2])
except Exception, e:
print indexError
return
if index < 0 or index >= len(hp.ENUM_HOSTS):
print indexError
return
hostInfo = hp.ENUM_HOSTS[index]
try:
#If this host data is already complete, just display it
if hostInfo['dataComplete'] == True:
hp.showCompleteHostInfo(index,False)
else:
print "Can't show host info because I don't have it. Please run 'host get %d'" % index
except KeyboardInterrupt, e:
pass
return
elif action == 'summary':
if argc == 3:
try:
index = int(argv[2])
hostInfo = hp.ENUM_HOSTS[index]
except:
print indexError
return
print 'Host:',hostInfo['name']
print 'XML File:',hostInfo['xmlFile']
for deviceName,deviceData in hostInfo['deviceList'].iteritems():
print deviceName
for k,v in deviceData.iteritems():
try:
v.has_key(False)
except:
print "\t%s: %s" % (k,v)
print ''