NetconEthernetTap.cpp 46 KB

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