2
0

tcp-proxy.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. // HACK! Will eventually use epoll() or something in Phy<> instead of select().
  28. // Also be sure to change ulimit -n and fs.file-max in /etc/sysctl.conf on relays.
  29. #if defined(__linux__) || defined(__LINUX__) || defined(__LINUX) || defined(LINUX)
  30. #include <linux/posix_types.h>
  31. #include <bits/types.h>
  32. #undef __FD_SETSIZE
  33. #define __FD_SETSIZE 1048576
  34. #undef FD_SETSIZE
  35. #define FD_SETSIZE 1048576
  36. #endif
  37. #include <stdio.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include <time.h>
  41. #include <stdint.h>
  42. #include <unistd.h>
  43. #include <signal.h>
  44. #include <map>
  45. #include <set>
  46. #include <string>
  47. #include <algorithm>
  48. #include <vector>
  49. #include "../osdep/Phy.hpp"
  50. #define ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS 300
  51. #define ZT_TCP_PROXY_TCP_PORT 443
  52. using namespace ZeroTier;
  53. /*
  54. * ZeroTier TCP Proxy Server
  55. *
  56. * This implements a simple packet encapsulation that is designed to look like
  57. * a TLS connection. It's not a TLS connection, but it sends TLS format record
  58. * headers. It could be extended in the future to implement a fake TLS
  59. * handshake.
  60. *
  61. * At the moment, each packet is just made to look like TLS application data:
  62. * <[1] TLS content type> - currently 0x17 for "application data"
  63. * <[1] TLS major version> - currently 0x03 for TLS 1.2
  64. * <[1] TLS minor version> - currently 0x03 for TLS 1.2
  65. * <[2] payload length> - 16-bit length of payload in bytes
  66. * <[...] payload> - Message payload
  67. *
  68. * TCP is inherently inefficient for encapsulating Ethernet, since TCP and TCP
  69. * like protocols over TCP lead to double-ACKs. So this transport is only used
  70. * to enable access when UDP or other datagram protocols are not available.
  71. *
  72. * Clients send a greeting, which is a four-byte message that contains:
  73. * <[1] ZeroTier major version>
  74. * <[1] minor version>
  75. * <[2] revision>
  76. *
  77. * If a client has sent a greeting, it uses the new version of this protocol
  78. * in which every encapsulated ZT packet is prepended by an IP address where
  79. * it should be forwarded (or where it came from for replies). This causes
  80. * this proxy to act as a remote UDP socket similar to a socks proxy, which
  81. * will allow us to move this function off the rootservers and onto dedicated
  82. * proxy nodes.
  83. *
  84. * Older ZT clients that do not send this message get their packets relayed
  85. * to/from 127.0.0.1:9993, which will allow them to talk to and relay via
  86. * the ZT node on the same machine as the proxy. We'll only support this for
  87. * as long as such nodes appear to be in the wild.
  88. */
  89. struct TcpProxyService;
  90. struct TcpProxyService
  91. {
  92. Phy<TcpProxyService *> *phy;
  93. int udpPortCounter;
  94. struct Client
  95. {
  96. char tcpReadBuf[131072];
  97. char tcpWriteBuf[131072];
  98. unsigned long tcpWritePtr;
  99. unsigned long tcpReadPtr;
  100. PhySocket *tcp;
  101. PhySocket *udp;
  102. time_t lastActivity;
  103. bool newVersion;
  104. };
  105. std::map< PhySocket *,Client > clients;
  106. PhySocket *getUnusedUdp(void *uptr)
  107. {
  108. for(int i=0;i<65535;++i) {
  109. ++udpPortCounter;
  110. if (udpPortCounter > 0xfffe)
  111. udpPortCounter = 1024;
  112. struct sockaddr_in laddr;
  113. memset(&laddr,0,sizeof(struct sockaddr_in));
  114. laddr.sin_family = AF_INET;
  115. laddr.sin_port = htons((uint16_t)udpPortCounter);
  116. PhySocket *udp = phy->udpBind(reinterpret_cast<struct sockaddr *>(&laddr),uptr);
  117. if (udp)
  118. return udp;
  119. }
  120. return (PhySocket *)0;
  121. }
  122. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  123. {
  124. if (!*uptr)
  125. return;
  126. if ((from->sa_family == AF_INET)&&(len >= 16)&&(len < 2048)) {
  127. Client &c = *((Client *)*uptr);
  128. c.lastActivity = time((time_t *)0);
  129. unsigned long mlen = len;
  130. if (c.newVersion)
  131. mlen += 7; // new clients get IP info
  132. if ((c.tcpWritePtr + 5 + mlen) <= sizeof(c.tcpWriteBuf)) {
  133. if (!c.tcpWritePtr)
  134. phy->tcpSetNotifyWritable(c.tcp,true);
  135. c.tcpWriteBuf[c.tcpWritePtr++] = 0x17; // look like TLS data
  136. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  137. c.tcpWriteBuf[c.tcpWritePtr++] = 0x03; // look like TLS 1.2
  138. c.tcpWriteBuf[c.tcpWritePtr++] = (char)((mlen >> 8) & 0xff);
  139. c.tcpWriteBuf[c.tcpWritePtr++] = (char)(mlen & 0xff);
  140. if (c.newVersion) {
  141. c.tcpWriteBuf[c.tcpWritePtr++] = (char)4; // IPv4
  142. *((uint32_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in *)from)->sin_addr.s_addr;
  143. c.tcpWritePtr += 4;
  144. *((uint16_t *)(c.tcpWriteBuf + c.tcpWritePtr)) = ((const struct sockaddr_in *)from)->sin_port;
  145. c.tcpWritePtr += 2;
  146. }
  147. for(unsigned long i=0;i<len;++i)
  148. c.tcpWriteBuf[c.tcpWritePtr++] = ((const char *)data)[i];
  149. }
  150. //printf("<< UDP %s:%d -> %.16llx\n",inet_ntoa(reinterpret_cast<const struct sockaddr_in *>(from)->sin_addr),(int)ntohs(reinterpret_cast<const struct sockaddr_in *>(from)->sin_port),(unsigned long long)&c);
  151. }
  152. }
  153. void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  154. {
  155. // unused, we don't initiate outbound connections
  156. }
  157. void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  158. {
  159. Client &c = clients[sockN];
  160. PhySocket *udp = getUnusedUdp((void *)&c);
  161. if (!udp) {
  162. phy->close(sockN);
  163. clients.erase(sockN);
  164. //printf("** TCP rejected, no more UDP ports to assign\n");
  165. return;
  166. }
  167. c.tcpWritePtr = 0;
  168. c.tcpReadPtr = 0;
  169. c.tcp = sockN;
  170. c.udp = udp;
  171. c.lastActivity = time((time_t *)0);
  172. c.newVersion = false;
  173. *uptrN = (void *)&c;
  174. //printf("<< TCP from %s -> %.16llx\n",inet_ntoa(reinterpret_cast<const struct sockaddr_in *>(from)->sin_addr),(unsigned long long)&c);
  175. }
  176. void phyOnTcpClose(PhySocket *sock,void **uptr)
  177. {
  178. if (!*uptr)
  179. return;
  180. Client &c = *((Client *)*uptr);
  181. phy->close(c.udp);
  182. clients.erase(sock);
  183. //printf("** TCP %.16llx closed\n",(unsigned long long)*uptr);
  184. }
  185. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  186. {
  187. Client &c = *((Client *)*uptr);
  188. c.lastActivity = time((time_t *)0);
  189. for(unsigned long i=0;i<len;++i) {
  190. if (c.tcpReadPtr >= sizeof(c.tcpReadBuf)) {
  191. phy->close(sock);
  192. return;
  193. }
  194. c.tcpReadBuf[c.tcpReadPtr++] = ((const char *)data)[i];
  195. if (c.tcpReadPtr >= 5) {
  196. unsigned long mlen = ( ((((unsigned long)c.tcpReadBuf[3]) & 0xff) << 8) | (((unsigned long)c.tcpReadBuf[4]) & 0xff) );
  197. if (c.tcpReadPtr >= (mlen + 5)) {
  198. if (mlen == 4) {
  199. // Right now just sending this means the client is 'new enough' for the IP header
  200. c.newVersion = true;
  201. //printf("<< TCP %.16llx HELLO\n",(unsigned long long)*uptr);
  202. } else if (mlen >= 7) {
  203. char *payload = c.tcpReadBuf + 5;
  204. unsigned long payloadLen = mlen;
  205. struct sockaddr_in dest;
  206. memset(&dest,0,sizeof(dest));
  207. if (c.newVersion) {
  208. if (*payload == (char)4) {
  209. // New clients tell us where their packets go.
  210. ++payload;
  211. dest.sin_family = AF_INET;
  212. dest.sin_addr.s_addr = *((uint32_t *)payload);
  213. payload += 4;
  214. dest.sin_port = *((uint16_t *)payload); // will be in network byte order already
  215. payload += 2;
  216. payloadLen -= 7;
  217. }
  218. } else {
  219. // For old clients we will just proxy everything to a local ZT instance. The
  220. // fact that this will come from 127.0.0.1 will in turn prevent that instance
  221. // from doing unite() with us. It'll just forward. There will not be many of
  222. // these.
  223. dest.sin_family = AF_INET;
  224. dest.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
  225. dest.sin_port = htons(9993);
  226. }
  227. // Note: we do not relay to privileged ports... just an abuse prevention rule.
  228. if ((ntohs(dest.sin_port) > 1024)&&(payloadLen >= 16)) {
  229. phy->udpSend(c.udp,(const struct sockaddr *)&dest,payload,payloadLen);
  230. //printf(">> TCP %.16llx to %s:%d\n",(unsigned long long)*uptr,inet_ntoa(dest.sin_addr),(int)ntohs(dest.sin_port));
  231. }
  232. }
  233. memmove(c.tcpReadBuf,c.tcpReadBuf + (mlen + 5),c.tcpReadPtr -= (mlen + 5));
  234. }
  235. }
  236. }
  237. }
  238. void phyOnTcpWritable(PhySocket *sock,void **uptr)
  239. {
  240. Client &c = *((Client *)*uptr);
  241. if (c.tcpWritePtr) {
  242. long n = phy->tcpSend(sock,c.tcpWriteBuf,c.tcpWritePtr);
  243. if (n > 0) {
  244. memmove(c.tcpWriteBuf,c.tcpWriteBuf + n,c.tcpWritePtr -= (unsigned long)n);
  245. if (!c.tcpWritePtr)
  246. phy->tcpSetNotifyWritable(sock,false);
  247. }
  248. } else phy->tcpSetNotifyWritable(sock,false);
  249. }
  250. void doHousekeeping()
  251. {
  252. std::vector<PhySocket *> toClose;
  253. time_t now = time((time_t *)0);
  254. for(std::map< PhySocket *,Client >::iterator c(clients.begin());c!=clients.end();++c) {
  255. if ((now - c->second.lastActivity) >= ZT_TCP_PROXY_CONNECTION_TIMEOUT_SECONDS) {
  256. toClose.push_back(c->first);
  257. toClose.push_back(c->second.udp);
  258. }
  259. }
  260. for(std::vector<PhySocket *>::iterator s(toClose.begin());s!=toClose.end();++s)
  261. phy->close(*s);
  262. }
  263. };
  264. int main(int argc,char **argv)
  265. {
  266. signal(SIGPIPE,SIG_IGN);
  267. signal(SIGHUP,SIG_IGN);
  268. srand(time((time_t *)0));
  269. TcpProxyService svc;
  270. Phy<TcpProxyService *> phy(&svc,false,true);
  271. svc.phy = &phy;
  272. svc.udpPortCounter = 1023;
  273. {
  274. struct sockaddr_in laddr;
  275. memset(&laddr,0,sizeof(laddr));
  276. laddr.sin_family = AF_INET;
  277. laddr.sin_port = htons(ZT_TCP_PROXY_TCP_PORT);
  278. if (!phy.tcpListen((const struct sockaddr *)&laddr)) {
  279. fprintf(stderr,"%s: fatal error: unable to bind TCP port %d\n",argv[0],ZT_TCP_PROXY_TCP_PORT);
  280. return 1;
  281. }
  282. }
  283. time_t lastDidHousekeeping = time((time_t *)0);
  284. for(;;) {
  285. phy.poll(120000);
  286. time_t now = time((time_t *)0);
  287. if ((now - lastDidHousekeeping) > 120) {
  288. lastDidHousekeeping = now;
  289. svc.doHousekeeping();
  290. }
  291. }
  292. return 0;
  293. }