NetconEthernetTap.cpp 48 KB

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