PortMapper.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. break;
  131. }
  132. closenatpmp(&natpmp);
  133. }
  134. if (!natPmpSuccess) {
  135. mode = 1;
  136. #ifdef ZT_PORTMAPPER_TRACE
  137. fprintf(stderr,"PortMapper: NAT-PMP: request failed, switching to UPnP mode"ZT_EOL_S);
  138. #endif
  139. }
  140. }
  141. // ---------------------------------------------------------------------
  142. // ---------------------------------------------------------------------
  143. // UPnP mode
  144. // ---------------------------------------------------------------------
  145. if (mode == 1) {
  146. char lanaddr[4096];
  147. 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
  148. char inport[16];
  149. char outport[16];
  150. struct UPNPUrls urls;
  151. struct IGDdatas data;
  152. int upnpError = 0;
  153. UPNPDev *devlist = upnpDiscoverAll(5000,(const char *)0,(const char *)0,0,0,2,&upnpError);
  154. if (devlist) {
  155. #ifdef ZT_PORTMAPPER_TRACE
  156. {
  157. UPNPDev *dev = devlist;
  158. while (dev) {
  159. fprintf(stderr,"PortMapper: found UPnP device at URL '%s': %s"ZT_EOL_S,dev->descURL,dev->st);
  160. dev = dev->pNext;
  161. }
  162. }
  163. #endif
  164. memset(lanaddr,0,sizeof(lanaddr));
  165. memset(externalip,0,sizeof(externalip));
  166. memset(&urls,0,sizeof(urls));
  167. memset(&data,0,sizeof(data));
  168. Utils::snprintf(inport,sizeof(inport),"%d",localPort);
  169. if ((UPNP_GetValidIGD(devlist,&urls,&data,lanaddr,sizeof(lanaddr)))&&(lanaddr[0])) {
  170. #ifdef ZT_PORTMAPPER_TRACE
  171. fprintf(stderr,"PortMapper: UPnP: my LAN IP address: %s"ZT_EOL_S,lanaddr);
  172. #endif
  173. if ((UPNP_GetExternalIPAddress(urls.controlURL,data.first.servicetype,externalip) == UPNPCOMMAND_SUCCESS)&&(externalip[0])) {
  174. #ifdef ZT_PORTMAPPER_TRACE
  175. fprintf(stderr,"PortMapper: UPnP: my external IP address: %s"ZT_EOL_S,externalip);
  176. #endif
  177. for(int tries=0;tries<60;++tries) {
  178. int tryPort = (int)localPort + tries;
  179. if (tryPort >= 65535)
  180. tryPort = (tryPort - 65535) + 1025;
  181. Utils::snprintf(outport,sizeof(outport),"%u",tryPort);
  182. // First check and see if this port is already mapped to the
  183. // same unique name. If so, keep this mapping and don't try
  184. // to map again since this can break buggy routers. But don't
  185. // fail if this command fails since not all routers support it.
  186. {
  187. char haveIntClient[128]; // 128 == big enough for all these as per miniupnpc "documentation"
  188. char haveIntPort[128];
  189. char haveDesc[128];
  190. char haveEnabled[128];
  191. char haveLeaseDuration[128];
  192. memset(haveIntClient,0,sizeof(haveIntClient));
  193. memset(haveIntPort,0,sizeof(haveIntPort));
  194. memset(haveDesc,0,sizeof(haveDesc));
  195. memset(haveEnabled,0,sizeof(haveEnabled));
  196. memset(haveLeaseDuration,0,sizeof(haveLeaseDuration));
  197. if ((UPNP_GetSpecificPortMappingEntry(urls.controlURL,data.first.servicetype,outport,"UDP",(const char *)0,haveIntClient,haveIntPort,haveDesc,haveEnabled,haveLeaseDuration) == UPNPCOMMAND_SUCCESS)&&(uniqueName == haveDesc)) {
  198. #ifdef ZT_PORTMAPPER_TRACE
  199. fprintf(stderr,"PortMapper: UPnP: reusing previously reserved external port: %s"ZT_EOL_S,outport);
  200. #endif
  201. Mutex::Lock sl(surface_l);
  202. surface.clear();
  203. InetAddress tmp(externalip);
  204. tmp.setPort(tryPort);
  205. surface.push_back(tmp);
  206. break;
  207. }
  208. }
  209. // Try to map this port
  210. int mapResult = 0;
  211. if ((mapResult = UPNP_AddPortMapping(urls.controlURL,data.first.servicetype,outport,inport,lanaddr,uniqueName.c_str(),"UDP",(const char *)0,"0")) == UPNPCOMMAND_SUCCESS) {
  212. #ifdef ZT_PORTMAPPER_TRACE
  213. fprintf(stderr,"PortMapper: UPnP: reserved external port: %s"ZT_EOL_S,outport);
  214. #endif
  215. Mutex::Lock sl(surface_l);
  216. surface.clear();
  217. InetAddress tmp(externalip);
  218. tmp.setPort(tryPort);
  219. surface.push_back(tmp);
  220. break;
  221. } else {
  222. #ifdef ZT_PORTMAPPER_TRACE
  223. fprintf(stderr,"PortMapper: UPnP: UPNP_AddPortMapping(%s) failed: %d"ZT_EOL_S,outport,mapResult);
  224. #endif
  225. Thread::sleep(1000);
  226. }
  227. }
  228. } else {
  229. mode = 0;
  230. #ifdef ZT_PORTMAPPER_TRACE
  231. fprintf(stderr,"PortMapper: UPnP: UPNP_GetExternalIPAddress failed, returning to NAT-PMP mode"ZT_EOL_S);
  232. #endif
  233. }
  234. } else {
  235. mode = 0;
  236. #ifdef ZT_PORTMAPPER_TRACE
  237. fprintf(stderr,"PortMapper: UPnP: UPNP_GetValidIGD failed, returning to NAT-PMP mode"ZT_EOL_S);
  238. #endif
  239. }
  240. freeUPNPDevlist(devlist);
  241. } else {
  242. mode = 0;
  243. #ifdef ZT_PORTMAPPER_TRACE
  244. fprintf(stderr,"PortMapper: upnpDiscover failed, returning to NAT-PMP mode: %d"ZT_EOL_S,upnpError);
  245. #endif
  246. }
  247. }
  248. // ---------------------------------------------------------------------
  249. #ifdef ZT_PORTMAPPER_TRACE
  250. fprintf(stderr,"UPNPClient: rescanning in %d ms"ZT_EOL_S,ZT_PORTMAPPER_REFRESH_DELAY);
  251. #endif
  252. Thread::sleep(ZT_PORTMAPPER_REFRESH_DELAY);
  253. }
  254. delete this;
  255. }
  256. volatile bool run;
  257. int localPort;
  258. std::string uniqueName;
  259. Mutex surface_l;
  260. std::vector<InetAddress> surface;
  261. };
  262. PortMapper::PortMapper(int localUdpPortToMap,const char *uniqueName)
  263. {
  264. _impl = new PortMapperImpl(localUdpPortToMap,uniqueName);
  265. Thread::start(_impl);
  266. }
  267. PortMapper::~PortMapper()
  268. {
  269. _impl->run = false;
  270. }
  271. std::vector<InetAddress> PortMapper::get() const
  272. {
  273. Mutex::Lock _l(_impl->surface_l);
  274. return _impl->surface;
  275. }
  276. } // namespace ZeroTier
  277. #endif // ZT_USE_MINIUPNPC