NetconEthernetTap.cpp 22 KB

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