PortMapper.cpp 9.6 KB

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