NetconEthernetTap.cpp 46 KB

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