tcp-proxy.cpp 10 KB

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