NetconEthernetTap.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. #ifdef ZT_ENABLE_NETCON
  28. #include <algorithm>
  29. #include <utility>
  30. #include <dlfcn.h>
  31. #include "NetconEthernetTap.hpp"
  32. #include "../node/Utils.hpp"
  33. #include "../osdep/OSUtils.hpp"
  34. #include "../osdep/Phy.hpp"
  35. #include "lwip/tcp_impl.h"
  36. #include "netif/etharp.h"
  37. #include "lwip/ip.h"
  38. #include "lwip/ip_addr.h"
  39. #include "lwip/ip_frag.h"
  40. #include "lwip/tcp.h"
  41. #include "LWIPStack.hpp"
  42. #include "NetconService.hpp"
  43. #include "Intercept.h"
  44. #include "NetconUtilities.hpp"
  45. #define APPLICATION_POLL_FREQ 1
  46. namespace ZeroTier {
  47. NetconEthernetTap::NetconEthernetTap(
  48. const char *homePath,
  49. const MAC &mac,
  50. unsigned int mtu,
  51. unsigned int metric,
  52. uint64_t nwid,
  53. const char *friendlyName,
  54. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  55. void *arg) :
  56. _phy(this,false,true),
  57. _unixListenSocket((PhySocket *)0),
  58. _handler(handler),
  59. _arg(arg),
  60. _nwid(nwid),
  61. _mac(mac),
  62. _homePath(homePath),
  63. _mtu(mtu),
  64. _enabled(true),
  65. _run(true)
  66. {
  67. char sockPath[4096];
  68. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",(unsigned long long)nwid);
  69. _dev = sockPath;
  70. lwipstack = new LWIPStack("ext/bin/lwip/liblwip.so"); // ext/bin/liblwip.so.debug for debug symbols
  71. if(!lwipstack) // TODO double check this check
  72. throw std::runtime_error("unable to load lwip lib.");
  73. lwipstack->lwip_init();
  74. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  75. if (!_unixListenSocket)
  76. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  77. _thread = Thread::start(this);
  78. }
  79. NetconEthernetTap::~NetconEthernetTap()
  80. {
  81. _run = false;
  82. _phy.whack();
  83. _phy.whack();
  84. Thread::join(_thread);
  85. _phy.close(_unixListenSocket,false);
  86. delete lwipstack;
  87. }
  88. void NetconEthernetTap::setEnabled(bool en)
  89. {
  90. _enabled = en;
  91. }
  92. bool NetconEthernetTap::enabled() const
  93. {
  94. return _enabled;
  95. }
  96. bool NetconEthernetTap::addIp(const InetAddress &ip)
  97. {
  98. Mutex::Lock _l(_ips_m);
  99. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  100. _ips.push_back(ip);
  101. std::sort(_ips.begin(),_ips.end());
  102. if (ip.isV4()) {
  103. // Set IP
  104. static ip_addr_t ipaddr, netmask, gw;
  105. IP4_ADDR(&gw,192,168,0,1);
  106. ipaddr.addr = *((u32_t *)ip.rawIpData());
  107. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  108. // Set up the lwip-netif for LWIP's sake
  109. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  110. interface.state = this;
  111. interface.output = lwipstack->_etharp_output;
  112. _mac.copyTo(interface.hwaddr, 6);
  113. interface.mtu = _mtu;
  114. interface.name[0] = 't';
  115. interface.name[1] = 'p';
  116. interface.linkoutput = low_level_output;
  117. interface.hwaddr_len = 6;
  118. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  119. lwipstack->netif_set_default(&interface);
  120. lwipstack->netif_set_up(&interface);
  121. }
  122. }
  123. return true;
  124. }
  125. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  126. {
  127. Mutex::Lock _l(_ips_m);
  128. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  129. if (i == _ips.end())
  130. return false;
  131. _ips.erase(i);
  132. if (ip.isV4()) {
  133. // TODO: dealloc from LWIP
  134. }
  135. return true;
  136. }
  137. std::vector<InetAddress> NetconEthernetTap::ips() const
  138. {
  139. Mutex::Lock _l(_ips_m);
  140. return _ips;
  141. }
  142. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  143. {
  144. struct pbuf *p,*q;
  145. //fprintf(stderr, "_put(%s,%s,%.4x,[data],%u)\n",from.toString().c_str(),to.toString().c_str(),etherType,len);
  146. if (!_enabled)
  147. return;
  148. //printf(">> %.4x %s\n",etherType,Utils::hex(data,len).c_str());
  149. struct eth_hdr ethhdr;
  150. from.copyTo(ethhdr.src.addr, 6);
  151. to.copyTo(ethhdr.dest.addr, 6);
  152. ethhdr.type = Utils::hton((uint16_t)etherType);
  153. // We allocate a pbuf chain of pbufs from the pool.
  154. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  155. if (p != NULL) {
  156. const char *dataptr = reinterpret_cast<const char *>(data);
  157. // First pbuf gets ethernet header at start
  158. q = p;
  159. if (q->len < sizeof(ethhdr)) {
  160. fprintf(stderr,"_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  161. return;
  162. }
  163. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  164. memcpy(q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  165. dataptr += q->len - sizeof(ethhdr);
  166. // Remaining pbufs (if any) get rest of data
  167. while ((q = q->next)) {
  168. memcpy(q->payload,dataptr,q->len);
  169. dataptr += q->len;
  170. }
  171. } else {
  172. fprintf(stderr, "_put(): Dropped packet: no pbufs available\n");
  173. return;
  174. }
  175. //printf("p->len == %u, p->payload == %s\n",p->len,Utils::hex(p->payload,p->len).c_str());
  176. {
  177. Mutex::Lock _l2(lwipstack->_lock);
  178. if(interface.input(p, &interface) != ERR_OK) {
  179. fprintf(stderr, "_put(): Error while RXing packet (netif->input)\n");
  180. }
  181. }
  182. }
  183. std::string NetconEthernetTap::deviceName() const
  184. {
  185. return _dev;
  186. }
  187. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  188. {
  189. }
  190. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  191. {
  192. std::vector<MulticastGroup> newGroups;
  193. Mutex::Lock _l(_multicastGroups_m);
  194. // TODO: get multicast subscriptions from LWIP
  195. std::vector<InetAddress> allIps(ips());
  196. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  197. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  198. std::sort(newGroups.begin(),newGroups.end());
  199. std::unique(newGroups.begin(),newGroups.end());
  200. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  201. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  202. added.push_back(*m);
  203. }
  204. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  205. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  206. removed.push_back(*m);
  207. }
  208. _multicastGroups.swap(newGroups);
  209. }
  210. TcpConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  211. {
  212. for(size_t i=0; i<tcp_connections.size(); i++) {
  213. if(tcp_connections[i]->pcb == pcb)
  214. return tcp_connections[i];
  215. }
  216. return NULL;
  217. }
  218. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(int fd)
  219. {
  220. for(size_t i=0; i<tcp_connections.size(); i++) {
  221. if(tcp_connections[i]->perceived_fd == fd)
  222. return tcp_connections[i];
  223. }
  224. return NULL;
  225. }
  226. /*
  227. * Closes a TcpConnection and associated LWIP PCB strcuture.
  228. */
  229. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  230. {
  231. //fprintf(stderr, "closeConnection(): closing: conn->type = %d, fd=%d\n", conn->type, _phy.getDescriptor(conn->sock));
  232. lwipstack->_tcp_arg(conn->pcb, NULL);
  233. lwipstack->_tcp_sent(conn->pcb, NULL);
  234. lwipstack->_tcp_recv(conn->pcb, NULL);
  235. lwipstack->_tcp_err(conn->pcb, NULL);
  236. lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  237. lwipstack->_tcp_close(conn->pcb);
  238. close(_phy.getDescriptor(conn->dataSock));
  239. close(conn->their_fd);
  240. _phy.close(conn->dataSock);
  241. for(int i=0; i<tcp_connections.size(); i++) {
  242. if(tcp_connections[i] == conn) {
  243. tcp_connections.erase(tcp_connections.begin() + i);
  244. }
  245. }
  246. delete conn;
  247. }
  248. void NetconEthernetTap::closeClient(PhySocket *sock)
  249. {
  250. for(int i=0; i<rpc_sockets.size(); i++) {
  251. if(rpc_sockets[i] == sock)
  252. rpc_sockets.erase(rpc_sockets.begin() + i);
  253. }
  254. close(_phy.getDescriptor(sock));
  255. _phy.close(sock);
  256. }
  257. void NetconEthernetTap::closeAll()
  258. {
  259. while(rpc_sockets.size())
  260. closeClient(rpc_sockets.front());
  261. while(tcp_connections.size())
  262. closeConnection(tcp_connections.front());
  263. }
  264. #define ZT_LWIP_TCP_TIMER_INTERVAL 10
  265. void NetconEthernetTap::threadMain()
  266. throw()
  267. {
  268. fprintf(stderr, "_threadMain()\n");
  269. uint64_t prev_tcp_time = 0;
  270. uint64_t prev_etharp_time = 0;
  271. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  272. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  273. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  274. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  275. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  276. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n", MEMP_NUM_TCP_SEG);
  277. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  278. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n", TCP_SND_QUEUELEN);
  279. fprintf(stderr, "- IP_REASSEMBLY = %d\n", IP_REASSEMBLY);
  280. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  281. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  282. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  283. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  284. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  285. // Main timer loop
  286. while (_run) {
  287. uint64_t now = OSUtils::now();
  288. uint64_t since_tcp = now - prev_tcp_time;
  289. uint64_t since_etharp = now - prev_etharp_time;
  290. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  291. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  292. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  293. prev_tcp_time = now;
  294. lwipstack->tcp_tmr();
  295. } else {
  296. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  297. }
  298. if (since_etharp >= ARP_TMR_INTERVAL) {
  299. prev_etharp_time = now;
  300. lwipstack->etharp_tmr();
  301. } else {
  302. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  303. }
  304. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  305. }
  306. closeAll();
  307. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  308. }
  309. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  310. {
  311. //fprintf(stderr, "phyOnUnixClose() CLOSING: %d\n", _phy.getDescriptor(sock));
  312. //closeClient(sock);
  313. // FIXME:
  314. }
  315. /*
  316. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  317. */
  318. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  319. {
  320. if(readable) {
  321. TcpConnection *conn = (TcpConnection*)*uptr;
  322. Mutex::Lock _l(lwipstack->_lock);
  323. handle_write(conn);
  324. }
  325. else {
  326. fprintf(stderr, "phyOnFileDescriptorActivity(): PhySocket not readable\n");
  327. }
  328. }
  329. // Unused -- no UDP or TCP from this thread/Phy<>
  330. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  331. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  332. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  333. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  334. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  335. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  336. /*
  337. * Creates a new NetconClient for the accepted RPC connection (unix domain socket)
  338. *
  339. * Subsequent socket connections from this client will be associated with this
  340. * NetconClient object.
  341. */
  342. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  343. {
  344. //fprintf(stderr, "phyOnUnixAccept() NEW CLIENT RPC: %d\n", _phy.getDescriptor(sockN));
  345. rpc_sockets.push_back(sockN);
  346. }
  347. /*
  348. * Processes incoming data on a client-specific RPC connection
  349. */
  350. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  351. {
  352. unsigned char *buf = (unsigned char*)data;
  353. switch(buf[0])
  354. {
  355. case RPC_SOCKET:
  356. fprintf(stderr, "RPC_SOCKET\n");
  357. struct socket_st socket_rpc;
  358. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  359. handle_socket(sock, uptr, &socket_rpc);
  360. break;
  361. case RPC_LISTEN:
  362. fprintf(stderr, "RPC_LISTEN\n");
  363. struct listen_st listen_rpc;
  364. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  365. handle_listen(sock, uptr, &listen_rpc);
  366. break;
  367. case RPC_BIND:
  368. fprintf(stderr, "RPC_BIND\n");
  369. struct bind_st bind_rpc;
  370. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  371. handle_bind(sock, uptr, &bind_rpc);
  372. break;
  373. case RPC_KILL_INTERCEPT:
  374. fprintf(stderr, "RPC_KILL_INTERCEPT\n");
  375. //scloseClient(sock);
  376. break;
  377. case RPC_CONNECT:
  378. fprintf(stderr, "RPC_CONNECT\n");
  379. struct connect_st connect_rpc;
  380. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  381. handle_connect(sock, uptr, &connect_rpc);
  382. break;
  383. case RPC_FD_MAP_COMPLETION:
  384. fprintf(stderr, "RPC_FD_MAP_COMPLETION\n");
  385. handle_retval(sock, uptr, buf);
  386. break;
  387. default:
  388. break;
  389. }
  390. }
  391. /*
  392. * Send a return value to the client for an RPC
  393. */
  394. int NetconEthernetTap::send_return_value(TcpConnection *conn, int retval)
  395. {
  396. char retmsg[4];
  397. memset(&retmsg, '\0', sizeof(retmsg));
  398. retmsg[0]=RPC_RETVAL;
  399. memcpy(&retmsg[1], &retval, sizeof(retval));
  400. int n = write(_phy.getDescriptor(conn->rpcSock), &retmsg, sizeof(retmsg));
  401. if(n > 0) {
  402. // signal that we've satisfied this requirement
  403. conn->pending = false;
  404. }
  405. else {
  406. fprintf(stderr, "unable to send return value to the intercept\n");
  407. closeConnection(conn);
  408. }
  409. return n;
  410. }
  411. /*------------------------------------------------------------------------------
  412. --------------------------------- LWIP callbacks -------------------------------
  413. ------------------------------------------------------------------------------*/
  414. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  415. // locked in this case!
  416. /*
  417. * Callback from LWIP for when a connection has been accepted and the PCB has been
  418. * put into an ACCEPT state.
  419. *
  420. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  421. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  422. * is then required to tell the service what new file descriptor it has allocated
  423. * for this connection. After the mapping is complete, the accepted socket can be
  424. * used.
  425. *
  426. * @param associated service state object
  427. * @param newly allocated PCB
  428. * @param error code
  429. * @return ERR_OK if everything is ok, -1 otherwise
  430. *
  431. */
  432. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  433. {
  434. fprintf(stderr, "nc_accept()\n");
  435. Larg *l = (Larg*)arg;
  436. TcpConnection *conn = l->conn;
  437. NetconEthernetTap *tap = l->tap;
  438. int larg_fd = tap->_phy.getDescriptor(conn->dataSock);
  439. if(conn) {
  440. ZT_PHY_SOCKFD_TYPE fds[2];
  441. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  442. TcpConnection *new_tcp_conn = new TcpConnection();
  443. new_tcp_conn->dataSock = tap->_phy.wrapSocket(fds[0], new_tcp_conn);
  444. new_tcp_conn->rpcSock = conn->rpcSock;
  445. new_tcp_conn->pcb = newpcb;
  446. new_tcp_conn->their_fd = fds[1];
  447. tap->tcp_connections.push_back(new_tcp_conn);
  448. int send_fd = tap->_phy.getDescriptor(conn->rpcSock);
  449. int n = write(larg_fd, "z", 1);
  450. if(n > 0) {
  451. if(sock_fd_write(send_fd, fds[1]) > 0) {
  452. new_tcp_conn->pending = true;
  453. fprintf(stderr, "nc_accept(): socketpair = { our=%d, their=%d}\n", fds[0], fds[1]);
  454. }
  455. else {
  456. fprintf(stderr, "nc_accept(%d): unable to send fd to client\n", larg_fd);
  457. }
  458. }
  459. else {
  460. fprintf(stderr, "nc_accept(%d): error writing signal byte (send_fd = %d, perceived_fd = %d)\n", larg_fd, send_fd, fds[1]);
  461. return -1;
  462. }
  463. tap->lwipstack->_tcp_arg(newpcb, new Larg(tap, new_tcp_conn));
  464. tap->lwipstack->_tcp_recv(newpcb, nc_recved);
  465. tap->lwipstack->_tcp_err(newpcb, nc_err);
  466. tap->lwipstack->_tcp_sent(newpcb, nc_sent);
  467. tap->lwipstack->_tcp_poll(newpcb, nc_poll, 0.5);
  468. tcp_accepted(conn->pcb);
  469. return ERR_OK;
  470. }
  471. else {
  472. fprintf(stderr, "nc_accept(%d): can't locate Connection object for PCB.\n", larg_fd);
  473. }
  474. return -1;
  475. }
  476. /*
  477. * Callback from LWIP for when data is available to be read from the network.
  478. *
  479. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  480. * send to the client over the associated unix socket.
  481. *
  482. * @param associated service state object
  483. * @param allocated PCB
  484. * @param chain of pbufs
  485. * @param error code
  486. * @return ERR_OK if everything is ok, -1 otherwise
  487. *
  488. */
  489. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  490. {
  491. fprintf(stderr, "nc_recved()\n");
  492. Larg *l = (Larg*)arg;
  493. int n;
  494. struct pbuf* q = p;
  495. if(!l->conn) {
  496. fprintf(stderr, "nc_recved(): no connection object\n");
  497. return ERR_OK; // ?
  498. }
  499. if(p == NULL) {
  500. if(l->conn) {
  501. fprintf(stderr, "nc_recved(): closing connection\n");
  502. l->tap->closeConnection(l->conn);
  503. }
  504. else {
  505. fprintf(stderr, "nc_recved(): can't locate connection via (arg)\n");
  506. }
  507. return err;
  508. }
  509. q = p;
  510. while(p != NULL) { // Cycle through pbufs and write them to the socket
  511. if(p->len <= 0)
  512. break; // ?
  513. if((n = l->tap->_phy.streamSend(l->conn->dataSock,p->payload, p->len)) > 0) {
  514. if(n < p->len) {
  515. fprintf(stderr, "nc_recved(): unable to write entire pbuf to buffer\n");
  516. }
  517. l->tap->lwipstack->_tcp_recved(tpcb, n); // TODO: would it be more efficient to call this once at the end?
  518. }
  519. else {
  520. fprintf(stderr, "nc_recved(): No data written to intercept buffer\n");
  521. }
  522. p = p->next;
  523. }
  524. l->tap->lwipstack->_pbuf_free(q); // free pbufs
  525. return ERR_OK;
  526. }
  527. /*
  528. * Callback from LWIP when an internal error is associtated with the given (arg)
  529. *
  530. * Since the PCB related to this error might no longer exist, only its perviously
  531. * associated (arg) is provided to us.
  532. *
  533. * @param associated service state object
  534. * @param error code
  535. *
  536. */
  537. void NetconEthernetTap::nc_err(void *arg, err_t err)
  538. {
  539. //fprintf(stderr, "nc_err\n");
  540. Larg *l = (Larg*)arg;
  541. if(l->conn) {
  542. fprintf(stderr, "nc_err(): closing connection\n");
  543. l->tap->closeConnection(l->conn);
  544. }
  545. else {
  546. fprintf(stderr, "nc_err(): can't locate connection object for PCB\n");
  547. }
  548. }
  549. /*
  550. * Callback from LWIP to do whatever work we might need to do.
  551. *
  552. * @param associated service state object
  553. * @param PCB we're polling on
  554. * @return ERR_OK if everything is ok, -1 otherwise
  555. *
  556. */
  557. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  558. {
  559. uint64_t now = OSUtils::now();
  560. //fprintf(stderr, "nc_poll(): now = %u\n", now);
  561. //fprintf(stderr, "nc_poll\n");
  562. Larg *l = (Larg*)arg;
  563. TcpConnection *conn = l->conn;
  564. NetconEthernetTap *tap = l->tap;
  565. if(conn && conn->idx) // if valid connection and non-zero index (indicating data present)
  566. tap->handle_write(conn);
  567. return ERR_OK;
  568. }
  569. /*
  570. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  571. * As a result, we should put our socket back into a notify-on-readability state
  572. * since there is now room on the PCB buffer to write to.
  573. *
  574. * NOTE: This could be used to track the amount of data sent by a connection.
  575. *
  576. * @param associated service state object
  577. * @param relevant PCB
  578. * @param length of data sent
  579. * @return ERR_OK if everything is ok, -1 otherwise
  580. *
  581. */
  582. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  583. {
  584. Larg *l = (Larg*)arg;
  585. if(len) {
  586. //fprintf(stderr, "ACKING len = %d, setting read-notify = true, (sndbuf = %d)\n", len, l->conn->pcb->snd_buf);
  587. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  588. //uint64_t now = OSUtils::now();
  589. //fprintf(stderr, "nc_sent(): now = %u\n", now);
  590. //l->tap->_phy.whack();
  591. //l->tap->handle_write(l->conn);
  592. }
  593. return ERR_OK;
  594. }
  595. /*
  596. * Callback from LWIP which sends a return value to the client to signal that
  597. * a connection was established for this PCB
  598. *
  599. * @param associated service state object
  600. * @param relevant PCB
  601. * @param error code
  602. * @return ERR_OK if everything is ok, -1 otherwise
  603. *
  604. */
  605. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  606. {
  607. //fprintf(stderr, "nc_connected\n");
  608. Larg *l = (Larg*)arg;
  609. l->tap->send_return_value(l->conn, err);
  610. return ERR_OK;
  611. }
  612. /*------------------------------------------------------------------------------
  613. ----------------------------- RPC Handler functions ----------------------------
  614. ------------------------------------------------------------------------------*/
  615. /*
  616. * Handles an RPC to bind an LWIP PCB to a given address and port
  617. *
  618. * @param Client that is making the RPC
  619. * @param structure containing the data and parameters for this client's RPC
  620. *
  621. */
  622. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  623. {
  624. struct sockaddr_in *connaddr;
  625. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  626. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  627. ip_addr_t conn_addr;
  628. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  629. TcpConnection *conn = getConnectionByTheirFD(bind_rpc->sockfd);
  630. if(conn) {
  631. if(conn->pcb->state == CLOSED){
  632. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  633. if(err != ERR_OK) {
  634. int ip = connaddr->sin_addr.s_addr;
  635. unsigned char d[4];
  636. d[0] = ip & 0xFF;
  637. d[1] = (ip >> 8) & 0xFF;
  638. d[2] = (ip >> 16) & 0xFF;
  639. d[3] = (ip >> 24) & 0xFF;
  640. fprintf(stderr, "handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  641. }
  642. }
  643. else fprintf(stderr, "handle_bind(): PCB not in CLOSED state. Ignoring BIND request.\n");
  644. }
  645. else fprintf(stderr, "handle_bind(): can't locate connection for PCB\n");
  646. }
  647. /*
  648. * Handles an RPC to put an LWIP PCB into LISTEN mode
  649. *
  650. * @param Client that is making the RPC
  651. * @param structure containing the data and parameters for this client's RPC
  652. *
  653. */
  654. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  655. {
  656. TcpConnection *conn = getConnectionByTheirFD(listen_rpc->sockfd);
  657. if(conn) {
  658. if(conn->pcb->state == LISTEN) {
  659. fprintf(stderr, "handle_listen(): PCB is already in listening state.\n");
  660. return;
  661. }
  662. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(conn->pcb);
  663. if(listening_pcb != NULL) {
  664. conn->pcb = listening_pcb;
  665. lwipstack->tcp_accept(listening_pcb, nc_accept);
  666. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  667. /* we need to wait for the client to send us the fd allocated on their end
  668. for this listening socket */
  669. conn->pending = true;
  670. }
  671. else {
  672. fprintf(stderr, "handle_listen(): unable to allocate memory for new listening PCB\n");
  673. }
  674. }
  675. else {
  676. fprintf(stderr, "handle_listen(): can't locate connection for PCB\n");
  677. }
  678. }
  679. /**
  680. * Handles a return value (client's perceived fd) and completes a mapping
  681. * so that we know what connection an RPC call should be associated with.
  682. *
  683. * @param Client that is making the RPC
  684. * @param structure containing the data and parameters for this client's RPC
  685. *
  686. */
  687. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, unsigned char* buf)
  688. {
  689. TcpConnection *conn = (TcpConnection*)*uptr;
  690. if(conn->pending) {
  691. memcpy(&(conn->perceived_fd), &buf[1], sizeof(int));
  692. //fprintf(stderr, "handle_retval(): Mapping [our=%d -> their=%d]\n",
  693. //_phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  694. conn->pending = false;
  695. }
  696. }
  697. /*
  698. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  699. *
  700. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  701. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  702. * is then required to tell the service what new file descriptor it has allocated
  703. * for this connection. After the mapping is complete, the socket can be used.
  704. *
  705. * @param Client that is making the RPC
  706. * @param structure containing the data and parameters for this client's RPC
  707. *
  708. */
  709. void NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  710. {
  711. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  712. if(newpcb != NULL) {
  713. ZT_PHY_SOCKFD_TYPE fds[2];
  714. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  715. TcpConnection *new_conn = new TcpConnection();
  716. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  717. *uptr = new_conn;
  718. new_conn->rpcSock = sock;
  719. new_conn->pcb = newpcb;
  720. new_conn->their_fd = fds[1];
  721. tcp_connections.push_back(new_conn);
  722. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  723. //fprintf(stderr, "handle_socket(): socketpair = { our=%d, their=%d}\n", fds[0], fds[1]);
  724. /* Once the client tells us what its fd is for the other end,
  725. we can then complete the mapping */
  726. new_conn->pending = true;
  727. }
  728. else {
  729. fprintf(stderr, "handle_socket(): Memory not available for new PCB\n");
  730. }
  731. }
  732. /*
  733. * Handles an RPC to connect to a given address and port
  734. *
  735. * @param Client that is making the RPC
  736. * @param structure containing the data and parameters for this client's RPC
  737. *
  738. */
  739. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  740. {
  741. TcpConnection *conn = (TcpConnection*)*uptr;
  742. struct sockaddr_in *connaddr;
  743. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  744. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  745. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  746. if(conn != NULL) {
  747. lwipstack->tcp_sent(conn->pcb, nc_sent); // FIXME: Move?
  748. lwipstack->tcp_recv(conn->pcb, nc_recved);
  749. lwipstack->tcp_err(conn->pcb, nc_err);
  750. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  751. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  752. int err = 0;
  753. if((err = lwipstack->tcp_connect(conn->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  754. {
  755. fprintf(stderr, "handle_connect(): unable to connect\n");
  756. // We should only return a value if failure happens immediately
  757. // Otherwise, we still need to wait for a callback from lwIP.
  758. // - This is because an ERR_OK from tcp_connect() only verifies
  759. // that the SYN packet was enqueued onto the stack properly,
  760. // that's it!
  761. // - Most instances of a retval for a connect() should happen
  762. // in the nc_connect() and nc_err() callbacks!
  763. send_return_value(conn, err);
  764. }
  765. // Everything seems to be ok, but we don't have enough info to retval
  766. conn->pending=true;
  767. }
  768. else {
  769. fprintf(stderr, "could not locate PCB based on their fd\n");
  770. }
  771. }
  772. void NetconEthernetTap::handle_write(TcpConnection *conn)
  773. {
  774. float max = (float)TCP_SND_BUF;
  775. int r;
  776. if(!conn) {
  777. fprintf(stderr, "handle_write(): could not locate connection for this fd\n");
  778. return;
  779. }
  780. if(conn->idx < max) {
  781. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  782. /* PCB send buffer is full,turn off readability notifications for the
  783. corresponding PhySocket until nc_sent() is called and confirms that there is
  784. now space on the buffer */
  785. if(sndbuf == 0) {
  786. //fprintf(stderr, "sndbuf = 0, setting read-notify = false\n");
  787. _phy.setNotifyReadable(conn->dataSock, false);
  788. lwipstack->_tcp_output(conn->pcb);
  789. return;
  790. }
  791. int read_fd = _phy.getDescriptor(conn->dataSock);
  792. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  793. //fprintf(stderr, "read = %d\n", r);
  794. conn->idx += r;
  795. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  796. * data to LWIP to be enqueued and eventually sent to the network. */
  797. if(r > 0) {
  798. int sz;
  799. // NOTE: this assumes that lwipstack->_lock is locked, either
  800. // because we are in a callback or have locked it manually.
  801. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  802. if(err != ERR_OK) {
  803. fprintf(stderr, "handle_write(): error while writing to PCB\n");
  804. return;
  805. }
  806. else {
  807. sz = (conn->idx)-r;
  808. if(sz) {
  809. memmove(&conn->buf, (conn->buf+r), sz);
  810. }
  811. conn->idx -= r;
  812. return;
  813. }
  814. }
  815. else {
  816. fprintf(stderr, "handle_write(): LWIP stack full\n");
  817. return;
  818. }
  819. }
  820. //else {
  821. // fprintf(stderr, "handle_write(): could not read from PhySocket for this connection\n");
  822. //}
  823. }
  824. }
  825. } // namespace ZeroTier
  826. #endif // ZT_ENABLE_NETCON