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