NetconEthernetTap.cpp 36 KB

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