-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsdd.py
2032 lines (1580 loc) · 72.9 KB
/
wsdd.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 python3
# Implements a target service according to the Web Service Discovery
# specification.
#
# The purpose is to enable non-Windows devices to be found by the 'Network
# (Neighborhood)' from Windows machines.
#
# see http://specs.xmlsoap.org/ws/2005/04/discovery/ws-discovery.pdf and
# related documents for details (look at README for more references)
#
# (c) Steffen Christgau, 2017-2024
import sys
import signal
import socket
import asyncio
import struct
import argparse
import uuid
import time
import random
import logging
import platform
import ctypes.util
import collections
import xml.etree.ElementTree as ElementTree
import http
import http.server
import urllib.request
import urllib.parse
import os
import pwd
import grp
import datetime
from typing import Any, Callable, ClassVar, Deque, Dict, List, Optional, Set, Union, Tuple, TYPE_CHECKING
# try to load more secure XML module first, fallback to default if not present
try:
if not TYPE_CHECKING:
from defusedxml.ElementTree import fromstring as ETfromString
except ModuleNotFoundError:
from xml.etree.ElementTree import fromstring as ETfromString
WSDD_VERSION: str = '0.8'
args: argparse.Namespace
logger: logging.Logger
class NetworkInterface:
_name: str
_index: int
_scope: int
def __init__(self, name: str, scope: int, index: int) -> None:
self._name = name
self._scope = scope
if index is not None:
self._index = index
else:
self._index = socket.if_nametoindex(self._name)
@property
def name(self) -> str:
return self._name
@property
def scope(self) -> int:
return self._scope
@property
def index(self) -> int:
return self._index
def __str__(self) -> str:
return self._name
def __eq__(self, other) -> bool:
return self._name == other.name
class NetworkAddress:
_family: int
_raw_address: bytes
_address_str: str
_interface: NetworkInterface
def __init__(self, family: int, raw: Union[bytes, str], interface: NetworkInterface) -> None:
self._family = family
self._raw_address = raw if isinstance(raw, bytes) else socket.inet_pton(family, raw.partition('%')[0])
self._interface = interface
self._address_str = socket.inet_ntop(self._family, self._raw_address)
@property
def address_str(self):
return self._address_str
@property
def family(self):
return self._family
@property
def interface(self):
return self._interface
@property
def is_multicastable(self):
# Nah, this check is not optimal but there are no local flags for
# addresses, but it should be safe for IPv4 anyways
# (https://tools.ietf.org/html/rfc5735#page-3)
return ((self._family == socket.AF_INET) and (self._raw_address[0] == 127)
or (self._family == socket.AF_INET6) and (self._raw_address[0:2] != b'\xfe\x80'))
@property
def raw(self):
return self._raw_address
@property
def transport_str(self):
"""the string representation of the local address overridden in network setup (for IPv6)"""
return self._address_str if self._family == socket.AF_INET else '[{}]'.format(self._address_str)
def __str__(self) -> str:
return '{}%{}'.format(self._address_str, self._interface.name)
def __eq__(self, other) -> bool:
return (self._family == other.family and self.raw == other.raw and self.interface == other.interface)
class UdpAddress(NetworkAddress):
_transport_address: Tuple
_port: int
def __init__(self, family, transport_address: Tuple, interface: NetworkInterface) -> None:
if not (family == socket.AF_INET or family == socket.AF_INET6):
raise RuntimeError('Unsupport address address family: {}.'.format(family))
self._transport_address = transport_address
self._port = transport_address[1]
super().__init__(family, transport_address[0], interface)
@property
def transport_address(self):
return self._transport_address
@property
def port(self):
return self._port
def __eq__(self, other) -> bool:
return self.transport_address == other.transport_address
class INetworkPacketHandler:
def handle_packet(self, msg: str, udp_src_address: UdpAddress) -> None:
pass
class MulticastHandler:
"""
A class for handling multicast traffic on a given interface for a
given address family. It provides multicast sender and receiver sockets
"""
# base interface addressing information
address: NetworkAddress
# individual interface-bound sockets for:
# - receiving multicast traffic
# - sending multicast from a socket bound to WSD port
# - sending unicast messages from a random port
recv_socket: socket.socket
mc_send_socket: socket.socket
uc_send_socket: socket.socket
# addresses used for communication and data
multicast_address: UdpAddress
listen_address: Tuple
aio_loop: asyncio.AbstractEventLoop
# dictionary that holds INetworkPacketHandlers instances for sockets created above
message_handlers: Dict[socket.socket, List[INetworkPacketHandler]]
def __init__(self, address: NetworkAddress, aio_loop: asyncio.AbstractEventLoop) -> None:
self.address = address
self.recv_socket = socket.socket(self.address.family, socket.SOCK_DGRAM)
self.recv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.mc_send_socket = socket.socket(self.address.family, socket.SOCK_DGRAM)
self.uc_send_socket = socket.socket(self.address.family, socket.SOCK_DGRAM)
self.uc_send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.message_handlers = {}
self.aio_loop = aio_loop
if self.address.family == socket.AF_INET:
self.init_v4()
elif self.address.family == socket.AF_INET6:
self.init_v6()
logger.info('joined multicast group {0} on {1}'.format(self.multicast_address.transport_str, self.address))
logger.debug('transport address on {0} is {1}'.format(self.address.interface.name, self.address.transport_str))
logger.debug('will listen for HTTP traffic on address {0}'.format(self.listen_address))
# register calbacks for incoming data (also for mc)
self.aio_loop.add_reader(self.recv_socket.fileno(), self.read_socket, self.recv_socket)
self.aio_loop.add_reader(self.mc_send_socket.fileno(), self.read_socket, self.mc_send_socket)
self.aio_loop.add_reader(self.uc_send_socket.fileno(), self.read_socket, self.uc_send_socket)
def cleanup(self) -> None:
self.aio_loop.remove_reader(self.recv_socket)
self.aio_loop.remove_reader(self.mc_send_socket)
self.aio_loop.remove_reader(self.uc_send_socket)
self.recv_socket.close()
self.mc_send_socket.close()
self.uc_send_socket.close()
def handles_address(self, address: NetworkAddress) -> bool:
return self.address == address
def init_v6(self) -> None:
idx = self.address.interface.index
raw_mc_addr = (WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0x575C, idx)
self.multicast_address = UdpAddress(self.address.family, raw_mc_addr, self.address.interface)
# v6: member_request = { multicast_addr, intf_idx }
mreq = (socket.inet_pton(self.address.family, WSD_MCAST_GRP_V6) + struct.pack('@I', idx))
self.recv_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
self.recv_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
# Could anyone ask the Linux folks for the rationale for this!?
if platform.system() == 'Linux':
try:
# supported starting from Linux 4.20
IPV6_MULTICAST_ALL = 29
self.recv_socket.setsockopt(socket.IPPROTO_IPV6, IPV6_MULTICAST_ALL, 0)
except OSError as e:
logger.warning('cannot unset all_multicast: {}'.format(e))
# bind to network interface, i.e. scope and handle OS differences,
# see Stevens: Unix Network Programming, Section 21.6, last paragraph
try:
self.recv_socket.bind((WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0, idx))
except OSError:
self.recv_socket.bind(('::', 0, 0, idx))
# bind unicast socket to interface address and WSD's udp port
self.uc_send_socket.bind((str(self.address), WSD_UDP_PORT, 0, idx))
self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, args.hoplimit)
self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, idx)
self.listen_address = (self.address.address_str, WSD_HTTP_PORT, 0, idx)
def init_v4(self) -> None:
idx = self.address.interface.index
raw_mc_addr = (WSD_MCAST_GRP_V4, WSD_UDP_PORT)
self.multicast_address = UdpAddress(self.address.family, raw_mc_addr, self.address.interface)
# v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx }
mreq = (socket.inet_pton(self.address.family, WSD_MCAST_GRP_V4) + self.address.raw + struct.pack('@I', idx))
self.recv_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
if platform.system() == 'Linux':
IP_MULTICAST_ALL = 49
self.recv_socket.setsockopt(socket.IPPROTO_IP, IP_MULTICAST_ALL, 0)
try:
self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT))
except OSError:
self.recv_socket.bind(('', WSD_UDP_PORT))
# bind unicast socket to interface address and WSD's udp port
self.uc_send_socket.bind((self.address.address_str, WSD_UDP_PORT))
self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq)
# OpenBSD requires the optlen to be sizeof(char) for LOOP and TTL options
# (see also https://github.com/python/cpython/issues/67316)
self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, struct.pack('B', 0))
self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, struct.pack('B', args.hoplimit))
self.listen_address = (self.address.address_str, WSD_HTTP_PORT)
def add_handler(self, socket: socket.socket, handler: INetworkPacketHandler) -> None:
# try:
# self.selector.register(socket, selectors.EVENT_READ, self)
# except KeyError:
# # accept attempts of multiple registrations
# pass
if socket in self.message_handlers:
self.message_handlers[socket].append(handler)
else:
self.message_handlers[socket] = [handler]
def remove_handler(self, socket: socket.socket, handler) -> None:
if socket in self.message_handlers:
if handler in self.message_handlers[socket]:
self.message_handlers[socket].remove(handler)
def read_socket(self, key: socket.socket) -> None:
# TODO: refactor this
s = None
if key == self.uc_send_socket:
s = self.uc_send_socket
elif key == self.mc_send_socket:
s = self.mc_send_socket
elif key == self.recv_socket:
s = self.recv_socket
else:
raise ValueError("Unknown socket passed as key.")
msg, raw_address = s.recvfrom(WSD_MAX_LEN)
address = UdpAddress(self.address.family, raw_address, self.address.interface)
if s in self.message_handlers:
for handler in self.message_handlers[s]:
handler.handle_packet(msg.decode('utf-8'), address)
def send(self, msg: bytes, addr: UdpAddress):
# Request from a client must be answered from a socket that is bound
# to the WSD port, i.e. the recv_socket. Messages to multicast
# addresses are sent over the dedicated send socket.
if addr == self.multicast_address:
self.mc_send_socket.sendto(msg, addr.transport_address)
else:
self.uc_send_socket.sendto(msg, addr.transport_address)
# constants for WSD XML/SOAP parsing
WSA_URI: str = 'http://schemas.xmlsoap.org/ws/2004/08/addressing'
WSD_URI: str = 'http://schemas.xmlsoap.org/ws/2005/04/discovery'
WSDP_URI: str = 'http://schemas.xmlsoap.org/ws/2006/02/devprof'
namespaces: Dict[str, str] = {
'soap': 'http://www.w3.org/2003/05/soap-envelope',
'wsa': WSA_URI,
'wsd': WSD_URI,
'wsx': 'http://schemas.xmlsoap.org/ws/2004/09/mex',
'wsdp': WSDP_URI,
'pnpx': 'http://schemas.microsoft.com/windows/pnpx/2005/10',
'pub': 'http://schemas.microsoft.com/windows/pub/2005/07'
}
WSD_MAX_KNOWN_MESSAGES: int = 10
WSD_PROBE: str = WSD_URI + '/Probe'
WSD_PROBE_MATCH: str = WSD_URI + '/ProbeMatches'
WSD_RESOLVE: str = WSD_URI + '/Resolve'
WSD_RESOLVE_MATCH: str = WSD_URI + '/ResolveMatches'
WSD_HELLO: str = WSD_URI + '/Hello'
WSD_BYE: str = WSD_URI + '/Bye'
WSD_GET: str = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Get'
WSD_GET_RESPONSE: str = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse'
WSD_TYPE_DEVICE: str = 'wsdp:Device'
PUB_COMPUTER: str = 'pub:Computer'
WSD_TYPE_DEVICE_COMPUTER: str = '{0} {1}'.format(WSD_TYPE_DEVICE, PUB_COMPUTER)
WSD_MCAST_GRP_V4: str = '239.255.255.250'
WSD_MCAST_GRP_V6: str = 'ff02::c' # link-local
WSA_ANON: str = WSA_URI + '/role/anonymous'
WSA_DISCOVERY: str = 'urn:schemas-xmlsoap-org:ws:2005:04:discovery'
MIME_TYPE_SOAP_XML: str = 'application/soap+xml'
# protocol assignments (WSD spec/Section 2.4)
WSD_UDP_PORT: int = 3702
WSD_HTTP_PORT: int = 5357
WSD_MAX_LEN: int = 32767
WSDD_LISTEN_PORT = 5359
# SOAP/UDP transmission constants
MULTICAST_UDP_REPEAT: int = 4
UNICAST_UDP_REPEAT: int = 2
UDP_MIN_DELAY: int = 50
UDP_MAX_DELAY: int = 250
UDP_UPPER_DELAY: int = 500
# servers must recond in 4 seconds after probe arrives
PROBE_TIMEOUT: int = 4
MAX_STARTUP_PROBE_DELAY: int = 3
# some globals
wsd_instance_id: int = int(time.time())
WSDMessage = Tuple[ElementTree.Element, str]
MessageTypeHandler = Callable[[ElementTree.Element, ElementTree.Element], Optional[WSDMessage]]
class WSDMessageHandler(INetworkPacketHandler):
known_messages: Deque[str] = collections.deque([], WSD_MAX_KNOWN_MESSAGES)
handlers: Dict[str, MessageTypeHandler]
pending_tasks: List[asyncio.Task]
def __init__(self) -> None:
self.handlers = {}
self.pending_tasks = []
def cleanup(self):
pass
# shortcuts for building WSD responses
def add_endpoint_reference(self, parent: ElementTree.Element, endpoint: Optional[str] = None) -> None:
epr = ElementTree.SubElement(parent, 'wsa:EndpointReference')
address = ElementTree.SubElement(epr, 'wsa:Address')
if endpoint is None:
address.text = args.uuid.urn
else:
address.text = endpoint
def add_metadata_version(self, parent: ElementTree.Element) -> None:
meta_data = ElementTree.SubElement(parent, 'wsd:MetadataVersion')
meta_data.text = '1'
def add_types(self, parent: ElementTree.Element) -> None:
dev_type = ElementTree.SubElement(parent, 'wsd:Types')
dev_type.text = WSD_TYPE_DEVICE_COMPUTER
def add_xaddr(self, parent: ElementTree.Element, transport_addr: str) -> None:
if transport_addr:
item = ElementTree.SubElement(parent, 'wsd:XAddrs')
item.text = 'http://{0}:{1}/{2}'.format(transport_addr, WSD_HTTP_PORT, args.uuid)
def build_message(self, to_addr: str, action_str: str, request_header: Optional[ElementTree.Element],
response: ElementTree.Element) -> str:
retval = self.xml_to_str(self.build_message_tree(to_addr, action_str, request_header, response)[0])
logger.debug('constructed xml for WSD message: {0}'.format(retval))
return retval
def build_message_tree(self, to_addr: str, action_str: str, request_header: Optional[ElementTree.Element],
body: Optional[ElementTree.Element]) -> Tuple[ElementTree.Element, str]:
"""
Build a WSD message with a given action string including SOAP header.
The message can be constructed based on a response to another
message (given by its header) and with a optional response that
serves as the message's body
"""
root = ElementTree.Element('soap:Envelope')
header = ElementTree.SubElement(root, 'soap:Header')
to = ElementTree.SubElement(header, 'wsa:To')
to.text = to_addr
action = ElementTree.SubElement(header, 'wsa:Action')
action.text = action_str
msg_id = ElementTree.SubElement(header, 'wsa:MessageID')
msg_id.text = uuid.uuid1().urn
if request_header is not None:
req_msg_id = request_header.find('./wsa:MessageID', namespaces)
if req_msg_id is not None:
relates_to = ElementTree.SubElement(header, 'wsa:RelatesTo')
relates_to.text = req_msg_id.text
self.add_header_elements(header, action_str)
body_root = ElementTree.SubElement(root, 'soap:Body')
if body is not None:
body_root.append(body)
for prefix, uri in namespaces.items():
root.attrib['xmlns:' + prefix] = uri
return root, msg_id.text
def add_header_elements(self, header: ElementTree.Element, extra: Any) -> None:
pass
def handle_message(self, msg: str, src: Optional[UdpAddress] = None) -> Optional[str]:
"""
handle a WSD message
"""
try:
tree = ETfromString(msg)
except ElementTree.ParseError:
return None
header = tree.find('./soap:Header', namespaces)
if header is None:
return None
msg_id_tag = header.find('./wsa:MessageID', namespaces)
if msg_id_tag is None:
return None
msg_id = str(msg_id_tag.text)
# check for duplicates
if self.is_duplicated_msg(msg_id):
logger.debug('known message ({0}): dropping it'.format(msg_id))
return None
action_tag = header.find('./wsa:Action', namespaces)
if action_tag is None:
return None
action: str = str(action_tag.text)
_, _, action_method = action.rpartition('/')
if src:
logger.info('{}:{}({}) - - "{} {} UDP" - -'.format(
src.transport_str, src.port, src.interface, action_method, msg_id))
else:
# http logging is already done by according server
logger.debug('processing WSD {} message ({})'.format(action_method, msg_id))
body = tree.find('./soap:Body', namespaces)
if body is None:
return None
logger.debug('incoming message content is {0}'.format(msg))
if action in self.handlers:
handler = self.handlers[action]
retval = handler(header, body)
if retval is not None:
response, response_type = retval
return self.build_message(WSA_ANON, response_type, header, response)
else:
logger.debug('unhandled action {0}/{1}'.format(action, msg_id))
return None
def is_duplicated_msg(self, msg_id: str) -> bool:
"""
Check for a duplicated message.
Implements SOAP-over-UDP Appendix II Item 2
"""
if msg_id in type(self).known_messages:
return True
type(self).known_messages.append(msg_id)
return False
def xml_to_str(self, xml: ElementTree.Element) -> str:
retval = '<?xml version="1.0" encoding="utf-8"?>'
retval = retval + ElementTree.tostring(xml, encoding='utf-8').decode('utf-8')
return retval
class WSDUDPMessageHandler(WSDMessageHandler):
"""
A message handler that handles traffic received via MutlicastHandler.
"""
mch: MulticastHandler
tearing_down: bool
def __init__(self, mch: MulticastHandler) -> None:
super().__init__()
self.mch = mch
self.tearing_down = False
def teardown(self):
self.tearing_down = True
def send_datagram(self, msg: str, dst: UdpAddress) -> None:
try:
self.mch.send(msg.encode('utf-8'), dst)
except Exception as e:
logger.error('error while sending packet on {}: {}'.format(self.mch.address.interface, e))
def enqueue_datagram(self, msg: str, address: UdpAddress, msg_type: Optional[str] = None) -> None:
if msg_type:
logger.info('scheduling {0} message via {1} to {2}'.format(msg_type, address.interface, address))
schedule_task = self.mch.aio_loop.create_task(self.schedule_datagram(msg, address))
# Add this task to the pending list during teardown to wait during shutdown
if self.tearing_down:
self.pending_tasks.append(schedule_task)
async def schedule_datagram(self, msg: str, address: UdpAddress) -> None:
"""
Schedule to send the given message to the given address.
Implements SOAP over UDP, Appendix I.
"""
self.send_datagram(msg, address)
delta = 0
msg_count = MULTICAST_UDP_REPEAT if address == self.mch.multicast_address else UNICAST_UDP_REPEAT
delta = random.randint(UDP_MIN_DELAY, UDP_MAX_DELAY)
for i in range(msg_count - 1):
await asyncio.sleep(delta / 1000.0)
self.send_datagram(msg, address)
delta = min(delta * 2, UDP_UPPER_DELAY)
class WSDDiscoveredDevice:
# a dict of discovered devices with their UUID as key
instances: Dict[str, 'WSDDiscoveredDevice'] = {}
addresses: Dict[str, Set[str]]
props: Dict[str, str]
display_name: str
last_seen: float
types: Set[str]
def __init__(self, xml_str: str, xaddr: str, interface: NetworkInterface) -> None:
self.last_seen = 0.0
self.addresses = {}
self.props = {}
self.display_name = ''
self.types = set()
self.update(xml_str, xaddr, interface)
def update(self, xml_str: str, xaddr: str, interface: NetworkInterface) -> None:
try:
tree = ETfromString(xml_str)
except ElementTree.ParseError:
return None
mds_path = 'soap:Body/wsx:Metadata/wsx:MetadataSection'
sections = tree.findall(mds_path, namespaces)
for section in sections:
dialect = section.attrib['Dialect']
if dialect == WSDP_URI + '/ThisDevice':
self.extract_wsdp_props(section, dialect)
elif dialect == WSDP_URI + '/ThisModel':
self.extract_wsdp_props(section, dialect)
elif dialect == WSDP_URI + '/Relationship':
host_xpath = 'wsdp:Relationship[@Type="{}/host"]/wsdp:Host'.format(WSDP_URI)
host_sec = section.find(host_xpath, namespaces)
if (host_sec):
self.extract_host_props(host_sec)
else:
logger.debug('unknown metadata dialect ({})'.format(dialect))
url = urllib.parse.urlparse(xaddr)
addr, _, _ = url.netloc.rpartition(':')
report = True
if interface.name not in self.addresses:
self.addresses[interface.name] = set([addr])
else:
if addr not in self.addresses[interface.name]:
self.addresses[interface.name].add(addr)
else:
report = False
self.last_seen = time.time()
if ('DisplayName' in self.props) and ('BelongsTo' in self.props) and (report):
self.display_name = self.props['DisplayName']
logger.info('discovered {} in {} on {}'.format(self.display_name, self.props['BelongsTo'], addr))
elif ('FriendlyName' in self.props) and (report):
self.display_name = self.props['FriendlyName']
logger.info('discovered {} on {}'.format(self.display_name, addr))
logger.debug(str(self.props))
def extract_wsdp_props(self, root: ElementTree.Element, dialect: str) -> None:
_, _, propsRoot = dialect.rpartition('/')
# XPath support is limited, so filter by namespace on our own
nodes = root.findall('./wsdp:{0}/*'.format(propsRoot), namespaces)
ns_prefix = '{{{}}}'.format(WSDP_URI)
prop_nodes = [n for n in nodes if n.tag.startswith(ns_prefix)]
for node in prop_nodes:
tag_name = node.tag[len(ns_prefix):]
self.props[tag_name] = str(node.text)
def extract_host_props(self, root: ElementTree.Element) -> None:
self.types = set(root.findtext('wsdp:Types', '', namespaces).split(' '))
if PUB_COMPUTER not in self.types:
return
comp = root.findtext(PUB_COMPUTER, '', namespaces)
self.props['DisplayName'], _, self.props['BelongsTo'] = (
comp.partition('/'))
class WSDClient(WSDUDPMessageHandler):
instances: ClassVar[List['WSDClient']] = []
probes: Dict[str, float]
def __init__(self, mch: MulticastHandler) -> None:
super().__init__(mch)
WSDClient.instances.append(self)
self.mch.add_handler(self.mch.mc_send_socket, self)
self.mch.add_handler(self.mch.recv_socket, self)
self.probes = {}
self.handlers[WSD_HELLO] = self.handle_hello
self.handlers[WSD_BYE] = self.handle_bye
self.handlers[WSD_PROBE_MATCH] = self.handle_probe_match
self.handlers[WSD_RESOLVE_MATCH] = self.handle_resolve_match
# avoid packet storm when hosts come up by delaying initial probe
time.sleep(random.randint(0, MAX_STARTUP_PROBE_DELAY))
self.send_probe()
def cleanup(self) -> None:
super().cleanup()
WSDClient.instances.remove(self)
self.mch.remove_handler(self.mch.mc_send_socket, self)
self.mch.remove_handler(self.mch.recv_socket, self)
def send_probe(self) -> None:
"""WS-Discovery, Section 4.3, Probe message"""
self.remove_outdated_probes()
probe = ElementTree.Element('wsd:Probe')
ElementTree.SubElement(probe, 'wsd:Types').text = WSD_TYPE_DEVICE
xml, i = self.build_message_tree(WSA_DISCOVERY, WSD_PROBE, None, probe)
self.enqueue_datagram(self.xml_to_str(xml), self.mch.multicast_address, msg_type='Probe')
self.probes[i] = time.time()
def teardown(self) -> None:
super().teardown()
self.remove_outdated_probes()
def handle_packet(self, msg: str, src: Optional[UdpAddress] = None) -> None:
self.handle_message(msg, src)
def __extract_xaddr(self, xaddrs: str) -> Optional[str]:
for addr in xaddrs.strip().split():
if (self.mch.address.family == socket.AF_INET6) and ('//[fe80::' in addr):
# use first link-local address for IPv6
return addr
elif self.mch.address.family == socket.AF_INET:
# use first (and very likely the only) IPv4 address
return addr
return None
def handle_hello(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
pm_path = 'wsd:Hello'
endpoint, xaddrs = self.extract_endpoint_metadata(body, pm_path)
if not xaddrs:
logger.info('Hello without XAddrs, sending resolve')
msg = self.build_resolve_message(str(endpoint))
self.enqueue_datagram(msg, self.mch.multicast_address)
return None
xaddr = self.__extract_xaddr(xaddrs)
if xaddr is None:
return None
logger.info('Hello from {} on {}'.format(endpoint, xaddr))
self.perform_metadata_exchange(endpoint, xaddr)
return None
def handle_bye(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
bye_path = 'wsd:Bye'
endpoint, _ = self.extract_endpoint_metadata(body, bye_path)
device_uuid = str(uuid.UUID(endpoint))
if device_uuid in WSDDiscoveredDevice.instances:
del WSDDiscoveredDevice.instances[device_uuid]
return None
def handle_probe_match(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
# do not handle to probematches issued not sent by ourself
rel_msg = header.findtext('wsa:RelatesTo', None, namespaces)
if rel_msg not in self.probes:
logger.debug("unknown probe {}".format(rel_msg))
return None
# if XAddrs are missing, issue resolve request
pm_path = 'wsd:ProbeMatches/wsd:ProbeMatch'
endpoint, xaddrs = self.extract_endpoint_metadata(body, pm_path)
if not xaddrs:
logger.debug('probe match without XAddrs, sending resolve')
msg = self.build_resolve_message(str(endpoint))
self.enqueue_datagram(msg, self.mch.multicast_address)
return None
xaddr = self.__extract_xaddr(xaddrs)
if xaddr is None:
return None
logger.debug('probe match for {} on {}'.format(endpoint, xaddr))
self.perform_metadata_exchange(endpoint, xaddr)
return None
def build_resolve_message(self, endpoint: str) -> str:
resolve = ElementTree.Element('wsd:Resolve')
self.add_endpoint_reference(resolve, endpoint)
return self.build_message(WSA_DISCOVERY, WSD_RESOLVE, None, resolve)
def handle_resolve_match(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
rm_path = 'wsd:ResolveMatches/wsd:ResolveMatch'
endpoint, xaddrs = self.extract_endpoint_metadata(body, rm_path)
if not endpoint or not xaddrs:
logger.debug('resolve match without endpoint/xaddr')
return None
xaddr = self.__extract_xaddr(xaddrs)
if xaddr is None:
return None
logger.debug('resolve match for {} on {}'.format(endpoint, xaddr))
self.perform_metadata_exchange(endpoint, xaddr)
return None
def extract_endpoint_metadata(self, body: ElementTree.Element, prefix: str) -> Tuple[Optional[str], Optional[str]]:
prefix = prefix + '/'
addr_path = 'wsa:EndpointReference/wsa:Address'
endpoint = body.findtext(prefix + addr_path, namespaces=namespaces)
xaddrs = body.findtext(prefix + 'wsd:XAddrs', namespaces=namespaces)
return endpoint, xaddrs
def perform_metadata_exchange(self, endpoint, xaddr: str):
if not (xaddr.startswith('http://') or xaddr.startswith('https://')):
logger.debug('invalid XAddr: {}'.format(xaddr))
return
host = None
url = xaddr
if self.mch.address.family == socket.AF_INET6:
host = '[{}]'.format(url.partition('[')[2].partition(']')[0])
url = url.replace(']', '%{}]'.format(self.mch.address.interface))
body = self.build_getmetadata_message(endpoint)
request = urllib.request.Request(url, data=body.encode('utf-8'), method='POST')
request.add_header('Content-Type', 'application/soap+xml')
request.add_header('User-Agent', 'wsdd')
if host is not None:
request.add_header('Host', host)
try:
with urllib.request.urlopen(request, None, args.metadata_timeout) as stream:
self.handle_metadata(stream.read(), endpoint, xaddr)
except urllib.error.URLError as e:
logger.warning('could not fetch metadata from: {} {}'.format(url, e))
def build_getmetadata_message(self, endpoint) -> str:
tree, _ = self.build_message_tree(endpoint, WSD_GET, None, None)
return self.xml_to_str(tree)
def handle_metadata(self, meta: str, endpoint: str, xaddr: str) -> None:
device_uuid = str(uuid.UUID(endpoint))
if device_uuid in WSDDiscoveredDevice.instances:
WSDDiscoveredDevice.instances[device_uuid].update(meta, xaddr, self.mch.address.interface)
else:
WSDDiscoveredDevice.instances[device_uuid] = WSDDiscoveredDevice(meta, xaddr, self.mch.address.interface)
def remove_outdated_probes(self) -> None:
cut = time.time() - PROBE_TIMEOUT * 2
self.probes = dict(filter(lambda x: x[1] > cut, self.probes.items()))
def add_header_elements(self, header: ElementTree.Element, extra: Any) -> None:
action_str = extra
if action_str == WSD_GET:
reply_to = ElementTree.SubElement(header, 'wsa:ReplyTo')
addr = ElementTree.SubElement(reply_to, 'wsa:Address')
addr.text = WSA_ANON
wsa_from = ElementTree.SubElement(header, 'wsa:From')
addr = ElementTree.SubElement(wsa_from, 'wsa:Address')
addr.text = args.uuid.urn
class WSDHost(WSDUDPMessageHandler):
"""Class for handling WSD requests coming from UDP datagrams."""
message_number: ClassVar[int] = 0
instances: ClassVar[List['WSDHost']] = []
def __init__(self, mch: MulticastHandler) -> None:
super().__init__(mch)
WSDHost.instances.append(self)
self.mch.add_handler(self.mch.recv_socket, self)
self.handlers[WSD_PROBE] = self.handle_probe
self.handlers[WSD_RESOLVE] = self.handle_resolve
self.send_hello()
def cleanup(self) -> None:
super().cleanup()
WSDHost.instances.remove(self)
def teardown(self) -> None:
super().teardown()
self.send_bye()
def handle_packet(self, msg: str, src: UdpAddress) -> None:
reply = self.handle_message(msg, src)
if reply:
self.enqueue_datagram(reply, src)
def send_hello(self) -> None:
"""WS-Discovery, Section 4.1, Hello message"""
hello = ElementTree.Element('wsd:Hello')
self.add_endpoint_reference(hello)
# THINK: Microsoft does not send the transport address here due to privacy reasons. Could make this optional.
self.add_xaddr(hello, self.mch.address.transport_str)
self.add_metadata_version(hello)
msg = self.build_message(WSA_DISCOVERY, WSD_HELLO, None, hello)
self.enqueue_datagram(msg, self.mch.multicast_address, msg_type='Hello')
def send_bye(self) -> None:
"""WS-Discovery, Section 4.2, Bye message"""
bye = ElementTree.Element('wsd:Bye')
self.add_endpoint_reference(bye)
msg = self.build_message(WSA_DISCOVERY, WSD_BYE, None, bye)
self.enqueue_datagram(msg, self.mch.multicast_address, msg_type='Bye')
def handle_probe(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
probe = body.find('./wsd:Probe', namespaces)
if probe is None:
return None
scopes = probe.find('./wsd:Scopes', namespaces)
if scopes:
# THINK: send fault message (see p. 21 in WSD)
logger.debug('scopes ({}) unsupported but probed'.format(scopes))
return None
types_elem = probe.find('./wsd:Types', namespaces)
if types_elem is None:
logger.debug('Probe message lacks wsd:Types element. Ignored.')
return None
types = types_elem.text
if not types == WSD_TYPE_DEVICE:
logger.debug('unknown discovery type ({}) for probe'.format(types))
return None
matches = ElementTree.Element('wsd:ProbeMatches')
match = ElementTree.SubElement(matches, 'wsd:ProbeMatch')
self.add_endpoint_reference(match)
self.add_types(match)
self.add_metadata_version(match)
return matches, WSD_PROBE_MATCH
def handle_resolve(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]:
resolve = body.find('./wsd:Resolve', namespaces)
if resolve is None:
return None
addr = resolve.find('./wsa:EndpointReference/wsa:Address', namespaces)
if addr is None:
logger.debug('invalid resolve request: missing endpoint address')
return None
if not addr.text == args.uuid.urn:
logger.debug('invalid resolve request: address ({}) does not match own one ({})'.format(
addr.text, args.uuid.urn))
return None
matches = ElementTree.Element('wsd:ResolveMatches')
match = ElementTree.SubElement(matches, 'wsd:ResolveMatch')
self.add_endpoint_reference(match)
self.add_types(match)
self.add_xaddr(match, self.mch.address.transport_str)
self.add_metadata_version(match)
return matches, WSD_RESOLVE_MATCH
def add_header_elements(self, header: ElementTree.Element, extra: Any):
ElementTree.SubElement(header, 'wsd:AppSequence', {
'InstanceId': str(wsd_instance_id),
'SequenceId': uuid.uuid1().urn,
'MessageNumber': str(type(self).message_number)})
type(self).message_number += 1