NetconEthernetTap.cpp 50 KB

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