NetconEthernetTap.cpp 38 KB

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