PortMapper.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifdef ZT_USE_MINIUPNPC
  27. // Uncomment to dump debug messages
  28. //#define ZT_PORTMAPPER_TRACE 1
  29. #ifdef __ANDROID__
  30. #include <android/log.h>
  31. #define PM_TRACE(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, "PortMapper", __VA_ARGS__))
  32. #else
  33. #define PM_TRACE(...) fprintf(stderr, __VA_ARGS__)
  34. #endif
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <string>
  39. #include "../node/Utils.hpp"
  40. #include "OSUtils.hpp"
  41. #include "PortMapper.hpp"
  42. // These must be defined to get rid of dynamic export stuff in libminiupnpc and libnatpmp
  43. #ifdef __WINDOWS__
  44. #ifndef MINIUPNP_STATICLIB
  45. #define MINIUPNP_STATICLIB
  46. #endif
  47. #ifndef STATICLIB
  48. #define STATICLIB
  49. #endif
  50. #endif
  51. #ifdef ZT_USE_SYSTEM_MINIUPNPC
  52. #include <miniupnpc/miniupnpc.h>
  53. #include <miniupnpc/upnpcommands.h>
  54. #else
  55. #ifdef __ANDROID__
  56. #include "miniupnpc.h"
  57. #include "upnpcommands.h"
  58. #else
  59. #include "../ext/miniupnpc/miniupnpc.h"
  60. #include "../ext/miniupnpc/upnpcommands.h"
  61. #endif
  62. #endif
  63. #ifdef ZT_USE_SYSTEM_NATPMP
  64. #include <natpmp.h>
  65. #else
  66. #ifdef __ANDROID__
  67. #include "natpmp.h"
  68. #else
  69. #include "../ext/libnatpmp/natpmp.h"
  70. #endif
  71. #endif
  72. namespace ZeroTier {
  73. class PortMapperImpl
  74. {
  75. public:
  76. PortMapperImpl(int localUdpPortToMap,const char *un) :
  77. run(true),
  78. localPort(localUdpPortToMap),
  79. uniqueName(un)
  80. {
  81. }
  82. ~PortMapperImpl() {}
  83. void threadMain()
  84. throw()
  85. {
  86. int mode = 0; // 0 == NAT-PMP, 1 == UPnP
  87. #ifdef ZT_PORTMAPPER_TRACE
  88. fprintf(stderr,"PortMapper: started for UDP port %d" ZT_EOL_S,localPort);
  89. #endif
  90. while (run) {
  91. // ---------------------------------------------------------------------
  92. // NAT-PMP mode (preferred)
  93. // ---------------------------------------------------------------------
  94. if (mode == 0) {
  95. natpmp_t natpmp;
  96. natpmpresp_t response;
  97. int r = 0;
  98. bool natPmpSuccess = false;
  99. for(int tries=0;tries<60;++tries) {
  100. int tryPort = (int)localPort + tries;
  101. if (tryPort >= 65535)
  102. tryPort = (tryPort - 65535) + 1025;
  103. memset(&natpmp,0,sizeof(natpmp));
  104. memset(&response,0,sizeof(response));
  105. if (initnatpmp(&natpmp,0,0) != 0) {
  106. mode = 1;
  107. closenatpmp(&natpmp);
  108. #ifdef ZT_PORTMAPPER_TRACE
  109. PM_TRACE("PortMapper: NAT-PMP: init failed, switching to UPnP mode" ZT_EOL_S);
  110. #endif
  111. break;
  112. }
  113. InetAddress publicAddress;
  114. sendpublicaddressrequest(&natpmp);
  115. int64_t myTimeout = OSUtils::now() + 5000;
  116. do {
  117. fd_set fds;
  118. struct timeval timeout;
  119. FD_ZERO(&fds);
  120. FD_SET(natpmp.s, &fds);
  121. getnatpmprequesttimeout(&natpmp, &timeout);
  122. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  123. r = readnatpmpresponseorretry(&natpmp, &response);
  124. if (OSUtils::now() >= myTimeout)
  125. break;
  126. } while (r == NATPMP_TRYAGAIN);
  127. if (r == 0) {
  128. publicAddress = InetAddress((uint32_t)response.pnu.publicaddress.addr.s_addr,0);
  129. } else {
  130. #ifdef ZT_PORTMAPPER_TRACE
  131. PM_TRACE("PortMapper: NAT-PMP: request for external address failed, aborting..." ZT_EOL_S);
  132. #endif
  133. closenatpmp(&natpmp);
  134. break;
  135. }
  136. sendnewportmappingrequest(&natpmp,NATPMP_PROTOCOL_UDP,localPort,tryPort,(ZT_PORTMAPPER_REFRESH_DELAY * 2) / 1000);
  137. myTimeout = OSUtils::now() + 10000;
  138. do {
  139. fd_set fds;
  140. struct timeval timeout;
  141. FD_ZERO(&fds);
  142. FD_SET(natpmp.s, &fds);
  143. getnatpmprequesttimeout(&natpmp, &timeout);
  144. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  145. r = readnatpmpresponseorretry(&natpmp, &response);
  146. if (OSUtils::now() >= myTimeout)
  147. break;
  148. } while (r == NATPMP_TRYAGAIN);
  149. if (r == 0) {
  150. publicAddress.setPort(response.pnu.newportmapping.mappedpublicport);
  151. #ifdef ZT_PORTMAPPER_TRACE
  152. char paddr[128];
  153. PM_TRACE("PortMapper: NAT-PMP: mapped %u to %s" ZT_EOL_S,(unsigned int)localPort,publicAddress.toString(paddr));
  154. #endif
  155. Mutex::Lock sl(surface_l);
  156. surface.clear();
  157. surface.push_back(publicAddress);
  158. natPmpSuccess = true;
  159. closenatpmp(&natpmp);
  160. break;
  161. } else {
  162. closenatpmp(&natpmp);
  163. // continue
  164. }
  165. }
  166. if (!natPmpSuccess) {
  167. mode = 1;
  168. #ifdef ZT_PORTMAPPER_TRACE
  169. PM_TRACE("PortMapper: NAT-PMP: request failed, switching to UPnP mode" ZT_EOL_S);
  170. #endif
  171. }
  172. }
  173. // ---------------------------------------------------------------------
  174. // ---------------------------------------------------------------------
  175. // UPnP mode
  176. // ---------------------------------------------------------------------
  177. if (mode == 1) {
  178. char lanaddr[4096];
  179. 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
  180. char inport[16];
  181. char outport[16];
  182. struct UPNPUrls urls;
  183. struct IGDdatas data;
  184. int upnpError = 0;
  185. UPNPDev *devlist = upnpDiscoverAll(5000,(const char *)0,(const char *)0,0,0,2,&upnpError);
  186. if (devlist) {
  187. #ifdef ZT_PORTMAPPER_TRACE
  188. {
  189. UPNPDev *dev = devlist;
  190. while (dev) {
  191. PM_TRACE("PortMapper: found UPnP device at URL '%s': %s" ZT_EOL_S,dev->descURL,dev->st);
  192. dev = dev->pNext;
  193. }
  194. }
  195. #endif
  196. memset(lanaddr,0,sizeof(lanaddr));
  197. memset(externalip,0,sizeof(externalip));
  198. memset(&urls,0,sizeof(urls));
  199. memset(&data,0,sizeof(data));
  200. OSUtils::ztsnprintf(inport,sizeof(inport),"%d",localPort);
  201. if ((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)&&(uniqueName == haveDesc)) {
  230. #ifdef ZT_PORTMAPPER_TRACE
  231. PM_TRACE("PortMapper: UPnP: reusing previously 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. }
  240. }
  241. // Try to map this port
  242. int mapResult = 0;
  243. if ((mapResult = UPNP_AddPortMapping(urls.controlURL,data.first.servicetype,outport,inport,lanaddr,uniqueName.c_str(),"UDP",(const char *)0,"0")) == UPNPCOMMAND_SUCCESS) {
  244. #ifdef ZT_PORTMAPPER_TRACE
  245. PM_TRACE("PortMapper: UPnP: reserved external port: %s" ZT_EOL_S,outport);
  246. #endif
  247. Mutex::Lock sl(surface_l);
  248. surface.clear();
  249. InetAddress tmp(externalip);
  250. tmp.setPort(tryPort);
  251. surface.push_back(tmp);
  252. break;
  253. } else {
  254. #ifdef ZT_PORTMAPPER_TRACE
  255. PM_TRACE("PortMapper: UPnP: UPNP_AddPortMapping(%s) failed: %d" ZT_EOL_S,outport,mapResult);
  256. #endif
  257. Thread::sleep(1000);
  258. }
  259. }
  260. } else {
  261. mode = 0;
  262. #ifdef ZT_PORTMAPPER_TRACE
  263. PM_TRACE("PortMapper: UPnP: UPNP_GetExternalIPAddress failed, returning to NAT-PMP mode" ZT_EOL_S);
  264. #endif
  265. }
  266. } else {
  267. mode = 0;
  268. #ifdef ZT_PORTMAPPER_TRACE
  269. PM_TRACE("PortMapper: UPnP: UPNP_GetValidIGD failed, returning to NAT-PMP mode" ZT_EOL_S);
  270. #endif
  271. }
  272. freeUPNPDevlist(devlist);
  273. } else {
  274. mode = 0;
  275. #ifdef ZT_PORTMAPPER_TRACE
  276. PM_TRACE("PortMapper: upnpDiscover failed, returning to NAT-PMP mode: %d" ZT_EOL_S,upnpError);
  277. #endif
  278. }
  279. }
  280. // ---------------------------------------------------------------------
  281. #ifdef ZT_PORTMAPPER_TRACE
  282. PM_TRACE("UPNPClient: rescanning in %d ms" ZT_EOL_S,ZT_PORTMAPPER_REFRESH_DELAY);
  283. #endif
  284. Thread::sleep(ZT_PORTMAPPER_REFRESH_DELAY);
  285. }
  286. delete this;
  287. }
  288. volatile bool run;
  289. int localPort;
  290. std::string uniqueName;
  291. Mutex surface_l;
  292. std::vector<InetAddress> surface;
  293. };
  294. PortMapper::PortMapper(int localUdpPortToMap,const char *uniqueName)
  295. {
  296. _impl = new PortMapperImpl(localUdpPortToMap,uniqueName);
  297. Thread::start(_impl);
  298. }
  299. PortMapper::~PortMapper()
  300. {
  301. _impl->run = false;
  302. }
  303. std::vector<InetAddress> PortMapper::get() const
  304. {
  305. Mutex::Lock _l(_impl->surface_l);
  306. return _impl->surface;
  307. }
  308. } // namespace ZeroTier
  309. #endif // ZT_USE_MINIUPNPC