NetconEthernetTap.cpp 28 KB

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