NetconEthernetTap.cpp 33 KB

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