PortMapper.cpp 9.7 KB

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