NetconEthernetTap.cpp 48 KB

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