NetconEthernetTap.cpp 38 KB

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