NetconEthernetTap.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 50
  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_BUF_SZ 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. /*
  62. * Outputs data from the pbuf queue to the interface
  63. */
  64. static err_t low_level_output(struct netif *netif, struct pbuf *p)
  65. {
  66. struct pbuf *q;
  67. char buf[ZT_MAX_MTU+32];
  68. char *bufptr;
  69. int totalLength = 0;
  70. ZeroTier::NetconEthernetTap *tap = (ZeroTier::NetconEthernetTap*)netif->state;
  71. bufptr = buf;
  72. // Copy data from each pbuf, one at a time
  73. for(q = p; q != NULL; q = q->next) {
  74. memcpy(bufptr, q->payload, q->len);
  75. bufptr += q->len;
  76. totalLength += q->len;
  77. }
  78. // [Send packet to network]
  79. // Split ethernet header and feed into handler
  80. struct eth_hdr *ethhdr;
  81. ethhdr = (struct eth_hdr *)buf;
  82. ZeroTier::MAC src_mac;
  83. ZeroTier::MAC dest_mac;
  84. src_mac.setTo(ethhdr->src.addr, 6);
  85. dest_mac.setTo(ethhdr->dest.addr, 6);
  86. tap->_handler(tap->_arg,tap->_nwid,src_mac,dest_mac,
  87. Utils::ntoh((uint16_t)ethhdr->type),0,buf + sizeof(struct eth_hdr),totalLength - sizeof(struct eth_hdr));
  88. return ERR_OK;
  89. }
  90. /*
  91. * TCP connection administered by service
  92. */
  93. class TcpConnection
  94. {
  95. public:
  96. bool listening;
  97. int pid, txsz, rxsz;
  98. PhySocket *rpcSock, *sock;
  99. struct tcp_pcb *pcb;
  100. struct sockaddr_storage *addr;
  101. unsigned char txbuf[DEFAULT_BUF_SZ];
  102. unsigned char rxbuf[DEFAULT_BUF_SZ];
  103. };
  104. /*
  105. * A helper class for passing a reference to _phy to LWIP callbacks as a "state"
  106. */
  107. class Larg
  108. {
  109. public:
  110. NetconEthernetTap *tap;
  111. TcpConnection *conn;
  112. Larg(NetconEthernetTap *_tap, TcpConnection *conn) : tap(_tap), conn(conn) {}
  113. };
  114. // ---------------------------------------------------------------------------
  115. NetconEthernetTap::NetconEthernetTap(
  116. const char *homePath,
  117. const MAC &mac,
  118. unsigned int mtu,
  119. unsigned int metric,
  120. uint64_t nwid,
  121. const char *friendlyName,
  122. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  123. void *arg) :
  124. _nwid(nwid),
  125. _handler(handler),
  126. _arg(arg),
  127. _phy(this,false,true),
  128. _unixListenSocket((PhySocket *)0),
  129. _mac(mac),
  130. _homePath(homePath),
  131. _mtu(mtu),
  132. _enabled(true),
  133. _run(true)
  134. {
  135. char sockPath[4096],lwipPath[4096];
  136. rpcCounter = -1;
  137. Utils::snprintf(sockPath,sizeof(sockPath),"%s%snc_%.16llx",homePath,ZT_PATH_SEPARATOR_S,_nwid,ZT_PATH_SEPARATOR_S,(unsigned long long)nwid);
  138. _dev = sockPath; // in netcon mode, set device to be just the network ID
  139. Utils::snprintf(lwipPath,sizeof(lwipPath),"%s%sliblwip.so",homePath,ZT_PATH_SEPARATOR_S);
  140. lwipstack = new LWIPStack(lwipPath);
  141. if(!lwipstack)
  142. throw std::runtime_error("unable to dynamically load a new instance of liblwip.so (searched ZeroTier home path)");
  143. lwipstack->lwip_init();
  144. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  145. dwr(MSG_INFO," NetconEthernetTap initialized!\n", _phy.getDescriptor(_unixListenSocket));
  146. if (!_unixListenSocket)
  147. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  148. _thread = Thread::start(this);
  149. }
  150. NetconEthernetTap::~NetconEthernetTap()
  151. {
  152. _run = false;
  153. _phy.whack();
  154. _phy.whack(); // TODO: Rationale?
  155. Thread::join(_thread);
  156. _phy.close(_unixListenSocket,false);
  157. delete lwipstack;
  158. }
  159. void NetconEthernetTap::setEnabled(bool en)
  160. {
  161. _enabled = en;
  162. }
  163. bool NetconEthernetTap::enabled() const
  164. {
  165. return _enabled;
  166. }
  167. bool NetconEthernetTap::addIp(const InetAddress &ip)
  168. {
  169. Mutex::Lock _l(_ips_m);
  170. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  171. _ips.push_back(ip);
  172. std::sort(_ips.begin(),_ips.end());
  173. if (ip.isV4()) {
  174. // Set IP
  175. static ip_addr_t ipaddr, netmask, gw;
  176. IP4_ADDR(&gw,192,168,0,1);
  177. ipaddr.addr = *((u32_t *)ip.rawIpData());
  178. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  179. // Set up the lwip-netif for LWIP's sake
  180. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  181. interface.state = this;
  182. interface.output = lwipstack->_etharp_output;
  183. _mac.copyTo(interface.hwaddr, 6);
  184. interface.mtu = _mtu;
  185. interface.name[0] = 't';
  186. interface.name[1] = 'p';
  187. interface.linkoutput = low_level_output;
  188. interface.hwaddr_len = 6;
  189. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  190. lwipstack->netif_set_default(&interface);
  191. lwipstack->netif_set_up(&interface);
  192. }
  193. }
  194. return true;
  195. }
  196. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  197. {
  198. Mutex::Lock _l(_ips_m);
  199. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  200. if (i == _ips.end())
  201. return false;
  202. _ips.erase(i);
  203. if (ip.isV4()) {
  204. // TODO: dealloc from LWIP
  205. }
  206. return true;
  207. }
  208. std::vector<InetAddress> NetconEthernetTap::ips() const
  209. {
  210. Mutex::Lock _l(_ips_m);
  211. return _ips;
  212. }
  213. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  214. {
  215. struct pbuf *p,*q;
  216. if (!_enabled)
  217. return;
  218. struct eth_hdr ethhdr;
  219. from.copyTo(ethhdr.src.addr, 6);
  220. to.copyTo(ethhdr.dest.addr, 6);
  221. ethhdr.type = Utils::hton((uint16_t)etherType);
  222. // We allocate a pbuf chain of pbufs from the pool.
  223. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  224. if (p != NULL) {
  225. const char *dataptr = reinterpret_cast<const char *>(data);
  226. // First pbuf gets ethernet header at start
  227. q = p;
  228. if (q->len < sizeof(ethhdr)) {
  229. dwr(MSG_ERROR,"_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  230. return;
  231. }
  232. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  233. memcpy((char*)q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  234. dataptr += q->len - sizeof(ethhdr);
  235. // Remaining pbufs (if any) get rest of data
  236. while ((q = q->next)) {
  237. memcpy(q->payload,dataptr,q->len);
  238. dataptr += q->len;
  239. }
  240. } else {
  241. dwr(MSG_ERROR,"put(): Dropped packet: no pbufs available\n");
  242. return;
  243. }
  244. {
  245. Mutex::Lock _l2(lwipstack->_lock);
  246. if(interface.input(p, &interface) != ERR_OK) {
  247. dwr(MSG_ERROR,"put(): Error while RXing packet (netif->input)\n");
  248. }
  249. }
  250. }
  251. std::string NetconEthernetTap::deviceName() const
  252. {
  253. return _dev;
  254. }
  255. void NetconEthernetTap::setFriendlyName(const char *friendlyName) {
  256. }
  257. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  258. {
  259. std::vector<MulticastGroup> newGroups;
  260. Mutex::Lock _l(_multicastGroups_m);
  261. // TODO: get multicast subscriptions from LWIP
  262. std::vector<InetAddress> allIps(ips());
  263. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  264. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  265. std::sort(newGroups.begin(),newGroups.end());
  266. std::unique(newGroups.begin(),newGroups.end());
  267. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  268. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  269. added.push_back(*m);
  270. }
  271. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  272. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  273. removed.push_back(*m);
  274. }
  275. _multicastGroups.swap(newGroups);
  276. }
  277. void NetconEthernetTap::threadMain()
  278. throw()
  279. {
  280. uint64_t prev_tcp_time = 0, prev_status_time = 0, prev_etharp_time = 0;
  281. // Main timer loop
  282. while (_run) {
  283. uint64_t now = OSUtils::now();
  284. uint64_t since_tcp = now - prev_tcp_time;
  285. uint64_t since_etharp = now - prev_etharp_time;
  286. uint64_t since_status = now - prev_status_time;
  287. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  288. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  289. uint64_t status_remaining = STATUS_TMR_INTERVAL;
  290. // Connection prunning
  291. if (since_status >= STATUS_TMR_INTERVAL) {
  292. prev_status_time = now;
  293. status_remaining = STATUS_TMR_INTERVAL - since_status;
  294. for(size_t i=0;i<_TcpConnections.size();++i) {
  295. if(!_TcpConnections[i]->sock)
  296. continue; // Skip, this is a pending connection
  297. int fd = _phy.getDescriptor(_TcpConnections[i]->sock);
  298. dwr(MSG_DEBUG," tap_thread(): tcp\\jobs = {%d, %d}\n", _TcpConnections.size(), jobmap.size());
  299. fcntl(fd, F_SETFL, O_NONBLOCK);
  300. unsigned char tmpbuf[BUF_SZ];
  301. int n = read(fd,&tmpbuf,BUF_SZ);
  302. if(_TcpConnections[i]->pcb->state == SYN_SENT) {
  303. dwr(MSG_DEBUG_EXTRA," tap_thread(): <%x> state = SYN_SENT, should finish or be removed soon\n", _TcpConnections[i]->sock);
  304. }
  305. if((n < 0 && errno != EAGAIN) || (n == 0 && errno == EAGAIN)) {
  306. dwr(MSG_DEBUG," tap_thread(): closing sock (%x)\n", _TcpConnections[i]->sock);
  307. closeConnection(_TcpConnections[i]->sock);
  308. } else if (n > 0) {
  309. dwr(MSG_DEBUG," tap_thread(): data read during connection check (%d bytes)\n", n);
  310. phyOnUnixData(_TcpConnections[i]->sock,_phy.getuptr(_TcpConnections[i]->sock),&tmpbuf,BUF_SZ);
  311. }
  312. }
  313. }
  314. // Main TCP/ETHARP timer section
  315. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  316. prev_tcp_time = now;
  317. lwipstack->tcp_tmr();
  318. // Makeshift poll
  319. for(size_t i=0;i<_TcpConnections.size();++i) {
  320. if(_TcpConnections[i]->txsz > 0){
  321. lwipstack->_lock.lock();
  322. handleWrite(_TcpConnections[i]);
  323. lwipstack->_lock.unlock();
  324. }
  325. }
  326. } else {
  327. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  328. }
  329. if (since_etharp >= ARP_TMR_INTERVAL) {
  330. prev_etharp_time = now;
  331. lwipstack->etharp_tmr();
  332. } else {
  333. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  334. }
  335. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  336. }
  337. dlclose(lwipstack->_libref);
  338. }
  339. // Unused -- no UDP or TCP from this thread/Phy<>
  340. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  341. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  342. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  343. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  344. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  345. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  346. TcpConnection *NetconEthernetTap::getConnection(PhySocket *sock)
  347. {
  348. Mutex::Lock _l(_tcpconns_m);
  349. for(size_t i=0;i<_TcpConnections.size();++i) {
  350. if(_TcpConnections[i]->sock == sock)
  351. return _TcpConnections[i];
  352. }
  353. return NULL;
  354. }
  355. TcpConnection *NetconEthernetTap::addConnection(TcpConnection *conn)
  356. {
  357. Mutex::Lock _l(_tcpconns_m);
  358. _TcpConnections.push_back(conn);
  359. return conn;
  360. }
  361. void NetconEthernetTap::removeConnection(TcpConnection *conn)
  362. {
  363. Mutex::Lock _l(_tcpconns_m);
  364. for(size_t i=0;i<_TcpConnections.size();++i) {
  365. if(_TcpConnections[i] == conn){
  366. _TcpConnections.erase(_TcpConnections.begin() + i);
  367. return;
  368. }
  369. }
  370. }
  371. void NetconEthernetTap::closeConnection(PhySocket *sock)
  372. {
  373. dwr(MSG_DEBUG,"closeConnection(%x)\n",sock);
  374. if(!sock) {
  375. dwr(MSG_DEBUG," closeConnection(): invalid PhySocket\n");
  376. return;
  377. }
  378. TcpConnection *conn = getConnection(sock);
  379. if(!conn)
  380. return;
  381. else
  382. removeConnection(conn);
  383. if(!conn->pcb)
  384. return;
  385. if(conn->pcb->state == SYN_SENT || conn->pcb->state == CLOSE_WAIT) {
  386. dwr(MSG_DEBUG," closeConnection(): invalid PCB state for this operation. ignoring.\n");
  387. return;
  388. }
  389. dwr(MSG_DEBUG," closeConnection(): PCB->state = %d\n", conn->pcb->state);
  390. if(lwipstack->_tcp_close(conn->pcb) != ERR_OK) {
  391. dwr(MSG_ERROR," closeConnection(): error while calling tcp_close()\n");
  392. }
  393. if(!sock)
  394. return;
  395. close(_phy.getDescriptor(sock));
  396. _phy.close(sock, false);
  397. }
  398. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr) {
  399. closeConnection(sock);
  400. }
  401. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {
  402. // Currently unused since phyOnUnixData() handles everything now
  403. }
  404. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {
  405. dwr(MSG_DEBUG,"\nphyOnUnixAccept(): new connection = %x\n", sockN);
  406. }
  407. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  408. {
  409. TcpConnection *conn = getConnection(sock);
  410. Mutex::Lock _l(_rx_buf_m);
  411. int len = conn->rxsz;
  412. int n = _phy.streamSend(conn->sock, conn->rxbuf, len);
  413. if(n > 0) {
  414. if(n < len) {
  415. dwr(MSG_ERROR,"\n phyOnUnixWritable(): unable to write entire \"block\" to stream\n");
  416. }
  417. if(len-n)
  418. memcpy(conn->rxbuf, conn->rxbuf+n, len-n);
  419. conn->rxsz -= n;
  420. float max = (float)DEFAULT_BUF_SZ;
  421. dwr(MSG_TRANSFER," <--- RX :: { TX: %.3f%% | RX: %.3f%% } :: %d bytes\n",
  422. (float)conn->txsz / max, (float)conn->rxsz / max, n);
  423. lwipstack->_tcp_recved(conn->pcb, n);
  424. if(conn->rxsz == 0){
  425. _phy.setNotifyWritable(conn->sock, false); // Nothing more to be notified about
  426. }
  427. } else {
  428. perror("\n");
  429. dwr(MSG_ERROR," phyOnUnixWritable(): errno = %d\n", errno);
  430. }
  431. }
  432. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  433. {
  434. uint64_t CANARY_num;
  435. pid_t pid, tid;
  436. int rpcCount, wlen = len;
  437. char cmd, timestamp[20], CANARY[CANARY_SZ], padding[] = {PADDING};
  438. void *payload;
  439. unsigned char *buf = (unsigned char*)data;
  440. std::pair<PhySocket*, void*> sockdata;
  441. PhySocket *rpcSock;
  442. bool foundJob = false, detected_rpc = false;
  443. TcpConnection *conn;
  444. // RPC
  445. char phrase[RPC_PHRASE_SZ];
  446. memset(phrase, 0, RPC_PHRASE_SZ);
  447. if(len == BUF_SZ) {
  448. memcpy(phrase, buf, RPC_PHRASE_SZ);
  449. if(strcmp(phrase, RPC_PHRASE) == 0)
  450. detected_rpc = true;
  451. }
  452. if(detected_rpc) {
  453. unloadRPC(data, pid, tid, rpcCount, timestamp, CANARY, cmd, payload);
  454. memcpy(&CANARY_num, CANARY, CANARY_SZ);
  455. dwr(MSG_DEBUG," <%x> RPC: (pid=%d, tid=%d, rpcCount=%d, timestamp=%s, cmd=%d)\n",
  456. sock, pid, tid, rpcCount, timestamp, cmd);
  457. if(cmd == RPC_SOCKET) {
  458. dwr(MSG_DEBUG," <%x> RPC_SOCKET\n", sock);
  459. // Create new lwip socket and associate it with this sock
  460. struct socket_st socket_rpc;
  461. memcpy(&socket_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct socket_st));
  462. TcpConnection * new_conn;
  463. if((new_conn = handleSocket(sock, uptr, &socket_rpc))) {
  464. new_conn->pid = pid; // Merely kept to look up application path/names later, not strictly necessary
  465. }
  466. } else {
  467. jobmap[CANARY_num] = std::make_pair<PhySocket*, void*>(sock, data);
  468. }
  469. write(_phy.getDescriptor(sock), "z", 1); // RPC ACK byte to maintain order
  470. }
  471. // STREAM
  472. else {
  473. int data_start = -1, data_end = -1, canary_pos = -1, padding_pos = -1;
  474. // Look for padding
  475. std::string padding_pattern(padding, padding+PADDING_SZ);
  476. std::string buffer(buf, buf + len);
  477. padding_pos = buffer.find(padding_pattern);
  478. canary_pos = padding_pos-CANARY_SZ;
  479. // Grab token, next we'll use it to look up an RPC job
  480. if(canary_pos > -1) {
  481. memcpy(&CANARY_num, buf+canary_pos, CANARY_SZ);
  482. if(CANARY_num != 0) {
  483. // Find job
  484. sockdata = jobmap[CANARY_num];
  485. if(!sockdata.first) {
  486. dwr(MSG_DEBUG," <%x> unable to locate job entry for %llu\n", sock, CANARY_num);
  487. return;
  488. } else
  489. foundJob = true;
  490. }
  491. }
  492. conn = getConnection(sock);
  493. if(!conn)
  494. return;
  495. if(padding_pos == -1) { // [DATA]
  496. memcpy(&conn->txbuf[conn->txsz], buf, wlen);
  497. } else { // Padding found, implies a canary is present
  498. // [CANARY]
  499. if(len == CANARY_SZ+PADDING_SZ && canary_pos == 0) {
  500. wlen = 0; // Nothing to write
  501. } else {
  502. // [CANARY] + [DATA]
  503. if(len > CANARY_SZ+PADDING_SZ && canary_pos == 0) {
  504. wlen = len - CANARY_SZ+PADDING_SZ;
  505. data_start = padding_pos+PADDING_SZ;
  506. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
  507. }
  508. // [CANARY] + [TOKEN]
  509. if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && canary_pos == len - CANARY_SZ+PADDING_SZ) {
  510. wlen = len - CANARY_SZ+PADDING_SZ;
  511. data_start = 0;
  512. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
  513. }
  514. // [CANARY] + [TOKEN] + [DATA]
  515. if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && len > (canary_pos + CANARY_SZ+PADDING_SZ)) {
  516. wlen = len - CANARY_SZ+PADDING_SZ;
  517. data_start = 0;
  518. data_end = padding_pos-CANARY_SZ;
  519. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, (data_end-data_start)+1);
  520. memcpy((&conn->txbuf)+conn->txsz, buf+(padding_pos+PADDING_SZ), len-(canary_pos+CANARY_SZ+PADDING_SZ));
  521. }
  522. }
  523. }
  524. // Write data from stream
  525. if(conn->txsz > (DEFAULT_BUF_SZ / 2)) {
  526. _phy.setNotifyReadable(sock, false);
  527. }
  528. lwipstack->_lock.lock();
  529. conn->txsz += wlen;
  530. handleWrite(conn);
  531. lwipstack->_lock.unlock();
  532. }
  533. if(foundJob) {
  534. rpcSock = sockdata.first;
  535. buf = (unsigned char*)sockdata.second;
  536. }
  537. // Process RPC if we have a corresponding jobmap entry
  538. if(foundJob) {
  539. unloadRPC(buf, pid, tid, rpcCount, timestamp, CANARY, cmd, payload);
  540. dwr(MSG_DEBUG," <%x> RPC: (pid=%d, tid=%d, rpcCount=%d, timestamp=%s, cmd=%d)\n",
  541. sock, pid, tid, rpcCount, timestamp, cmd);
  542. switch(cmd) {
  543. case RPC_BIND:
  544. dwr(MSG_DEBUG," <%x> RPC_BIND\n", sock);
  545. struct bind_st bind_rpc;
  546. memcpy(&bind_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct bind_st));
  547. handleBind(sock, rpcSock, uptr, &bind_rpc);
  548. break;
  549. case RPC_LISTEN:
  550. dwr(MSG_DEBUG," <%x> RPC_LISTEN\n", sock);
  551. struct listen_st listen_rpc;
  552. memcpy(&listen_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct listen_st));
  553. handleListen(sock, rpcSock, uptr, &listen_rpc);
  554. break;
  555. case RPC_GETSOCKNAME:
  556. dwr(MSG_DEBUG," <%x> RPC_GETSOCKNAME\n", sock);
  557. struct getsockname_st getsockname_rpc;
  558. memcpy(&getsockname_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct getsockname_st));
  559. handleGetsockname(sock, rpcSock, uptr, &getsockname_rpc);
  560. break;
  561. case RPC_CONNECT:
  562. dwr(MSG_DEBUG," <%x> RPC_CONNECT\n", sock);
  563. struct connect_st connect_rpc;
  564. memcpy(&connect_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct connect_st));
  565. handleConnect(sock, rpcSock, conn, &connect_rpc);
  566. jobmap.erase(CANARY_num);
  567. return; // Keep open RPC, we'll use it once in nc_connected to send retval
  568. default:
  569. break;
  570. }
  571. closeConnection(sockdata.first); // close RPC after sending retval, no longer needed
  572. jobmap.erase(CANARY_num);
  573. return;
  574. }
  575. }
  576. int NetconEthernetTap::sendReturnValue(PhySocket *sock, int retval, int _errno = 0){
  577. return sendReturnValue(_phy.getDescriptor(sock), retval, _errno);
  578. }
  579. int NetconEthernetTap::sendReturnValue(int fd, int retval, int _errno = 0)
  580. {
  581. dwr(MSG_DEBUG," sendReturnValue(): fd = %d, retval = %d, errno = %d\n", fd, retval, _errno);
  582. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  583. char retmsg[sz];
  584. memset(&retmsg, 0, sizeof(retmsg));
  585. retmsg[0]=RPC_RETVAL;
  586. memcpy(&retmsg[1], &retval, sizeof(retval));
  587. memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
  588. return write(fd, &retmsg, sz);
  589. }
  590. void NetconEthernetTap::unloadRPC(void *data, pid_t &pid, pid_t &tid,
  591. int &rpcCount, char (timestamp[RPC_TIMESTAMP_SZ]), char (CANARY[sizeof(uint64_t)]), char &cmd, void* &payload)
  592. {
  593. unsigned char *buf = (unsigned char*)data;
  594. memcpy(&pid, &buf[IDX_PID], sizeof(pid_t));
  595. memcpy(&tid, &buf[IDX_TID], sizeof(pid_t));
  596. memcpy(&rpcCount, &buf[IDX_COUNT], sizeof(int));
  597. memcpy(timestamp, &buf[IDX_TIME], RPC_TIMESTAMP_SZ);
  598. memcpy(&cmd, &buf[IDX_PAYLOAD], sizeof(char));
  599. memcpy(CANARY, &buf[IDX_PAYLOAD+1], CANARY_SZ);
  600. }
  601. /*------------------------------------------------------------------------------
  602. --------------------------------- LWIP callbacks -------------------------------
  603. ------------------------------------------------------------------------------*/
  604. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newPCB, err_t err)
  605. {
  606. Larg *l = (Larg*)arg;
  607. TcpConnection *conn = l->conn;
  608. NetconEthernetTap *tap = l->tap;
  609. if(!conn->sock)
  610. return -1;
  611. int fd = tap->_phy.getDescriptor(conn->sock);
  612. if(conn) {
  613. // create new socketpair
  614. ZT_PHY_SOCKFD_TYPE fds[2];
  615. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  616. if(errno < 0) {
  617. l->tap->sendReturnValue(conn, -1, errno);
  618. dwr(MSG_ERROR," nc_accept(): unable to create socketpair\n");
  619. return ERR_MEM;
  620. }
  621. }
  622. // create and populate new TcpConnection
  623. TcpConnection *newTcpConn = new TcpConnection();
  624. tap->addConnection(newTcpConn);
  625. newTcpConn->pcb = newPCB;
  626. newTcpConn->sock = tap->_phy.wrapSocket(fds[0], newTcpConn);
  627. if(sock_fd_write(fd, fds[1]) < 0)
  628. return -1;
  629. else {
  630. //close(fds[1]); // close other end of socketpair
  631. }
  632. tap->lwipstack->_tcp_arg(newPCB, new Larg(tap, newTcpConn));
  633. tap->lwipstack->_tcp_recv(newPCB, nc_recved);
  634. tap->lwipstack->_tcp_err(newPCB, nc_err);
  635. tap->lwipstack->_tcp_sent(newPCB, nc_sent);
  636. tap->lwipstack->_tcp_poll(newPCB, nc_poll, 1);
  637. if(conn->pcb->state == LISTEN) {
  638. dwr(MSG_DEBUG," nc_accept(): can't call tcp_accept() on LISTEN socket (pcb = %x)\n", conn->pcb);
  639. return ERR_OK;
  640. }
  641. tcp_accepted(conn->pcb); // Let lwIP know that it can queue additional incoming connections
  642. return ERR_OK;
  643. } else
  644. dwr(MSG_ERROR," nc_accept(): can't locate Connection object for PCB.\n");
  645. return -1;
  646. }
  647. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *PCB, struct pbuf *p, err_t err)
  648. {
  649. Larg *l = (Larg*)arg;
  650. int tot = 0;
  651. struct pbuf* q = p;
  652. if(!l->conn) {
  653. dwr(MSG_ERROR," nc_recved(): no connection\n");
  654. return ERR_OK;
  655. }
  656. if(p == NULL) {
  657. if(l->conn && !l->conn->listening) {
  658. dwr(MSG_INFO," nc_recved(): closing connection\n");
  659. if(l->tap->lwipstack->_tcp_close(l->conn->pcb) != ERR_OK)
  660. dwr(MSG_ERROR," nc_recved(): error while calling tcp_close()\n");
  661. l->tap->closeConnection(l->conn->sock);
  662. return ERR_ABRT;
  663. }
  664. return err;
  665. }
  666. Mutex::Lock _l(l->tap->_rx_buf_m);
  667. // Cycle through pbufs and write them to the RX buffer
  668. // The RX buffer will be emptied via phyOnUnixWritable()
  669. while(p != NULL) {
  670. if(p->len <= 0)
  671. break;
  672. int avail = DEFAULT_BUF_SZ - l->conn->rxsz;
  673. int len = p->len;
  674. if(avail < len)
  675. dwr(MSG_ERROR," nc_recved(): not enough room (%d bytes) on RX buffer\n", avail);
  676. memcpy(l->conn->rxbuf + (l->conn->rxsz), p->payload, len);
  677. l->conn->rxsz += len;
  678. p = p->next;
  679. tot += len;
  680. }
  681. if(tot)
  682. l->tap->_phy.setNotifyWritable(l->conn->sock, true);
  683. l->tap->lwipstack->_pbuf_free(q);
  684. return ERR_OK;
  685. }
  686. void NetconEthernetTap::nc_err(void *arg, err_t err)
  687. {
  688. dwr(MSG_DEBUG,"nc_err() = %d\n", err);
  689. Larg *l = (Larg*)arg;
  690. if(!l->conn)
  691. dwr(MSG_ERROR,"nc_err(): connection is NULL!\n");
  692. int fd = l->tap->_phy.getDescriptor(l->conn->sock);
  693. switch(err)
  694. {
  695. case ERR_MEM:
  696. dwr(MSG_ERROR,"nc_err(): ERR_MEM->ENOMEM\n");
  697. l->tap->sendReturnValue(fd, -1, ENOMEM);
  698. break;
  699. case ERR_BUF:
  700. dwr(MSG_ERROR,"nc_err(): ERR_BUF->ENOBUFS\n");
  701. l->tap->sendReturnValue(fd, -1, ENOBUFS);
  702. break;
  703. case ERR_TIMEOUT:
  704. dwr(MSG_ERROR,"nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  705. l->tap->sendReturnValue(fd, -1, ETIMEDOUT);
  706. break;
  707. case ERR_RTE:
  708. dwr(MSG_ERROR,"nc_err(): ERR_RTE->ENETUNREACH\n");
  709. l->tap->sendReturnValue(fd, -1, ENETUNREACH);
  710. break;
  711. case ERR_INPROGRESS:
  712. dwr(MSG_ERROR,"nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  713. l->tap->sendReturnValue(fd, -1, EINPROGRESS);
  714. break;
  715. case ERR_VAL:
  716. dwr(MSG_ERROR,"nc_err(): ERR_VAL->EINVAL\n");
  717. l->tap->sendReturnValue(fd, -1, EINVAL);
  718. break;
  719. case ERR_WOULDBLOCK:
  720. dwr(MSG_ERROR,"nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  721. l->tap->sendReturnValue(fd, -1, EWOULDBLOCK);
  722. break;
  723. case ERR_USE:
  724. dwr(MSG_ERROR,"nc_err(): ERR_USE->EADDRINUSE\n");
  725. l->tap->sendReturnValue(fd, -1, EADDRINUSE);
  726. break;
  727. case ERR_ISCONN:
  728. dwr(MSG_ERROR,"nc_err(): ERR_ISCONN->EISCONN\n");
  729. l->tap->sendReturnValue(fd, -1, EISCONN);
  730. break;
  731. case ERR_ABRT:
  732. dwr(MSG_ERROR,"nc_err(): ERR_ABRT->ECONNREFUSED\n");
  733. l->tap->sendReturnValue(fd, -1, ECONNREFUSED);
  734. break;
  735. // FIXME: Below are errors which don't have a standard errno correlate
  736. case ERR_RST:
  737. l->tap->sendReturnValue(fd, -1, -1);
  738. break;
  739. case ERR_CLSD:
  740. l->tap->sendReturnValue(fd, -1, -1);
  741. break;
  742. case ERR_CONN:
  743. l->tap->sendReturnValue(fd, -1, -1);
  744. break;
  745. case ERR_ARG:
  746. l->tap->sendReturnValue(fd, -1, -1);
  747. break;
  748. case ERR_IF:
  749. l->tap->sendReturnValue(fd, -1, -1);
  750. break;
  751. default:
  752. break;
  753. }
  754. dwr(MSG_ERROR,"nc_err(): closing connection\n");
  755. l->tap->closeConnection(l->conn);
  756. }
  757. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *PCB)
  758. {
  759. return ERR_OK;
  760. }
  761. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *PCB, u16_t len)
  762. {
  763. Larg *l = (Larg*)arg;
  764. if(len) {
  765. float max = (float)DEFAULT_BUF_SZ;
  766. if(l->conn->txsz < max / 2) {
  767. l->tap->_phy.setNotifyReadable(l->conn->sock, true);
  768. l->tap->_phy.whack();
  769. }
  770. }
  771. return ERR_OK;
  772. }
  773. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *PCB, err_t err)
  774. {
  775. Larg *l = (Larg*)arg;
  776. l->tap->sendReturnValue(l->tap->_phy.getDescriptor(l->conn->rpcSock), ERR_OK);
  777. return ERR_OK;
  778. }
  779. /*------------------------------------------------------------------------------
  780. ----------------------------- RPC Handler functions ----------------------------
  781. ------------------------------------------------------------------------------*/
  782. void NetconEthernetTap::handleGetsockname(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct getsockname_st *getsockname_rpc)
  783. {
  784. TcpConnection *conn = getConnection(sock);
  785. char retmsg[sizeof(struct sockaddr_storage)];
  786. memset(&retmsg, 0, sizeof(retmsg));
  787. if ((conn)&&(conn->addr))
  788. memcpy(&retmsg, conn->addr, sizeof(struct sockaddr_storage));
  789. write(_phy.getDescriptor(rpcSock), &retmsg, sizeof(struct sockaddr_storage));
  790. }
  791. void NetconEthernetTap::handleBind(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct bind_st *bind_rpc)
  792. {
  793. struct sockaddr_in *rawAddr = (struct sockaddr_in *) &bind_rpc->addr;
  794. int port = lwipstack->ntohs(rawAddr->sin_port);
  795. ip_addr_t connAddr;
  796. connAddr.addr = *((u32_t *)_ips[0].rawIpData());
  797. TcpConnection *conn = getConnection(sock);
  798. dwr(MSG_DEBUG," handleBind(%d)\n", bind_rpc->sockfd);
  799. if(conn) {
  800. if(conn->pcb->state == CLOSED){
  801. int err = lwipstack->tcp_bind(conn->pcb, &connAddr, port);
  802. int ip = rawAddr->sin_addr.s_addr;
  803. unsigned char d[4];
  804. d[0] = ip & 0xFF;
  805. d[1] = (ip >> 8) & 0xFF;
  806. d[2] = (ip >> 16) & 0xFF;
  807. d[3] = (ip >> 24) & 0xFF;
  808. dwr(MSG_DEBUG," handleBind(): %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], port);
  809. if(err != ERR_OK) {
  810. dwr(MSG_ERROR," handleBind(): err = %d\n", err);
  811. if(err == ERR_USE)
  812. sendReturnValue(rpcSock, -1, EADDRINUSE);
  813. if(err == ERR_MEM)
  814. sendReturnValue(rpcSock, -1, ENOMEM);
  815. if(err == ERR_BUF)
  816. sendReturnValue(rpcSock, -1, ENOMEM);
  817. } else {
  818. conn->addr = (struct sockaddr_storage *) &bind_rpc->addr;
  819. sendReturnValue(rpcSock, ERR_OK, ERR_OK); // Success
  820. }
  821. } else {
  822. dwr(MSG_ERROR," handleBind(): PCB (%x) not in CLOSED state. Ignoring BIND request.\n", conn->pcb);
  823. sendReturnValue(rpcSock, -1, EINVAL);
  824. }
  825. } else {
  826. dwr(MSG_ERROR," handleBind(): unable to locate TcpConnection.\n");
  827. sendReturnValue(rpcSock, -1, EBADF);
  828. }
  829. }
  830. void NetconEthernetTap::handleListen(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct listen_st *listen_rpc)
  831. {
  832. TcpConnection *conn = getConnection(sock);
  833. if(!conn){
  834. dwr(MSG_ERROR," handleListen(): unable to locate TcpConnection.\n");
  835. sendReturnValue(rpcSock, -1, EBADF);
  836. return;
  837. }
  838. if(conn->pcb->state == LISTEN) {
  839. dwr(MSG_ERROR," handleListen(): PCB is already in listening state.\n");
  840. sendReturnValue(rpcSock, ERR_OK, ERR_OK);
  841. return;
  842. }
  843. struct tcp_pcb* listeningPCB;
  844. #ifdef TCP_LISTEN_BACKLOG
  845. listeningPCB = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  846. #else
  847. listeningPCB = lwipstack->tcp_listen(conn->pcb);
  848. #endif
  849. if(listeningPCB != NULL) {
  850. conn->pcb = listeningPCB;
  851. lwipstack->tcp_accept(listeningPCB, nc_accept);
  852. lwipstack->tcp_arg(listeningPCB, new Larg(this, conn));
  853. /* we need to wait for the client to send us the fd allocated on their end
  854. for this listening socket */
  855. fcntl(_phy.getDescriptor(conn->sock), F_SETFL, O_NONBLOCK);
  856. conn->listening = true;
  857. sendReturnValue(rpcSock, ERR_OK, ERR_OK);
  858. return;
  859. }
  860. sendReturnValue(rpcSock, -1, -1);
  861. }
  862. TcpConnection * NetconEthernetTap::handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  863. {
  864. struct tcp_pcb *newPCB = lwipstack->tcp_new();
  865. if(newPCB != NULL) {
  866. TcpConnection *newConn = new TcpConnection();
  867. *uptr = newConn;
  868. newConn->sock = sock;
  869. newConn->pcb = newPCB;
  870. return addConnection(newConn);;
  871. }
  872. dwr(MSG_ERROR," handleSocket(): Memory not available for new PCB\n");
  873. sendReturnValue(_phy.getDescriptor(sock), -1, ENOMEM);
  874. return NULL;
  875. }
  876. void NetconEthernetTap::handleConnect(PhySocket *sock, PhySocket *rpcSock, TcpConnection *conn, struct connect_st* connect_rpc)
  877. {
  878. struct sockaddr_in *rawAddr = (struct sockaddr_in *) &connect_rpc->__addr;
  879. int port = lwipstack->ntohs(rawAddr->sin_port);
  880. ip_addr_t connAddr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  881. if(conn != NULL) {
  882. lwipstack->tcp_sent(conn->pcb, nc_sent);
  883. lwipstack->tcp_recv(conn->pcb, nc_recved);
  884. lwipstack->tcp_err(conn->pcb, nc_err);
  885. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  886. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  887. int err = 0, ip = rawAddr->sin_addr.s_addr;
  888. unsigned char d[4];
  889. d[0] = ip & 0xFF;
  890. d[1] = (ip >> 8) & 0xFF;
  891. d[2] = (ip >> 16) & 0xFF;
  892. d[3] = (ip >> 24) & 0xFF;
  893. dwr(MSG_DEBUG," handleConnect(): %d.%d.%d.%d: %d\n", d[0],d[1],d[2],d[3], port);
  894. dwr(MSG_DEBUG," handleConnect(): pcb->state = %x\n", conn->pcb->state);
  895. if(conn->pcb->state != CLOSED) {
  896. dwr(MSG_DEBUG," handleConnect(): PCB != CLOSED, cannot connect using this PCB\n");
  897. sendReturnValue(rpcSock, -1, EAGAIN);
  898. return;
  899. }
  900. if((err = lwipstack->tcp_connect(conn->pcb,&connAddr,port,nc_connected)) < 0)
  901. {
  902. if(err == ERR_ISCONN) {
  903. sendReturnValue(rpcSock, -1, EISCONN); // Already in connected state
  904. return;
  905. } if(err == ERR_USE) {
  906. sendReturnValue(rpcSock, -1, EADDRINUSE); // Already in use
  907. return;
  908. } if(err == ERR_VAL) {
  909. sendReturnValue(rpcSock, -1, EINVAL); // Invalid ipaddress parameter
  910. return;
  911. } if(err == ERR_RTE) {
  912. sendReturnValue(rpcSock, -1, ENETUNREACH); // No route to host
  913. return;
  914. } if(err == ERR_BUF) {
  915. sendReturnValue(rpcSock, -1, EAGAIN); // No more ports available
  916. return;
  917. }
  918. if(err == ERR_MEM) {
  919. /* Can occur for the following reasons: tcp_enqueue_flags()
  920. 1) tcp_enqueue_flags is always called with either SYN or FIN in flags.
  921. We need one available snd_buf byte to do that.
  922. This means we can't send FIN while snd_buf==0. A better fix would be to
  923. not include SYN and FIN sequence numbers in the snd_buf count.
  924. 2) Cannot allocate new pbuf
  925. 3) Cannot allocate new TCP segment
  926. */
  927. sendReturnValue(rpcSock, -1, EAGAIN); // FIXME: Doesn't describe the problem well, but closest match
  928. return;
  929. }
  930. // We should only return a value if failure happens immediately
  931. // Otherwise, we still need to wait for a callback from lwIP.
  932. // - This is because an ERR_OK from tcp_connect() only verifies
  933. // that the SYN packet was enqueued onto the stack properly,
  934. // that's it!
  935. // - Most instances of a retval for a connect() should happen
  936. // in the nc_connect() and nc_err() callbacks!
  937. dwr(MSG_ERROR," handleConnect(): unable to connect\n");
  938. sendReturnValue(rpcSock, -1, EAGAIN);
  939. }
  940. // Everything seems to be ok, but we don't have enough info to retval
  941. conn->listening=true;
  942. conn->rpcSock=rpcSock; // used for return value from lwip CB
  943. } else {
  944. dwr(MSG_ERROR," handleConnect(): could not locate PCB based on their fd\n");
  945. sendReturnValue(rpcSock, -1, EBADF);
  946. }
  947. }
  948. void NetconEthernetTap::handleWrite(TcpConnection *conn)
  949. {
  950. if(!conn || !conn->pcb) {
  951. dwr(MSG_ERROR," handleWrite(): invalid connection/PCB\n");
  952. return;
  953. }
  954. // How much we are currently allowed to write to the connection
  955. int err, sz, r, sndbuf = conn->pcb->snd_buf;
  956. if(!sndbuf) {
  957. /* PCB send buffer is full, turn off readability notifications for the
  958. corresponding PhySocket until nc_sent() is called and confirms that there is
  959. now space on the buffer */
  960. dwr(MSG_DEBUG," handleWrite(): sndbuf == 0, LWIP stack is full\n");
  961. _phy.setNotifyReadable(conn->sock, false);
  962. return;
  963. }
  964. if(conn->txsz <= 0)
  965. return; // Nothing to write
  966. if(!conn->listening)
  967. lwipstack->_tcp_output(conn->pcb);
  968. if(conn->sock) {
  969. r = conn->txsz < sndbuf ? conn->txsz : sndbuf;
  970. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  971. * data to LWIP to be enqueued and eventually sent to the network. */
  972. if(r > 0) {
  973. err = lwipstack->_tcp_write(conn->pcb, &conn->txbuf, r, TCP_WRITE_FLAG_COPY);
  974. lwipstack->_tcp_output(conn->pcb);
  975. if(err != ERR_OK) {
  976. dwr(MSG_ERROR," handleWrite(): error while writing to PCB, (err = %d)\n", err);
  977. if(err == -1)
  978. dwr(MSG_DEBUG," handleWrite(): out of memory\n");
  979. return;
  980. } else {
  981. sz = (conn->txsz)-r;
  982. if(sz)
  983. memmove(&conn->txbuf, (conn->txbuf+r), sz);
  984. conn->txsz -= r;
  985. float max = (float)DEFAULT_BUF_SZ;
  986. dwr(MSG_TRANSFER," TX ---> :: { TX: %.3f%% | RX: %.3f%% } :: %d bytes\n",
  987. (float)conn->txsz / max, (float)conn->rxsz / max, r);
  988. return;
  989. }
  990. }
  991. }
  992. }
  993. } // namespace ZeroTier