NetconEthernetTap.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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 20
  46. #define ZT_LWIP_TCP_TIMER_INTERVAL 10
  47. #define STATUS_TMR_INTERVAL 500 // How often we check connection statuses
  48. namespace ZeroTier {
  49. NetconEthernetTap::NetconEthernetTap(
  50. const char *homePath,
  51. const MAC &mac,
  52. unsigned int mtu,
  53. unsigned int metric,
  54. uint64_t nwid,
  55. const char *friendlyName,
  56. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  57. void *arg) :
  58. _phy(this,false,true),
  59. _unixListenSocket((PhySocket *)0),
  60. _handler(handler),
  61. _arg(arg),
  62. _nwid(nwid),
  63. _mac(mac),
  64. _homePath(homePath),
  65. _mtu(mtu),
  66. _enabled(true),
  67. _run(true)
  68. {
  69. char sockPath[4096];
  70. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",(unsigned long long)nwid);
  71. _dev = sockPath;
  72. lwipstack = new LWIPStack("ext/bin/lwip/liblwip.so"); // ext/bin/liblwip.so.debug for debug symbols
  73. if(!lwipstack) // TODO double check this check
  74. throw std::runtime_error("unable to load lwip lib.");
  75. lwipstack->lwip_init();
  76. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  77. if (!_unixListenSocket)
  78. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  79. _thread = Thread::start(this);
  80. }
  81. NetconEthernetTap::~NetconEthernetTap()
  82. {
  83. _run = false;
  84. _phy.whack();
  85. _phy.whack();
  86. Thread::join(_thread);
  87. _phy.close(_unixListenSocket,false);
  88. delete lwipstack;
  89. }
  90. void NetconEthernetTap::setEnabled(bool en)
  91. {
  92. _enabled = en;
  93. }
  94. bool NetconEthernetTap::enabled() const
  95. {
  96. return _enabled;
  97. }
  98. bool NetconEthernetTap::addIp(const InetAddress &ip)
  99. {
  100. Mutex::Lock _l(_ips_m);
  101. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  102. _ips.push_back(ip);
  103. std::sort(_ips.begin(),_ips.end());
  104. if (ip.isV4()) {
  105. // Set IP
  106. static ip_addr_t ipaddr, netmask, gw;
  107. IP4_ADDR(&gw,192,168,0,1);
  108. ipaddr.addr = *((u32_t *)ip.rawIpData());
  109. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  110. // Set up the lwip-netif for LWIP's sake
  111. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  112. interface.state = this;
  113. interface.output = lwipstack->_etharp_output;
  114. _mac.copyTo(interface.hwaddr, 6);
  115. interface.mtu = _mtu;
  116. interface.name[0] = 't';
  117. interface.name[1] = 'p';
  118. interface.linkoutput = low_level_output;
  119. interface.hwaddr_len = 6;
  120. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  121. lwipstack->netif_set_default(&interface);
  122. lwipstack->netif_set_up(&interface);
  123. }
  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. // TODO: dealloc from LWIP
  136. }
  137. return true;
  138. }
  139. std::vector<InetAddress> NetconEthernetTap::ips() const
  140. {
  141. Mutex::Lock _l(_ips_m);
  142. return _ips;
  143. }
  144. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  145. {
  146. struct pbuf *p,*q;
  147. if (!_enabled)
  148. return;
  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((char*)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. {
  176. Mutex::Lock _l2(lwipstack->_lock);
  177. if(interface.input(p, &interface) != ERR_OK) {
  178. fprintf(stderr, "_put(): Error while RXing packet (netif->input)\n");
  179. }
  180. }
  181. }
  182. std::string NetconEthernetTap::deviceName() const
  183. {
  184. return _dev;
  185. }
  186. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  187. {
  188. }
  189. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  190. {
  191. std::vector<MulticastGroup> newGroups;
  192. Mutex::Lock _l(_multicastGroups_m);
  193. // TODO: get multicast subscriptions from LWIP
  194. std::vector<InetAddress> allIps(ips());
  195. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  196. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  197. std::sort(newGroups.begin(),newGroups.end());
  198. std::unique(newGroups.begin(),newGroups.end());
  199. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  200. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  201. added.push_back(*m);
  202. }
  203. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  204. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  205. removed.push_back(*m);
  206. }
  207. _multicastGroups.swap(newGroups);
  208. }
  209. TcpConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  210. {
  211. for(size_t i=0; i<tcp_connections.size(); i++) {
  212. if(tcp_connections[i]->pcb == pcb)
  213. return tcp_connections[i];
  214. }
  215. return NULL;
  216. }
  217. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(PhySocket *sock, int fd)
  218. {
  219. for(size_t i=0; i<tcp_connections.size(); i++) {
  220. if(tcp_connections[i]->perceived_fd == fd && tcp_connections[i]->rpcSock == sock)
  221. return tcp_connections[i];
  222. }
  223. return NULL;
  224. }
  225. /*
  226. * Closes a TcpConnection and associated LWIP PCB strcuture.
  227. */
  228. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  229. {
  230. fprintf(stderr, "closeConnection(%x, %d)\n", conn->pcb, _phy.getDescriptor(conn->dataSock));
  231. lwipstack->_tcp_arg(conn->pcb, NULL);
  232. lwipstack->_tcp_sent(conn->pcb, NULL);
  233. lwipstack->_tcp_recv(conn->pcb, NULL);
  234. lwipstack->_tcp_err(conn->pcb, NULL);
  235. lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  236. lwipstack->_tcp_close(conn->pcb);
  237. if(conn->dataSock) {
  238. close(_phy.getDescriptor(conn->dataSock));
  239. _phy.close(conn->dataSock,false);
  240. }
  241. /* Eventually we might want to use a map here instead */
  242. for(int i=0; i<tcp_connections.size(); i++) {
  243. if(tcp_connections[i] == conn) {
  244. tcp_connections.erase(tcp_connections.begin() + i);
  245. break;
  246. }
  247. }
  248. delete conn;
  249. }
  250. /*
  251. * Close a single RPC connection and associated PhySocket
  252. */
  253. void NetconEthernetTap::closeClient(PhySocket *sock)
  254. {
  255. for(size_t i=0; i<rpc_sockets.size(); i++) {
  256. if(rpc_sockets[i] == sock){
  257. rpc_sockets.erase(rpc_sockets.begin() + i);
  258. break;
  259. }
  260. }
  261. close(_phy.getDescriptor(sock));
  262. _phy.close(sock);
  263. }
  264. /*
  265. * Close all RPC and TCP connections
  266. */
  267. void NetconEthernetTap::closeAll()
  268. {
  269. while(rpc_sockets.size())
  270. closeClient(rpc_sockets.front());
  271. while(tcp_connections.size())
  272. closeConnection(tcp_connections.front());
  273. }
  274. #include <sys/resource.h>
  275. void NetconEthernetTap::threadMain()
  276. throw()
  277. {
  278. //signal(SIGPIPE, SIG_IGN);
  279. uint64_t prev_tcp_time = 0;
  280. uint64_t prev_status_time = 0;
  281. uint64_t prev_etharp_time = 0;
  282. /*
  283. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  284. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  285. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  286. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  287. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  288. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n", MEMP_NUM_TCP_SEG);
  289. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  290. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n", TCP_SND_QUEUELEN);
  291. fprintf(stderr, "- TCP_MAXRTX = %d\n", TCP_MAXRTX);
  292. fprintf(stderr, "- IP_REASSEMBLY = %d\n", IP_REASSEMBLY);
  293. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  294. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  295. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  296. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  297. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  298. */
  299. // Main timer loop
  300. while (_run) {
  301. uint64_t now = OSUtils::now();
  302. uint64_t since_tcp = now - prev_tcp_time;
  303. uint64_t since_etharp = now - prev_etharp_time;
  304. uint64_t since_status = now - prev_status_time;
  305. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  306. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  307. uint64_t status_remaining = STATUS_TMR_INTERVAL;
  308. if (since_status >= STATUS_TMR_INTERVAL && true == false) {
  309. prev_status_time = now;
  310. if(rpc_sockets.size() || tcp_connections.size()) {
  311. /* Here we will periodically check the list of rpc_sockets for those that
  312. do not currently have any data connection associated with them. If they are
  313. unused, then we will try to read from them, if they fail, we can safely assume
  314. that the client has closed their end and we can close ours */
  315. for(size_t i = 0; i<tcp_connections.size(); i++) {
  316. if(tcp_connections[i]->listening) {
  317. char c;
  318. if (read(_phy.getDescriptor(tcp_connections[i]->dataSock), &c, 1) < 0) {
  319. // Still in listening state
  320. }
  321. else {
  322. // Here we should handle the case there there is incoming data (?)
  323. fprintf(stderr, "Listening socketpair closed. Removing RPC connection (%d)\n",
  324. _phy.getDescriptor(tcp_connections[i]->dataSock));
  325. closeConnection(tcp_connections[i]);
  326. }
  327. }
  328. }
  329. }
  330. fprintf(stderr, "tcp_conns = %d, rpc_socks = %d\n", tcp_connections.size(), rpc_sockets.size());
  331. for(size_t i=0, associated = 0; i<rpc_sockets.size(); i++, associated = 0) {
  332. for(size_t j=0; j<tcp_connections.size(); j++) {
  333. if (tcp_connections[j]->rpcSock == rpc_sockets[i])
  334. associated++;
  335. }
  336. if(!associated){
  337. // No TCP connections are associated, this is a candidate for removal
  338. unsigned char tmpbuf[BUF_SZ];
  339. if(read(_phy.getDescriptor(rpc_sockets[i]),&tmpbuf,BUF_SZ) < 0) {
  340. fprintf(stderr, "run() ---> RPC close(%d)\n", _phy.getDescriptor(rpc_sockets[i]));
  341. closeClient(rpc_sockets[i]);
  342. }
  343. else {
  344. // Handle RPC call, this is rare
  345. fprintf(stderr, "run(): RPC read during connection check\n");
  346. exit(0); // FIXME: This should be addressed - Raise APPLICATION_POLL_FREQ to make it less likely
  347. phyOnUnixData(rpc_sockets[i],NULL,&tmpbuf,BUF_SZ);
  348. }
  349. }
  350. }
  351. }
  352. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  353. prev_tcp_time = now;
  354. lwipstack->tcp_tmr();
  355. } else {
  356. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  357. }
  358. if (since_etharp >= ARP_TMR_INTERVAL) {
  359. prev_etharp_time = now;
  360. lwipstack->etharp_tmr();
  361. } else {
  362. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  363. }
  364. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  365. }
  366. closeAll();
  367. dlclose(lwipstack->_libref);
  368. }
  369. // Unused -- no UDP or TCP from this thread/Phy<>
  370. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  371. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  372. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  373. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  374. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  375. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  376. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  377. {
  378. // FIXME: What do?
  379. }
  380. /*
  381. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  382. */
  383. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  384. {
  385. if(readable) {
  386. TcpConnection *conn = (TcpConnection*)*uptr;
  387. if(conn->dataSock) // Sometimes a connection may be closed via nc_recved, check first
  388. {
  389. //Mutex::Lock _l(lwipstack->_lock);
  390. lwipstack->_lock.lock();
  391. handle_write(conn);
  392. lwipstack->_lock.unlock();
  393. }
  394. }
  395. else {
  396. fprintf(stderr, "phyOnFileDescriptorActivity(): PhySocket not readable\n");
  397. }
  398. }
  399. /*
  400. * Add a new PhySocket for the client connection
  401. */
  402. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {
  403. rpc_sockets.push_back(sockN);
  404. }
  405. /*
  406. * Processes incoming data on a client-specific RPC connection
  407. */
  408. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  409. {
  410. unsigned char *buf = (unsigned char*)data;
  411. switch(buf[0])
  412. {
  413. case RPC_SOCKET:
  414. fprintf(stderr, "RPC_SOCKET\n");
  415. struct socket_st socket_rpc;
  416. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  417. handle_socket(sock, uptr, &socket_rpc);
  418. break;
  419. case RPC_LISTEN:
  420. fprintf(stderr, "RPC_LISTEN\n");
  421. struct listen_st listen_rpc;
  422. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  423. handle_listen(sock, uptr, &listen_rpc);
  424. break;
  425. case RPC_BIND:
  426. fprintf(stderr, "RPC_BIND\n");
  427. struct bind_st bind_rpc;
  428. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  429. handle_bind(sock, uptr, &bind_rpc);
  430. break;
  431. case RPC_CONNECT:
  432. fprintf(stderr, "RPC_CONNECT\n");
  433. struct connect_st connect_rpc;
  434. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  435. handle_connect(sock, uptr, &connect_rpc);
  436. break;
  437. case RPC_MAP:
  438. fprintf(stderr, "RPC_MAP\n");
  439. handle_retval(sock, uptr, buf);
  440. break;
  441. default:
  442. break;
  443. }
  444. }
  445. /*
  446. * Send a 'retval' and 'errno' to the client for an RPC over connection->rpcSock
  447. */
  448. int NetconEthernetTap::send_return_value(TcpConnection *conn, int retval, int _errno = 0)
  449. {
  450. if(conn) {
  451. int n = send_return_value(_phy.getDescriptor(conn->rpcSock), retval, _errno);
  452. if(n > 0)
  453. conn->pending = false;
  454. else {
  455. fprintf(stderr, "Unable to send return value to the intercept. Closing connection\n");
  456. closeConnection(conn);
  457. }
  458. return n;
  459. }
  460. return -1;
  461. }
  462. int NetconEthernetTap::send_return_value(int fd, int retval, int _errno = 0)
  463. {
  464. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  465. char retmsg[sz];
  466. memset(&retmsg, '\0', sizeof(retmsg));
  467. retmsg[0]=RPC_RETVAL;
  468. memcpy(&retmsg[1], &retval, sizeof(retval));
  469. memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
  470. return write(fd, &retmsg, sz);
  471. }
  472. /*------------------------------------------------------------------------------
  473. --------------------------------- LWIP callbacks -------------------------------
  474. ------------------------------------------------------------------------------*/
  475. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  476. // locked in this case!
  477. /*
  478. * Callback from LWIP for when a connection has been accepted and the PCB has been
  479. * put into an ACCEPT state.
  480. *
  481. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  482. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  483. * is then required to tell the service what new file descriptor it has allocated
  484. * for this connection. After the mapping is complete, the accepted socket can be
  485. * used.
  486. *
  487. * @param associated service state object
  488. * @param newly allocated PCB
  489. * @param error code
  490. * @return ERR_OK if everything is ok, -1 otherwise
  491. i := should be implemented in intercept lib
  492. I := is implemented in intercept lib
  493. X := is implemented in service
  494. ? := required treatment Unknown
  495. - := Not needed
  496. [ ] EAGAIN or EWOULDBLOCK - The socket is marked nonblocking and no connections are present
  497. to be accepted. POSIX.1-2001 allows either error to be returned for
  498. this case, and does not require these constants to have the same value,
  499. so a portable application should check for both possibilities.
  500. [I] EBADF - The descriptor is invalid.
  501. [I] ECONNABORTED - A connection has been aborted.
  502. [i] EFAULT - The addr argument is not in a writable part of the user address space.
  503. [-] EINTR - The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).
  504. [I] EINVAL - Socket is not listening for connections, or addrlen is invalid (e.g., is negative).
  505. [I] EINVAL - (accept4()) invalid value in flags.
  506. [I] EMFILE - The per-process limit of open file descriptors has been reached.
  507. [ ] ENFILE - The system limit on the total number of open files has been reached.
  508. [ ] ENOBUFS, ENOMEM - Not enough free memory. This often means that the memory allocation is
  509. limited by the socket buffer limits, not by the system memory.
  510. [I] ENOTSOCK - The descriptor references a file, not a socket.
  511. [I] EOPNOTSUPP - The referenced socket is not of type SOCK_STREAM.
  512. [ ] EPROTO - Protocol error.
  513. *
  514. */
  515. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  516. {
  517. fprintf(stderr, "nc_accept()\n");
  518. Larg *l = (Larg*)arg;
  519. TcpConnection *conn = l->conn;
  520. NetconEthernetTap *tap = l->tap;
  521. int larg_fd = tap->_phy.getDescriptor(conn->dataSock);
  522. if(conn) {
  523. ZT_PHY_SOCKFD_TYPE fds[2];
  524. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  525. if(errno < 0) {
  526. l->tap->send_return_value(conn, -1, errno);
  527. fprintf(stderr, "nc_accept(): unable to create socketpair\n");
  528. return ERR_MEM;
  529. }
  530. }
  531. TcpConnection *new_tcp_conn = new TcpConnection();
  532. new_tcp_conn->dataSock = tap->_phy.wrapSocket(fds[0], new_tcp_conn);
  533. new_tcp_conn->rpcSock = conn->rpcSock;
  534. new_tcp_conn->pcb = newpcb;
  535. new_tcp_conn->their_fd = fds[1];
  536. tap->tcp_connections.push_back(new_tcp_conn);
  537. fprintf(stderr, "socketpair = {%d, %d}\n", fds[0], fds[1]);
  538. int send_fd = tap->_phy.getDescriptor(conn->rpcSock);
  539. fprintf(stderr, "write(%d,...)\n", larg_fd);
  540. int n = write(larg_fd, "z", 1); // accept() in library waits for this byte
  541. if(n > 0) {
  542. if(sock_fd_write(send_fd, fds[1]) > 0) {
  543. close(fds[1]); // close other end of socketpair
  544. new_tcp_conn->pending = true;
  545. }
  546. else {
  547. fprintf(stderr, "nc_accept(%d): unable to send fd to client\n", larg_fd);
  548. }
  549. }
  550. else {
  551. fprintf(stderr, "nc_accept(%d): error writing signal byte (send_fd = %d, perceived_fd = %d)\n", larg_fd, send_fd, fds[1]);
  552. return -1;
  553. }
  554. tap->lwipstack->_tcp_arg(newpcb, new Larg(tap, new_tcp_conn));
  555. tap->lwipstack->_tcp_recv(newpcb, nc_recved);
  556. tap->lwipstack->_tcp_err(newpcb, nc_err);
  557. tap->lwipstack->_tcp_sent(newpcb, nc_sent);
  558. tap->lwipstack->_tcp_poll(newpcb, nc_poll, 0.5);
  559. tcp_accepted(conn->pcb); // Let lwIP know that it can queue additional incoming connections
  560. return ERR_OK;
  561. }
  562. else {
  563. fprintf(stderr, "nc_accept(%d): can't locate Connection object for PCB.\n", larg_fd);
  564. }
  565. return -1;
  566. }
  567. /*
  568. * Callback from LWIP for when data is available to be read from the network.
  569. *
  570. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  571. * send to the client over the associated unix socket.
  572. *
  573. * @param associated service state object
  574. * @param allocated PCB
  575. * @param chain of pbufs
  576. * @param error code
  577. * @return ERR_OK if everything is ok, -1 otherwise
  578. *
  579. */
  580. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  581. {
  582. Larg *l = (Larg*)arg;
  583. int n;
  584. struct pbuf* q = p;
  585. if(!l->conn) {
  586. fprintf(stderr, "nc_recved(): no connection object\n");
  587. return ERR_OK; // ?
  588. }
  589. if(p == NULL) {
  590. if(l->conn) {
  591. fprintf(stderr, "nc_recved(): closing connection\n");
  592. l->tap->closeConnection(l->conn);
  593. }
  594. else {
  595. fprintf(stderr, "nc_recved(): can't locate connection via (arg)\n");
  596. }
  597. return err;
  598. }
  599. q = p;
  600. while(p != NULL) { // Cycle through pbufs and write them to the socket
  601. if(p->len <= 0)
  602. break; // ?
  603. if((n = l->tap->_phy.streamSend(l->conn->dataSock,p->payload, p->len)) > 0) {
  604. if(n < p->len) {
  605. fprintf(stderr, "nc_recved(): unable to write entire pbuf to buffer\n");
  606. }
  607. l->tap->lwipstack->_tcp_recved(tpcb, n); // TODO: would it be more efficient to call this once at the end?
  608. }
  609. else {
  610. fprintf(stderr, "nc_recved(): No data written to intercept buffer\n");
  611. }
  612. p = p->next;
  613. }
  614. l->tap->lwipstack->_pbuf_free(q); // free pbufs
  615. return ERR_OK;
  616. }
  617. /*
  618. * Callback from LWIP when an internal error is associtated with the given (arg)
  619. *
  620. * Since the PCB related to this error might no longer exist, only its perviously
  621. * associated (arg) is provided to us.
  622. *
  623. * @param associated service state object
  624. * @param error code
  625. *
  626. */
  627. void NetconEthernetTap::nc_err(void *arg, err_t err)
  628. {
  629. Larg *l = (Larg*)arg;
  630. //fprintf(stderr, "larg = %x, nc_err() = %d\n", l, err);
  631. if(!l->conn)
  632. fprintf(stderr, "nc_err(): Connection is NULL!\n");
  633. if(l->conn) {
  634. switch(err)
  635. {
  636. case ERR_MEM:
  637. fprintf(stderr, "nc_err(): ERR_MEM->ENOMEM\n");
  638. l->tap->send_return_value(l->conn, -1, ENOMEM);
  639. break;
  640. case ERR_BUF:
  641. fprintf(stderr, "nc_err(): ERR_BUF->ENOBUFS\n");
  642. l->tap->send_return_value(l->conn, -1, ENOBUFS);
  643. break;
  644. case ERR_TIMEOUT:
  645. fprintf(stderr, "nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  646. l->tap->send_return_value(l->conn, -1, ETIMEDOUT);
  647. break;
  648. case ERR_RTE:
  649. fprintf(stderr, "nc_err(): ERR_RTE->ENETUNREACH\n");
  650. l->tap->send_return_value(l->conn, -1, ENETUNREACH);
  651. break;
  652. case ERR_INPROGRESS:
  653. fprintf(stderr, "nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  654. l->tap->send_return_value(l->conn, -1, EINPROGRESS);
  655. break;
  656. case ERR_VAL:
  657. fprintf(stderr, "nc_err(): ERR_VAL->EINVAL\n");
  658. l->tap->send_return_value(l->conn, -1, EINVAL);
  659. break;
  660. case ERR_WOULDBLOCK:
  661. fprintf(stderr, "nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  662. l->tap->send_return_value(l->conn, -1, EWOULDBLOCK);
  663. break;
  664. case ERR_USE:
  665. fprintf(stderr, "nc_err(): ERR_USE->EADDRINUSE\n");
  666. l->tap->send_return_value(l->conn, -1, EADDRINUSE);
  667. break;
  668. case ERR_ISCONN:
  669. fprintf(stderr, "nc_err(): ERR_ISCONN->EISCONN\n");
  670. l->tap->send_return_value(l->conn, -1, EISCONN);
  671. break;
  672. case ERR_ABRT:
  673. fprintf(stderr, "nc_err(): ERR_ABRT->ECONNREFUSED\n");
  674. l->tap->send_return_value(l->conn, -1, ECONNREFUSED);
  675. break;
  676. // FIXME: Below are errors which don't have a standard errno correlate
  677. case ERR_RST:
  678. l->tap->send_return_value(l->conn, -1, -1);
  679. break;
  680. case ERR_CLSD:
  681. l->tap->send_return_value(l->conn, -1, -1);
  682. break;
  683. case ERR_CONN:
  684. l->tap->send_return_value(l->conn, -1, -1);
  685. break;
  686. case ERR_ARG:
  687. l->tap->send_return_value(l->conn, -1, -1);
  688. break;
  689. case ERR_IF:
  690. l->tap->send_return_value(l->conn, -1, -1);
  691. break;
  692. default:
  693. break;
  694. }
  695. fprintf(stderr, "nc_err(): closing connection\n");
  696. l->tap->closeConnection(l->conn);
  697. }
  698. else {
  699. fprintf(stderr, "nc_err(): can't locate connection object for PCB\n");
  700. }
  701. }
  702. /*
  703. * Callback from LWIP to do whatever work we might need to do.
  704. *
  705. * @param associated service state object
  706. * @param PCB we're polling on
  707. * @return ERR_OK if everything is ok, -1 otherwise
  708. *
  709. */
  710. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  711. {
  712. //Larg *l = (Larg*)arg;
  713. /*
  714. Larg *l = (Larg*)arg;
  715. TcpConnection *conn = l->conn;
  716. NetconEthernetTap *tap = l->tap;
  717. if(conn && conn->idx) // if valid connection and non-zero index (indicating data present)
  718. tap->handle_write(conn);
  719. */
  720. return ERR_OK;
  721. }
  722. /*
  723. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  724. * As a result, we should put our socket back into a notify-on-readability state
  725. * since there is now room on the PCB buffer to write to.
  726. *
  727. * NOTE: This could be used to track the amount of data sent by a connection.
  728. *
  729. * @param associated service state object
  730. * @param relevant PCB
  731. * @param length of data sent
  732. * @return ERR_OK if everything is ok, -1 otherwise
  733. *
  734. */
  735. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  736. {
  737. //fprintf(stderr, "nc_sent()\n");
  738. Larg *l = (Larg*)arg;
  739. if(len) {
  740. //fprintf(stderr, "ACKING len = %d, setting read-notify = true, (sndbuf = %d)\n", len, l->conn->pcb->snd_buf);
  741. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  742. //uint64_t now = OSUtils::now();
  743. //fprintf(stderr, "nc_sent(): now = %u\n", now);
  744. l->tap->_phy.whack();
  745. }
  746. return ERR_OK;
  747. }
  748. /*
  749. * Callback from LWIP which sends a return value to the client to signal that
  750. * a connection was established for this PCB
  751. *
  752. * @param associated service state object
  753. * @param relevant PCB
  754. * @param error code
  755. * @return ERR_OK if everything is ok, -1 otherwise
  756. *
  757. */
  758. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  759. {
  760. fprintf(stderr, "nc_connected()\n");
  761. Larg *l = (Larg*)arg;
  762. l->tap->send_return_value(l->conn, ERR_OK);
  763. return ERR_OK;
  764. }
  765. /*------------------------------------------------------------------------------
  766. ----------------------------- RPC Handler functions ----------------------------
  767. ------------------------------------------------------------------------------*/
  768. /**
  769. * Handles a return value (client's perceived fd) and completes a mapping
  770. * so that we know what connection an RPC call should be associated with.
  771. *
  772. * @param PhySocket associated with this RPC connection
  773. * @param structure containing the data and parameters for this client's RPC
  774. *
  775. */
  776. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, unsigned char* buf)
  777. {
  778. TcpConnection *conn = (TcpConnection*)*uptr;
  779. if(!conn->pending)
  780. return;
  781. // Copy data from buffer to TcpConnection object, update status
  782. memcpy(&(conn->perceived_fd), &buf[1], sizeof(int));
  783. conn->pending = false;
  784. fprintf(stderr, "handle_retval(): CONN:%x - Mapping [our=%d -> their=%d]\n",conn,
  785. _phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  786. /* Check for pre-existing connection for this socket ---
  787. This block is in response to interesting behaviour from redis-server. A
  788. socket is created, setsockopt is called and the socket is set to IPV6 but fails (for now),
  789. then it is closed and re-opened and consequently remapped. With two pipes mapped
  790. to the same socket, makes it possible that we write to the wrong pipe and fail. So
  791. this block merely searches for a possible duplicate mapping and erases it
  792. */
  793. for(size_t i=0; i<tcp_connections.size(); i++) {
  794. if(tcp_connections[i] == conn)
  795. continue;
  796. if(tcp_connections[i]->rpcSock == conn->rpcSock) {
  797. if(tcp_connections[i]->perceived_fd == conn->perceived_fd) {
  798. int n;
  799. if((n = send(_phy.getDescriptor(tcp_connections[i]->dataSock), "z", 1, MSG_NOSIGNAL)) < 0) {
  800. fprintf(stderr, "handle_retval(): CONN:%x - Socket (%d) already mapped (originally CONN:%x)\n", conn, tcp_connections[i]->perceived_fd, tcp_connections[i]);
  801. closeConnection(tcp_connections[i]);
  802. }
  803. else {
  804. fprintf(stderr, "handle_retval(): CONN:%x - This socket is mapped to two different pipes (?). Exiting.\n", conn);
  805. exit(0);
  806. }
  807. }
  808. }
  809. }
  810. }
  811. /*
  812. * Handles an RPC to bind an LWIP PCB to a given address and port
  813. *
  814. * @param PhySocket associated with this RPC connection
  815. * @param structure containing the data and parameters for this client's RPC
  816. *
  817. i := should be implemented in intercept lib
  818. I := is implemented in intercept lib
  819. X := is implemented in service
  820. ? := required treatment Unknown
  821. - := Not needed
  822. [ ] EACCES - The address is protected, and the user is not the superuser.
  823. [X] EADDRINUSE - The given address is already in use.
  824. [I] EBADF - sockfd is not a valid descriptor.
  825. [X] EINVAL - The socket is already bound to an address.
  826. [I] ENOTSOCK - sockfd is a descriptor for a file, not a socket.
  827. [X] ENOMEM - Insufficient kernel memory was available.
  828. - The following errors are specific to UNIX domain (AF_UNIX) sockets:
  829. [-] EACCES - Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
  830. [-] EADDRNOTAVAIL - A nonexistent interface was requested or the requested address was not local.
  831. [-] EFAULT - addr points outside the user's accessible address space.
  832. [-] EINVAL - The addrlen is wrong, or the socket was not in the AF_UNIX family.
  833. [-] ELOOP - Too many symbolic links were encountered in resolving addr.
  834. [-] ENAMETOOLONG - s addr is too long.
  835. [-] ENOENT - The file does not exist.
  836. [-] ENOTDIR - A component of the path prefix is not a directory.
  837. [-] EROFS - The socket inode would reside on a read-only file system.
  838. */
  839. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  840. {
  841. struct sockaddr_in *connaddr;
  842. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  843. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  844. ip_addr_t conn_addr;
  845. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  846. TcpConnection *conn = getConnectionByTheirFD(sock, bind_rpc->sockfd);
  847. if(conn) {
  848. if(conn->pcb->state == CLOSED){
  849. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  850. if(err != ERR_OK) {
  851. int ip = connaddr->sin_addr.s_addr;
  852. unsigned char d[4];
  853. d[0] = ip & 0xFF;
  854. d[1] = (ip >> 8) & 0xFF;
  855. d[2] = (ip >> 16) & 0xFF;
  856. d[3] = (ip >> 24) & 0xFF;
  857. fprintf(stderr, "handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  858. fprintf(stderr, "err = %d\n", err);
  859. if(err == ERR_USE)
  860. send_return_value(conn, -1, EADDRINUSE);
  861. if(err == ERR_MEM)
  862. send_return_value(conn, -1, ENOMEM);
  863. if(err == ERR_BUF)
  864. send_return_value(conn, -1, ENOMEM); // FIXME: Closest match
  865. }
  866. else
  867. send_return_value(conn, ERR_OK, ERR_OK); // Success
  868. }
  869. else {
  870. fprintf(stderr, "handle_bind(): PCB (%x) not in CLOSED state. Ignoring BIND request.\n", conn->pcb);
  871. send_return_value(conn, -1, EINVAL);
  872. }
  873. }
  874. else {
  875. fprintf(stderr, "handle_bind(): can't locate connection for PCB\n");
  876. send_return_value(conn, -1, EBADF);
  877. }
  878. }
  879. /*
  880. * Handles an RPC to put an LWIP PCB into LISTEN mode
  881. *
  882. * @param PhySocket associated with this RPC connection
  883. * @param structure containing the data and parameters for this client's RPC
  884. *
  885. i := should be implemented in intercept lib
  886. I := is implemented in intercept lib
  887. X := is implemented in service
  888. ? := required treatment Unknown
  889. - := Not needed
  890. [?] EADDRINUSE - Another socket is already listening on the same port.
  891. [IX] EBADF - The argument sockfd is not a valid descriptor.
  892. [I] ENOTSOCK - The argument sockfd is not a socket.
  893. [I] EOPNOTSUPP - The socket is not of a type that supports the listen() operation.
  894. */
  895. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  896. {
  897. TcpConnection *conn = getConnectionByTheirFD(sock, listen_rpc->sockfd);
  898. if(conn) {
  899. if(conn->pcb->state == LISTEN) {
  900. fprintf(stderr, "handle_listen(): PCB is already in listening state.\n");
  901. return;
  902. }
  903. struct tcp_pcb* listening_pcb;
  904. #ifdef TCP_LISTEN_BACKLOG
  905. listening_pcb = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  906. #else
  907. listening_pcb = lwipstack->tcp_listen(conn->pcb);
  908. #endif
  909. if(listening_pcb != NULL) {
  910. conn->pcb = listening_pcb;
  911. lwipstack->tcp_accept(listening_pcb, nc_accept);
  912. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  913. /* we need to wait for the client to send us the fd allocated on their end
  914. for this listening socket */
  915. fcntl(_phy.getDescriptor(conn->dataSock), F_SETFL, O_NONBLOCK);
  916. conn->listening = true;
  917. conn->pending = true;
  918. send_return_value(conn, ERR_OK, ERR_OK);
  919. }
  920. else {
  921. /*
  922. fprintf(stderr, "handle_listen(): unable to allocate memory for new listening PCB\n");
  923. // FIXME: This does not have an equivalent errno value
  924. // lwip will reclaim space with a tcp_listen call since a PCB in a LISTEN
  925. // state takes up less space. If something goes wrong during the creation of a
  926. // new listening socket we should return an error that implies we can't use this
  927. // socket, even if the reason isn't describing what really happened internally.
  928. // See: http://lwip.wikia.com/wiki/Raw/TCP
  929. send_return_value(conn, -1, EBADF);
  930. */
  931. }
  932. }
  933. else {
  934. /*
  935. // We can't find a connection mapped to the socket fd provided
  936. fprintf(stderr, "handle_listen(): can't locate connection for PCB\n");
  937. send_return_value(conn, -1, EBADF);
  938. */
  939. }
  940. }
  941. /*
  942. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  943. *
  944. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  945. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  946. * is then required to tell the service what new file descriptor it has allocated
  947. * for this connection. After the mapping is complete, the socket can be used.
  948. *
  949. * @param PhySocket associated with this RPC connection
  950. * @param structure containing the data and parameters for this client's RPC
  951. *
  952. i := should be implemented in intercept lib
  953. I := is implemented in intercept lib
  954. X := is implemented in service
  955. ? := required treatment Unknown
  956. - := Not needed
  957. [-] EACCES - Permission to create a socket of the specified type and/or protocol is denied.
  958. [I] EAFNOSUPPORT - The implementation does not support the specified address family.
  959. [I] EINVAL - Unknown protocol, or protocol family not available.
  960. [I] EINVAL - Invalid flags in type.
  961. [I] EMFILE - Process file table overflow.
  962. [?] ENFILE - The system limit on the total number of open files has been reached.
  963. [X] ENOBUFS or ENOMEM - Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
  964. [?] EPROTONOSUPPORT - The protocol type or the specified protocol is not supported within this domain.
  965. */
  966. void NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  967. {
  968. int rpc_fd = _phy.getDescriptor(sock);
  969. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  970. fprintf(stderr, "handle_socket(): pcb=%x, (state == CLOSED) = %d\n", newpcb, (newpcb->state==CLOSED));
  971. if(newpcb != NULL) {
  972. ZT_PHY_SOCKFD_TYPE fds[2];
  973. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  974. if(errno < 0) {
  975. send_return_value(rpc_fd, -1, errno);
  976. return;
  977. }
  978. }
  979. fprintf(stderr, "socketpair = {%d, %d}\n", fds[0], fds[1]);
  980. TcpConnection *new_conn = new TcpConnection();
  981. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  982. *uptr = new_conn;
  983. new_conn->rpcSock = sock;
  984. new_conn->pcb = newpcb;
  985. new_conn->their_fd = fds[1];
  986. tcp_connections.push_back(new_conn);
  987. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  988. close(fds[1]); // close other end of socketpair
  989. // Once the client tells us what its fd is on the other end, we can then complete the mapping
  990. new_conn->pending = true;
  991. }
  992. else {
  993. sock_fd_write(rpc_fd, -1); // Send a bad fd, to signal error
  994. fprintf(stderr, "handle_socket(): Memory not available for new PCB\n");
  995. send_return_value(rpc_fd, -1, ENOMEM);
  996. }
  997. }
  998. /*
  999. * Handles an RPC to connect to a given address and port
  1000. *
  1001. * @param PhySocket associated with this RPC connection
  1002. * @param structure containing the data and parameters for this client's RPC
  1003. --- Error handling in this method will only catch problems which are immedately
  1004. apprent. Some errors will need to be caught in the nc_connected(0 callback
  1005. i := should be implemented in intercept lib
  1006. I := is implemented in intercept lib
  1007. X := is implemented in service
  1008. ? := required treatment Unknown
  1009. - := Not needed
  1010. [-] EACCES - For UNIX domain sockets, which are identified by pathname: Write permission is denied ...
  1011. [?] EACCES, EPERM - The user tried to connect to a broadcast address without having the socket broadcast flag enabled ...
  1012. [X] EADDRINUSE - Local address is already in use.
  1013. [I] EAFNOSUPPORT - The passed address didn't have the correct address family in its sa_family field.
  1014. [X] EAGAIN - No more free local ports or insufficient entries in the routing cache.
  1015. [ ] EALREADY - The socket is nonblocking and a previous connection attempt has not yet been completed.
  1016. [IX] EBADF - The file descriptor is not a valid index in the descriptor table.
  1017. [ ] ECONNREFUSED - No-one listening on the remote address.
  1018. [i] EFAULT - The socket structure address is outside the user's address space.
  1019. [ ] EINPROGRESS - The socket is nonblocking and the connection cannot be completed immediately.
  1020. [-] EINTR - The system call was interrupted by a signal that was caught.
  1021. [X] EISCONN - The socket is already connected.
  1022. [X] ENETUNREACH - Network is unreachable.
  1023. [I] ENOTSOCK - The file descriptor is not associated with a socket.
  1024. [X] ETIMEDOUT - Timeout while attempting connection.
  1025. [X] EINVAL - Invalid argument, SVr4, generally makes sense to set this
  1026. *
  1027. */
  1028. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  1029. {
  1030. TcpConnection *conn = (TcpConnection*)*uptr;
  1031. struct sockaddr_in *connaddr;
  1032. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  1033. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  1034. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  1035. if(conn != NULL) {
  1036. lwipstack->tcp_sent(conn->pcb, nc_sent);
  1037. lwipstack->tcp_recv(conn->pcb, nc_recved);
  1038. lwipstack->tcp_err(conn->pcb, nc_err);
  1039. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  1040. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  1041. int err = 0;
  1042. if((err = lwipstack->tcp_connect(conn->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  1043. {
  1044. if(err == ERR_ISCONN) {
  1045. send_return_value(conn, -1, EISCONN); // Already in connected state
  1046. return;
  1047. }
  1048. if(err == ERR_USE) {
  1049. send_return_value(conn, -1, EADDRINUSE); // Already in use
  1050. return;
  1051. }
  1052. if(err == ERR_VAL) {
  1053. send_return_value(conn, -1, EINVAL); // Invalid ipaddress parameter
  1054. return;
  1055. }
  1056. if(err == ERR_RTE) {
  1057. send_return_value(conn, -1, ENETUNREACH); // No route to host
  1058. return;
  1059. }
  1060. if(err == ERR_BUF) {
  1061. send_return_value(conn, -1, EAGAIN); // No more ports available
  1062. return;
  1063. }
  1064. if(err == ERR_MEM)
  1065. {
  1066. /* Can occur for the following reasons: tcp_enqueue_flags()
  1067. 1) tcp_enqueue_flags is always called with either SYN or FIN in flags.
  1068. We need one available snd_buf byte to do that.
  1069. This means we can't send FIN while snd_buf==0. A better fix would be to
  1070. not include SYN and FIN sequence numbers in the snd_buf count.
  1071. 2) Cannot allocate new pbuf
  1072. 3) Cannot allocate new TCP segment
  1073. */
  1074. send_return_value(conn, -1, EAGAIN); // FIXME: Doesn't describe the problem well, but closest match
  1075. return;
  1076. }
  1077. // We should only return a value if failure happens immediately
  1078. // Otherwise, we still need to wait for a callback from lwIP.
  1079. // - This is because an ERR_OK from tcp_connect() only verifies
  1080. // that the SYN packet was enqueued onto the stack properly,
  1081. // that's it!
  1082. // - Most instances of a retval for a connect() should happen
  1083. // in the nc_connect() and nc_err() callbacks!
  1084. fprintf(stderr, "handle_connect(): unable to connect\n");
  1085. send_return_value(conn, -1, EAGAIN);
  1086. }
  1087. // Everything seems to be ok, but we don't have enough info to retval
  1088. conn->pending=true;
  1089. }
  1090. else {
  1091. fprintf(stderr, "could not locate PCB based on their fd\n");
  1092. send_return_value(conn, -1, EBADF);
  1093. }
  1094. }
  1095. void NetconEthernetTap::handle_write(TcpConnection *conn)
  1096. {
  1097. float max = (float)TCP_SND_BUF;
  1098. int r;
  1099. if(!conn) {
  1100. fprintf(stderr, "handle_write(): could not locate connection for this fd\n");
  1101. return;
  1102. }
  1103. if(conn->idx < max) {
  1104. if(!conn->pcb) {
  1105. fprintf(stderr, "handle_write(): conn->pcb == NULL. Failed to write.\n");
  1106. return;
  1107. }
  1108. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  1109. /* PCB send buffer is full,turn off readability notifications for the
  1110. corresponding PhySocket until nc_sent() is called and confirms that there is
  1111. now space on the buffer */
  1112. if(sndbuf == 0) {
  1113. _phy.setNotifyReadable(conn->dataSock, false);
  1114. return;
  1115. }
  1116. if(!conn->listening)
  1117. lwipstack->_tcp_output(conn->pcb);
  1118. if(conn->dataSock) {
  1119. int read_fd = _phy.getDescriptor(conn->dataSock);
  1120. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  1121. conn->idx += r;
  1122. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  1123. * data to LWIP to be enqueued and eventually sent to the network. */
  1124. if(r > 0) {
  1125. int sz;
  1126. // NOTE: this assumes that lwipstack->_lock is locked, either
  1127. // because we are in a callback or have locked it manually.
  1128. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  1129. lwipstack->_tcp_output(conn->pcb);
  1130. if(err != ERR_OK) {
  1131. fprintf(stderr, "handle_write(): error while writing to PCB, (err = %d)\n", err);
  1132. return;
  1133. }
  1134. else {
  1135. sz = (conn->idx)-r;
  1136. if(sz) {
  1137. memmove(&conn->buf, (conn->buf+r), sz);
  1138. }
  1139. conn->idx -= r;
  1140. return;
  1141. }
  1142. }
  1143. else {
  1144. fprintf(stderr, "handle_write(): LWIP stack full\n");
  1145. return;
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. } // namespace ZeroTier
  1152. #endif // ZT_ENABLE_NETCON