2
0

PortMapper.cpp 10 KB

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