NetconEthernetTap.cpp 46 KB

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