PortMapper.cpp 9.7 KB

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