|
| 1 | +import ipaddress |
| 2 | +import logging |
| 3 | + |
| 4 | +import miniupnpc |
| 5 | +import trio |
| 6 | + |
| 7 | +logger = logging.getLogger("libp2p.discovery.upnp") |
| 8 | + |
| 9 | + |
| 10 | +class UpnpManager: |
| 11 | + """ |
| 12 | + A simple, self-contained manager for UPnP port mapping that can be used |
| 13 | + alongside a libp2p Host. |
| 14 | + """ |
| 15 | + |
| 16 | + def __init__(self) -> None: |
| 17 | + self._gateway = miniupnpc.UPnP() |
| 18 | + self._lan_addr: str | None = None |
| 19 | + self._external_ip: str | None = None |
| 20 | + |
| 21 | + def _validate_igd(self) -> bool: |
| 22 | + """ |
| 23 | + Validate that the selected device is actually an Internet Gateway Device. |
| 24 | +
|
| 25 | + :return: True if the device is a valid IGD, False otherwise. |
| 26 | + """ |
| 27 | + try: |
| 28 | + # Check if we can get basic IGD information |
| 29 | + if not self._gateway.lanaddr: |
| 30 | + logger.debug("IGD validation failed: No LAN address available") |
| 31 | + return False |
| 32 | + |
| 33 | + # Try to get the external IP - this is a good test of IGD validity |
| 34 | + external_ip = self._gateway.externalipaddress() |
| 35 | + if not external_ip: |
| 36 | + logger.debug("IGD validation failed: No external IP address available") |
| 37 | + return False |
| 38 | + |
| 39 | + # Additional validation: check if we can get the connection type |
| 40 | + # This is a more advanced IGD feature that non-IGD devices typically |
| 41 | + # don't support |
| 42 | + try: |
| 43 | + connection_type = self._gateway.connectiontype() |
| 44 | + if connection_type: |
| 45 | + logger.debug(f"IGD connection type: {connection_type}") |
| 46 | + except Exception: |
| 47 | + # Connection type is optional, so we don't fail if it's not available |
| 48 | + logger.debug("IGD connection type not available (this is optional)") |
| 49 | + |
| 50 | + return True |
| 51 | + except Exception as e: |
| 52 | + logger.debug(f"IGD validation failed: {e}") |
| 53 | + return False |
| 54 | + |
| 55 | + async def discover(self) -> bool: |
| 56 | + """ |
| 57 | + Discover the UPnP IGD on the network. |
| 58 | +
|
| 59 | + :return: True if a gateway is found, False otherwise. |
| 60 | + """ |
| 61 | + logger.debug("Discovering UPnP gateway...") |
| 62 | + try: |
| 63 | + try: |
| 64 | + num_devices = await trio.to_thread.run_sync(self._gateway.discover) |
| 65 | + except Exception as e: |
| 66 | + # The miniupnpc library has a documented quirk where `discover()` can |
| 67 | + # raise an exception with the message "Success" on some platforms |
| 68 | + # (particularly Windows) due to inconsistent error handling in the C |
| 69 | + # library. This is a known issue in miniupnpc where successful |
| 70 | + # discovery sometimes raises an exception instead of returning a count. |
| 71 | + # See: https://github.com/miniupnp/miniupnp/issues/ |
| 72 | + if str(e) == "Success": # type: ignore |
| 73 | + num_devices = 1 |
| 74 | + else: |
| 75 | + logger.exception("UPnP discovery exception") |
| 76 | + return False |
| 77 | + |
| 78 | + if num_devices > 0: |
| 79 | + logger.debug(f"Found {num_devices} UPnP device(s), selecting IGD...") |
| 80 | + try: |
| 81 | + await trio.to_thread.run_sync(self._gateway.selectigd) |
| 82 | + except Exception as e: |
| 83 | + logger.error(f"Failed to select IGD: {e}") |
| 84 | + logger.error( |
| 85 | + "UPnP devices were found, but none are valid Internet " |
| 86 | + "Gateway Devices. Check your router's UPnP/IGD settings." |
| 87 | + ) |
| 88 | + return False |
| 89 | + |
| 90 | + # Validate that the selected device is actually an IGD |
| 91 | + if not await trio.to_thread.run_sync(self._validate_igd): |
| 92 | + logger.error( |
| 93 | + "Selected UPnP device is not a valid Internet Gateway Device. " |
| 94 | + "The device may be a smart home device or other UPnP device " |
| 95 | + "that doesn't support port mapping." |
| 96 | + ) |
| 97 | + return False |
| 98 | + |
| 99 | + self._lan_addr = self._gateway.lanaddr |
| 100 | + self._external_ip = await trio.to_thread.run_sync( |
| 101 | + self._gateway.externalipaddress |
| 102 | + ) |
| 103 | + logger.debug(f"UPnP gateway found: {self._external_ip}") |
| 104 | + |
| 105 | + if self._external_ip is None: |
| 106 | + logger.error("Gateway did not return an external IP address") |
| 107 | + return False |
| 108 | + |
| 109 | + ip_obj = ipaddress.ip_address(self._external_ip) |
| 110 | + if ip_obj.is_private: |
| 111 | + logger.warning( |
| 112 | + "UPnP gateway has a private IP; you may be behind a double NAT." |
| 113 | + ) |
| 114 | + return False |
| 115 | + return True |
| 116 | + else: |
| 117 | + logger.debug("No UPnP devices found") |
| 118 | + return False |
| 119 | + except Exception: |
| 120 | + logger.exception("UPnP discovery failed") |
| 121 | + return False |
| 122 | + |
| 123 | + async def add_port_mapping(self, port: int, protocol: str = "TCP") -> bool: |
| 124 | + """ |
| 125 | + Request a new port mapping from the gateway. |
| 126 | +
|
| 127 | + :param port: the internal port to map |
| 128 | + :param protocol: the protocol to map (TCP or UDP) |
| 129 | + :return: True on success, False otherwise |
| 130 | + """ |
| 131 | + try: |
| 132 | + port = int(port) |
| 133 | + if not 0 < port < 65536: |
| 134 | + logger.error(f"Invalid port number for mapping: {port}") |
| 135 | + return False |
| 136 | + except (ValueError, TypeError): |
| 137 | + logger.error(f"Invalid port value: {port}") |
| 138 | + return False |
| 139 | + if port < 1024: |
| 140 | + logger.warning( |
| 141 | + f"Mapping a well-known (privileged) port ({port}) may fail or " |
| 142 | + "require root." |
| 143 | + ) |
| 144 | + |
| 145 | + if not self._lan_addr: |
| 146 | + logger.error( |
| 147 | + "Cannot add port mapping: discovery has not been run successfully." |
| 148 | + ) |
| 149 | + return False |
| 150 | + |
| 151 | + logger.debug(f"Requesting UPnP mapping for {protocol} port {port}...") |
| 152 | + try: |
| 153 | + await trio.to_thread.run_sync( |
| 154 | + lambda: self._gateway.addportmapping( |
| 155 | + port, protocol, self._lan_addr, port, "py-libp2p", "" |
| 156 | + ) |
| 157 | + ) |
| 158 | + logger.info( |
| 159 | + f"Successfully mapped external port {self._external_ip}:{port} " |
| 160 | + f"to internal port {self._lan_addr}:{port}" |
| 161 | + ) |
| 162 | + return True |
| 163 | + except Exception: |
| 164 | + logger.exception(f"Failed to map port {port}") |
| 165 | + return False |
| 166 | + |
| 167 | + async def remove_port_mapping(self, port: int, protocol: str = "TCP") -> bool: |
| 168 | + """ |
| 169 | + Remove an existing port mapping. |
| 170 | +
|
| 171 | + :param port: the external port to unmap |
| 172 | + :param protocol: the protocol (TCP or UDP) |
| 173 | + :return: True on success, False otherwise |
| 174 | + """ |
| 175 | + try: |
| 176 | + port = int(port) |
| 177 | + if not 0 < port < 65536: |
| 178 | + logger.error(f"Invalid port number for removal: {port}") |
| 179 | + return False |
| 180 | + except (ValueError, TypeError): |
| 181 | + logger.error(f"Invalid port value: {port}") |
| 182 | + return False |
| 183 | + |
| 184 | + logger.debug(f"Removing UPnP mapping for {protocol} port {port}...") |
| 185 | + try: |
| 186 | + await trio.to_thread.run_sync( |
| 187 | + lambda: self._gateway.deleteportmapping(port, protocol) |
| 188 | + ) |
| 189 | + logger.info(f"Successfully removed mapping for port {port}") |
| 190 | + return True |
| 191 | + except Exception: |
| 192 | + logger.exception(f"Failed to remove mapping for port {port}") |
| 193 | + return False |
| 194 | + |
| 195 | + def get_external_ip(self) -> str | None: |
| 196 | + return self._external_ip |
0 commit comments