NetconEthernetTap.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. // Connection prunning
  262. if (since_status >= STATUS_TMR_INTERVAL) {
  263. prev_status_time = now;
  264. for(size_t i=0;i<_TcpConnections.size();++i) {
  265. if(!_TcpConnections[i]->sock)
  266. continue;
  267. int fd = _phy.getDescriptor(_TcpConnections[i]->sock);
  268. dwr(MSG_DEBUG," tap_thread(): tcp\\jobs = {%d, %d}\n", _TcpConnections.size(), jobmap.size());
  269. fcntl(fd, F_SETFL, O_NONBLOCK);
  270. unsigned char tmpbuf[BUF_SZ];
  271. int n = read(fd,&tmpbuf,BUF_SZ);
  272. if(_TcpConnections[i]->pcb->state == SYN_SENT) {
  273. dwr(MSG_DEBUG_EXTRA," tap_thread(): <%x> state = SYN_SENT, should finish or be removed soon\n", _TcpConnections[i]->sock);
  274. }
  275. if((n < 0 && errno != EAGAIN) || (n == 0 && errno == EAGAIN)) {
  276. dwr(MSG_DEBUG," tap_thread(): closing sock (%x)\n", _TcpConnections[i]->sock);
  277. closeConnection(_TcpConnections[i]->sock);
  278. } else if (n > 0) {
  279. dwr(MSG_DEBUG," tap_thread(): data read during connection check (%d bytes)\n", n);
  280. phyOnUnixData(_TcpConnections[i]->sock,_phy.getuptr(_TcpConnections[i]->sock),&tmpbuf,n);
  281. }
  282. }
  283. }
  284. // Main TCP/ETHARP timer section
  285. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  286. prev_tcp_time = now;
  287. lwipstack->tcp_tmr();
  288. // Makeshift poll
  289. for(size_t i=0;i<_TcpConnections.size();++i) {
  290. if(_TcpConnections[i]->txsz > 0){
  291. lwipstack->_lock.lock();
  292. handleWrite(_TcpConnections[i]);
  293. lwipstack->_lock.unlock();
  294. }
  295. }
  296. } else {
  297. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  298. }
  299. if (since_etharp >= ARP_TMR_INTERVAL) {
  300. prev_etharp_time = now;
  301. lwipstack->etharp_tmr();
  302. } else {
  303. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  304. }
  305. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  306. }
  307. dlclose(lwipstack->_libref);
  308. }
  309. // Unused -- no UDP or TCP from this thread/Phy<>
  310. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  311. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  312. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  313. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  314. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  315. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  316. TcpConnection *NetconEthernetTap::getConnection(PhySocket *sock)
  317. {
  318. for(size_t i=0;i<_TcpConnections.size();++i) {
  319. if(_TcpConnections[i]->sock == sock)
  320. return _TcpConnections[i];
  321. }
  322. return NULL;
  323. }
  324. void NetconEthernetTap::closeConnection(PhySocket *sock)
  325. {
  326. // Here we assume _tcpconns_m is already locked by caller
  327. if(!sock) {
  328. dwr(MSG_DEBUG," closeConnection(): invalid PhySocket\n");
  329. return;
  330. }
  331. TcpConnection *conn = getConnection(sock);
  332. if(!conn)
  333. return;
  334. if(conn->pcb && conn->pcb->state != CLOSED) {
  335. dwr(MSG_DEBUG," closeConnection(%x): PCB->state = %d\n", sock, conn->pcb->state);
  336. if(conn->pcb->state == SYN_SENT) {
  337. dwr(MSG_DEBUG," closeConnection(%x): invalid PCB state for this operation. ignoring.\n", sock);
  338. return;
  339. }
  340. if(lwipstack->_tcp_close(conn->pcb) == ERR_OK) {
  341. // Unregister callbacks for this PCB
  342. lwipstack->_tcp_arg(conn->pcb, NULL);
  343. lwipstack->_tcp_recv(conn->pcb, NULL);
  344. lwipstack->_tcp_err(conn->pcb, NULL);
  345. lwipstack->_tcp_sent(conn->pcb, NULL);
  346. lwipstack->_tcp_poll(conn->pcb, NULL, 1);
  347. }
  348. else {
  349. dwr(MSG_ERROR," closeConnection(%x): error while calling tcp_close()\n", sock);
  350. }
  351. }
  352. for(size_t i=0;i<_TcpConnections.size();++i) {
  353. if(_TcpConnections[i] == conn){
  354. _TcpConnections.erase(_TcpConnections.begin() + i);
  355. delete conn;
  356. break;
  357. }
  358. }
  359. if(!sock)
  360. return;
  361. close(_phy.getDescriptor(sock));
  362. _phy.close(sock, false);
  363. }
  364. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr) {
  365. Mutex::Lock _l(_tcpconns_m);
  366. closeConnection(sock);
  367. }
  368. void NetconEthernetTap::phyOnUnixWritable(PhySocket *sock,void **uptr)
  369. {
  370. Mutex::Lock _l(_tcpconns_m);
  371. Mutex::Lock _l2(_rx_buf_m);
  372. TcpConnection *conn = getConnection(sock);
  373. int len = conn->rxsz;
  374. int n = _phy.streamSend(conn->sock, conn->rxbuf, len);
  375. if(n > 0) {
  376. if(n < len) {
  377. dwr(MSG_ERROR,"\n phyOnUnixWritable(): unable to write entire \"block\" to stream\n");
  378. }
  379. if(len-n)
  380. memcpy(conn->rxbuf, conn->rxbuf+n, len-n);
  381. conn->rxsz -= n;
  382. float max = (float)DEFAULT_BUF_SZ;
  383. dwr(MSG_TRANSFER," <--- RX :: {TX: %.3f%%, RX: %.3f%%, sock=%x} :: %d bytes\n",
  384. (float)conn->txsz / max, (float)conn->rxsz / max, sock, n);
  385. lwipstack->_tcp_recved(conn->pcb, n);
  386. if(conn->rxsz == 0){
  387. _phy.setNotifyWritable(conn->sock, false); // Nothing more to be notified about
  388. }
  389. } else {
  390. perror("\n");
  391. dwr(MSG_ERROR," phyOnUnixWritable(): errno = %d\n", errno);
  392. }
  393. }
  394. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  395. {
  396. uint64_t CANARY_num;
  397. pid_t pid, tid;
  398. int rpcCount, wlen = len;
  399. char cmd, timestamp[20], CANARY[CANARY_SZ], padding[] = {PADDING};
  400. void *payload;
  401. unsigned char *buf = (unsigned char*)data;
  402. std::pair<PhySocket*, void*> sockdata;
  403. PhySocket *rpcSock;
  404. bool foundJob = false, detected_rpc = false;
  405. TcpConnection *conn;
  406. // RPC
  407. char phrase[RPC_PHRASE_SZ];
  408. memset(phrase, 0, RPC_PHRASE_SZ);
  409. if(len == BUF_SZ) {
  410. memcpy(phrase, buf, RPC_PHRASE_SZ);
  411. if(strcmp(phrase, RPC_PHRASE) == 0)
  412. detected_rpc = true;
  413. }
  414. if(detected_rpc) {
  415. unloadRPC(data, pid, tid, rpcCount, timestamp, CANARY, cmd, payload);
  416. memcpy(&CANARY_num, CANARY, CANARY_SZ);
  417. dwr(MSG_DEBUG," <%x> RPC: (pid=%d, tid=%d, rpcCount=%d, timestamp=%s, cmd=%d)\n",
  418. sock, pid, tid, rpcCount, timestamp, cmd);
  419. if(cmd == RPC_SOCKET) {
  420. dwr(MSG_DEBUG," <%x> RPC_SOCKET\n", sock);
  421. // Create new lwip socket and associate it with this sock
  422. struct socket_st socket_rpc;
  423. memcpy(&socket_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct socket_st));
  424. TcpConnection * new_conn;
  425. if((new_conn = handleSocket(sock, uptr, &socket_rpc))) {
  426. new_conn->pid = pid; // Merely kept to look up application path/names later, not strictly necessary
  427. }
  428. } else {
  429. jobmap[CANARY_num] = std::make_pair<PhySocket*, void*>(sock, data);
  430. }
  431. write(_phy.getDescriptor(sock), "z", 1); // RPC ACK byte to maintain order
  432. }
  433. // STREAM
  434. else {
  435. int data_start = -1, data_end = -1, canary_pos = -1, padding_pos = -1;
  436. // Look for padding
  437. std::string padding_pattern(padding, padding+PADDING_SZ);
  438. std::string buffer(buf, buf + len);
  439. padding_pos = buffer.find(padding_pattern);
  440. canary_pos = padding_pos-CANARY_SZ;
  441. // Grab token, next we'll use it to look up an RPC job
  442. if(canary_pos > -1) {
  443. memcpy(&CANARY_num, buf+canary_pos, CANARY_SZ);
  444. if(CANARY_num != 0) {
  445. // Find job
  446. sockdata = jobmap[CANARY_num];
  447. if(!sockdata.first) {
  448. dwr(MSG_DEBUG," <%x> unable to locate job entry for %llu\n", sock, CANARY_num);
  449. return;
  450. } else
  451. foundJob = true;
  452. }
  453. }
  454. conn = getConnection(sock);
  455. if(!conn)
  456. return;
  457. if(padding_pos == -1) { // [DATA]
  458. memcpy(&conn->txbuf[conn->txsz], buf, wlen);
  459. } else { // Padding found, implies a canary is present
  460. // [CANARY]
  461. if(len == CANARY_SZ+PADDING_SZ && canary_pos == 0) {
  462. wlen = 0; // Nothing to write
  463. } else {
  464. // [CANARY] + [DATA]
  465. if(len > CANARY_SZ+PADDING_SZ && canary_pos == 0) {
  466. wlen = len - CANARY_SZ+PADDING_SZ;
  467. data_start = padding_pos+PADDING_SZ;
  468. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
  469. }
  470. // [DATA] + [CANARY]
  471. if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && canary_pos == len - CANARY_SZ+PADDING_SZ) {
  472. wlen = len - CANARY_SZ+PADDING_SZ;
  473. data_start = 0;
  474. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, wlen);
  475. }
  476. // [DATA] + [CANARY] + [DATA]
  477. if(len > CANARY_SZ+PADDING_SZ && canary_pos > 0 && len > (canary_pos + CANARY_SZ+PADDING_SZ)) {
  478. wlen = len - CANARY_SZ+PADDING_SZ;
  479. data_start = 0;
  480. data_end = padding_pos-CANARY_SZ;
  481. memcpy((&conn->txbuf)+conn->txsz, buf+data_start, (data_end-data_start)+1);
  482. memcpy((&conn->txbuf)+conn->txsz, buf+(padding_pos+PADDING_SZ), len-(canary_pos+CANARY_SZ+PADDING_SZ));
  483. }
  484. }
  485. }
  486. // Write data from stream
  487. if(conn->txsz > (DEFAULT_BUF_SZ / 2)) {
  488. _phy.setNotifyReadable(sock, false);
  489. }
  490. lwipstack->_lock.lock();
  491. conn->txsz += wlen;
  492. handleWrite(conn);
  493. lwipstack->_lock.unlock();
  494. }
  495. if(foundJob) {
  496. rpcSock = sockdata.first;
  497. buf = (unsigned char*)sockdata.second;
  498. }
  499. // Process RPC if we have a corresponding jobmap entry
  500. if(foundJob) {
  501. unloadRPC(buf, pid, tid, rpcCount, timestamp, CANARY, cmd, payload);
  502. dwr(MSG_DEBUG," <%x> RPC: (pid=%d, tid=%d, rpcCount=%d, timestamp=%s, cmd=%d)\n",
  503. sock, pid, tid, rpcCount, timestamp, cmd);
  504. switch(cmd) {
  505. case RPC_BIND:
  506. struct bind_st bind_rpc;
  507. memcpy(&bind_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct bind_st));
  508. handleBind(sock, rpcSock, uptr, &bind_rpc);
  509. break;
  510. case RPC_LISTEN:
  511. struct listen_st listen_rpc;
  512. memcpy(&listen_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct listen_st));
  513. handleListen(sock, rpcSock, uptr, &listen_rpc);
  514. break;
  515. case RPC_GETSOCKNAME:
  516. struct getsockname_st getsockname_rpc;
  517. memcpy(&getsockname_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct getsockname_st));
  518. handleGetsockname(sock, rpcSock, uptr, &getsockname_rpc);
  519. break;
  520. case RPC_CONNECT:
  521. struct connect_st connect_rpc;
  522. memcpy(&connect_rpc, &buf[IDX_PAYLOAD+STRUCT_IDX], sizeof(struct connect_st));
  523. handleConnect(sock, rpcSock, conn, &connect_rpc);
  524. jobmap.erase(CANARY_num);
  525. return; // Keep open RPC, we'll use it once in nc_connected to send retval
  526. default:
  527. break;
  528. }
  529. Mutex::Lock _l(_tcpconns_m);
  530. closeConnection(sockdata.first); // close RPC after sending retval, no longer needed
  531. jobmap.erase(CANARY_num);
  532. return;
  533. }
  534. }
  535. int NetconEthernetTap::sendReturnValue(PhySocket *sock, int retval, int _errno = 0){
  536. return sendReturnValue(_phy.getDescriptor(sock), retval, _errno);
  537. }
  538. int NetconEthernetTap::sendReturnValue(int fd, int retval, int _errno = 0)
  539. {
  540. dwr(MSG_DEBUG," sendReturnValue(): fd = %d, retval = %d, errno = %d\n", fd, retval, _errno);
  541. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  542. char retmsg[sz];
  543. memset(&retmsg, 0, sizeof(retmsg));
  544. retmsg[0]=RPC_RETVAL;
  545. memcpy(&retmsg[1], &retval, sizeof(retval));
  546. memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
  547. return write(fd, &retmsg, sz);
  548. }
  549. void NetconEthernetTap::unloadRPC(void *data, pid_t &pid, pid_t &tid,
  550. int &rpcCount, char (timestamp[RPC_TIMESTAMP_SZ]), char (CANARY[sizeof(uint64_t)]), char &cmd, void* &payload)
  551. {
  552. unsigned char *buf = (unsigned char*)data;
  553. memcpy(&pid, &buf[IDX_PID], sizeof(pid_t));
  554. memcpy(&tid, &buf[IDX_TID], sizeof(pid_t));
  555. memcpy(&rpcCount, &buf[IDX_COUNT], sizeof(int));
  556. memcpy(timestamp, &buf[IDX_TIME], RPC_TIMESTAMP_SZ);
  557. memcpy(&cmd, &buf[IDX_PAYLOAD], sizeof(char));
  558. memcpy(CANARY, &buf[IDX_PAYLOAD+1], CANARY_SZ);
  559. }
  560. /*------------------------------------------------------------------------------
  561. --------------------------------- LWIP callbacks -------------------------------
  562. ------------------------------------------------------------------------------*/
  563. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newPCB, err_t err)
  564. {
  565. Larg *l = (Larg*)arg;
  566. Mutex::Lock _l(l->tap->_tcpconns_m);
  567. TcpConnection *conn = l->conn;
  568. NetconEthernetTap *tap = l->tap;
  569. if(!conn->sock)
  570. return -1;
  571. int fd = tap->_phy.getDescriptor(conn->sock);
  572. if(conn) {
  573. // create new socketpair
  574. ZT_PHY_SOCKFD_TYPE fds[2];
  575. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  576. if(errno < 0) {
  577. l->tap->sendReturnValue(conn, -1, errno);
  578. dwr(MSG_ERROR," nc_accept(): unable to create socketpair\n");
  579. return ERR_MEM;
  580. }
  581. }
  582. // create and populate new TcpConnection
  583. TcpConnection *newTcpConn = new TcpConnection();
  584. l->tap->_TcpConnections.push_back(newTcpConn);
  585. newTcpConn->pcb = newPCB;
  586. newTcpConn->sock = tap->_phy.wrapSocket(fds[0], newTcpConn);
  587. if(sock_fd_write(fd, fds[1]) < 0)
  588. return -1;
  589. tap->lwipstack->_tcp_arg(newPCB, new Larg(tap, newTcpConn));
  590. tap->lwipstack->_tcp_recv(newPCB, nc_recved);
  591. tap->lwipstack->_tcp_err(newPCB, nc_err);
  592. tap->lwipstack->_tcp_sent(newPCB, nc_sent);
  593. tap->lwipstack->_tcp_poll(newPCB, nc_poll, 1);
  594. if(conn->pcb->state == LISTEN) {
  595. dwr(MSG_DEBUG," nc_accept(): can't call tcp_accept() on LISTEN socket (pcb = %x)\n", conn->pcb);
  596. return ERR_OK;
  597. }
  598. tcp_accepted(conn->pcb); // Let lwIP know that it can queue additional incoming connections
  599. return ERR_OK;
  600. } else
  601. dwr(MSG_ERROR," nc_accept(): can't locate Connection object for PCB.\n");
  602. return -1;
  603. }
  604. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *PCB, struct pbuf *p, err_t err)
  605. {
  606. Larg *l = (Larg*)arg;
  607. int tot = 0;
  608. struct pbuf* q = p;
  609. Mutex::Lock _l(l->tap->_tcpconns_m);
  610. if(!l->conn) {
  611. dwr(MSG_ERROR," nc_recved(): no connection\n");
  612. return ERR_OK;
  613. }
  614. if(p == NULL) {
  615. if(l->conn->pcb->state == CLOSE_WAIT){
  616. l->tap->closeConnection(l->conn->sock);
  617. return ERR_ABRT;
  618. }
  619. return err;
  620. }
  621. Mutex::Lock _l2(l->tap->_rx_buf_m);
  622. // Cycle through pbufs and write them to the RX buffer
  623. // The RX buffer will be emptied via phyOnUnixWritable()
  624. while(p != NULL) {
  625. if(p->len <= 0)
  626. break;
  627. int avail = DEFAULT_BUF_SZ - l->conn->rxsz;
  628. int len = p->len;
  629. if(avail < len)
  630. dwr(MSG_ERROR," nc_recved(): not enough room (%d bytes) on RX buffer\n", avail);
  631. memcpy(l->conn->rxbuf + (l->conn->rxsz), p->payload, len);
  632. l->conn->rxsz += len;
  633. p = p->next;
  634. tot += len;
  635. }
  636. if(tot)
  637. l->tap->_phy.setNotifyWritable(l->conn->sock, true);
  638. l->tap->lwipstack->_pbuf_free(q);
  639. return ERR_OK;
  640. }
  641. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *PCB, u16_t len)
  642. {
  643. Larg *l = (Larg*)arg;
  644. Mutex::Lock _l(l->tap->_tcpconns_m);
  645. if(l->conn->probation && l->conn->txsz == 0){
  646. l->conn->probation = false; // TX buffer now empty, removing from probation
  647. }
  648. if(l && l->conn && len && !l->conn->probation) {
  649. if(l->conn->txsz < (float)DEFAULT_BUF_SOFTMAX) {
  650. l->tap->_phy.setNotifyReadable(l->conn->sock, true);
  651. l->tap->_phy.whack();
  652. }
  653. }
  654. return ERR_OK;
  655. }
  656. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *PCB, err_t err)
  657. {
  658. Larg *l = (Larg*)arg;
  659. if(l && l->conn)
  660. l->tap->sendReturnValue(l->tap->_phy.getDescriptor(l->conn->rpcSock), ERR_OK);
  661. return ERR_OK;
  662. }
  663. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *PCB)
  664. {
  665. return ERR_OK;
  666. }
  667. void NetconEthernetTap::nc_err(void *arg, err_t err)
  668. {
  669. dwr(MSG_DEBUG,"nc_err() = %d\n", err);
  670. Larg *l = (Larg*)arg;
  671. Mutex::Lock _l(l->tap->_tcpconns_m);
  672. if(!l->conn)
  673. dwr(MSG_ERROR,"nc_err(): connection is NULL!\n");
  674. int fd = l->tap->_phy.getDescriptor(l->conn->sock);
  675. switch(err)
  676. {
  677. case ERR_MEM:
  678. dwr(MSG_ERROR,"nc_err(): ERR_MEM->ENOMEM\n");
  679. l->tap->sendReturnValue(fd, -1, ENOMEM);
  680. break;
  681. case ERR_BUF:
  682. dwr(MSG_ERROR,"nc_err(): ERR_BUF->ENOBUFS\n");
  683. l->tap->sendReturnValue(fd, -1, ENOBUFS);
  684. break;
  685. case ERR_TIMEOUT:
  686. dwr(MSG_ERROR,"nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  687. l->tap->sendReturnValue(fd, -1, ETIMEDOUT);
  688. break;
  689. case ERR_RTE:
  690. dwr(MSG_ERROR,"nc_err(): ERR_RTE->ENETUNREACH\n");
  691. l->tap->sendReturnValue(fd, -1, ENETUNREACH);
  692. break;
  693. case ERR_INPROGRESS:
  694. dwr(MSG_ERROR,"nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  695. l->tap->sendReturnValue(fd, -1, EINPROGRESS);
  696. break;
  697. case ERR_VAL:
  698. dwr(MSG_ERROR,"nc_err(): ERR_VAL->EINVAL\n");
  699. l->tap->sendReturnValue(fd, -1, EINVAL);
  700. break;
  701. case ERR_WOULDBLOCK:
  702. dwr(MSG_ERROR,"nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  703. l->tap->sendReturnValue(fd, -1, EWOULDBLOCK);
  704. break;
  705. case ERR_USE:
  706. dwr(MSG_ERROR,"nc_err(): ERR_USE->EADDRINUSE\n");
  707. l->tap->sendReturnValue(fd, -1, EADDRINUSE);
  708. break;
  709. case ERR_ISCONN:
  710. dwr(MSG_ERROR,"nc_err(): ERR_ISCONN->EISCONN\n");
  711. l->tap->sendReturnValue(fd, -1, EISCONN);
  712. break;
  713. case ERR_ABRT:
  714. dwr(MSG_ERROR,"nc_err(): ERR_ABRT->ECONNREFUSED\n");
  715. l->tap->sendReturnValue(fd, -1, ECONNREFUSED);
  716. break;
  717. // FIXME: Below are errors which don't have a standard errno correlate
  718. case ERR_RST:
  719. l->tap->sendReturnValue(fd, -1, -1);
  720. break;
  721. case ERR_CLSD:
  722. l->tap->sendReturnValue(fd, -1, -1);
  723. break;
  724. case ERR_CONN:
  725. l->tap->sendReturnValue(fd, -1, -1);
  726. break;
  727. case ERR_ARG:
  728. l->tap->sendReturnValue(fd, -1, -1);
  729. break;
  730. case ERR_IF:
  731. l->tap->sendReturnValue(fd, -1, -1);
  732. break;
  733. default:
  734. break;
  735. }
  736. dwr(MSG_ERROR,"nc_err(): closing connection\n");
  737. l->tap->closeConnection(l->conn);
  738. }
  739. /*------------------------------------------------------------------------------
  740. ----------------------------- RPC Handler functions ----------------------------
  741. ------------------------------------------------------------------------------*/
  742. void NetconEthernetTap::handleGetsockname(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct getsockname_st *getsockname_rpc)
  743. {
  744. Mutex::Lock _l(_tcpconns_m);
  745. TcpConnection *conn = getConnection(sock);
  746. char retmsg[sizeof(struct sockaddr_storage)];
  747. memset(&retmsg, 0, sizeof(retmsg));
  748. if ((conn)&&(conn->addr))
  749. memcpy(&retmsg, conn->addr, sizeof(struct sockaddr_storage));
  750. write(_phy.getDescriptor(rpcSock), &retmsg, sizeof(struct sockaddr_storage));
  751. }
  752. void NetconEthernetTap::handleBind(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct bind_st *bind_rpc)
  753. {
  754. Mutex::Lock _l(_tcpconns_m);
  755. struct sockaddr_in *rawAddr = (struct sockaddr_in *) &bind_rpc->addr;
  756. int port = lwipstack->ntohs(rawAddr->sin_port);
  757. ip_addr_t connAddr;
  758. connAddr.addr = *((u32_t *)_ips[0].rawIpData());
  759. TcpConnection *conn = getConnection(sock);
  760. dwr(MSG_DEBUG," handleBind(%d)\n", bind_rpc->sockfd);
  761. if(conn) {
  762. if(conn->pcb->state == CLOSED){
  763. int err = lwipstack->tcp_bind(conn->pcb, &connAddr, port);
  764. int ip = rawAddr->sin_addr.s_addr;
  765. unsigned char d[4];
  766. d[0] = ip & 0xFF;
  767. d[1] = (ip >> 8) & 0xFF;
  768. d[2] = (ip >> 16) & 0xFF;
  769. d[3] = (ip >> 24) & 0xFF;
  770. dwr(MSG_DEBUG," handleBind(): %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], port);
  771. if(err != ERR_OK) {
  772. dwr(MSG_ERROR," handleBind(): err = %d\n", err);
  773. if(err == ERR_USE)
  774. sendReturnValue(rpcSock, -1, EADDRINUSE);
  775. if(err == ERR_MEM)
  776. sendReturnValue(rpcSock, -1, ENOMEM);
  777. if(err == ERR_BUF)
  778. sendReturnValue(rpcSock, -1, ENOMEM);
  779. } else {
  780. conn->addr = (struct sockaddr_storage *) &bind_rpc->addr;
  781. sendReturnValue(rpcSock, ERR_OK, ERR_OK); // Success
  782. }
  783. } else {
  784. dwr(MSG_ERROR," handleBind(): PCB (%x) not in CLOSED state. Ignoring BIND request.\n", conn->pcb);
  785. sendReturnValue(rpcSock, -1, EINVAL);
  786. }
  787. } else {
  788. dwr(MSG_ERROR," handleBind(): unable to locate TcpConnection.\n");
  789. sendReturnValue(rpcSock, -1, EBADF);
  790. }
  791. }
  792. void NetconEthernetTap::handleListen(PhySocket *sock, PhySocket *rpcSock, void **uptr, struct listen_st *listen_rpc)
  793. {
  794. Mutex::Lock _l(_tcpconns_m);
  795. TcpConnection *conn = getConnection(sock);
  796. if(!conn){
  797. dwr(MSG_ERROR," handleListen(): unable to locate TcpConnection.\n");
  798. sendReturnValue(rpcSock, -1, EBADF);
  799. return;
  800. }
  801. if(conn->pcb->state == LISTEN) {
  802. dwr(MSG_ERROR," handleListen(): PCB is already in listening state.\n");
  803. sendReturnValue(rpcSock, ERR_OK, ERR_OK);
  804. return;
  805. }
  806. struct tcp_pcb* listeningPCB;
  807. #ifdef TCP_LISTEN_BACKLOG
  808. listeningPCB = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  809. #else
  810. listeningPCB = lwipstack->tcp_listen(conn->pcb);
  811. #endif
  812. if(listeningPCB != NULL) {
  813. conn->pcb = listeningPCB;
  814. lwipstack->tcp_accept(listeningPCB, nc_accept);
  815. lwipstack->tcp_arg(listeningPCB, new Larg(this, conn));
  816. /* we need to wait for the client to send us the fd allocated on their end
  817. for this listening socket */
  818. fcntl(_phy.getDescriptor(conn->sock), F_SETFL, O_NONBLOCK);
  819. conn->listening = true;
  820. sendReturnValue(rpcSock, ERR_OK, ERR_OK);
  821. return;
  822. }
  823. sendReturnValue(rpcSock, -1, -1);
  824. }
  825. TcpConnection * NetconEthernetTap::handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  826. {
  827. Mutex::Lock _l(_tcpconns_m);
  828. struct tcp_pcb *newPCB = lwipstack->tcp_new();
  829. if(newPCB != NULL) {
  830. TcpConnection *newConn = new TcpConnection();
  831. *uptr = newConn;
  832. newConn->sock = sock;
  833. newConn->pcb = newPCB;
  834. _TcpConnections.push_back(newConn);
  835. return newConn;
  836. }
  837. dwr(MSG_ERROR," handleSocket(): Memory not available for new PCB\n");
  838. sendReturnValue(_phy.getDescriptor(sock), -1, ENOMEM);
  839. return NULL;
  840. }
  841. void NetconEthernetTap::handleConnect(PhySocket *sock, PhySocket *rpcSock, TcpConnection *conn, struct connect_st* connect_rpc)
  842. {
  843. Mutex::Lock _l(_tcpconns_m);
  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(rawAddr);
  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. if(!conn->probation) {
  927. dwr(MSG_DEBUG," handleWrite(): sndbuf == 0, LWIP stack is full\n");
  928. _phy.setNotifyReadable(conn->sock, false);
  929. conn->probation = true;
  930. }
  931. return;
  932. }
  933. if(conn->txsz <= 0)
  934. return; // Nothing to write
  935. if(!conn->listening)
  936. lwipstack->_tcp_output(conn->pcb);
  937. if(conn->sock) {
  938. r = conn->txsz < sndbuf ? conn->txsz : sndbuf;
  939. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  940. * data to LWIP to be enqueued and eventually sent to the network. */
  941. if(r > 0) {
  942. err = lwipstack->_tcp_write(conn->pcb, &conn->txbuf, r, TCP_WRITE_FLAG_COPY);
  943. lwipstack->_tcp_output(conn->pcb);
  944. if(err != ERR_OK) {
  945. dwr(MSG_ERROR," handleWrite(): error while writing to PCB, (err = %d)\n", err);
  946. if(err == -1)
  947. dwr(MSG_DEBUG," handleWrite(): out of memory\n");
  948. return;
  949. } else {
  950. sz = (conn->txsz)-r;
  951. if(sz)
  952. memmove(&conn->txbuf, (conn->txbuf+r), sz);
  953. conn->txsz -= r;
  954. float max = (float)DEFAULT_BUF_SZ;
  955. dwr(MSG_TRANSFER," TX ---> :: {TX: %.3f%%, RX: %.3f%%, sock=%x} :: %d bytes\n",
  956. (float)conn->txsz / max, (float)conn->rxsz / max, conn->sock, r);
  957. return;
  958. }
  959. }
  960. }
  961. }
  962. } // namespace ZeroTier