| 1 | import ipaddress |
| 2 | import socket |
| 3 | import sys |
| 4 | import time |
| 5 | from urllib.parse import urlsplit |
| 6 | |
| 7 | |
| 8 | def description_location(packet, sender, gateway): |
| 9 | if sender != (gateway, 1900) or len(packet) > 8192: |
| 10 | return None |
| 11 | try: |
| 12 | header, _ = packet.decode("ascii").split("\r\n\r\n", 1) |
| 13 | status, *lines = header.split("\r\n") |
| 14 | if status != "HTTP/1.1 200 OK": |
| 15 | return None |
| 16 | headers = {} |
| 17 | for line in lines: |
| 18 | name, value = line.split(":", 1) |
| 19 | if not name or any(not (c.isalnum() or c in "!#$%&'*+-.^_`|~") for c in name): |
| 20 | return None |
| 21 | name = name.lower() |
| 22 | if name in headers: |
| 23 | return None |
| 24 | headers[name] = value.strip(" \t") |
| 25 | if headers.get("st") != "upnp:rootdevice": |
| 26 | return None |
| 27 | location = headers["location"] |
| 28 | if any(ord(c) <= 32 or ord(c) >= 127 for c in location): |
| 29 | return None |
| 30 | url = urlsplit(location) |
| 31 | if (url.scheme != "http" or url.hostname != gateway or url.port == 0 |
| 32 | or url.username is not None or url.password is not None |
| 33 | or url.fragment or not url.path.startswith("/")): |
| 34 | return None |
| 35 | return location |
| 36 | except (ValueError, KeyError): |
| 37 | return None |
| 38 | |
| 39 | |
| 40 | def discover(gateway, timeout=3.0): |
| 41 | gateway = str(ipaddress.IPv4Address(gateway)) |
| 42 | request = ( |
| 43 | 'M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\n' |
| 44 | 'MAN: "ssdp:discover"\r\nMX: 1\r\nST: upnp:rootdevice\r\n\r\n' |
| 45 | ).encode("ascii") |
| 46 | deadline = time.monotonic() + timeout |
| 47 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp: |
| 48 | udp.settimeout(timeout) |
| 49 | udp.sendto(request, (gateway, 1900)) |
| 50 | for _ in range(64): |
| 51 | remaining = deadline - time.monotonic() |
| 52 | if remaining <= 0: |
| 53 | break |
| 54 | udp.settimeout(remaining) |
| 55 | try: |
| 56 | packet, sender = udp.recvfrom(8193) |
| 57 | except socket.timeout: |
| 58 | break |
| 59 | location = description_location(packet, sender, gateway) |
| 60 | if location is not None: |
| 61 | return location |
| 62 | raise TimeoutError(f"No valid UPnP description from {gateway}:1900") |
| 63 | |
| 64 | |
| 65 | if __name__ == "__main__": |
| 66 | if len(sys.argv) != 2: |
| 67 | sys.exit("Usage: upnp-discover.py GATEWAY_IPV4") |
| 68 | try: |
| 69 | print(discover(sys.argv[1])) |
| 70 | except (OSError, ValueError) as error: |
| 71 | sys.exit(str(error)) |