NetconEthernetTap.cpp 27 KB

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