PortMapper.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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: 2025-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 <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <string>
  26. #include "../node/Utils.hpp"
  27. #include "OSUtils.hpp"
  28. #include "PortMapper.hpp"
  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. #ifdef __ANDROID__
  43. #include "miniupnpc.h"
  44. #include "upnpcommands.h"
  45. #else
  46. #include "../ext/miniupnpc/miniupnpc.h"
  47. #include "../ext/miniupnpc/upnpcommands.h"
  48. #endif
  49. #endif
  50. #ifdef ZT_USE_SYSTEM_NATPMP
  51. #include <natpmp.h>
  52. #else
  53. #ifdef __ANDROID__
  54. #include "natpmp.h"
  55. #else
  56. #include "../ext/libnatpmp/natpmp.h"
  57. #endif
  58. #endif
  59. namespace ZeroTier {
  60. class PortMapperImpl
  61. {
  62. public:
  63. PortMapperImpl(int localUdpPortToMap,const char *un) :
  64. run(true),
  65. localPort(localUdpPortToMap),
  66. uniqueName(un)
  67. {
  68. }
  69. ~PortMapperImpl() {}
  70. void threadMain()
  71. throw()
  72. {
  73. int mode = 0; // 0 == NAT-PMP, 1 == UPnP
  74. #ifdef ZT_PORTMAPPER_TRACE
  75. fprintf(stderr,"PortMapper: started for UDP port %d" ZT_EOL_S,localPort);
  76. #endif
  77. while (run) {
  78. // ---------------------------------------------------------------------
  79. // NAT-PMP mode (preferred)
  80. // ---------------------------------------------------------------------
  81. if (mode == 0) {
  82. natpmp_t natpmp;
  83. natpmpresp_t response;
  84. int r = 0;
  85. bool natPmpSuccess = false;
  86. for(int tries=0;tries<60;++tries) {
  87. int tryPort = (int)localPort + tries;
  88. if (tryPort >= 65535)
  89. tryPort = (tryPort - 65535) + 1025;
  90. memset(&natpmp,0,sizeof(natpmp));
  91. memset(&response,0,sizeof(response));
  92. if (initnatpmp(&natpmp,0,0) != 0) {
  93. mode = 1;
  94. closenatpmp(&natpmp);
  95. #ifdef ZT_PORTMAPPER_TRACE
  96. PM_TRACE("PortMapper: NAT-PMP: init failed, switching to UPnP mode" ZT_EOL_S);
  97. #endif
  98. break;
  99. }
  100. InetAddress publicAddress;
  101. sendpublicaddressrequest(&natpmp);
  102. int64_t myTimeout = OSUtils::now() + 5000;
  103. do {
  104. fd_set fds;
  105. struct timeval timeout;
  106. FD_ZERO(&fds);
  107. FD_SET(natpmp.s, &fds);
  108. getnatpmprequesttimeout(&natpmp, &timeout);
  109. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  110. r = readnatpmpresponseorretry(&natpmp, &response);
  111. if (OSUtils::now() >= myTimeout)
  112. break;
  113. } while (r == NATPMP_TRYAGAIN);
  114. if (r == 0) {
  115. publicAddress = InetAddress((uint32_t)response.pnu.publicaddress.addr.s_addr,0);
  116. } else {
  117. #ifdef ZT_PORTMAPPER_TRACE
  118. PM_TRACE("PortMapper: NAT-PMP: request for external address failed, aborting..." ZT_EOL_S);
  119. #endif
  120. closenatpmp(&natpmp);
  121. break;
  122. }
  123. sendnewportmappingrequest(&natpmp,NATPMP_PROTOCOL_UDP,localPort,tryPort,(ZT_PORTMAPPER_REFRESH_DELAY * 2) / 1000);
  124. myTimeout = OSUtils::now() + 10000;
  125. do {
  126. fd_set fds;
  127. struct timeval timeout;
  128. FD_ZERO(&fds);
  129. FD_SET(natpmp.s, &fds);
  130. getnatpmprequesttimeout(&natpmp, &timeout);
  131. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  132. r = readnatpmpresponseorretry(&natpmp, &response);
  133. if (OSUtils::now() >= myTimeout)
  134. break;
  135. } while (r == NATPMP_TRYAGAIN);
  136. if (r == 0) {
  137. publicAddress.setPort(response.pnu.newportmapping.mappedpublicport);
  138. #ifdef ZT_PORTMAPPER_TRACE
  139. char paddr[128];
  140. PM_TRACE("PortMapper: NAT-PMP: mapped %u to %s" ZT_EOL_S,(unsigned int)localPort,publicAddress.toString(paddr));
  141. #endif
  142. Mutex::Lock sl(surface_l);
  143. surface.clear();
  144. surface.push_back(publicAddress);
  145. natPmpSuccess = true;
  146. closenatpmp(&natpmp);
  147. break;
  148. } else {
  149. closenatpmp(&natpmp);
  150. // continue
  151. }
  152. }
  153. if (!natPmpSuccess) {
  154. mode = 1;
  155. #ifdef ZT_PORTMAPPER_TRACE
  156. PM_TRACE("PortMapper: NAT-PMP: request failed, switching to UPnP mode" ZT_EOL_S);
  157. #endif
  158. }
  159. }
  160. // ---------------------------------------------------------------------
  161. // ---------------------------------------------------------------------
  162. // UPnP mode
  163. // ---------------------------------------------------------------------
  164. if (mode == 1) {
  165. char lanaddr[4096];
  166. 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
  167. char inport[16];
  168. char outport[16];
  169. struct UPNPUrls urls;
  170. struct IGDdatas data;
  171. int upnpError = 0;
  172. UPNPDev *devlist = upnpDiscoverAll(5000,(const char *)0,(const char *)0,0,0,2,&upnpError);
  173. if (devlist) {
  174. #ifdef ZT_PORTMAPPER_TRACE
  175. {
  176. UPNPDev *dev = devlist;
  177. while (dev) {
  178. PM_TRACE("PortMapper: found UPnP device at URL '%s': %s" ZT_EOL_S,dev->descURL,dev->st);
  179. dev = dev->pNext;
  180. }
  181. }
  182. #endif
  183. memset(lanaddr,0,sizeof(lanaddr));
  184. memset(externalip,0,sizeof(externalip));
  185. memset(&urls,0,sizeof(urls));
  186. memset(&data,0,sizeof(data));
  187. OSUtils::ztsnprintf(inport,sizeof(inport),"%d",localPort);
  188. if ((UPNP_GetValidIGD(devlist,&urls,&data,lanaddr,sizeof(lanaddr)))&&(lanaddr[0])) {
  189. #ifdef ZT_PORTMAPPER_TRACE
  190. PM_TRACE("PortMapper: UPnP: my LAN IP address: %s" ZT_EOL_S,lanaddr);
  191. #endif
  192. if ((UPNP_GetExternalIPAddress(urls.controlURL,data.first.servicetype,externalip) == UPNPCOMMAND_SUCCESS)&&(externalip[0])) {
  193. #ifdef ZT_PORTMAPPER_TRACE
  194. PM_TRACE("PortMapper: UPnP: my external IP address: %s" ZT_EOL_S,externalip);
  195. #endif
  196. for(int tries=0;tries<60;++tries) {
  197. int tryPort = (int)localPort + tries;
  198. if (tryPort >= 65535)
  199. tryPort = (tryPort - 65535) + 1025;
  200. OSUtils::ztsnprintf(outport,sizeof(outport),"%u",tryPort);
  201. // First check and see if this port is already mapped to the
  202. // same unique name. If so, keep this mapping and don't try
  203. // to map again since this can break buggy routers. But don't
  204. // fail if this command fails since not all routers support it.
  205. {
  206. char haveIntClient[128]; // 128 == big enough for all these as per miniupnpc "documentation"
  207. char haveIntPort[128];
  208. char haveDesc[128];
  209. char haveEnabled[128];
  210. char haveLeaseDuration[128];
  211. memset(haveIntClient,0,sizeof(haveIntClient));
  212. memset(haveIntPort,0,sizeof(haveIntPort));
  213. memset(haveDesc,0,sizeof(haveDesc));
  214. memset(haveEnabled,0,sizeof(haveEnabled));
  215. memset(haveLeaseDuration,0,sizeof(haveLeaseDuration));
  216. if ((UPNP_GetSpecificPortMappingEntry(urls.controlURL,data.first.servicetype,outport,"UDP",(const char *)0,haveIntClient,haveIntPort,haveDesc,haveEnabled,haveLeaseDuration) == UPNPCOMMAND_SUCCESS)&&(uniqueName == haveDesc)) {
  217. #ifdef ZT_PORTMAPPER_TRACE
  218. PM_TRACE("PortMapper: UPnP: reusing previously reserved external port: %s" ZT_EOL_S,outport);
  219. #endif
  220. Mutex::Lock sl(surface_l);
  221. surface.clear();
  222. InetAddress tmp(externalip);
  223. tmp.setPort(tryPort);
  224. surface.push_back(tmp);
  225. break;
  226. }
  227. }
  228. // Try to map this port
  229. int mapResult = 0;
  230. if ((mapResult = UPNP_AddPortMapping(urls.controlURL,data.first.servicetype,outport,inport,lanaddr,uniqueName.c_str(),"UDP",(const char *)0,"0")) == UPNPCOMMAND_SUCCESS) {
  231. #ifdef ZT_PORTMAPPER_TRACE
  232. PM_TRACE("PortMapper: UPnP: 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. } else {
  241. #ifdef ZT_PORTMAPPER_TRACE
  242. PM_TRACE("PortMapper: UPnP: UPNP_AddPortMapping(%s) failed: %d" ZT_EOL_S,outport,mapResult);
  243. #endif
  244. Thread::sleep(1000);
  245. }
  246. }
  247. } else {
  248. mode = 0;
  249. #ifdef ZT_PORTMAPPER_TRACE
  250. PM_TRACE("PortMapper: UPnP: UPNP_GetExternalIPAddress failed, returning to NAT-PMP mode" ZT_EOL_S);
  251. #endif
  252. }
  253. } else {
  254. mode = 0;
  255. #ifdef ZT_PORTMAPPER_TRACE
  256. PM_TRACE("PortMapper: UPnP: UPNP_GetValidIGD failed, returning to NAT-PMP mode" ZT_EOL_S);
  257. #endif
  258. }
  259. freeUPNPDevlist(devlist);
  260. } else {
  261. mode = 0;
  262. #ifdef ZT_PORTMAPPER_TRACE
  263. PM_TRACE("PortMapper: upnpDiscover failed, returning to NAT-PMP mode: %d" ZT_EOL_S,upnpError);
  264. #endif
  265. }
  266. }
  267. // ---------------------------------------------------------------------
  268. #ifdef ZT_PORTMAPPER_TRACE
  269. PM_TRACE("UPNPClient: rescanning in %d ms" ZT_EOL_S,ZT_PORTMAPPER_REFRESH_DELAY);
  270. #endif
  271. Thread::sleep(ZT_PORTMAPPER_REFRESH_DELAY);
  272. }
  273. delete this;
  274. }
  275. volatile bool run;
  276. int localPort;
  277. std::string uniqueName;
  278. Mutex surface_l;
  279. std::vector<InetAddress> surface;
  280. };
  281. PortMapper::PortMapper(int localUdpPortToMap,const char *uniqueName)
  282. {
  283. _impl = new PortMapperImpl(localUdpPortToMap,uniqueName);
  284. Thread::start(_impl);
  285. }
  286. PortMapper::~PortMapper()
  287. {
  288. _impl->run = false;
  289. }
  290. std::vector<InetAddress> PortMapper::get() const
  291. {
  292. Mutex::Lock _l(_impl->surface_l);
  293. return _impl->surface;
  294. }
  295. } // namespace ZeroTier
  296. #endif // ZT_USE_MINIUPNPC