1
0

NetconEthernetTap.cpp 23 KB

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