NetconEthernetTap.cpp 21 KB

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