PortMapper.cpp 10 KB

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