NetconEthernetTap.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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. if(interface.input(p, &interface) != ERR_OK) {
  177. fprintf(stderr, "_put(): Error while RXing packet (netif->input)\n");
  178. }
  179. }
  180. std::string NetconEthernetTap::deviceName() const
  181. {
  182. return _dev;
  183. }
  184. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  185. {
  186. }
  187. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  188. {
  189. std::vector<MulticastGroup> newGroups;
  190. Mutex::Lock _l(_multicastGroups_m);
  191. // TODO: get multicast subscriptions from LWIP
  192. std::vector<InetAddress> allIps(ips());
  193. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  194. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  195. std::sort(newGroups.begin(),newGroups.end());
  196. std::unique(newGroups.begin(),newGroups.end());
  197. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  198. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  199. added.push_back(*m);
  200. }
  201. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  202. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  203. removed.push_back(*m);
  204. }
  205. _multicastGroups.swap(newGroups);
  206. }
  207. NetconConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  208. {
  209. NetconConnection *c;
  210. for(size_t i=0; i<clients.size(); i++) {
  211. c = clients[i]->containsPCB(pcb);
  212. if(c) return c;
  213. }
  214. return NULL;
  215. }
  216. NetconConnection *NetconEthernetTap::getConnectionByThisFD(int fd)
  217. {
  218. for(size_t i=0; i<clients.size(); i++) {
  219. for(size_t j=0; j<clients[i]->connections.size(); j++) {
  220. if(_phy.getDescriptor(clients[i]->connections[j]->sock) == fd)
  221. return clients[i]->connections[j];
  222. }
  223. }
  224. return NULL;
  225. }
  226. NetconClient *NetconEthernetTap::getClientByPCB(struct tcp_pcb *pcb)
  227. {
  228. for(size_t i=0; i<clients.size(); i++) {
  229. if(clients[i]->containsPCB(pcb))
  230. return clients[i];
  231. }
  232. return NULL;
  233. }
  234. void NetconEthernetTap::closeAllClients()
  235. {
  236. for(size_t i=0; i<clients.size(); i++){
  237. closeClient(clients[i]);
  238. }
  239. }
  240. /*
  241. * Closes a NetconConnection and associated LWIP PCB strcuture.
  242. */
  243. void NetconEthernetTap::closeConnection(NetconConnection *conn)
  244. {
  245. NetconClient *client = conn->owner;
  246. lwipstack->tcp_arg(conn->pcb, NULL);
  247. lwipstack->tcp_sent(conn->pcb, NULL);
  248. lwipstack->tcp_recv(conn->pcb, NULL);
  249. lwipstack->tcp_err(conn->pcb, NULL);
  250. lwipstack->tcp_poll(conn->pcb, NULL, 0);
  251. lwipstack->tcp_close(conn->pcb);
  252. _phy.close(conn->sock);
  253. lwipstack->tcp_close(conn->pcb);
  254. client->removeConnection(conn->sock);
  255. }
  256. /*
  257. * Closes a NetconClient and all associated NetconConnections (rpc, data, and unmapped)
  258. */
  259. void NetconEthernetTap::closeClient(NetconClient *client)
  260. {
  261. closeConnection(client->rpc);
  262. closeConnection(client->unmapped_conn);
  263. for(size_t i=0; i<client->connections.size(); i++)
  264. {
  265. close(_phy.getDescriptor(client->connections[i]->sock));
  266. lwipstack->tcp_close(client->connections[i]->pcb);
  267. delete client->connections[i];
  268. client->connections.erase(client->connections.begin() + i);
  269. }
  270. }
  271. #define ZT_LWIP_TCP_TIMER_INTERVAL 10
  272. void NetconEthernetTap::threadMain()
  273. throw()
  274. {
  275. uint64_t prev_tcp_time = 0;
  276. uint64_t prev_etharp_time = 0;
  277. /*
  278. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  279. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  280. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  281. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  282. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  283. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n", MEMP_NUM_TCP_SEG);
  284. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  285. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n", TCP_SND_QUEUELEN);
  286. fprintf(stderr, "- IP_REASSEMBLY = %d\n", IP_REASSEMBLY);
  287. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  288. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  289. fprintf(stderr, "- NO_SYS = %d\n", NO_SYS);
  290. fprintf(stderr, "- LWIP_SOCKET = %d\n", LWIP_SOCKET);
  291. fprintf(stderr, "- LWIP_NETCONN = %d\n", LWIP_NETCONN);
  292. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  293. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  294. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  295. fprintf(stderr, "- DEFAULT_READ_BUFFER_SIZE = %d\n", DEFAULT_READ_BUFFER_SIZE);
  296. */
  297. //fprintf(stderr, "- LWIP_DEBUG = %d\n", LWIP_DEBUG);
  298. fprintf(stderr, "- TCP_DEBUG = %d\n", TCP_DEBUG);
  299. // Main timer loop
  300. while (_run) {
  301. uint64_t now = OSUtils::now();
  302. uint64_t since_tcp = now - prev_tcp_time;
  303. uint64_t since_etharp = now - prev_etharp_time;
  304. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  305. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  306. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  307. prev_tcp_time = now;
  308. lwipstack->tcp_tmr();
  309. } else {
  310. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  311. }
  312. if (since_etharp >= ARP_TMR_INTERVAL) {
  313. prev_etharp_time = now;
  314. lwipstack->etharp_tmr();
  315. } else {
  316. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  317. }
  318. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  319. }
  320. closeAllClients();
  321. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  322. }
  323. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  324. {
  325. fprintf(stderr, "phyOnUnixClose()\n");
  326. close(_phy.getDescriptor(sock));
  327. }
  328. /*
  329. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  330. */
  331. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  332. {
  333. if(readable) {
  334. int r;
  335. NetconConnection *c = ((NetconClient*)*uptr)->getConnection(sock);
  336. if(c->idx < DEFAULT_READ_BUFFER_SIZE) {
  337. if((r = read(_phy.getDescriptor(sock), (&c->buf)+c->idx, DEFAULT_READ_BUFFER_SIZE-(c->idx))) > 0) {
  338. c->idx += r;
  339. handle_write(c);
  340. }
  341. }
  342. }
  343. }
  344. // Unused -- no UDP or TCP from this thread/Phy<>
  345. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  346. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  347. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  348. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  349. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  350. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  351. /*
  352. * Creates a new NetconClient for the accepted RPC connection (unix domain socket)
  353. *
  354. * Subsequent socket connections from this client will be associated with this
  355. * NetconClient object.
  356. */
  357. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  358. {
  359. NetconClient *newClient = new NetconClient();
  360. newClient->rpc = newClient->addConnection(RPC, sockN);
  361. *uptrN = newClient;
  362. clients.push_back(newClient);
  363. }
  364. /*
  365. * Processes incoming data on a client-specific RPC connection
  366. */
  367. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  368. {
  369. unsigned char *buf = (unsigned char*)data;
  370. NetconClient *client = (NetconClient*)*uptr;
  371. switch(buf[0])
  372. {
  373. case RPC_SOCKET:
  374. fprintf(stderr, "RPC_SOCKET\n");
  375. struct socket_st socket_rpc;
  376. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  377. client->tid = socket_rpc.__tid;
  378. handle_socket(client, &socket_rpc);
  379. break;
  380. case RPC_LISTEN:
  381. fprintf(stderr, "RPC_LISTEN\n");
  382. struct listen_st listen_rpc;
  383. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  384. client->tid = listen_rpc.__tid;
  385. handle_listen(client, &listen_rpc);
  386. break;
  387. case RPC_BIND:
  388. fprintf(stderr, "RPC_BIND\n");
  389. struct bind_st bind_rpc;
  390. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  391. client->tid = bind_rpc.__tid;
  392. handle_bind(client, &bind_rpc);
  393. break;
  394. case RPC_KILL_INTERCEPT:
  395. fprintf(stderr, "RPC_KILL_INTERCEPT\n");
  396. closeClient(client);
  397. break;
  398. case RPC_CONNECT:
  399. fprintf(stderr, "RPC_CONNECT\n");
  400. struct connect_st connect_rpc;
  401. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  402. client->tid = connect_rpc.__tid;
  403. handle_connect(client, &connect_rpc);
  404. break;
  405. case RPC_FD_MAP_COMPLETION:
  406. fprintf(stderr, "RPC_FD_MAP_COMPLETION\n");
  407. handle_retval(client, buf);
  408. break;
  409. default:
  410. break;
  411. }
  412. }
  413. /*
  414. * Send a return value to the client for an RPC
  415. */
  416. int NetconEthernetTap::send_return_value(NetconClient *client, int retval)
  417. {
  418. char retmsg[4];
  419. memset(&retmsg, '\0', sizeof(retmsg));
  420. retmsg[0]=RPC_RETVAL;
  421. memcpy(&retmsg[1], &retval, sizeof(retval));
  422. int n = write(_phy.getDescriptor(client->rpc->sock), &retmsg, sizeof(retmsg));
  423. if(n > 0) {
  424. // signal that we've satisfied this requirement
  425. client->waiting_for_retval = false;
  426. }
  427. else {
  428. fprintf(stderr, "unable to send return value to the intercept\n");
  429. closeClient(client);
  430. }
  431. return n;
  432. }
  433. /*------------------------------------------------------------------------------
  434. --------------------------------- LWIP callbacks -------------------------------
  435. ------------------------------------------------------------------------------*/
  436. /*
  437. * Callback from LWIP to do whatever work we might need to do.
  438. *
  439. * @param associated service state object
  440. * @param PCB we're polling on
  441. * @return ERR_OK if everything is ok, -1 otherwise
  442. *
  443. */
  444. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  445. {
  446. Larg *l = (Larg*)arg;
  447. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  448. NetconEthernetTap *tap = l->tap;
  449. if(c)
  450. tap->handle_write(c);
  451. return ERR_OK;
  452. }
  453. /*
  454. * Callback from LWIP for when a connection has been accepted and the PCB has been
  455. * put into an ACCEPT state.
  456. *
  457. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  458. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  459. * is then required to tell the service what new file descriptor it has allocated
  460. * for this connection. After the mapping is complete, the accepted socket can be
  461. * used.
  462. *
  463. * @param associated service state object
  464. * @param newly allocated PCB
  465. * @param error code
  466. * @return ERR_OK if everything is ok, -1 otherwise
  467. *
  468. */
  469. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  470. {
  471. Larg *l = (Larg*)arg;
  472. int larg_fd = l->tap->_phy.getDescriptor(l->sock);
  473. NetconEthernetTap *tap = l->tap;
  474. NetconConnection *c = tap->getConnectionByThisFD(larg_fd);
  475. if(c) {
  476. NetconClient *client = c->owner;
  477. if(!client){
  478. fprintf(stderr, "nc_accpet(%d): unable to locate client for this PCB\n", larg_fd);
  479. return -1;
  480. }
  481. ZT_PHY_SOCKFD_TYPE fds[2];
  482. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  483. NetconConnection *new_conn = client->addConnection(BUFFER, tap->_phy.wrapSocket(fds[0], client));
  484. client->connections.push_back(new_conn);
  485. new_conn->pcb = newpcb;
  486. int send_fd = tap->_phy.getDescriptor(client->rpc->sock);
  487. int n = write(larg_fd, "z", 1);
  488. if(n > 0) {
  489. if(sock_fd_write(send_fd, fds[1]) > 0) {
  490. client->unmapped_conn = new_conn;
  491. }
  492. else {
  493. fprintf(stderr, "nc_accept(%d): unable to send fd to client\n", larg_fd);
  494. }
  495. }
  496. else {
  497. fprintf(stderr, "nc_accept(%d): error writing signal byte (send_fd = %d, their_fd = %d)\n", larg_fd, send_fd, fds[1]);
  498. return -1;
  499. }
  500. tap->lwipstack->tcp_arg(newpcb, new Larg(tap, new_conn->sock));
  501. tap->lwipstack->tcp_recv(newpcb, nc_recved);
  502. tap->lwipstack->tcp_err(newpcb, nc_err);
  503. tap->lwipstack->tcp_sent(newpcb, nc_sent);
  504. tap->lwipstack->tcp_poll(newpcb, nc_poll, 1);
  505. tcp_accepted(c->pcb);
  506. return ERR_OK;
  507. }
  508. else {
  509. fprintf(stderr, "nc_accept(%d): can't locate Connection object for PCB.\n", larg_fd);
  510. }
  511. return -1;
  512. }
  513. /*
  514. * Callback from LWIP for when data is available to be read from the network.
  515. *
  516. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  517. * send to the client over the associated unix socket.
  518. *
  519. * @param associated service state object
  520. * @param allocated PCB
  521. * @param chain of pbufs
  522. * @param error code
  523. * @return ERR_OK if everything is ok, -1 otherwise
  524. *
  525. */
  526. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  527. {
  528. Larg *l = (Larg*)arg;
  529. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  530. NetconEthernetTap *tap = l->tap;
  531. int n;
  532. struct pbuf* q = p;
  533. if(!c) {
  534. fprintf(stderr, "nc_recved(): no connection object\n");
  535. return ERR_OK; // ?
  536. }
  537. if(p == NULL) {
  538. if(c) {
  539. fprintf(stderr, "nc_recved(): closing connection\n");
  540. tap->_phy.close(c->sock);
  541. tap->closeConnection(c);
  542. }
  543. else {
  544. fprintf(stderr, "nc_recved(): can't locate connection via (arg)\n");
  545. }
  546. return err;
  547. }
  548. q = p;
  549. while(p != NULL) { // Cycle through pbufs and write them to the socket
  550. if(p->len <= 0)
  551. break; // ?
  552. if((n = tap->_phy.streamSend(c->sock,p->payload, p->len)) > 0) {
  553. if(n < p->len) {
  554. fprintf(stderr, "nc_recved(): unable to write entire pbuf to buffer\n");
  555. }
  556. tap->lwipstack->tcp_recved(tpcb, n);
  557. }
  558. else {
  559. fprintf(stderr, "nc_recved(): No data written to intercept buffer\n");
  560. }
  561. p = p->next;
  562. }
  563. tap->lwipstack->pbuf_free(q); // free pbufs
  564. return ERR_OK;
  565. }
  566. /*
  567. * Callback from LWIP when an internal error is associtated with the given (arg)
  568. *
  569. * Since the PCB related to this error might no longer exist, only its perviously
  570. * associated (arg) is provided to us.
  571. *
  572. * @param associated service state object
  573. * @param error code
  574. *
  575. */
  576. void NetconEthernetTap::nc_err(void *arg, err_t err)
  577. {
  578. fprintf(stderr, "nc_err\n");
  579. Larg *l = (Larg*)arg;
  580. NetconEthernetTap *tap = l->tap;
  581. NetconConnection *c = tap->getConnectionByThisFD(tap->_phy.getDescriptor(l->sock));
  582. if(c) {
  583. tap->closeConnection(c);
  584. }
  585. else {
  586. fprintf(stderr, "can't locate connection object for PCB\n");
  587. }
  588. }
  589. /*
  590. * Callback from LWIP
  591. *
  592. * This could be used to track the amount of data sent by a connection.
  593. *
  594. * @param associated service state object
  595. * @param relevant PCB
  596. * @param length of data sent
  597. * @return ERR_OK if everything is ok, -1 otherwise
  598. *
  599. */
  600. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  601. {
  602. //fprintf(stderr, "nc_sent\n");
  603. return len;
  604. }
  605. /*
  606. * Callback from LWIP which sends a return value to the client to signal that
  607. * a connection was established for this PCB
  608. *
  609. * @param associated service state object
  610. * @param relevant PCB
  611. * @param error code
  612. * @return ERR_OK if everything is ok, -1 otherwise
  613. *
  614. */
  615. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  616. {
  617. fprintf(stderr, "nc_connected\n");
  618. Larg *l = (Larg*)arg;
  619. NetconEthernetTap *tap = l->tap;
  620. for(size_t i=0; i<tap->clients.size(); i++) {
  621. if(tap->clients[i]->containsPCB(tpcb)) {
  622. tap->send_return_value(tap->clients[i],err);
  623. }
  624. }
  625. return err;
  626. }
  627. /*------------------------------------------------------------------------------
  628. ----------------------------- RPC Handler functions ----------------------------
  629. ------------------------------------------------------------------------------*/
  630. /*
  631. * Handles an RPC to bind an LWIP PCB to a given address and port
  632. *
  633. * @param Client that is making the RPC
  634. * @param structure containing the data and parameters for this client's RPC
  635. *
  636. */
  637. void NetconEthernetTap::handle_bind(NetconClient *client, struct bind_st *bind_rpc)
  638. {
  639. struct sockaddr_in *connaddr;
  640. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  641. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  642. ip_addr_t conn_addr;
  643. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  644. NetconConnection *c = client->getConnectionByTheirFD(bind_rpc->sockfd);
  645. if(c) {
  646. if(c->pcb->state == CLOSED){
  647. int err = lwipstack->tcp_bind(c->pcb, &conn_addr, conn_port);
  648. if(err != ERR_OK) {
  649. int ip = connaddr->sin_addr.s_addr;
  650. unsigned char d[4];
  651. d[0] = ip & 0xFF;
  652. d[1] = (ip >> 8) & 0xFF;
  653. d[2] = (ip >> 16) & 0xFF;
  654. d[3] = (ip >> 24) & 0xFF;
  655. fprintf(stderr, "handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  656. }
  657. }
  658. else fprintf(stderr, "handle_bind(): PCB not in CLOSED state. Ignoring BIND request.\n");
  659. }
  660. else fprintf(stderr, "handle_bind(): can't locate connection for PCB\n");
  661. }
  662. /*
  663. * Handles an RPC to put an LWIP PCB into LISTEN mode
  664. *
  665. * @param Client that is making the RPC
  666. * @param structure containing the data and parameters for this client's RPC
  667. *
  668. */
  669. void NetconEthernetTap::handle_listen(NetconClient *client, struct listen_st *listen_rpc)
  670. {
  671. NetconConnection *c = client->getConnectionByTheirFD(listen_rpc->sockfd);
  672. if(c) {
  673. if(c->pcb->state == LISTEN) {
  674. fprintf(stderr, "handle_listen(): PCB is already in listening state.\n");
  675. return;
  676. }
  677. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(c->pcb);
  678. if(listening_pcb != NULL) {
  679. c->pcb = listening_pcb;
  680. lwipstack->tcp_accept(listening_pcb, nc_accept);
  681. lwipstack->tcp_arg(listening_pcb, new Larg(this, c->sock));
  682. /* we need to wait for the client to send us the fd allocated on their end
  683. for this listening socket */
  684. client->waiting_for_retval=true;
  685. }
  686. else {
  687. fprintf(stderr, "handle_listen(): unable to allocate memory for new listening PCB\n");
  688. }
  689. }
  690. else {
  691. fprintf(stderr, "handle_listen(): can't locate connection for PCB\n");
  692. }
  693. }
  694. /**
  695. * Handles a return value (client's perceived fd) and completes a mapping
  696. * so that we know what connection an RPC call should be associated with.
  697. *
  698. * @param Client that is making the RPC
  699. * @param structure containing the data and parameters for this client's RPC
  700. *
  701. */
  702. void NetconEthernetTap::handle_retval(NetconClient *client, unsigned char* buf)
  703. {
  704. if(client->unmapped_conn != NULL) {
  705. memcpy(&(client->unmapped_conn->their_fd), &buf[1], sizeof(int));
  706. client->connections.push_back(client->unmapped_conn);
  707. client->unmapped_conn = NULL;
  708. }
  709. }
  710. /*
  711. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  712. *
  713. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  714. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  715. * is then required to tell the service what new file descriptor it has allocated
  716. * for this connection. After the mapping is complete, the socket can be used.
  717. *
  718. * @param Client that is making the RPC
  719. * @param structure containing the data and parameters for this client's RPC
  720. *
  721. */
  722. void NetconEthernetTap::handle_socket(NetconClient *client, struct socket_st* socket_rpc)
  723. {
  724. struct tcp_pcb *pcb = lwipstack->tcp_new();
  725. if(pcb != NULL) {
  726. ZT_PHY_SOCKFD_TYPE fds[2];
  727. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  728. NetconConnection *new_conn = client->addConnection(BUFFER, _phy.wrapSocket(fds[0], client));
  729. new_conn->pcb = pcb;
  730. PhySocket *sock = client->rpc->sock;
  731. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  732. /* Once the client tells us what its fd is for the other end,
  733. we can then complete the mapping */
  734. client->unmapped_conn = new_conn;
  735. }
  736. else {
  737. fprintf(stderr, "handle_socket(): Memory not available for new PCB\n");
  738. }
  739. }
  740. /*
  741. * Handles an RPC to connect to a given address and port
  742. *
  743. * @param Client that is making the RPC
  744. * @param structure containing the data and parameters for this client's RPC
  745. *
  746. */
  747. void NetconEthernetTap::handle_connect(NetconClient *client, struct connect_st* connect_rpc)
  748. {
  749. struct sockaddr_in *connaddr;
  750. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  751. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  752. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  753. NetconConnection *c = client->getConnectionByTheirFD(connect_rpc->__fd);
  754. if(c != NULL) {
  755. lwipstack->tcp_sent(c->pcb, nc_sent); // FIXME: Move?
  756. lwipstack->tcp_recv(c->pcb, nc_recved);
  757. lwipstack->tcp_err(c->pcb, nc_err);
  758. lwipstack->tcp_poll(c->pcb, nc_poll, APPLICATION_POLL_FREQ);
  759. lwipstack->tcp_arg(c->pcb, new Larg(this, c->sock));
  760. int err = 0;
  761. if((err = lwipstack->tcp_connect(c->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  762. {
  763. fprintf(stderr, "handle_connect(): unable to connect\n");
  764. // We should only return a value if failure happens immediately
  765. // Otherwise, we still need to wait for a callback from lwIP.
  766. // - This is because an ERR_OK from tcp_connect() only verifies
  767. // that the SYN packet was enqueued onto the stack properly,
  768. // that's it!
  769. // - Most instances of a retval for a connect() should happen
  770. // in the nc_connect() and nc_err() callbacks!
  771. send_return_value(client, err);
  772. }
  773. // Everything seems to be ok, but we don't have enough info to retval
  774. client->waiting_for_retval=true;
  775. }
  776. else {
  777. fprintf(stderr, "could not locate PCB based on their fd\n");
  778. }
  779. }
  780. /*
  781. * Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  782. * data to LWIP to be enqueued and eventually sent to the network.
  783. * *
  784. * @param Client that is making the RPC
  785. * @param structure containing the data and parameters for this client's RPC
  786. *
  787. * TODO: Optimize write logic (should we stop using poll?)
  788. */
  789. void NetconEthernetTap::handle_write(NetconConnection *c)
  790. {
  791. if(c) {
  792. int sndbuf = c->pcb->snd_buf;
  793. float avail = (float)sndbuf;
  794. float max = (float)TCP_SND_BUF;
  795. float load = 1.0 - (avail / max);
  796. if(load >= 0.9) {
  797. return;
  798. }
  799. int sz, write_allowance = sndbuf < c->idx ? sndbuf : c->idx;
  800. if(write_allowance > 0) {
  801. int err = lwipstack->tcp_write(c->pcb, &c->buf, write_allowance, 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 = (c->idx)-write_allowance;
  808. if(sz) {
  809. memmove(&c->buf, (c->buf+write_allowance), sz);
  810. }
  811. c->idx -= write_allowance;
  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 locate connection for this fd\n");
  822. }
  823. }
  824. } // namespace ZeroTier
  825. #endif // ZT_ENABLE_NETCON