NetconEthernetTap.cpp 40 KB

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