PortMapper.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifdef ZT_USE_MINIUPNPC
  14. // Uncomment to dump debug messages
  15. // #define ZT_PORTMAPPER_TRACE 1
  16. #ifdef __ANDROID__
  17. #include <android/log.h>
  18. #define PM_TRACE(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, "PortMapper", __VA_ARGS__))
  19. #else
  20. #define PM_TRACE(...) fprintf(stderr, __VA_ARGS__)
  21. #endif
  22. #include "../node/Utils.hpp"
  23. #include "OSUtils.hpp"
  24. #include "PortMapper.hpp"
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <string>
  29. // These must be defined to get rid of dynamic export stuff in libminiupnpc and libnatpmp
  30. #ifdef __WINDOWS__
  31. #ifndef MINIUPNP_STATICLIB
  32. #define MINIUPNP_STATICLIB
  33. #endif
  34. #ifndef STATICLIB
  35. #define STATICLIB
  36. #endif
  37. #endif
  38. #ifdef ZT_USE_SYSTEM_MINIUPNPC
  39. #include <miniupnpc/miniupnpc.h>
  40. #include <miniupnpc/upnpcommands.h>
  41. #else
  42. #include "../ext/miniupnpc/miniupnpc.h"
  43. #include "../ext/miniupnpc/upnpcommands.h"
  44. #endif
  45. #ifdef ZT_USE_SYSTEM_NATPMP
  46. #include <natpmp.h>
  47. #else
  48. #ifdef __ANDROID__
  49. #include "natpmp.h"
  50. #else
  51. #include "../ext/libnatpmp/natpmp.h"
  52. #endif
  53. #endif
  54. namespace ZeroTier {
  55. class PortMapperImpl {
  56. public:
  57. PortMapperImpl(int localUdpPortToMap, const char* un) : run(true), localPort(localUdpPortToMap), uniqueName(un)
  58. {
  59. }
  60. ~PortMapperImpl()
  61. {
  62. }
  63. void threadMain() throw()
  64. {
  65. int mode = 0; // 0 == NAT-PMP, 1 == UPnP
  66. int retrytime = 500;
  67. #ifdef ZT_PORTMAPPER_TRACE
  68. fprintf(stderr, "PortMapper: started for UDP port %d" ZT_EOL_S, localPort);
  69. #endif
  70. while (run) {
  71. {
  72. // use initnatpmp to check if we can bind a port at all
  73. natpmp_t _natpmp;
  74. int result = initnatpmp(&_natpmp, 0, 0);
  75. if (result == NATPMP_ERR_CANNOTGETGATEWAY || result == NATPMP_ERR_SOCKETERROR) {
  76. closenatpmp(&_natpmp);
  77. #ifdef ZT_PORTMAPPER_TRACE
  78. PM_TRACE("PortMapper: init failed %d. You might not have an internet connection yet. Trying again in %d" ZT_EOL_S, result, retrytime);
  79. #endif
  80. Thread::sleep(retrytime);
  81. retrytime = retrytime * 2;
  82. if (retrytime > ZT_PORTMAPPER_REFRESH_DELAY / 10) {
  83. retrytime = ZT_PORTMAPPER_REFRESH_DELAY / 10;
  84. }
  85. continue;
  86. }
  87. else {
  88. closenatpmp(&_natpmp);
  89. retrytime = 500;
  90. }
  91. }
  92. // ---------------------------------------------------------------------
  93. // NAT-PMP mode (preferred)
  94. // ---------------------------------------------------------------------
  95. if (mode == 0) {
  96. natpmp_t natpmp;
  97. natpmpresp_t response;
  98. int r = 0;
  99. bool natPmpSuccess = false;
  100. for (int tries = 0; tries < 60; ++tries) {
  101. int tryPort = (int)localPort + tries;
  102. if (tryPort >= 65535)
  103. tryPort = (tryPort - 65535) + 1025;
  104. memset(&natpmp, 0, sizeof(natpmp));
  105. memset(&response, 0, sizeof(response));
  106. if (initnatpmp(&natpmp, 0, 0) != 0) {
  107. mode = 1;
  108. closenatpmp(&natpmp);
  109. #ifdef ZT_PORTMAPPER_TRACE
  110. PM_TRACE("PortMapper: NAT-PMP: init failed, switching to UPnP mode" ZT_EOL_S);
  111. #endif
  112. break;
  113. }
  114. InetAddress publicAddress;
  115. sendpublicaddressrequest(&natpmp);
  116. int64_t myTimeout = OSUtils::now() + 5000;
  117. do {
  118. fd_set fds;
  119. struct timeval timeout;
  120. FD_ZERO(&fds);
  121. FD_SET(natpmp.s, &fds);
  122. getnatpmprequesttimeout(&natpmp, &timeout);
  123. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  124. r = readnatpmpresponseorretry(&natpmp, &response);
  125. if (OSUtils::now() >= myTimeout)
  126. break;
  127. } while (r == NATPMP_TRYAGAIN);
  128. if (r == 0) {
  129. publicAddress = InetAddress((uint32_t)response.pnu.publicaddress.addr.s_addr, 0);
  130. }
  131. else {
  132. #ifdef ZT_PORTMAPPER_TRACE
  133. PM_TRACE("PortMapper: NAT-PMP: request for external address failed, aborting..." ZT_EOL_S);
  134. #endif
  135. closenatpmp(&natpmp);
  136. break;
  137. }
  138. sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_UDP, localPort, tryPort, (ZT_PORTMAPPER_REFRESH_DELAY * 2) / 1000);
  139. myTimeout = OSUtils::now() + 10000;
  140. do {
  141. fd_set fds;
  142. struct timeval timeout;
  143. FD_ZERO(&fds);
  144. FD_SET(natpmp.s, &fds);
  145. getnatpmprequesttimeout(&natpmp, &timeout);
  146. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  147. r = readnatpmpresponseorretry(&natpmp, &response);
  148. if (OSUtils::now() >= myTimeout)
  149. break;
  150. } while (r == NATPMP_TRYAGAIN);
  151. if (r == 0) {
  152. publicAddress.setPort(response.pnu.newportmapping.mappedpublicport);
  153. #ifdef ZT_PORTMAPPER_TRACE
  154. char paddr[128];
  155. PM_TRACE("PortMapper: NAT-PMP: mapped %u to %s" ZT_EOL_S, (unsigned int)localPort, publicAddress.toString(paddr));
  156. #endif
  157. Mutex::Lock sl(surface_l);
  158. surface.clear();
  159. surface.push_back(publicAddress);
  160. natPmpSuccess = true;
  161. closenatpmp(&natpmp);
  162. break;
  163. }
  164. else {
  165. closenatpmp(&natpmp);
  166. // continue
  167. }
  168. }
  169. if (! natPmpSuccess) {
  170. mode = 1;
  171. #ifdef ZT_PORTMAPPER_TRACE
  172. PM_TRACE("PortMapper: NAT-PMP: request failed, switching to UPnP mode" ZT_EOL_S);
  173. #endif
  174. continue;
  175. }
  176. }
  177. // ---------------------------------------------------------------------
  178. // ---------------------------------------------------------------------
  179. // UPnP mode
  180. // ---------------------------------------------------------------------
  181. if (mode == 1) {
  182. char lanaddr[4096];
  183. char externalip[4096]; // no range checking? so make these buffers larger than any UDP packet a uPnP server could send us as a precaution :P
  184. char inport[16];
  185. char outport[16];
  186. struct UPNPUrls urls;
  187. struct IGDdatas data;
  188. int upnpError = 0;
  189. UPNPDev* devlist = upnpDiscoverAll(5000, (const char*)0, (const char*)0, 0, 0, 2, &upnpError);
  190. if (devlist) {
  191. #ifdef ZT_PORTMAPPER_TRACE
  192. {
  193. UPNPDev* dev = devlist;
  194. while (dev) {
  195. PM_TRACE("PortMapper: found UPnP device at URL '%s': %s" ZT_EOL_S, dev->descURL, dev->st);
  196. dev = dev->pNext;
  197. }
  198. }
  199. #endif
  200. memset(lanaddr, 0, sizeof(lanaddr));
  201. memset(externalip, 0, sizeof(externalip));
  202. memset(&urls, 0, sizeof(urls));
  203. memset(&data, 0, sizeof(data));
  204. OSUtils::ztsnprintf(inport, sizeof(inport), "%d", localPort);
  205. int foundValidIGD = 0;
  206. if ((foundValidIGD = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr))) && (lanaddr[0])) {
  207. #ifdef ZT_PORTMAPPER_TRACE
  208. PM_TRACE("PortMapper: UPnP: my LAN IP address: %s" ZT_EOL_S, lanaddr);
  209. #endif
  210. if ((UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalip) == UPNPCOMMAND_SUCCESS) && (externalip[0])) {
  211. #ifdef ZT_PORTMAPPER_TRACE
  212. PM_TRACE("PortMapper: UPnP: my external IP address: %s" ZT_EOL_S, externalip);
  213. #endif
  214. for (int tries = 0; tries < 60; ++tries) {
  215. int tryPort = (int)localPort + tries;
  216. if (tryPort >= 65535)
  217. tryPort = (tryPort - 65535) + 1025;
  218. OSUtils::ztsnprintf(outport, sizeof(outport), "%u", tryPort);
  219. // First check and see if this port is already mapped to the
  220. // same unique name. If so, keep this mapping and don't try
  221. // to map again since this can break buggy routers. But don't
  222. // fail if this command fails since not all routers support it.
  223. {
  224. char haveIntClient[128]; // 128 == big enough for all these as per miniupnpc "documentation"
  225. char haveIntPort[128];
  226. char haveDesc[128];
  227. char haveEnabled[128];
  228. char haveLeaseDuration[128];
  229. memset(haveIntClient, 0, sizeof(haveIntClient));
  230. memset(haveIntPort, 0, sizeof(haveIntPort));
  231. memset(haveDesc, 0, sizeof(haveDesc));
  232. memset(haveEnabled, 0, sizeof(haveEnabled));
  233. memset(haveLeaseDuration, 0, sizeof(haveLeaseDuration));
  234. if ((UPNP_GetSpecificPortMappingEntry(urls.controlURL, data.first.servicetype, outport, "UDP", (const char*)0, haveIntClient, haveIntPort, haveDesc, haveEnabled, haveLeaseDuration) == UPNPCOMMAND_SUCCESS)
  235. && (uniqueName == haveDesc)) {
  236. #ifdef ZT_PORTMAPPER_TRACE
  237. PM_TRACE("PortMapper: UPnP: reusing previously reserved external port: %s" ZT_EOL_S, outport);
  238. #endif
  239. Mutex::Lock sl(surface_l);
  240. surface.clear();
  241. InetAddress tmp(externalip);
  242. tmp.setPort(tryPort);
  243. surface.push_back(tmp);
  244. break;
  245. }
  246. }
  247. // Try to map this port
  248. int mapResult = 0;
  249. if ((mapResult = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, outport, inport, lanaddr, uniqueName.c_str(), "UDP", (const char*)0, "0")) == UPNPCOMMAND_SUCCESS) {
  250. #ifdef ZT_PORTMAPPER_TRACE
  251. PM_TRACE("PortMapper: UPnP: reserved external port: %s" ZT_EOL_S, outport);
  252. #endif
  253. Mutex::Lock sl(surface_l);
  254. surface.clear();
  255. InetAddress tmp(externalip);
  256. tmp.setPort(tryPort);
  257. surface.push_back(tmp);
  258. break;
  259. }
  260. else {
  261. #ifdef ZT_PORTMAPPER_TRACE
  262. PM_TRACE("PortMapper: UPnP: UPNP_AddPortMapping(%s) failed: %d" ZT_EOL_S, outport, mapResult);
  263. #endif
  264. Thread::sleep(1000);
  265. }
  266. }
  267. }
  268. else {
  269. mode = 0;
  270. #ifdef ZT_PORTMAPPER_TRACE
  271. PM_TRACE("PortMapper: UPnP: UPNP_GetExternalIPAddress failed, returning to NAT-PMP mode" ZT_EOL_S);
  272. #endif
  273. }
  274. }
  275. else {
  276. mode = 0;
  277. #ifdef ZT_PORTMAPPER_TRACE
  278. PM_TRACE("PortMapper: UPnP: UPNP_GetValidIGD failed, returning to NAT-PMP mode" ZT_EOL_S);
  279. #endif
  280. }
  281. freeUPNPDevlist(devlist);
  282. if (foundValidIGD) {
  283. FreeUPNPUrls(&urls);
  284. }
  285. }
  286. else {
  287. mode = 0;
  288. #ifdef ZT_PORTMAPPER_TRACE
  289. PM_TRACE("PortMapper: upnpDiscover failed, returning to NAT-PMP mode: %d" ZT_EOL_S, upnpError);
  290. #endif
  291. }
  292. }
  293. // ---------------------------------------------------------------------
  294. #ifdef ZT_PORTMAPPER_TRACE
  295. PM_TRACE("UPNPClient: rescanning in %d ms" ZT_EOL_S, ZT_PORTMAPPER_REFRESH_DELAY);
  296. #endif
  297. Thread::sleep(ZT_PORTMAPPER_REFRESH_DELAY);
  298. }
  299. delete this;
  300. }
  301. volatile bool run;
  302. int localPort;
  303. std::string uniqueName;
  304. Mutex surface_l;
  305. std::vector<InetAddress> surface;
  306. };
  307. PortMapper::PortMapper(int localUdpPortToMap, const char* uniqueName)
  308. {
  309. _impl = new PortMapperImpl(localUdpPortToMap, uniqueName);
  310. Thread::start(_impl);
  311. }
  312. PortMapper::~PortMapper()
  313. {
  314. _impl->run = false;
  315. }
  316. std::vector<InetAddress> PortMapper::get() const
  317. {
  318. Mutex::Lock _l(_impl->surface_l);
  319. return _impl->surface;
  320. }
  321. } // namespace ZeroTier
  322. #endif // ZT_USE_MINIUPNPC