PortMapper.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. #ifdef ZT_PORTMAPPER_TRACE
  108. PM_TRACE("PortMapper: NAT-PMP: init failed, switching to UPnP mode" ZT_EOL_S);
  109. #endif
  110. break;
  111. }
  112. InetAddress publicAddress;
  113. sendpublicaddressrequest(&natpmp);
  114. uint64_t myTimeout = OSUtils::now() + 5000;
  115. do {
  116. fd_set fds;
  117. struct timeval timeout;
  118. FD_ZERO(&fds);
  119. FD_SET(natpmp.s, &fds);
  120. getnatpmprequesttimeout(&natpmp, &timeout);
  121. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  122. r = readnatpmpresponseorretry(&natpmp, &response);
  123. if (OSUtils::now() >= myTimeout)
  124. break;
  125. } while (r == NATPMP_TRYAGAIN);
  126. if (r == 0) {
  127. publicAddress = InetAddress((uint32_t)response.pnu.publicaddress.addr.s_addr,0);
  128. } else {
  129. #ifdef ZT_PORTMAPPER_TRACE
  130. PM_TRACE("PortMapper: NAT-PMP: request for external address failed, aborting..." ZT_EOL_S);
  131. #endif
  132. closenatpmp(&natpmp);
  133. break;
  134. }
  135. sendnewportmappingrequest(&natpmp,NATPMP_PROTOCOL_UDP,localPort,tryPort,(ZT_PORTMAPPER_REFRESH_DELAY * 2) / 1000);
  136. myTimeout = OSUtils::now() + 10000;
  137. do {
  138. fd_set fds;
  139. struct timeval timeout;
  140. FD_ZERO(&fds);
  141. FD_SET(natpmp.s, &fds);
  142. getnatpmprequesttimeout(&natpmp, &timeout);
  143. select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
  144. r = readnatpmpresponseorretry(&natpmp, &response);
  145. if (OSUtils::now() >= myTimeout)
  146. break;
  147. } while (r == NATPMP_TRYAGAIN);
  148. if (r == 0) {
  149. publicAddress.setPort(response.pnu.newportmapping.mappedpublicport);
  150. #ifdef ZT_PORTMAPPER_TRACE
  151. char paddr[128];
  152. PM_TRACE("PortMapper: NAT-PMP: mapped %u to %s" ZT_EOL_S,(unsigned int)localPort,publicAddress.toString(paddr));
  153. #endif
  154. Mutex::Lock sl(surface_l);
  155. surface.clear();
  156. surface.push_back(publicAddress);
  157. natPmpSuccess = true;
  158. closenatpmp(&natpmp);
  159. break;
  160. } else {
  161. closenatpmp(&natpmp);
  162. // continue
  163. }
  164. }
  165. if (!natPmpSuccess) {
  166. mode = 1;
  167. #ifdef ZT_PORTMAPPER_TRACE
  168. PM_TRACE("PortMapper: NAT-PMP: request failed, switching to UPnP mode" ZT_EOL_S);
  169. #endif
  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. if ((UPNP_GetValidIGD(devlist,&urls,&data,lanaddr,sizeof(lanaddr)))&&(lanaddr[0])) {
  201. #ifdef ZT_PORTMAPPER_TRACE
  202. PM_TRACE("PortMapper: UPnP: my LAN IP address: %s" ZT_EOL_S,lanaddr);
  203. #endif
  204. if ((UPNP_GetExternalIPAddress(urls.controlURL,data.first.servicetype,externalip) == UPNPCOMMAND_SUCCESS)&&(externalip[0])) {
  205. #ifdef ZT_PORTMAPPER_TRACE
  206. PM_TRACE("PortMapper: UPnP: my external IP address: %s" ZT_EOL_S,externalip);
  207. #endif
  208. for(int tries=0;tries<60;++tries) {
  209. int tryPort = (int)localPort + tries;
  210. if (tryPort >= 65535)
  211. tryPort = (tryPort - 65535) + 1025;
  212. OSUtils::ztsnprintf(outport,sizeof(outport),"%u",tryPort);
  213. // First check and see if this port is already mapped to the
  214. // same unique name. If so, keep this mapping and don't try
  215. // to map again since this can break buggy routers. But don't
  216. // fail if this command fails since not all routers support it.
  217. {
  218. char haveIntClient[128]; // 128 == big enough for all these as per miniupnpc "documentation"
  219. char haveIntPort[128];
  220. char haveDesc[128];
  221. char haveEnabled[128];
  222. char haveLeaseDuration[128];
  223. memset(haveIntClient,0,sizeof(haveIntClient));
  224. memset(haveIntPort,0,sizeof(haveIntPort));
  225. memset(haveDesc,0,sizeof(haveDesc));
  226. memset(haveEnabled,0,sizeof(haveEnabled));
  227. memset(haveLeaseDuration,0,sizeof(haveLeaseDuration));
  228. if ((UPNP_GetSpecificPortMappingEntry(urls.controlURL,data.first.servicetype,outport,"UDP",(const char *)0,haveIntClient,haveIntPort,haveDesc,haveEnabled,haveLeaseDuration) == UPNPCOMMAND_SUCCESS)&&(uniqueName == haveDesc)) {
  229. #ifdef ZT_PORTMAPPER_TRACE
  230. PM_TRACE("PortMapper: UPnP: reusing previously reserved external port: %s" ZT_EOL_S,outport);
  231. #endif
  232. Mutex::Lock sl(surface_l);
  233. surface.clear();
  234. InetAddress tmp(externalip);
  235. tmp.setPort(tryPort);
  236. surface.push_back(tmp);
  237. break;
  238. }
  239. }
  240. // Try to map this port
  241. int mapResult = 0;
  242. if ((mapResult = UPNP_AddPortMapping(urls.controlURL,data.first.servicetype,outport,inport,lanaddr,uniqueName.c_str(),"UDP",(const char *)0,"0")) == UPNPCOMMAND_SUCCESS) {
  243. #ifdef ZT_PORTMAPPER_TRACE
  244. PM_TRACE("PortMapper: UPnP: reserved external port: %s" ZT_EOL_S,outport);
  245. #endif
  246. Mutex::Lock sl(surface_l);
  247. surface.clear();
  248. InetAddress tmp(externalip);
  249. tmp.setPort(tryPort);
  250. surface.push_back(tmp);
  251. break;
  252. } else {
  253. #ifdef ZT_PORTMAPPER_TRACE
  254. PM_TRACE("PortMapper: UPnP: UPNP_AddPortMapping(%s) failed: %d" ZT_EOL_S,outport,mapResult);
  255. #endif
  256. Thread::sleep(1000);
  257. }
  258. }
  259. } else {
  260. mode = 0;
  261. #ifdef ZT_PORTMAPPER_TRACE
  262. PM_TRACE("PortMapper: UPnP: UPNP_GetExternalIPAddress failed, returning to NAT-PMP mode" ZT_EOL_S);
  263. #endif
  264. }
  265. } else {
  266. mode = 0;
  267. #ifdef ZT_PORTMAPPER_TRACE
  268. PM_TRACE("PortMapper: UPnP: UPNP_GetValidIGD failed, returning to NAT-PMP mode" ZT_EOL_S);
  269. #endif
  270. }
  271. freeUPNPDevlist(devlist);
  272. } else {
  273. mode = 0;
  274. #ifdef ZT_PORTMAPPER_TRACE
  275. PM_TRACE("PortMapper: upnpDiscover failed, returning to NAT-PMP mode: %d" ZT_EOL_S,upnpError);
  276. #endif
  277. }
  278. }
  279. // ---------------------------------------------------------------------
  280. #ifdef ZT_PORTMAPPER_TRACE
  281. PM_TRACE("UPNPClient: rescanning in %d ms" ZT_EOL_S,ZT_PORTMAPPER_REFRESH_DELAY);
  282. #endif
  283. Thread::sleep(ZT_PORTMAPPER_REFRESH_DELAY);
  284. }
  285. delete this;
  286. }
  287. volatile bool run;
  288. int localPort;
  289. std::string uniqueName;
  290. Mutex surface_l;
  291. std::vector<InetAddress> surface;
  292. };
  293. PortMapper::PortMapper(int localUdpPortToMap,const char *uniqueName)
  294. {
  295. _impl = new PortMapperImpl(localUdpPortToMap,uniqueName);
  296. Thread::start(_impl);
  297. }
  298. PortMapper::~PortMapper()
  299. {
  300. _impl->run = false;
  301. }
  302. std::vector<InetAddress> PortMapper::get() const
  303. {
  304. Mutex::Lock _l(_impl->surface_l);
  305. return _impl->surface;
  306. }
  307. } // namespace ZeroTier
  308. #endif // ZT_USE_MINIUPNPC