2
0

tcp-proxy.cpp 9.7 KB

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