PortMapper.cpp 9.6 KB

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