NetconEthernetTap.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. void NetconEthernetTap::threadMain()
  134. throw()
  135. {
  136. static ip_addr_t ipaddr, netmask, gw;
  137. char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0};
  138. IP4_ADDR(&gw, 192,168,0,1);
  139. IP4_ADDR(&netmask, 255,255,255,0);
  140. IP4_ADDR(&ipaddr, 192,168,0,2);
  141. strncpy(ip_str, lwipstack->ipaddr_ntoa(&ipaddr), sizeof(ip_str));
  142. strncpy(nm_str, lwipstack->ipaddr_ntoa(&netmask), sizeof(nm_str));
  143. strncpy(gw_str, lwipstack->ipaddr_ntoa(&gw), sizeof(gw_str));
  144. unsigned long tcp_time = ARP_TMR_INTERVAL / 5000;
  145. unsigned long ipreass_time = TCP_TMR_INTERVAL / 1000;
  146. unsigned long etharp_time = IP_TMR_INTERVAL / 1000;
  147. unsigned long prev_tcp_time = 0;
  148. unsigned long prev_etharp_time = 0;
  149. unsigned long curr_time;
  150. unsigned long since_tcp;
  151. unsigned long since_etharp;
  152. struct timeval tv;
  153. struct timeval tv_sel;
  154. while (_run) {
  155. gettimeofday(&tv, NULL);
  156. curr_time = (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000;
  157. since_tcp = curr_time - prev_tcp_time;
  158. since_etharp = curr_time - prev_etharp_time;
  159. int min_time = min(since_tcp, since_etharp) * 1000; // usec
  160. if(since_tcp > tcp_time)
  161. {
  162. prev_tcp_time = curr_time+1;
  163. lwipstack->tcp_tmr();
  164. }
  165. if(since_etharp > etharp_time)
  166. {
  167. prev_etharp_time = curr_time;
  168. lwipstack->etharp_tmr();
  169. }
  170. // should be set every time since tv_sel is modified after each select() call
  171. tv_sel.tv_sec = 0;
  172. tv_sel.tv_usec = min_time;
  173. _phy.poll(min_time * 1000); // conversion from usec to millisec, TODO: double check
  174. }
  175. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  176. }
  177. // Unused -- no UDP or TCP from this thread/Phy<>
  178. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  179. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  180. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  181. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  182. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  183. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  184. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  185. {
  186. NetconClient newClient = new NetconClient();
  187. newClient->rpc = new NetconConnection();
  188. newClient->rpc->type = NetconConnectionType.RPC;
  189. newClient->rpc->sock = *uptrN;
  190. }
  191. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  192. {
  193. NIntercept *h = (NIntercept*)_phy.getuptr(sock);
  194. h->close();
  195. }
  196. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  197. {
  198. NetconConnection *c = *uptr->getConnection(sock);
  199. int r;
  200. if(c->type == NetconConnectionType.BUFFER) {
  201. if(c) {
  202. if(c->idx < DEFAULT_READ_BUFFER_SIZE) {
  203. if((r = read(sws->sock, (&c->buf)+c->idx, DEFAULT_READ_BUFFER_SIZE-(c->idx))) > 0) {
  204. c->idx += r;
  205. handle_write(c);
  206. }
  207. }
  208. }
  209. else {
  210. //dwr(-1, "can't find connection for this fd: %d\n", ns->allfds[i].fd);
  211. }
  212. }
  213. if(c->type == NetconConnectionType.RPC)
  214. {
  215. NetconClient client = (NetconClient*)*uptr;
  216. switch(data[0])
  217. {
  218. case RPC_SOCKET:
  219. struct socket_st socket_rpc;
  220. memcpy(&socket_rpc, &data[1], sizeof(struct socket_st));
  221. client->tid = socket_rpc.__tid;
  222. //dwr(h->tid,"__RPC_SOCKET\n");
  223. handle_socket(client, &socket_rpc);
  224. break;
  225. case RPC_LISTEN:
  226. struct listen_st listen_rpc;
  227. memcpy(&listen_rpc, &data[1], sizeof(struct listen_st));
  228. client->tid = listen_rpc.__tid;
  229. //dwr(h->tid,"__RPC_LISTEN\n");
  230. handle_listen(client, &listen_rpc);
  231. break;
  232. case RPC_BIND:
  233. struct bind_st bind_rpc;
  234. memcpy(&bind_rpc, &data[1], sizeof(struct bind_st));
  235. client->tid = bind_rpc.__tid;
  236. //dwr(h->tid,"__RPC_BIND\n");
  237. handle_bind(client, &bind_rpc);
  238. break;
  239. case RPC_KILL_INTERCEPT:
  240. //dwr(h->tid,"__RPC_KILL_INTERCEPT\n");
  241. handle_kill_intercept(client);
  242. break;
  243. case RPC_CONNECT:
  244. struct connect_st connect_rpc;
  245. memcpy(&connect_rpc, &data[1], sizeof(struct connect_st));
  246. client->tid = connect_rpc.__tid;
  247. //dwr("__RPC_CONNECT\n");
  248. handle_connect(h, &connect_rpc);
  249. break;
  250. case RPC_FD_MAP_COMPLETION:
  251. //dwr("__RPC_FD_MAP_COMPLETION\n");
  252. handle_retval(client, data);
  253. break;
  254. default:
  255. break;
  256. }
  257. }
  258. }
  259. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  260. {
  261. }
  262. int NetconEthernetTap::send_return_value(NetconIntercept *h, int retval)
  263. {
  264. if(!h->waiting_for_retval){
  265. //dwr(h->tid, "ERROR: intercept isn't waiting for return value. Why are we here?\n");
  266. return 0;
  267. }
  268. char retmsg[4];
  269. memset(&retmsg, '\0', sizeof(retmsg));
  270. retmsg[0]=RPC_RETVAL;
  271. memcpy(&retmsg[1], &retval, sizeof(retval));
  272. int n = write(h->rpc, &retmsg, sizeof(retmsg));
  273. if(n > 0) {
  274. /* signal that we've satisfied this requirement */
  275. h->waiting_for_retval = false;
  276. }
  277. else {
  278. /* in the event that we can't write to the intercept's RPC, we
  279. should assume that it has failed to connect */
  280. //dwr(h->tid, "ERROR: unable to send return value to the intercept\n");
  281. //dwr(h->tid, "removing intercept.\n");
  282. nc_service->remove_intercept(h);
  283. }
  284. return n;
  285. }
  286. /*------------------------------------------------------------------------------
  287. --------------------------------- LWIP callbacks -------------------------------
  288. ------------------------------------------------------------------------------*/
  289. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  290. {
  291. NetconConnection* c = nc_service->get_connection_by_buf_sock((intptr_t)arg);
  292. if(c)
  293. handle_write(c);
  294. return ERR_OK;
  295. }
  296. err_t NetconEthernetTap::nc_accept(void* arg, struct tcp_pcb *newpcb, err_t err)
  297. {
  298. NetconConnection *c = nc_service->get_connection_by_buf_sock((intptr_t)arg);
  299. if(c && c->owner) {
  300. // Generate new socketpair and Connection. Use newly-allocated PCB
  301. int fd[2];
  302. socketpair(PF_LOCAL, SOCK_STREAM, 0, fd);
  303. NetconConnection *new_connection = nc_service->add_connection(c->owner, c->owner->tid, fd[0], -1, newpcb);
  304. //dwr(c->owner->tid, "socketpair { fd[0]=%d, fd[1]=%d }\n", fd[0], fd[1]);
  305. if(new_connection == NULL) {
  306. //printf("error adding new connection\n");
  307. return -1;
  308. }
  309. new_connection->owner->unmapped_conn = new_connection;
  310. // write byte to let accept call know we have a new connection
  311. int n = write(c->our_fd, "z", 1);
  312. if(n > 0) {
  313. //dwr(c->owner->tid, "sending socketpair fd... %d\n", fd[1]);
  314. sock_fd_write(c->owner->rpc, fd[1]);
  315. }
  316. else {
  317. //dwr(c->owner->tid, "nc_accept() - unknown error writing signal byte to listening socket\n");
  318. return -1;
  319. }
  320. // Set PCB-specific callbacks
  321. //dwr(c->owner->tid, "tcp_arg(pcb, %d)\n", new_connection->our_fd);
  322. lwipstack->tcp_arg(newpcb, (void*)(intptr_t)(new_connection->our_fd));
  323. lwipstack->tcp_recv(newpcb, nc_recved);
  324. lwipstack->tcp_err(newpcb, nc_err);
  325. lwipstack->tcp_sent(newpcb, nc_sent);
  326. lwipstack->tcp_poll(newpcb, nc_poll, APPLICATION_POLL_FREQ);
  327. tcp_accepted(c->pcb);
  328. return ERR_OK;
  329. }
  330. else {
  331. //dwr("can't locate Connection object for PCB\n");
  332. }
  333. return -1;
  334. }
  335. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  336. {
  337. int n;
  338. struct pbuf* q = p;
  339. NetconConnection *c = nc_service->get_connection_by_buf_sock((intptr_t)arg);
  340. if(c) {
  341. //dwr(c->owner->tid, "nc_recved(%d)\n", (intptr_t)arg);
  342. }
  343. else {
  344. //dwr(-1, "nc_recved(%d): unable to locate connection\n", (intptr_t)arg);
  345. return ERR_OK; // ?
  346. }
  347. if(p == NULL) {
  348. //dwr(c->owner->tid, "nc_recved() = %s\n", lwiperror(err));
  349. if(c)
  350. //dwr(c->owner->tid, "nc_recved()\n");
  351. if(c) {
  352. //dwr(c->owner->tid, "closing connection\n");
  353. nc_close(tpcb);
  354. close(c->our_fd); /* TODO: Check logic */
  355. nc_service->remove_connection(c);
  356. }
  357. else {
  358. //dwr(-1, "can't locate connection via (arg)\n");
  359. }
  360. return err;
  361. }
  362. q = p;
  363. while(p != NULL) { // Cycle through pbufs and write them to the socket
  364. //dwr(c->owner->tid, "writing data to mapped sock (%d)\n", c->our_fd);
  365. if(p->len <= 0)
  366. break; // ?
  367. if((n = write(c->our_fd, p->payload, p->len)) > 0) {
  368. if(n < p->len) {
  369. //dwr(c->owner->tid, "ERROR: unable to write entire pbuf to buffer\n");
  370. }
  371. lwipstack->tcp_recved(tpcb, n);
  372. }
  373. else {
  374. //dwr(c->owner->tid, "ERROR: No data written to intercept buffer.\n");
  375. }
  376. p = p->next;
  377. }
  378. lwipstack->pbuf_free(q); /* free pbufs */
  379. return ERR_OK;
  380. }
  381. void NetconEthernetTap::nc_err(void *arg, err_t err)
  382. {
  383. NetconConnection *c = nc_service->get_connection_by_this_fd((intptr_t)arg);
  384. if(c) {
  385. //dwr(c->owner->tid, "nc_err: %s\n", lwiperror(err));
  386. nc_service->remove_connection(c);
  387. //tcp_close(c->pcb);
  388. //dwr(-1, "connection removed.\n");
  389. }
  390. else {
  391. //dwr("ERROR: can't locate connection object for PCB.\n");
  392. }
  393. //nc_service->print_fd_set();
  394. }
  395. void NetconEthernetTap::nc_close(struct tcp_pcb* tpcb)
  396. {
  397. NetconConnection *c = nc_service->get_connection_by_pcb(tpcb);
  398. if(c) {
  399. //dwr(c->owner->tid, "nc_close(): closing connection (their=%d, our=%d)\n", c->their_fd, c->our_fd);
  400. }
  401. else {
  402. //dwr(-1, "nc_close(): closing connection\n");
  403. }
  404. lwipstack->tcp_arg(tpcb, NULL);
  405. lwipstack->tcp_sent(tpcb, NULL);
  406. lwipstack->tcp_recv(tpcb, NULL);
  407. lwipstack->tcp_err(tpcb, NULL);
  408. lwipstack->tcp_poll(tpcb, NULL, 0);
  409. int err = lwipstack->tcp_close(tpcb);
  410. //dwr(-1, "tcp_close: %s\n", lwiperror(err));
  411. }
  412. err_t NetconEthernetTap::nc_send(struct tcp_pcb *tpcb)
  413. {
  414. return ERR_OK;
  415. }
  416. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  417. {
  418. NetconConnection *c = nc_service->get_connection_by_pcb(tpcb);
  419. if(c)
  420. c->data_sent += len;
  421. return len;
  422. }
  423. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  424. {
  425. NetconClient *client = nc_service->get_intercept_by_pcb(tpcb);
  426. if(h) {
  427. //dwr(h->tid, "nc_connected()\n");
  428. send_return_value(h,err);
  429. }
  430. return err;
  431. }
  432. /*------------------------------------------------------------------------------
  433. ----------------------------- RPC Handler functions ----------------------------
  434. ------------------------------------------------------------------------------*/
  435. void NetconEthernetTap::handle_bind(NetconClient *client, struct bind_st *bind_rpc)
  436. {
  437. // FIXME: Is this hack still needed?
  438. struct sockaddr_in *connaddr;
  439. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  440. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  441. ip_addr_t conn_addr;
  442. IP4_ADDR(&conn_addr, 192,168,0,2);
  443. int ip = connaddr->sin_addr.s_addr;
  444. unsigned char bytes[4];
  445. bytes[0] = ip & 0xFF;
  446. bytes[1] = (ip >> 8) & 0xFF;
  447. bytes[2] = (ip >> 16) & 0xFF;
  448. bytes[3] = (ip >> 24) & 0xFF;
  449. // "binding to: %d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]
  450. NetconConnection *c = client->getConnectionByTheirFD(bind_rpc->sockfd);
  451. if(c) {
  452. if(c->pcb->state == CLOSED){
  453. int err = lwipstack->tcp_bind(c->pcb, &conn_addr, conn_port);
  454. if(err != ERR_OK) {
  455. // error while binding to addr/port
  456. }
  457. else {
  458. // bind successful
  459. }
  460. }
  461. else {
  462. // PCB not in CLOSED state. Ignoring BIND request.
  463. }
  464. }
  465. else {
  466. // can't locate connection for PCB
  467. }
  468. }
  469. void NetconEthernetTap::handle_listen(NetconClient *client, struct listen_st *listen_rpc)
  470. {
  471. NetconConnection *c = client->getConnectionByTheirFD(listen_rpc->sockfd);
  472. if(c) {
  473. if(c->pcb->state == LISTEN) {
  474. // PCB is already in listening state.
  475. return;
  476. }
  477. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(c->pcb);
  478. if(listening_pcb != NULL) {
  479. c->pcb = listening_pcb;
  480. lwipstack->tcp_accept(listening_pcb, nc_accept);
  481. int our_fd = _phy.getDescriptor(c->sock);
  482. lwipstack->tcp_arg(listening_pcb, (void*)(intptr_t)our_fd);
  483. client->waiting_for_retval=true;
  484. }
  485. else {
  486. // unable to allocate memory for new listening PCB
  487. }
  488. }
  489. else {
  490. // can't locate connection for PCB
  491. }
  492. }
  493. void NetconEthernetTap::handle_retval(NetconClient *client, unsigned char* buf)
  494. {
  495. if(client->unmapped_conn != NULL) {
  496. memcpy(&(client->unmapped_conn->their_fd), &buf[1], sizeof(int));
  497. h->unmapped_conn = NULL;
  498. }
  499. }
  500. void NetconEthernetTap::handle_socket(NetconClient *client, struct socket_st* socket_rpc)
  501. {
  502. struct tcp_pcb *pcb = lwipstack->tcp_new();
  503. if(pcb != NULL) {
  504. int *their_fd;
  505. NetconConnection new_conn = new NetconConnection();
  506. new_conn->sock = _phy.createSocketPair(&their_fd, client);
  507. new_conn->their_fd = their_fd;
  508. new_conn->pcb = pcb;
  509. new_conn->type = NetconConnectionType.BUFFER;
  510. sock_fd_write(_phy.getDescriptor(client->rpc->sock), their_fd);
  511. h->unmapped_conn = new_connection;
  512. }
  513. else {
  514. // Memory not available for new PCB
  515. }
  516. }
  517. void NetconEthernetTap::handle_connect(NetconClient *client, struct connect_st* connect_rpc)
  518. {
  519. // FIXME: Parse out address information -- Probably a more elegant way to do this
  520. struct sockaddr_in *connaddr;
  521. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  522. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  523. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  524. NetconConnection *c = client->getConnectionByTheirFD(connect_rpc->__fd);
  525. if(c!= NULL) {
  526. lwipstack->tcp_sent(c->pcb, nc_sent); // FIXME: Move?
  527. lwipstack->tcp_recv(c->pcb, nc_recved);
  528. lwipstack->tcp_err(c->pcb, nc_err);
  529. lwipstack->tcp_poll(c->pcb, nc_poll, APPLICATION_POLL_FREQ);
  530. lwipstack->tcp_arg(c->pcb,(void*)(intptr_t)c->our_fd);
  531. int err = 0;
  532. if((err = lwipstack->tcp_connect(c->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  533. {
  534. // dwr(h->tid, "tcp_connect() = %s\n", lwiperror(err));
  535. // We should only return a value if failure happens immediately
  536. // Otherwise, we still need to wait for a callback from lwIP.
  537. // - This is because an ERR_OK from tcp_connect() only verifies
  538. // that the SYN packet was enqueued onto the stack properly,
  539. // that's it!
  540. // - Most instances of a retval for a connect() should happen
  541. // in the nc_connect() and nc_err() callbacks!
  542. send_return_value(client, err);
  543. }
  544. // Everything seems to be ok, but we don't have enough info to retval
  545. client->waiting_for_retval=true;
  546. }
  547. else {
  548. // could not locate PCB based on their fd
  549. }
  550. }
  551. void NetconEthernetTap::handle_write(NetconConnection *c)
  552. {
  553. if(c) {
  554. int sndbuf = c->pcb->snd_buf;
  555. float avail = (float)sndbuf;
  556. float max = (float)TCP_SND_BUF;
  557. float load = 1.0 - (avail / max);
  558. if(load >= 0.9) {
  559. return;
  560. }
  561. int write_allowance = sndbuf < c->idx ? sndbuf : c->idx;
  562. int sz;
  563. if(write_allowance > 0) {
  564. int err = lwipstack->tcp_write(c->pcb, &c->buf, write_allowance, TCP_WRITE_FLAG_COPY);
  565. if(err != ERR_OK) {
  566. // error while writing to PCB
  567. return;
  568. }
  569. else {
  570. sz = (c->idx)-write_allowance;
  571. if(sz) {
  572. memmove(&c->buf, (c->buf+write_allowance), sz);
  573. }
  574. c->idx -= write_allowance;
  575. c->data_sent += write_allowance;
  576. return;
  577. }
  578. }
  579. else {
  580. // lwIP stack full
  581. return;
  582. }
  583. }
  584. else {
  585. // could not locate connection for this fd
  586. }
  587. }
  588. } // namespace ZeroTier
  589. #endif // ZT_ENABLE_NETCON