NetconEthernetTap.cpp 35 KB

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