heiher / natmap

TCP/UDP port mapping for full cone NAT
MIT License
1.3k stars 98 forks source link

Add more relaxed open socket #11

Closed lars18th closed 1 year ago

lars18th commented 1 year ago

Hi,

I know that the technical base of this tool is to open the socket from the bind port. But in some platforms the current implementation fails with messages like:

for UDP:

[E] get_sock src/hev-sock.c:66
[E] hev_sock_client_tcp src/hev-sock.c:130
[E] tnsk_run src/hev-tnsk.c:93

or for TCP:

[E] get_sock src/hev-sock.c:66
[E] hev_sock_client_udp src/hev-sock.c:189
[E] unsk_run src/hev-unsk.c:48

If you check the source code, the trouble is gneerated in these lines: https://github.com/heiher/natmap/blob/2075302a059d9b8f6d174658fe8e099c38a83639/src/hev-sock.c#L63-L66

And althrough this error could be created by insufficient privileges to bind to that port, in some platforms the problem is different: for example because the socket can't be opened reusing the address:port. But this could not be a problem if you use the firewall method to redirect the incoming connections. In this case you could bind without the REUSE options and all will continue working. The only requirement in this case is that you can't open other process using the same "bind" port for listening.

Therefore, I suggest that you incorporate these two changes:

  1. Spplit the check for the SO_REUSEADDR from the SO_REUSEPORT option. The reason is to know which call is specifically responsible of the error.
  2. Convert these errors to warnings. Then the user could use the firewall method in platforms without reuse support.

Please, consider it. Regards.

lars18th commented 1 year ago

Hi,

This is more or less a dirty example of what I request:

diff --git a/src/hev-sock.c b/src/hev-sock.c
index 874aded..eb46ee8 100644
--- a/src/hev-sock.c
+++ b/src/hev-sock.c
@@ -61,11 +61,18 @@ get_sock (struct addrinfo *ai)
     }

     res |= setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof (int));
+    if (res < 0) {
+        LOG (E);
+        // WARNING only;
+        //close (fd);
+        //return -1;
+    }
     res |= setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof (int));
     if (res < 0) {
         LOG (E);
-        close (fd);
-        return -1;
+        // WARNING only;
+        //close (fd);
+        //return -1;
     }

     return fd;
heiher commented 1 year ago

Pushed: https://github.com/heiher/natmap/commit/068e8dd04a91f6a0c8bb1aa7fd6a14fc16240a66

Thanks for your suggestion.