-
Notifications
You must be signed in to change notification settings - Fork 174
Add NAT traversal via UPnP port mapping #771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GautamBytes
wants to merge
12
commits into
libp2p:main
Choose a base branch
from
GautamBytes:feat/upnp-nat-traversal
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
3c2de79
feat(upnp): add NAT traversal via UPnP port mapping
GautamBytes 25ff339
Merge branch 'main' into feat/upnp-nat-traversal
seetadev 30a285b
Merge branch 'main' into feat/upnp-nat-traversal
seetadev d7b6e7c
Merge branch 'main' into feat/upnp-nat-traversal
seetadev 24c4750
Merge branch 'main' into feat/upnp-nat-traversal
seetadev 4a7e125
Merge branch 'main' into feat/upnp-nat-traversal
seetadev 9e9a60a
Integrate UPnP into Host lifecycle
GautamBytes 191ced5
Merge branch 'main' into feat/upnp-nat-traversal
seetadev c8a12b1
Merge branch 'main' into feat/upnp-nat-traversal
seetadev eae7ab1
Merge branch 'main' into feat/upnp-nat-traversal
GautamBytes 68adc86
Improve UPnP implementation with tests
GautamBytes 23ebda1
Merge branch 'feat/upnp-nat-traversal' of https://github.com/GautamBy…
GautamBytes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# UPnP Example | ||
|
||
This example demonstrates how to use the integrated UPnP behaviour to automatically create a port mapping on your local network's gateway (e.g., your home router). | ||
|
||
This allows peers from the public internet to directly dial your node, which is a crucial step for NAT traversal. | ||
|
||
## Usage | ||
|
||
First, ensure you have installed the necessary dependencies from the root of the repository: | ||
|
||
```sh | ||
pip install -e ".[upnp]" | ||
``` | ||
|
||
Then, run the script in a terminal: | ||
|
||
```sh | ||
python examples/upnp/upnp_demo.py | ||
``` | ||
|
||
The script will start a libp2p host and immediately try to discover a UPnP-enabled gateway on the network. | ||
|
||
- If it **succeeds**, it will print the new external address that has been mapped. | ||
- If it **fails** (e.g., your router doesn't have UPnP enabled or you're behind a double NAT), it will print a descriptive error message. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import argparse | ||
import logging | ||
|
||
import multiaddr | ||
import trio | ||
|
||
from libp2p import new_host | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger("upnp-demo") | ||
|
||
|
||
async def run(port: int) -> None: | ||
listen_maddr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") | ||
host = new_host(enable_upnp=True) | ||
|
||
async with host.run(listen_addrs=[listen_maddr]): | ||
try: | ||
logger.info(f"Host started with ID: {host.get_id().pretty()}") | ||
logger.info(f"Listening on: {host.get_addrs()}") | ||
logger.info("Host is running. Press Ctrl+C to shut down.") | ||
logger.info("If UPnP discovery was successful, ports are now mapped.") | ||
await trio.sleep_forever() | ||
except KeyboardInterrupt: | ||
logger.info("Shutting down...") | ||
finally: | ||
# UPnP teardown is automatic via host.run() | ||
logger.info("Shutdown complete.") | ||
|
||
|
||
def main() -> None: | ||
parser = argparse.ArgumentParser(description="UPnP example for py-libp2p") | ||
parser.add_argument( | ||
"-p", "--port", type=int, default=0, help="Local TCP port (0 for random)" | ||
) | ||
args = parser.parse_args() | ||
|
||
try: | ||
trio.run(run, args.port) | ||
except KeyboardInterrupt: | ||
pass | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
import ipaddress | ||
import logging | ||
|
||
try: | ||
import miniupnpc # type: ignore[import-error] | ||
except ImportError: | ||
miniupnpc = None | ||
import trio | ||
|
||
logger = logging.getLogger("libp2p.discovery.upnp") | ||
|
||
|
||
class UpnpManager: | ||
""" | ||
A simple, self-contained manager for UPnP port mapping that can be used | ||
alongside a libp2p Host. | ||
""" | ||
|
||
def __init__(self) -> None: | ||
if miniupnpc is None: | ||
raise RuntimeError( | ||
"UPnP support requires the miniupnpc library; " | ||
"install with `pip install libp2p[upnp]`" | ||
) | ||
self._gateway = miniupnpc.UPnP() | ||
self._lan_addr: str | None = None | ||
self._external_ip: str | None = None | ||
|
||
async def discover(self) -> bool: | ||
""" | ||
Discover the UPnP IGD on the network. | ||
|
||
:return: True if a gateway is found, False otherwise. | ||
""" | ||
logger.debug("Discovering UPnP gateway...") | ||
try: | ||
try: | ||
num_devices = await trio.to_thread.run_sync(self._gateway.discover) | ||
except Exception as e: | ||
# The miniupnpc library has a known quirk where `discover()` can | ||
# raise an exception with the message "Success" on some platforms | ||
# (e.g., Windows) instead of returning a number of devices. We treat | ||
# this as a successful discovery of 1 device. | ||
if str(e) == "Success": # type: ignore | ||
num_devices = 1 | ||
else: | ||
logger.exception("UPnP discovery exception") | ||
return False | ||
|
||
if num_devices > 0: | ||
await trio.to_thread.run_sync(self._gateway.selectigd) | ||
self._lan_addr = self._gateway.lanaddr | ||
self._external_ip = await trio.to_thread.run_sync( | ||
self._gateway.externalipaddress | ||
) | ||
logger.debug(f"UPnP gateway found: {self._external_ip}") | ||
|
||
if self._external_ip is None: | ||
logger.error("Gateway did not return an external IP address") | ||
return False | ||
|
||
ip_obj = ipaddress.ip_address(self._external_ip) | ||
if ip_obj.is_private: | ||
logger.warning( | ||
"UPnP gateway has a private IP; you may be behind a double NAT." | ||
) | ||
return False | ||
return True | ||
else: | ||
logger.debug("No UPnP devices found") | ||
return False | ||
except Exception: | ||
logger.exception("UPnP discovery failed") | ||
return False | ||
|
||
async def add_port_mapping(self, port: int, protocol: str = "TCP") -> bool: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if port <= 0 or port > 65535:
logger.error(f"Invalid port number: {port}")
return False
if port < 1024:
logger.warning(f"Mapping a well-known port: {port} (may fail)") Setting up these kinds of warning for sketchy port numbers in the params, would save computation time in cases of misbehaviour. Also add similar checks to |
||
""" | ||
Request a new port mapping from the gateway. | ||
|
||
:param port: the internal port to map | ||
:param protocol: the protocol to map (TCP or UDP) | ||
:return: True on success, False otherwise | ||
""" | ||
if not 0 < port < 65536: | ||
logger.error(f"Invalid port number for mapping: {port}") | ||
return False | ||
if port < 1024: | ||
logger.warning( | ||
f"Mapping a well-known (privileged) port ({port}) may fail or " | ||
"require root." | ||
) | ||
|
||
if not self._lan_addr: | ||
logger.error( | ||
"Cannot add port mapping: discovery has not been run successfully." | ||
) | ||
return False | ||
|
||
logger.debug(f"Requesting UPnP mapping for {protocol} port {port}...") | ||
try: | ||
await trio.to_thread.run_sync( | ||
lambda: self._gateway.addportmapping( | ||
port, protocol, self._lan_addr, port, "py-libp2p", "" | ||
) | ||
) | ||
logger.info( | ||
f"Successfully mapped external port {self._external_ip}:{port} " | ||
f"to internal port {self._lan_addr}:{port}" | ||
) | ||
return True | ||
except Exception: | ||
logger.exception(f"Failed to map port {port}") | ||
return False | ||
|
||
async def remove_port_mapping(self, port: int, protocol: str = "TCP") -> bool: | ||
""" | ||
Remove an existing port mapping. | ||
|
||
:param port: the external port to unmap | ||
:param protocol: the protocol (TCP or UDP) | ||
:return: True on success, False otherwise | ||
""" | ||
if not 0 < port < 65536: | ||
logger.error(f"Invalid port number for removal: {port}") | ||
return False | ||
|
||
logger.debug(f"Removing UPnP mapping for {protocol} port {port}...") | ||
try: | ||
await trio.to_thread.run_sync( | ||
lambda: self._gateway.deleteportmapping(port, protocol) | ||
) | ||
logger.info(f"Successfully removed mapping for port {port}") | ||
return True | ||
except Exception: | ||
logger.exception(f"Failed to remove mapping for port {port}") | ||
return False | ||
|
||
def get_external_ip(self) -> str | None: | ||
return self._external_ip |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
UpnpManager
would benefit with unit testsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure , will be adding that asap!