NetconEthernetTap.cpp 21 KB

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