NetconEthernetTap.cpp 28 KB

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