NetconEthernetTap.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. if(since_tcp > tcp_time)
  319. {
  320. prev_tcp_time = curr_time+1;
  321. lwipstack->tcp_tmr();
  322. }
  323. if(since_etharp > etharp_time)
  324. {
  325. prev_etharp_time = curr_time;
  326. lwipstack->etharp_tmr();
  327. }
  328. _phy.poll(min_time / 1000); // conversion from usec to millisec, TODO: double check
  329. }
  330. closeAllClients();
  331. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  332. }
  333. void NetconEthernetTap::phyOnSocketPairEndpointClose(PhySocket *sock, void **uptr)
  334. {
  335. fprintf(stderr, "phyOnSocketPairEndpointClose\n");
  336. _phy.setNotifyWritable(sock, false);
  337. NetconClient *client = (NetconClient*)*uptr;
  338. closeConnection(client->getConnection(sock));
  339. }
  340. void NetconEthernetTap::phyOnSocketPairEndpointData(PhySocket *sock, void **uptr, void *buf, unsigned long n)
  341. {
  342. fprintf(stderr, "phyOnSocketPairEndpointData\n");
  343. int r;
  344. NetconConnection *c = ((NetconClient*)*uptr)->getConnection(sock);
  345. if(c) {
  346. if(c->idx < DEFAULT_READ_BUFFER_SIZE) {
  347. if((r = read(_phy.getDescriptor(c->sock), (&c->buf)+c->idx, DEFAULT_READ_BUFFER_SIZE-(c->idx))) > 0) {
  348. c->idx += r;
  349. handle_write(c);
  350. }
  351. }
  352. }
  353. }
  354. void NetconEthernetTap::phyOnSocketPairEndpointWritable(PhySocket *sock, void **uptr)
  355. {
  356. fprintf(stderr, "phyOnSocketPairEndpointWritable\n");
  357. _phy.setNotifyWritable(sock, false);
  358. }
  359. // Unused -- no UDP or TCP from this thread/Phy<>
  360. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  361. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  362. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  363. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  364. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  365. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  366. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  367. {
  368. fprintf(stderr, "phyOnUnixAccept\n");
  369. NetconClient *newClient = new NetconClient();
  370. newClient->rpc = newClient->addConnection(RPC, sockN);
  371. *uptrN = newClient;
  372. clients.push_back(newClient);
  373. }
  374. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  375. {
  376. fprintf(stderr, "phyOnUnixClose\n");
  377. _phy.setNotifyWritable(sock, false);
  378. //fprintf(stderr, "phyOnUnixClose\n");
  379. closeClient(((NetconClient*)*uptr));
  380. }
  381. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  382. {
  383. fprintf(stderr, "phyOnUnixData\n");
  384. unsigned char *buf = (unsigned char*)data;
  385. NetconClient *client = (NetconClient*)*uptr;
  386. if(!client)
  387. fprintf(stderr, "!client\n");
  388. switch(buf[0])
  389. {
  390. case RPC_SOCKET:
  391. fprintf(stderr, "RPC_SOCKET\n");
  392. struct socket_st socket_rpc;
  393. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  394. client->tid = socket_rpc.__tid;
  395. handle_socket(client, &socket_rpc);
  396. break;
  397. case RPC_LISTEN:
  398. fprintf(stderr, "RPC_LISTEN\n");
  399. struct listen_st listen_rpc;
  400. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  401. client->tid = listen_rpc.__tid;
  402. handle_listen(client, &listen_rpc);
  403. break;
  404. case RPC_BIND:
  405. fprintf(stderr, "RPC_BIND\n");
  406. struct bind_st bind_rpc;
  407. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  408. client->tid = bind_rpc.__tid;
  409. handle_bind(client, &bind_rpc);
  410. break;
  411. case RPC_KILL_INTERCEPT:
  412. fprintf(stderr, "RPC_KILL_INTERCEPT\n");
  413. closeClient(client);
  414. break;
  415. case RPC_CONNECT:
  416. fprintf(stderr, "RPC_CONNECT\n");
  417. struct connect_st connect_rpc;
  418. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  419. client->tid = connect_rpc.__tid;
  420. handle_connect(client, &connect_rpc);
  421. break;
  422. case RPC_FD_MAP_COMPLETION:
  423. fprintf(stderr, "RPC_FD_MAP_COMPLETION\n");
  424. handle_retval(client, buf);
  425. break;
  426. default:
  427. break;
  428. }
  429. }
  430. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  431. {
  432. }
  433. int NetconEthernetTap::send_return_value(NetconClient *client, int retval)
  434. {
  435. fprintf(stderr, "send_return_value\n");
  436. if(!client->waiting_for_retval){
  437. fprintf(stderr, "intercept isn't waiting for return value. Why are we here?\n");
  438. return 0;
  439. }
  440. char retmsg[4];
  441. memset(&retmsg, '\0', sizeof(retmsg));
  442. retmsg[0]=RPC_RETVAL;
  443. memcpy(&retmsg[1], &retval, sizeof(retval));
  444. int n = write(_phy.getDescriptor(client->rpc->sock), &retmsg, sizeof(retmsg));
  445. if(n > 0) {
  446. // signal that we've satisfied this requirement
  447. client->waiting_for_retval = false;
  448. }
  449. else {
  450. fprintf(stderr, "unable to send return value to the intercept\n");
  451. closeClient(client);
  452. }
  453. return n;
  454. }
  455. /*------------------------------------------------------------------------------
  456. --------------------------------- LWIP callbacks -------------------------------
  457. ------------------------------------------------------------------------------*/
  458. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  459. {
  460. fprintf(stderr, "nc_poll(): [pcb = %x], [larg = %x]\n", tpcb, l);
  461. Larg *l = (Larg*)arg;
  462. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  463. NetconEthernetTap *tap = l->tap;
  464. if(c && c->idx > 0){
  465. fprintf(stderr, "nc_poll(): calling handle_Write()\n");
  466. tap->handle_write(c);
  467. }
  468. return ERR_OK;
  469. }
  470. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  471. {
  472. Larg *l = (Larg*)arg;
  473. fprintf(stderr, "nc_accept(): [pcb = %x], [larg = %x]\n", newpcb, l);
  474. int our_fd = l->tap->_phy.getDescriptor(l->sock);
  475. fprintf(stderr, "nc_accept(): our_fd = %d\n", our_fd);
  476. NetconEthernetTap *tap = l->tap;
  477. NetconConnection *c = tap->getConnectionByThisFD(our_fd);
  478. if(c) {
  479. NetconClient *client = c->owner;
  480. if(!client){
  481. fprintf(stderr, "nc_accpet(): unable to locate client for this PCB\n");
  482. return -1;
  483. }
  484. int their_fd;
  485. NetconConnection *new_conn = client->addConnection(BUFFER, tap->_phy.createSocketPair(their_fd, client));
  486. client->connections.push_back(new_conn);
  487. new_conn->their_fd = their_fd;
  488. new_conn->pcb = newpcb;
  489. PhySocket *sock = client->rpc->sock;
  490. int send_fd = tap->_phy.getDescriptor(sock);
  491. int rpc_fd = tap->_phy.getDescriptor(new_conn->sock);
  492. int n = write(rpc_fd, "z", 1);
  493. if(n > 0) {
  494. sock_fd_write(send_fd, their_fd);
  495. client->unmapped_conn = new_conn;
  496. }
  497. else {
  498. fprintf(stderr, "nc_accept(): error writing signal byte (rpc_fd = %d, send_fd = %d, their_fd = %d)\n", rpc_fd, send_fd, their_fd);
  499. return -1;
  500. }
  501. tap->lwipstack->tcp_arg(newpcb, l);
  502. tap->lwipstack->tcp_recv(newpcb, nc_recved);
  503. tap->lwipstack->tcp_err(newpcb, nc_err);
  504. tap->lwipstack->tcp_sent(newpcb, nc_sent);
  505. tap->lwipstack->tcp_poll(newpcb, nc_poll, 1);
  506. tcp_accepted(c->pcb);
  507. return ERR_OK;
  508. }
  509. else {
  510. fprintf(stderr, "nc_accept(): can't locate Connection object for PCB. \n");
  511. }
  512. return -1;
  513. return ERR_OK;
  514. }
  515. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  516. {
  517. fprintf(stderr, "nc_recved\n");
  518. Larg *l = (Larg*)arg;
  519. fprintf(stderr, "nc_recved(): [pcb = %x], [larg = %x]\n", tpcb, l);
  520. if(!l)
  521. fprintf(stderr, "nc_recved(): could not find Larg for this [pcb = %x]\n", tpcb);
  522. fprintf(stderr, "nc_recved(): tap = %x\n", l->tap);
  523. NetconConnection *c = l->tap->getConnectionByPCB(tpcb);
  524. if(!c)
  525. fprintf(stderr, "nc_recved(): unable to locate connection\n");
  526. NetconEthernetTap *tap = l->tap;
  527. int n;
  528. struct pbuf* q = p;
  529. int our_fd = tap->_phy.getDescriptor(c->sock);
  530. if(!c) {
  531. return ERR_OK; // ?
  532. }
  533. if(p == NULL) {
  534. if(c) {
  535. nc_close(tpcb);
  536. close(our_fd); // TODO: Check logic
  537. tap->closeConnection(c);
  538. }
  539. else {
  540. fprintf(stderr, "can't locate connection via (arg)\n");
  541. }
  542. return err;
  543. }
  544. q = p;
  545. while(p != NULL) { // Cycle through pbufs and write them to the socket
  546. if(p->len <= 0)
  547. break; // ?
  548. if((n = write(our_fd, p->payload, p->len)) > 0) {
  549. if(n < p->len) {
  550. fprintf(stderr, "ERROR: unable to write entire pbuf to buffer\n");
  551. //tap->_phy.setNotifyWritable(l->sock, true);
  552. }
  553. tap->lwipstack->tcp_recved(tpcb, n);
  554. }
  555. else {
  556. fprintf(stderr, "Error: No data written to intercept buffer\n");
  557. }
  558. p = p->next;
  559. }
  560. tap->lwipstack->pbuf_free(q); // free pbufs
  561. return ERR_OK;
  562. }
  563. void NetconEthernetTap::nc_err(void *arg, err_t err)
  564. {
  565. fprintf(stderr, "nc_err\n");
  566. Larg *l = (Larg*)arg;
  567. NetconEthernetTap *tap = l->tap;
  568. NetconConnection *c = tap->getConnectionByThisFD(tap->_phy.getDescriptor(l->sock));
  569. if(c) {
  570. tap->closeConnection(c);
  571. }
  572. else {
  573. fprintf(stderr, "can't locate connection object for PCB\n");
  574. }
  575. }
  576. void NetconEthernetTap::nc_close(struct tcp_pcb* tpcb)
  577. {
  578. fprintf(stderr, "nc_close\n");
  579. //closeConnection(getConnectionByPCB(tpcb));
  580. /*
  581. lwipstack->tcp_arg(tpcb, NULL);
  582. lwipstack->tcp_sent(tpcb, NULL);
  583. lwipstack->tcp_recv(tpcb, NULL);
  584. lwipstack->tcp_err(tpcb, NULL);
  585. lwipstack->tcp_poll(tpcb, NULL, 0);
  586. lwipstack->tcp_close(tpcb);
  587. */
  588. }
  589. err_t NetconEthernetTap::nc_send(struct tcp_pcb *tpcb)
  590. {
  591. fprintf(stderr, "nc_send\n");
  592. return ERR_OK;
  593. }
  594. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  595. {
  596. fprintf(stderr, "nc_sent\n");
  597. return len;
  598. }
  599. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  600. {
  601. fprintf(stderr, "nc_connected\n");
  602. Larg *l = (Larg*)arg;
  603. NetconEthernetTap *tap = l->tap;
  604. for(size_t i=0; i<tap->clients.size(); i++) {
  605. if(tap->clients[i]->containsPCB(tpcb)) {
  606. tap->send_return_value(tap->clients[i],err);
  607. }
  608. }
  609. return err;
  610. }
  611. /*------------------------------------------------------------------------------
  612. ----------------------------- RPC Handler functions ----------------------------
  613. ------------------------------------------------------------------------------*/
  614. void NetconEthernetTap::handle_bind(NetconClient *client, struct bind_st *bind_rpc)
  615. {
  616. // FIXME: Is this hack still needed?
  617. struct sockaddr_in *connaddr;
  618. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  619. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  620. ip_addr_t conn_addr;
  621. //IP4_ADDR(&conn_addr, 192,168,0,2);
  622. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  623. int ip = connaddr->sin_addr.s_addr;
  624. unsigned char bytes[4];
  625. bytes[0] = ip & 0xFF;
  626. bytes[1] = (ip >> 8) & 0xFF;
  627. bytes[2] = (ip >> 16) & 0xFF;
  628. bytes[3] = (ip >> 24) & 0xFF;
  629. fprintf(stderr, "binding to: %d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]);
  630. fprintf(stderr, "PORT = %d\n", conn_port);
  631. NetconConnection *c = client->getConnectionByTheirFD(bind_rpc->sockfd);
  632. if(c) {
  633. if(c->pcb->state == CLOSED){
  634. int err = lwipstack->tcp_bind(c->pcb, &conn_addr, conn_port);
  635. if(err != ERR_OK) {
  636. fprintf(stderr, "error while binding to addr/port\n");
  637. }
  638. else {
  639. fprintf(stderr, "bind successful\n");
  640. }
  641. }
  642. else {
  643. fprintf(stderr, "PCB not in CLOSED state. Ignoring BIND request.\n");
  644. }
  645. }
  646. else {
  647. fprintf(stderr, "can't locate connection for PCB\n");
  648. }
  649. }
  650. void NetconEthernetTap::handle_listen(NetconClient *client, struct listen_st *listen_rpc)
  651. {
  652. NetconConnection *c = client->getConnectionByTheirFD(listen_rpc->sockfd);
  653. if(c) {
  654. if(c->pcb->state == LISTEN) {
  655. fprintf(stderr, "PCB is already in listening state.\n");
  656. return;
  657. }
  658. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(c->pcb);
  659. if(listening_pcb != NULL) {
  660. fprintf(stderr, "handle_listen(): c->pcb(%x) = listening_pcb(%x)\n", c->pcb, listening_pcb);
  661. c->pcb = listening_pcb;
  662. lwipstack->tcp_accept(listening_pcb, nc_accept);
  663. lwipstack->tcp_arg(listening_pcb, new Larg(this, c->sock));
  664. client->waiting_for_retval=true;
  665. }
  666. else {
  667. fprintf(stderr, "unable to allocate memory for new listening PCB\n");
  668. }
  669. }
  670. else {
  671. fprintf(stderr, "can't locate connection for PCB\n");
  672. }
  673. }
  674. void NetconEthernetTap::handle_retval(NetconClient *client, unsigned char* buf)
  675. {
  676. if(client->unmapped_conn != NULL) {
  677. memcpy(&(client->unmapped_conn->their_fd), &buf[1], sizeof(int));
  678. fprintf(stderr, "handle_retval(): RXed their_fd = %d\n", client->unmapped_conn->their_fd);
  679. client->connections.push_back(client->unmapped_conn);
  680. client->unmapped_conn = NULL;
  681. }
  682. }
  683. void NetconEthernetTap::handle_socket(NetconClient *client, struct socket_st* socket_rpc)
  684. {
  685. struct tcp_pcb *pcb = lwipstack->tcp_new();
  686. if(pcb != NULL) {
  687. int their_fd;
  688. PhySocket *our_sock = _phy.createSocketPair(their_fd, client);
  689. int our_fd = _phy.getDescriptor(our_sock);
  690. NetconConnection *new_conn = client->addConnection(BUFFER, our_sock);
  691. new_conn->their_fd = their_fd;
  692. new_conn->pcb = pcb;
  693. PhySocket *sock = client->rpc->sock;
  694. int send_fd = _phy.getDescriptor(sock);
  695. sock_fd_write(send_fd, their_fd);
  696. client->unmapped_conn = new_conn;
  697. fprintf(stderr, "handle_socket(): [pcb = %x], their_fd = %d, send_fd = %d, our_fd = %d\n", pcb, their_fd, send_fd, our_fd);
  698. }
  699. else {
  700. fprintf(stderr, "Memory not available for new PCB\n");
  701. }
  702. }
  703. void NetconEthernetTap::handle_connect(NetconClient *client, struct connect_st* connect_rpc)
  704. {
  705. // FIXME: Parse out address information -- Probably a more elegant way to do this
  706. struct sockaddr_in *connaddr;
  707. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  708. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  709. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  710. fprintf(stderr, "getConnectionByTheirFD(%d)\n", connect_rpc->__fd);
  711. NetconConnection *c = client->getConnectionByTheirFD(connect_rpc->__fd);
  712. if(c!= NULL) {
  713. lwipstack->tcp_sent(c->pcb, nc_sent); // FIXME: Move?
  714. lwipstack->tcp_recv(c->pcb, nc_recved);
  715. lwipstack->tcp_err(c->pcb, nc_err);
  716. lwipstack->tcp_poll(c->pcb, nc_poll, APPLICATION_POLL_FREQ);
  717. lwipstack->tcp_arg(c->pcb, new Larg(this, c->sock));
  718. int err = 0;
  719. if((err = lwipstack->tcp_connect(c->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  720. {
  721. // dwr(h->tid, "tcp_connect() = %s\n", lwiperror(err));
  722. // We should only return a value if failure happens immediately
  723. // Otherwise, we still need to wait for a callback from lwIP.
  724. // - This is because an ERR_OK from tcp_connect() only verifies
  725. // that the SYN packet was enqueued onto the stack properly,
  726. // that's it!
  727. // - Most instances of a retval for a connect() should happen
  728. // in the nc_connect() and nc_err() callbacks!
  729. //fprintf(stderr, "failed to connect: %s\n", lwiperror(err));
  730. send_return_value(client, err);
  731. }
  732. // Everything seems to be ok, but we don't have enough info to retval
  733. client->waiting_for_retval=true;
  734. }
  735. else {
  736. fprintf(stderr, "could not locate PCB based on their fd\n");
  737. }
  738. }
  739. void NetconEthernetTap::handle_write(NetconConnection *c)
  740. {
  741. fprintf(stderr, "handle_write()\n");
  742. if(c) {
  743. int sndbuf = c->pcb->snd_buf;
  744. float avail = (float)sndbuf;
  745. float max = (float)TCP_SND_BUF;
  746. float load = 1.0 - (avail / max);
  747. if(load >= 0.9) {
  748. return;
  749. }
  750. int write_allowance = sndbuf < c->idx ? sndbuf : c->idx;
  751. int sz;
  752. fprintf(stderr, "handle_write(): write_allowance = %d, pcb->sndbuf = %d\n", write_allowance, sndbuf);
  753. if(write_allowance > 0) {
  754. int err = lwipstack->tcp_write(c->pcb, &c->buf, write_allowance, TCP_WRITE_FLAG_COPY);
  755. if(err != ERR_OK) {
  756. fprintf(stderr, "handle_write(): error while writing to PCB\n");
  757. return;
  758. }
  759. else {
  760. sz = (c->idx)-write_allowance;
  761. if(sz) {
  762. memmove(&c->buf, (c->buf+write_allowance), sz);
  763. }
  764. c->idx -= write_allowance;
  765. //c->data_sent += write_allowance;
  766. return;
  767. }
  768. }
  769. else {
  770. fprintf(stderr, "handle_write(): lwIP stack full\n");
  771. return;
  772. }
  773. }
  774. else {
  775. fprintf(stderr, "handle_write(): could not locate connection for this fd\n");
  776. }
  777. }
  778. } // namespace ZeroTier
  779. #endif // ZT_ENABLE_NETCON