NetconEthernetTap.cpp 28 KB

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