NetconEthernetTap.cpp 49 KB

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