PortMapper.cpp 9.6 KB

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