NetconEthernetTap.cpp 36 KB

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