NetconEthernetTap.cpp 27 KB

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