NetconEthernetTap.cpp 46 KB

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