NetconEthernetTap.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 "NetconEthernetTap.hpp"
  31. #include "../node/Utils.hpp"
  32. #include "../osdep/OSUtils.hpp"
  33. #include "../osdep/Phy.hpp"
  34. #include "lwip/tcp_impl.h"
  35. #include "netif/etharp.h"
  36. #include "lwip/ip.h"
  37. #include "lwip/ip_addr.h"
  38. #include "lwip/ip_frag.h"
  39. #include "LWIPStack.hpp"
  40. #include "NetconService.h"
  41. #include "Intercept.h"
  42. #include "NetconUtilities.hpp"
  43. #define APPLICATION_POLL_FREQ 1
  44. namespace ZeroTier {
  45. NetconEthernetTap::NetconEthernetTap(
  46. const char *homePath,
  47. const MAC &mac,
  48. unsigned int mtu,
  49. unsigned int metric,
  50. uint64_t nwid,
  51. const char *friendlyName,
  52. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  53. void *arg) :
  54. _phy(this,false,true),
  55. _unixListenSocket((PhySocket *)0),
  56. _handler(handler),
  57. _arg(arg),
  58. _nwid(nwid),
  59. _homePath(homePath),
  60. _mtu(mtu),
  61. _enabled(true),
  62. _run(true)
  63. {
  64. char sockPath[4096];
  65. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",(unsigned long long)nwid);
  66. _dev = sockPath;
  67. lwipstack = new LWIPStack("/root/dev/netcon/liblwip.so");
  68. if(!lwipstack) // TODO double check this check
  69. throw std::runtime_error("unable to load lwip lib.");
  70. lwipstack->lwip_init();
  71. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  72. if (!_unixListenSocket)
  73. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  74. _thread = Thread::start(this);
  75. }
  76. NetconEthernetTap::~NetconEthernetTap()
  77. {
  78. _run = false;
  79. _phy.whack();
  80. _phy.whack();
  81. Thread::join(_thread);
  82. _phy.close(_unixListenSocket,false);
  83. }
  84. void NetconEthernetTap::setEnabled(bool en)
  85. {
  86. _enabled = en;
  87. }
  88. bool NetconEthernetTap::enabled() const
  89. {
  90. return _enabled;
  91. }
  92. bool NetconEthernetTap::addIp(const InetAddress &ip)
  93. {
  94. Mutex::Lock _l(_ips_m);
  95. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  96. _ips.push_back(ip);
  97. std::sort(_ips.begin(),_ips.end());
  98. // TODO: alloc IP in LWIP
  99. //netif_set_addr(netif, ipaddr, netmask, gw);
  100. }
  101. }
  102. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  103. {
  104. Mutex::Lock _l(_ips_m);
  105. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  106. if (i == _ips.end())
  107. return false;
  108. _ips.erase(i);
  109. // TODO: dealloc IP from LWIP
  110. return true;
  111. }
  112. std::vector<InetAddress> NetconEthernetTap::ips() const
  113. {
  114. Mutex::Lock _l(_ips_m);
  115. return _ips;
  116. }
  117. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  118. {
  119. if (!_enabled)
  120. return;
  121. }
  122. std::string NetconEthernetTap::deviceName() const
  123. {
  124. return _dev;
  125. }
  126. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  127. {
  128. }
  129. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  130. {
  131. // TODO: get multicast subscriptions from LWIP
  132. }
  133. NetconConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  134. {
  135. NetconConnection *c;
  136. for(int i=0; i<clients.size(); i++) {
  137. c = clients[i]->containsPCB(pcb);
  138. if(c) {
  139. return c;
  140. }
  141. }
  142. }
  143. NetconConnection *NetconEthernetTap::getConnectionByThisFD(int fd)
  144. {
  145. NetconConnection *c;
  146. for(int i=0; i<clients.size(); i++) {
  147. c = clients[i]->getConnectionByThisFD(fd);
  148. if(c) {
  149. return c;
  150. }
  151. }
  152. }
  153. void NetconEthernetTap::closeClient(NetconClient *client)
  154. {
  155. // erase from clients vector
  156. client->close();
  157. }
  158. void NetconEthernetTap::threadMain()
  159. throw()
  160. {
  161. static ip_addr_t ipaddr, netmask, gw;
  162. char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0};
  163. IP4_ADDR(&gw, 192,168,0,1);
  164. IP4_ADDR(&netmask, 255,255,255,0);
  165. IP4_ADDR(&ipaddr, 192,168,0,2);
  166. strncpy(ip_str, lwipstack->ipaddr_ntoa(&ipaddr), sizeof(ip_str));
  167. strncpy(nm_str, lwipstack->ipaddr_ntoa(&netmask), sizeof(nm_str));
  168. strncpy(gw_str, lwipstack->ipaddr_ntoa(&gw), sizeof(gw_str));
  169. unsigned long tcp_time = ARP_TMR_INTERVAL / 5000;
  170. unsigned long ipreass_time = TCP_TMR_INTERVAL / 1000;
  171. unsigned long etharp_time = IP_TMR_INTERVAL / 1000;
  172. unsigned long prev_tcp_time = 0;
  173. unsigned long prev_etharp_time = 0;
  174. unsigned long curr_time;
  175. unsigned long since_tcp;
  176. unsigned long since_etharp;
  177. struct timeval tv;
  178. struct timeval tv_sel;
  179. while (_run) {
  180. gettimeofday(&tv, NULL);
  181. curr_time = (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000;
  182. since_tcp = curr_time - prev_tcp_time;
  183. since_etharp = curr_time - prev_etharp_time;
  184. int min_time = min(since_tcp, since_etharp) * 1000; // usec
  185. if(since_tcp > tcp_time)
  186. {
  187. prev_tcp_time = curr_time+1;
  188. lwipstack->tcp_tmr();
  189. }
  190. if(since_etharp > etharp_time)
  191. {
  192. prev_etharp_time = curr_time;
  193. lwipstack->etharp_tmr();
  194. }
  195. // should be set every time since tv_sel is modified after each select() call
  196. tv_sel.tv_sec = 0;
  197. tv_sel.tv_usec = min_time;
  198. _phy.poll(min_time * 1000); // conversion from usec to millisec, TODO: double check
  199. }
  200. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  201. }
  202. // Unused -- no UDP or TCP from this thread/Phy<>
  203. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  204. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  205. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  206. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  207. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  208. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  209. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  210. {
  211. NetconClient *newClient = new NetconClient();
  212. newClient->addConnection(NetconConnectionType.RPC, *uptrN)
  213. }
  214. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  215. {
  216. *uptr->close();
  217. }
  218. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  219. {
  220. NetconConnection *c = *uptr->getConnection(sock);
  221. int r;
  222. if(c->type == NetconConnectionType.BUFFER) {
  223. if(c) {
  224. if(c->idx < DEFAULT_READ_BUFFER_SIZE) {
  225. if((r = read(sws->sock, (&c->buf)+c->idx, DEFAULT_READ_BUFFER_SIZE-(c->idx))) > 0) {
  226. c->idx += r;
  227. handle_write(c);
  228. }
  229. }
  230. }
  231. else {
  232. // can't find connection for this fd
  233. }
  234. }
  235. if(c->type == NetconConnectionType.RPC)
  236. {
  237. NetconClient *client = (NetconClient*)*uptr;
  238. switch((unsigned char*)data[0])
  239. {
  240. case RPC_SOCKET:
  241. struct socket_st socket_rpc;
  242. memcpy(&socket_rpc, &data[1], sizeof(struct socket_st));
  243. client->tid = socket_rpc.__tid;
  244. handle_socket(client, &socket_rpc);
  245. break;
  246. case RPC_LISTEN:
  247. struct listen_st listen_rpc;
  248. memcpy(&listen_rpc, &data[1], sizeof(struct listen_st));
  249. client->tid = listen_rpc.__tid;
  250. handle_listen(client, &listen_rpc);
  251. break;
  252. case RPC_BIND:
  253. struct bind_st bind_rpc;
  254. memcpy(&bind_rpc, &data[1], sizeof(struct bind_st));
  255. client->tid = bind_rpc.__tid;
  256. handle_bind(client, &bind_rpc);
  257. break;
  258. case RPC_KILL_INTERCEPT:
  259. client->close();
  260. break;
  261. case RPC_CONNECT:
  262. struct connect_st connect_rpc;
  263. memcpy(&connect_rpc, &data[1], sizeof(struct connect_st));
  264. client->tid = connect_rpc.__tid;
  265. handle_connect(client, &connect_rpc);
  266. break;
  267. case RPC_FD_MAP_COMPLETION:
  268. handle_retval(client, data);
  269. break;
  270. default:
  271. break;
  272. }
  273. }
  274. }
  275. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  276. {
  277. }
  278. int NetconEthernetTap::send_return_value(NetconClient *client, int retval)
  279. {
  280. if(!client->waiting_for_retval){
  281. // intercept isn't waiting for return value. Why are we here?
  282. return 0;
  283. }
  284. char retmsg[4];
  285. memset(&retmsg, '\0', sizeof(retmsg));
  286. retmsg[0]=RPC_RETVAL;
  287. memcpy(&retmsg[1], &retval, sizeof(retval));
  288. int n = write(_phy.getDescriptor(client->rpc->sock), &retmsg, sizeof(retmsg));
  289. if(n > 0) {
  290. // signal that we've satisfied this requirement
  291. client->waiting_for_retval = false;
  292. }
  293. else {
  294. // unable to send return value to the intercept
  295. closeClient(client);
  296. }
  297. return n;
  298. }
  299. /*------------------------------------------------------------------------------
  300. --------------------------------- LWIP callbacks -------------------------------
  301. ------------------------------------------------------------------------------*/
  302. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  303. {
  304. NetconConnection *c = getConnectionByPCB(tpcb); // TODO: make sure this works, if not, use arg to look up the connection
  305. if(c)
  306. handle_write(c);
  307. return ERR_OK;
  308. }
  309. err_t NetconEthernetTap::nc_accept(void* arg, struct tcp_pcb *newpcb, err_t err)
  310. {
  311. NetconConnection *c = nc_service->get_connection_by_buf_sock((intptr_t)arg);
  312. if(c && c->owner) {
  313. // Generate new socketpair and Connection. Use newly-allocated PCB
  314. int fd[2];
  315. socketpair(PF_LOCAL, SOCK_STREAM, 0, fd);
  316. NetconConnection *new_connection = nc_service->add_connection(c->owner, c->owner->tid, fd[0], -1, newpcb);
  317. //dwr(c->owner->tid, "socketpair { fd[0]=%d, fd[1]=%d }\n", fd[0], fd[1]);
  318. if(new_connection == NULL) {
  319. //printf("error adding new connection\n");
  320. return -1;
  321. }
  322. new_connection->owner->unmapped_conn = new_connection;
  323. // write byte to let accept call know we have a new connection
  324. int n = write(c->our_fd, "z", 1);
  325. if(n > 0) {
  326. //dwr(c->owner->tid, "sending socketpair fd... %d\n", fd[1]);
  327. sock_fd_write(c->owner->rpc, fd[1]);
  328. }
  329. else {
  330. //dwr(c->owner->tid, "nc_accept() - unknown error writing signal byte to listening socket\n");
  331. return -1;
  332. }
  333. // Set PCB-specific callbacks
  334. //dwr(c->owner->tid, "tcp_arg(pcb, %d)\n", new_connection->our_fd);
  335. lwipstack->tcp_arg(newpcb, (void*)(intptr_t)(new_connection->our_fd));
  336. lwipstack->tcp_recv(newpcb, nc_recved);
  337. lwipstack->tcp_err(newpcb, nc_err);
  338. lwipstack->tcp_sent(newpcb, nc_sent);
  339. lwipstack->tcp_poll(newpcb, nc_poll, APPLICATION_POLL_FREQ);
  340. tcp_accepted(c->pcb);
  341. return ERR_OK;
  342. }
  343. else {
  344. //dwr("can't locate Connection object for PCB\n");
  345. }
  346. return -1;
  347. }
  348. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  349. {
  350. int n;
  351. struct pbuf* q = p;
  352. NetconConnection *c = nc_service->get_connection_by_buf_sock((intptr_t)arg);
  353. if(c) {
  354. //dwr(c->owner->tid, "nc_recved(%d)\n", (intptr_t)arg);
  355. }
  356. else {
  357. //dwr(-1, "nc_recved(%d): unable to locate connection\n", (intptr_t)arg);
  358. return ERR_OK; // ?
  359. }
  360. if(p == NULL) {
  361. //dwr(c->owner->tid, "nc_recved() = %s\n", lwiperror(err));
  362. if(c)
  363. //dwr(c->owner->tid, "nc_recved()\n");
  364. if(c) {
  365. //dwr(c->owner->tid, "closing connection\n");
  366. nc_close(tpcb);
  367. close(c->our_fd); /* TODO: Check logic */
  368. nc_service->remove_connection(c);
  369. }
  370. else {
  371. //dwr(-1, "can't locate connection via (arg)\n");
  372. }
  373. return err;
  374. }
  375. q = p;
  376. while(p != NULL) { // Cycle through pbufs and write them to the socket
  377. //dwr(c->owner->tid, "writing data to mapped sock (%d)\n", c->our_fd);
  378. if(p->len <= 0)
  379. break; // ?
  380. if((n = write(c->our_fd, p->payload, p->len)) > 0) {
  381. if(n < p->len) {
  382. //dwr(c->owner->tid, "ERROR: unable to write entire pbuf to buffer\n");
  383. }
  384. lwipstack->tcp_recved(tpcb, n);
  385. }
  386. else {
  387. //dwr(c->owner->tid, "ERROR: No data written to intercept buffer.\n");
  388. }
  389. p = p->next;
  390. }
  391. lwipstack->pbuf_free(q); /* free pbufs */
  392. return ERR_OK;
  393. }
  394. void NetconEthernetTap::nc_err(void *arg, err_t err)
  395. {
  396. NetconConnection *c = getConnectionByThisFD((intptr)arg);
  397. if(c) {
  398. nc_service->remove_connection(c);
  399. //tcp_close(c->pcb);
  400. }
  401. else {
  402. // can't locate connection object for PCB
  403. }
  404. }
  405. void NetconEthernetTap::nc_close(struct tcp_pcb* tpcb)
  406. {
  407. NetconConnection *c = getConnectionByPCB(tpcb);
  408. lwipstack->tcp_arg(tpcb, NULL);
  409. lwipstack->tcp_sent(tpcb, NULL);
  410. lwipstack->tcp_recv(tpcb, NULL);
  411. lwipstack->tcp_err(tpcb, NULL);
  412. lwipstack->tcp_poll(tpcb, NULL, 0);
  413. lwipstack->tcp_close(tpcb);
  414. }
  415. err_t NetconEthernetTap::nc_send(struct tcp_pcb *tpcb)
  416. {
  417. return ERR_OK;
  418. }
  419. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  420. {
  421. NetconConnection *c = getConnectionByPCB(tpcb);
  422. if(c)
  423. c->data_sent += len;
  424. return len;
  425. }
  426. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  427. {
  428. for(int i=0; i<clients.size(); i++) {
  429. if(clients[i].containsPCB(tpcb)) {
  430. send_return_value(clients[i],err);
  431. }
  432. }
  433. return err;
  434. }
  435. /*------------------------------------------------------------------------------
  436. ----------------------------- RPC Handler functions ----------------------------
  437. ------------------------------------------------------------------------------*/
  438. void NetconEthernetTap::handle_bind(NetconClient *client, struct bind_st *bind_rpc)
  439. {
  440. // FIXME: Is this hack still needed?
  441. struct sockaddr_in *connaddr;
  442. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  443. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  444. ip_addr_t conn_addr;
  445. IP4_ADDR(&conn_addr, 192,168,0,2);
  446. int ip = connaddr->sin_addr.s_addr;
  447. unsigned char bytes[4];
  448. bytes[0] = ip & 0xFF;
  449. bytes[1] = (ip >> 8) & 0xFF;
  450. bytes[2] = (ip >> 16) & 0xFF;
  451. bytes[3] = (ip >> 24) & 0xFF;
  452. // "binding to: %d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]
  453. NetconConnection *c = client->getConnectionByTheirFD(bind_rpc->sockfd);
  454. if(c) {
  455. if(c->pcb->state == CLOSED){
  456. int err = lwipstack->tcp_bind(c->pcb, &conn_addr, conn_port);
  457. if(err != ERR_OK) {
  458. // error while binding to addr/port
  459. }
  460. else {
  461. // bind successful
  462. }
  463. }
  464. else {
  465. // PCB not in CLOSED state. Ignoring BIND request.
  466. }
  467. }
  468. else {
  469. // can't locate connection for PCB
  470. }
  471. }
  472. void NetconEthernetTap::handle_listen(NetconClient *client, struct listen_st *listen_rpc)
  473. {
  474. NetconConnection *c = client->getConnectionByTheirFD(listen_rpc->sockfd);
  475. if(c) {
  476. if(c->pcb->state == LISTEN) {
  477. // PCB is already in listening state.
  478. return;
  479. }
  480. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(c->pcb);
  481. if(listening_pcb != NULL) {
  482. c->pcb = listening_pcb;
  483. lwipstack->tcp_accept(listening_pcb, nc_accept);
  484. int our_fd = _phy.getDescriptor(c->sock);
  485. lwipstack->tcp_arg(listening_pcb, (void*)(intptr_t)our_fd);
  486. client->waiting_for_retval=true;
  487. }
  488. else {
  489. // unable to allocate memory for new listening PCB
  490. }
  491. }
  492. else {
  493. // can't locate connection for PCB
  494. }
  495. }
  496. void NetconEthernetTap::handle_retval(NetconClient *client, unsigned char* buf)
  497. {
  498. if(client->unmapped_conn != NULL) {
  499. memcpy(&(client->unmapped_conn->their_fd), &buf[1], sizeof(int));
  500. client->unmapped_conn = NULL;
  501. }
  502. }
  503. void NetconEthernetTap::handle_socket(NetconClient *client, struct socket_st* socket_rpc)
  504. {
  505. struct tcp_pcb *pcb = lwipstack->tcp_new();
  506. if(pcb != NULL) {
  507. int *their_fd;
  508. client->addConnection(NetconConnectionType.BUFFER, _phy.createSocketPair(&their_fd, client));
  509. new_conn->their_fd = their_fd;
  510. new_conn->pcb = pcb;
  511. sock_fd_write(_phy.getDescriptor(client->rpc->sock), their_fd);
  512. client->unmapped_conn = new_conn;
  513. }
  514. else {
  515. // Memory not available for new PCB
  516. }
  517. }
  518. void NetconEthernetTap::handle_connect(NetconClient *client, struct connect_st* connect_rpc)
  519. {
  520. // FIXME: Parse out address information -- Probably a more elegant way to do this
  521. struct sockaddr_in *connaddr;
  522. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  523. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  524. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  525. NetconConnection *c = client->getConnectionByTheirFD(connect_rpc->__fd);
  526. if(c!= NULL) {
  527. lwipstack->tcp_sent(c->pcb, nc_sent); // FIXME: Move?
  528. lwipstack->tcp_recv(c->pcb, nc_recved);
  529. lwipstack->tcp_err(c->pcb, nc_err);
  530. lwipstack->tcp_poll(c->pcb, nc_poll, APPLICATION_POLL_FREQ);
  531. lwipstack->tcp_arg(c->pcb,(void*)(intptr_t)c->our_fd);
  532. int err = 0;
  533. if((err = lwipstack->tcp_connect(c->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  534. {
  535. // dwr(h->tid, "tcp_connect() = %s\n", lwiperror(err));
  536. // We should only return a value if failure happens immediately
  537. // Otherwise, we still need to wait for a callback from lwIP.
  538. // - This is because an ERR_OK from tcp_connect() only verifies
  539. // that the SYN packet was enqueued onto the stack properly,
  540. // that's it!
  541. // - Most instances of a retval for a connect() should happen
  542. // in the nc_connect() and nc_err() callbacks!
  543. send_return_value(client, err);
  544. }
  545. // Everything seems to be ok, but we don't have enough info to retval
  546. client->waiting_for_retval=true;
  547. }
  548. else {
  549. // could not locate PCB based on their fd
  550. }
  551. }
  552. void NetconEthernetTap::handle_write(NetconConnection *c)
  553. {
  554. if(c) {
  555. int sndbuf = c->pcb->snd_buf;
  556. float avail = (float)sndbuf;
  557. float max = (float)TCP_SND_BUF;
  558. float load = 1.0 - (avail / max);
  559. if(load >= 0.9) {
  560. return;
  561. }
  562. int write_allowance = sndbuf < c->idx ? sndbuf : c->idx;
  563. int sz;
  564. if(write_allowance > 0) {
  565. int err = lwipstack->tcp_write(c->pcb, &c->buf, write_allowance, TCP_WRITE_FLAG_COPY);
  566. if(err != ERR_OK) {
  567. // error while writing to PCB
  568. return;
  569. }
  570. else {
  571. sz = (c->idx)-write_allowance;
  572. if(sz) {
  573. memmove(&c->buf, (c->buf+write_allowance), sz);
  574. }
  575. c->idx -= write_allowance;
  576. //c->data_sent += write_allowance;
  577. return;
  578. }
  579. }
  580. else {
  581. // lwIP stack full
  582. return;
  583. }
  584. }
  585. else {
  586. // could not locate connection for this fd
  587. }
  588. }
  589. } // namespace ZeroTier
  590. #endif // ZT_ENABLE_NETCON