NetconEthernetTap.cpp 47 KB

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