NetconEthernetTap.cpp 20 KB

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