NetconEthernetTap.cpp 23 KB

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