NetconEthernetTap.cpp 26 KB

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