NetconEthernetTap.cpp 45 KB

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