NetconEthernetTap.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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 "../node/Node.hpp" // for TRACE
  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 "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("/root/dev/netcon/liblwip.so");
  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. Mutex::Lock _l2(_arp_m);
  103. _arp.setLocal((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(ip)->sin_addr.s_addr),_mac);
  104. }
  105. // TODO: alloc IP in LWIP
  106. //netif_set_addr(netif, ipaddr, netmask, gw);
  107. }
  108. return true; // TODO: what is exapected?
  109. }
  110. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  111. {
  112. Mutex::Lock _l(_ips_m);
  113. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  114. if (i == _ips.end())
  115. return false;
  116. _ips.erase(i);
  117. if (ip.isV4()) {
  118. Mutex::Lock _l2(_arp_m);
  119. _arp.remove((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(ip)->sin_addr.s_addr));
  120. }
  121. // TODO: dealloc IP from LWIP
  122. return true;
  123. }
  124. std::vector<InetAddress> NetconEthernetTap::ips() const
  125. {
  126. Mutex::Lock _l(_ips_m);
  127. return _ips;
  128. }
  129. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  130. {
  131. if (!_enabled)
  132. return;
  133. if (etherType == ZT_ETHERTYPE_ARP) {
  134. char arpReplyBuf[ZT_ARP_BUF_LENGTH];
  135. unsigned int arpReplyLen = 0;
  136. MAC arpReplyDest;
  137. Mutex::Lock _l2(_arp_m);
  138. _arp.processIncomingArp(data,len,arpReplyBuf,arpReplyLen,arpReplyDest);
  139. if (arpReplyLen > 0)
  140. _handler(_arg,_nwid,_mac,from,ZT_ETHERTYPE_ARP,0,arpReplyBuf,arpReplyLen);
  141. } else if (etherType == ZT_ETHERTYPE_IPV4) {
  142. // TODO: pass IPv4 packets into LWIP
  143. }
  144. }
  145. std::string NetconEthernetTap::deviceName() const
  146. {
  147. return _dev;
  148. }
  149. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  150. {
  151. }
  152. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  153. {
  154. std::vector<MulticastGroup> newGroups;
  155. Mutex::Lock _l(_multicastGroups_m);
  156. // TODO: get multicast subscriptions from LWIP
  157. std::vector<InetAddress> allIps(ips());
  158. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  159. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  160. std::sort(newGroups.begin(),newGroups.end());
  161. std::unique(newGroups.begin(),newGroups.end());
  162. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  163. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  164. added.push_back(*m);
  165. }
  166. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  167. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  168. removed.push_back(*m);
  169. }
  170. _multicastGroups.swap(newGroups);
  171. }
  172. NetconConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  173. {
  174. NetconConnection *c;
  175. for(size_t i=0; i<clients.size(); i++) {
  176. c = clients[i]->containsPCB(pcb);
  177. if(c) {
  178. return c;
  179. }
  180. }
  181. return NULL;
  182. }
  183. NetconConnection *NetconEthernetTap::getConnectionByThisFD(int fd)
  184. {
  185. for(size_t i=0; i<clients.size(); i++) {
  186. for(size_t j=0; j<clients[i]->connections.size(); j++) {
  187. if(_phy.getDescriptor(clients[i]->connections[j]->sock) == fd) {
  188. return clients[i]->connections[j];
  189. }
  190. }
  191. }
  192. return NULL;
  193. }
  194. NetconClient *NetconEthernetTap::getClientByPCB(struct tcp_pcb *pcb)
  195. {
  196. for(size_t i=0; i<clients.size(); i++) {
  197. if(clients[i]->containsPCB(pcb)) {
  198. return clients[i];
  199. }
  200. }
  201. return NULL;
  202. }
  203. void NetconEthernetTap::closeClient(NetconClient *client)
  204. {
  205. NetconConnection *temp_conn;
  206. closeConnection(client->rpc);
  207. for(size_t i=0; i<client->connections.size(); i++) {
  208. temp_conn = client->connections[i];
  209. closeConnection(client->connections[i]);
  210. delete temp_conn;
  211. }
  212. delete client;
  213. }
  214. void NetconEthernetTap::closeConnection(NetconConnection *conn)
  215. {
  216. NetconClient *client = conn->owner;
  217. _phy.close(conn->sock);
  218. lwipstack->tcp_close(conn->pcb);
  219. client->removeConnection(conn->sock);
  220. }
  221. void NetconEthernetTap::threadMain()
  222. throw()
  223. {
  224. TRACE("starting threadMain()");
  225. static ip_addr_t ipaddr, netmask, gw;
  226. char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0};
  227. IP4_ADDR(&gw, 192,168,0,1);
  228. IP4_ADDR(&netmask, 255,255,255,0);
  229. IP4_ADDR(&ipaddr, 192,168,0,2);
  230. strncpy(ip_str, lwipstack->ipaddr_ntoa(&ipaddr), sizeof(ip_str));
  231. strncpy(nm_str, lwipstack->ipaddr_ntoa(&netmask), sizeof(nm_str));
  232. strncpy(gw_str, lwipstack->ipaddr_ntoa(&gw), sizeof(gw_str));
  233. unsigned long tcp_time = ARP_TMR_INTERVAL / 5000;
  234. unsigned long etharp_time = IP_TMR_INTERVAL / 1000;
  235. unsigned long prev_tcp_time = 0;
  236. unsigned long prev_etharp_time = 0;
  237. unsigned long curr_time;
  238. unsigned long since_tcp;
  239. unsigned long since_etharp;
  240. struct timeval tv;
  241. while (_run) {
  242. gettimeofday(&tv, NULL);
  243. curr_time = (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000;
  244. since_tcp = curr_time - prev_tcp_time;
  245. since_etharp = curr_time - prev_etharp_time;
  246. int min_time = min(since_tcp, since_etharp) * 1000; // usec
  247. if(since_tcp > tcp_time)
  248. {
  249. prev_tcp_time = curr_time+1;
  250. lwipstack->tcp_tmr();
  251. }
  252. if(since_etharp > etharp_time)
  253. {
  254. prev_etharp_time = curr_time;
  255. lwipstack->etharp_tmr();
  256. }
  257. _phy.poll(min_time / 1000); // conversion from usec to millisec, TODO: double check
  258. }
  259. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  260. }
  261. void NetconEthernetTap::phyOnSocketPairEndpointClose(PhySocket *sock, void **uptr)
  262. {
  263. NetconClient *client = (NetconClient*)*uptr;
  264. closeConnection(client->getConnection(sock));
  265. }
  266. void NetconEthernetTap::phyOnSocketPairEndpointData(PhySocket *sock, void **uptr, void *buf, unsigned long n)
  267. {
  268. int r;
  269. NetconConnection *c = ((NetconClient*)*uptr)->getConnection(sock);
  270. if(c) {
  271. if(c->idx < DEFAULT_READ_BUFFER_SIZE) {
  272. if((r = read(_phy.getDescriptor(c->sock), (&c->buf)+c->idx, DEFAULT_READ_BUFFER_SIZE-(c->idx))) > 0) {
  273. c->idx += r;
  274. handle_write(c);
  275. }
  276. }
  277. }
  278. }
  279. void NetconEthernetTap::phyOnSocketPairEndpointWritable(PhySocket *sock, void **uptr)
  280. {
  281. //_phy.setNotifyWritable(sock, false);
  282. }
  283. // Unused -- no UDP or TCP from this thread/Phy<>
  284. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  285. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  286. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  287. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  288. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  289. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  290. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  291. {
  292. NetconClient *newClient = new NetconClient();
  293. newClient->addConnection(RPC, *uptrN);
  294. }
  295. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  296. {
  297. closeClient(((NetconClient*)*uptr));
  298. }
  299. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  300. {
  301. unsigned char *buf = (unsigned char*)data;
  302. NetconClient *client = (NetconClient*)*uptr;
  303. switch(buf[0])
  304. {
  305. case RPC_SOCKET:
  306. TRACE("RPC_SOCKET");
  307. struct socket_st socket_rpc;
  308. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  309. client->tid = socket_rpc.__tid;
  310. handle_socket(client, &socket_rpc);
  311. break;
  312. case RPC_LISTEN:
  313. TRACE("RPC_LISTEN");
  314. struct listen_st listen_rpc;
  315. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  316. client->tid = listen_rpc.__tid;
  317. handle_listen(client, &listen_rpc);
  318. break;
  319. case RPC_BIND:
  320. TRACE("RPC_BIND");
  321. struct bind_st bind_rpc;
  322. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  323. client->tid = bind_rpc.__tid;
  324. handle_bind(client, &bind_rpc);
  325. break;
  326. case RPC_KILL_INTERCEPT:
  327. TRACE("RPC_KILL_INTERCEPT");
  328. closeClient(client);
  329. break;
  330. case RPC_CONNECT:
  331. TRACE("RPC_CONNECT");
  332. struct connect_st connect_rpc;
  333. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  334. client->tid = connect_rpc.__tid;
  335. handle_connect(client, &connect_rpc);
  336. break;
  337. case RPC_FD_MAP_COMPLETION:
  338. TRACE("RPC_FD_MAP_COMPLETION");
  339. handle_retval(client, buf);
  340. break;
  341. default:
  342. break;
  343. }
  344. }
  345. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  346. {
  347. }
  348. int NetconEthernetTap::send_return_value(NetconClient *client, int retval)
  349. {
  350. if(!client->waiting_for_retval){
  351. TRACE("intercept isn't waiting for return value. Why are we here?");
  352. return 0;
  353. }
  354. char retmsg[4];
  355. memset(&retmsg, '\0', sizeof(retmsg));
  356. retmsg[0]=RPC_RETVAL;
  357. memcpy(&retmsg[1], &retval, sizeof(retval));
  358. int n = write(_phy.getDescriptor(client->rpc->sock), &retmsg, sizeof(retmsg));
  359. if(n > 0) {
  360. // signal that we've satisfied this requirement
  361. client->waiting_for_retval = false;
  362. }
  363. else {
  364. TRACE("unable to send return value to the intercept");
  365. closeClient(client);
  366. }
  367. return n;
  368. }
  369. /*------------------------------------------------------------------------------
  370. --------------------------------- LWIP callbacks -------------------------------
  371. ------------------------------------------------------------------------------*/
  372. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  373. {
  374. TRACE("nc_poll");
  375. Larg *l = (Larg*)arg;
  376. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  377. NetconEthernetTap *tap = l->tap;
  378. if(c)
  379. tap->handle_write(c);
  380. return ERR_OK;
  381. }
  382. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  383. {
  384. TRACE("nc_accept");
  385. return ERR_OK;
  386. }
  387. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  388. {
  389. TRACE("nc_recved");
  390. Larg *l = (Larg*)arg;
  391. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  392. NetconEthernetTap *tap = l->tap;
  393. int n;
  394. struct pbuf* q = p;
  395. int our_fd = tap->_phy.getDescriptor(c->sock);
  396. if(!c) {
  397. return ERR_OK; // ?
  398. }
  399. if(p == NULL) {
  400. if(c) {
  401. nc_close(tpcb);
  402. close(our_fd); // TODO: Check logic
  403. tap->closeConnection(c);
  404. }
  405. else {
  406. TRACE("can't locate connection via (arg)");
  407. }
  408. return err;
  409. }
  410. q = p;
  411. while(p != NULL) { // Cycle through pbufs and write them to the socket
  412. if(p->len <= 0)
  413. break; // ?
  414. if((n = write(our_fd, p->payload, p->len)) > 0) {
  415. if(n < p->len) {
  416. TRACE("ERROR: unable to write entire pbuf to buffer");
  417. //tap->_phy.setNotifyWritable(l->sock, true);
  418. }
  419. tap->lwipstack->tcp_recved(tpcb, n);
  420. }
  421. else {
  422. TRACE("Error: No data written to intercept buffer");
  423. }
  424. p = p->next;
  425. }
  426. tap->lwipstack->pbuf_free(q); // free pbufs
  427. return ERR_OK;
  428. }
  429. void NetconEthernetTap::nc_err(void *arg, err_t err)
  430. {
  431. TRACE("nc_err");
  432. Larg *l = (Larg*)arg;
  433. NetconEthernetTap *tap = l->tap;
  434. NetconConnection *c = tap->getConnectionByThisFD(tap->_phy.getDescriptor(l->sock));
  435. if(c) {
  436. tap->closeConnection(c);
  437. }
  438. else {
  439. TRACE("can't locate connection object for PCB");
  440. }
  441. }
  442. void NetconEthernetTap::nc_close(struct tcp_pcb* tpcb)
  443. {
  444. TRACE("nc_close");
  445. //closeConnection(getConnectionByPCB(tpcb));
  446. /*
  447. lwipstack->tcp_arg(tpcb, NULL);
  448. lwipstack->tcp_sent(tpcb, NULL);
  449. lwipstack->tcp_recv(tpcb, NULL);
  450. lwipstack->tcp_err(tpcb, NULL);
  451. lwipstack->tcp_poll(tpcb, NULL, 0);
  452. lwipstack->tcp_close(tpcb);
  453. */
  454. }
  455. err_t NetconEthernetTap::nc_send(struct tcp_pcb *tpcb)
  456. {
  457. TRACE("nc_send");
  458. return ERR_OK;
  459. }
  460. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  461. {
  462. TRACE("nc_sent");
  463. return len;
  464. }
  465. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  466. {
  467. TRACE("nc_connected");
  468. Larg *l = (Larg*)arg;
  469. NetconEthernetTap *tap = l->tap;
  470. for(size_t i=0; i<tap->clients.size(); i++) {
  471. if(tap->clients[i]->containsPCB(tpcb)) {
  472. tap->send_return_value(tap->clients[i],err);
  473. }
  474. }
  475. return err;
  476. }
  477. /*------------------------------------------------------------------------------
  478. ----------------------------- RPC Handler functions ----------------------------
  479. ------------------------------------------------------------------------------*/
  480. void NetconEthernetTap::handle_bind(NetconClient *client, struct bind_st *bind_rpc)
  481. {
  482. // FIXME: Is this hack still needed?
  483. struct sockaddr_in *connaddr;
  484. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  485. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  486. ip_addr_t conn_addr;
  487. IP4_ADDR(&conn_addr, 192,168,0,2);
  488. /*
  489. int ip = connaddr->sin_addr.s_addr;
  490. unsigned char bytes[4];
  491. bytes[0] = ip & 0xFF;
  492. bytes[1] = (ip >> 8) & 0xFF;
  493. bytes[2] = (ip >> 16) & 0xFF;
  494. bytes[3] = (ip >> 24) & 0xFF;
  495. "binding to: %d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]
  496. */
  497. NetconConnection *c = client->getConnectionByTheirFD(bind_rpc->sockfd);
  498. if(c) {
  499. if(c->pcb->state == CLOSED){
  500. int err = lwipstack->tcp_bind(c->pcb, &conn_addr, conn_port);
  501. if(err != ERR_OK) {
  502. TRACE("error while binding to addr/port");
  503. }
  504. else {
  505. TRACE("bind successful");
  506. }
  507. }
  508. else {
  509. TRACE("PCB not in CLOSED state. Ignoring BIND request.");
  510. }
  511. }
  512. else {
  513. TRACE("can't locate connection for PCB");
  514. }
  515. }
  516. void NetconEthernetTap::handle_listen(NetconClient *client, struct listen_st *listen_rpc)
  517. {
  518. NetconConnection *c = client->getConnectionByTheirFD(listen_rpc->sockfd);
  519. if(c) {
  520. if(c->pcb->state == LISTEN) {
  521. TRACE("PCB is already in listening state.");
  522. return;
  523. }
  524. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(c->pcb);
  525. if(listening_pcb != NULL) {
  526. c->pcb = listening_pcb;
  527. lwipstack->tcp_accept(listening_pcb, nc_accept);
  528. lwipstack->tcp_arg(listening_pcb, new Larg(this, c->sock));
  529. client->waiting_for_retval=true;
  530. }
  531. else {
  532. TRACE("unable to allocate memory for new listening PCB");
  533. }
  534. }
  535. else {
  536. TRACE("can't locate connection for PCB");
  537. }
  538. }
  539. void NetconEthernetTap::handle_retval(NetconClient *client, unsigned char* buf)
  540. {
  541. if(client->unmapped_conn != NULL) {
  542. memcpy(&(client->unmapped_conn->their_fd), &buf[1], sizeof(int));
  543. client->unmapped_conn = NULL;
  544. }
  545. }
  546. void NetconEthernetTap::handle_socket(NetconClient *client, struct socket_st* socket_rpc)
  547. {
  548. struct tcp_pcb *pcb = lwipstack->tcp_new();
  549. if(pcb != NULL) {
  550. int *their_fd = NULL;
  551. NetconConnection *new_conn = client->addConnection(BUFFER, _phy.createSocketPair(*their_fd, client));
  552. new_conn->their_fd = *their_fd;
  553. new_conn->pcb = pcb;
  554. sock_fd_write(_phy.getDescriptor(client->rpc->sock), *their_fd);
  555. client->unmapped_conn = new_conn;
  556. }
  557. else {
  558. TRACE("Memory not available for new PCB");
  559. }
  560. }
  561. void NetconEthernetTap::handle_connect(NetconClient *client, struct connect_st* connect_rpc)
  562. {
  563. // FIXME: Parse out address information -- Probably a more elegant way to do this
  564. struct sockaddr_in *connaddr;
  565. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  566. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  567. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  568. NetconConnection *c = client->getConnectionByTheirFD(connect_rpc->__fd);
  569. if(c!= NULL) {
  570. lwipstack->tcp_sent(c->pcb, NetconEthernetTap::nc_sent); // FIXME: Move?
  571. lwipstack->tcp_recv(c->pcb, nc_recved);
  572. lwipstack->tcp_err(c->pcb, nc_err);
  573. lwipstack->tcp_poll(c->pcb, nc_poll, APPLICATION_POLL_FREQ);
  574. lwipstack->tcp_arg(c->pcb, new Larg(this, c->sock));
  575. int err = 0;
  576. if((err = lwipstack->tcp_connect(c->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  577. {
  578. // dwr(h->tid, "tcp_connect() = %s\n", lwiperror(err));
  579. // We should only return a value if failure happens immediately
  580. // Otherwise, we still need to wait for a callback from lwIP.
  581. // - This is because an ERR_OK from tcp_connect() only verifies
  582. // that the SYN packet was enqueued onto the stack properly,
  583. // that's it!
  584. // - Most instances of a retval for a connect() should happen
  585. // in the nc_connect() and nc_err() callbacks!
  586. send_return_value(client, err);
  587. }
  588. // Everything seems to be ok, but we don't have enough info to retval
  589. client->waiting_for_retval=true;
  590. }
  591. else {
  592. TRACE("could not locate PCB based on their fd");
  593. }
  594. }
  595. void NetconEthernetTap::handle_write(NetconConnection *c)
  596. {
  597. if(c) {
  598. int sndbuf = c->pcb->snd_buf;
  599. float avail = (float)sndbuf;
  600. float max = (float)TCP_SND_BUF;
  601. float load = 1.0 - (avail / max);
  602. if(load >= 0.9) {
  603. return;
  604. }
  605. int write_allowance = sndbuf < c->idx ? sndbuf : c->idx;
  606. int sz;
  607. if(write_allowance > 0) {
  608. int err = lwipstack->tcp_write(c->pcb, &c->buf, write_allowance, TCP_WRITE_FLAG_COPY);
  609. if(err != ERR_OK) {
  610. TRACE("error while writing to PCB");
  611. return;
  612. }
  613. else {
  614. sz = (c->idx)-write_allowance;
  615. if(sz) {
  616. memmove(&c->buf, (c->buf+write_allowance), sz);
  617. }
  618. c->idx -= write_allowance;
  619. //c->data_sent += write_allowance;
  620. return;
  621. }
  622. }
  623. else {
  624. TRACE("lwIP stack full");
  625. return;
  626. }
  627. }
  628. else {
  629. TRACE("could not locate connection for this fd");
  630. }
  631. }
  632. } // namespace ZeroTier
  633. #endif // ZT_ENABLE_NETCON