NetconEthernetTap.cpp 34 KB

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