NetconEthernetTap.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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. #ifdef ZT_ENABLE_NETCON
  28. #include <algorithm>
  29. #include <utility>
  30. #include <dlfcn.h>
  31. #include <sys/poll.h>
  32. #include "NetconEthernetTap.hpp"
  33. #include "../node/Utils.hpp"
  34. #include "../osdep/OSUtils.hpp"
  35. #include "../osdep/Phy.hpp"
  36. #include "Intercept.h"
  37. #include "LWIPStack.hpp"
  38. #include "lwip/tcp_impl.h"
  39. #include "netif/etharp.h"
  40. #include "lwip/api.h"
  41. #include "lwip/ip.h"
  42. #include "lwip/ip_addr.h"
  43. #include "lwip/ip_frag.h"
  44. #include "lwip/tcp.h"
  45. #include "common.inc.c"
  46. #define APPLICATION_POLL_FREQ 20
  47. #define ZT_LWIP_TCP_TIMER_INTERVAL 5
  48. #define STATUS_TMR_INTERVAL 3000 // How often we check connection statuses
  49. namespace ZeroTier {
  50. // ---------------------------------------------------------------------------
  51. /*
  52. static void clearscreen(){
  53. fprintf(stderr, "\033[2J");
  54. }
  55. static void gotoxy(int x,int y) {
  56. fprintf(stderr, "%c[%d;%df",0x1B,y,x);
  57. }
  58. */
  59. // Gets the process/path name associated with a pid
  60. static void get_path_from_pid(char* dest, int pid)
  61. {
  62. char ppath[80];
  63. sprintf(ppath, "/proc/%d/exe", pid);
  64. if (readlink (ppath, dest, 80) != -1){
  65. }
  66. }
  67. // Gets the process/path name associated with a fd
  68. /*
  69. static void get_path_from_fd(char* dest, int pid, int fd)
  70. {
  71. char ppfd[80];
  72. sprintf(ppfd, "/proc/%d/fd/%d", pid, fd);
  73. if (readlink (ppfd, dest, 80) != -1){
  74. }
  75. }
  76. */
  77. static err_t tapif_init(struct netif *netif)
  78. {
  79. // Actual init functionality is in addIp() of tap
  80. return ERR_OK;
  81. }
  82. static err_t low_level_output(struct netif *netif, struct pbuf *p)
  83. {
  84. struct pbuf *q;
  85. char buf[ZT_MAX_MTU+32];
  86. char *bufptr;
  87. int tot_len = 0;
  88. ZeroTier::NetconEthernetTap *tap = (ZeroTier::NetconEthernetTap*)netif->state;
  89. /* initiate transfer(); */
  90. bufptr = buf;
  91. for(q = p; q != NULL; q = q->next) {
  92. /* Send the data from the pbuf to the interface, one pbuf at a
  93. time. The size of the data in each pbuf is kept in the ->len
  94. variable. */
  95. /* send data from(q->payload, q->len); */
  96. memcpy(bufptr, q->payload, q->len);
  97. bufptr += q->len;
  98. tot_len += q->len;
  99. }
  100. // [Send packet to network]
  101. // Split ethernet header and feed into handler
  102. struct eth_hdr *ethhdr;
  103. ethhdr = (struct eth_hdr *)buf;
  104. ZeroTier::MAC src_mac;
  105. ZeroTier::MAC dest_mac;
  106. src_mac.setTo(ethhdr->src.addr, 6);
  107. dest_mac.setTo(ethhdr->dest.addr, 6);
  108. tap->_handler(tap->_arg,tap->_nwid,src_mac,dest_mac,
  109. Utils::ntoh((uint16_t)ethhdr->type),0,buf + sizeof(struct eth_hdr),tot_len - sizeof(struct eth_hdr));
  110. return ERR_OK;
  111. }
  112. /*
  113. * TCP connection administered by service
  114. */
  115. class TcpConnection
  116. {
  117. public:
  118. int perceived_fd;
  119. int their_fd;
  120. bool pending;
  121. bool listening;
  122. int pid;
  123. unsigned long written;
  124. unsigned long acked;
  125. PhySocket *rpcSock;
  126. PhySocket *dataSock;
  127. struct tcp_pcb *pcb;
  128. unsigned char buf[DEFAULT_READ_BUFFER_SIZE];
  129. int idx;
  130. };
  131. /*
  132. * A helper class for passing a reference to _phy to LWIP callbacks as a "state"
  133. */
  134. class Larg
  135. {
  136. public:
  137. NetconEthernetTap *tap;
  138. TcpConnection *conn;
  139. Larg(NetconEthernetTap *_tap, TcpConnection *conn) : tap(_tap), conn(conn) {}
  140. };
  141. // ---------------------------------------------------------------------------
  142. NetconEthernetTap::NetconEthernetTap(
  143. const char *homePath,
  144. const MAC &mac,
  145. unsigned int mtu,
  146. unsigned int metric,
  147. uint64_t nwid,
  148. const char *friendlyName,
  149. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  150. void *arg) :
  151. _nwid(nwid),
  152. _handler(handler),
  153. _arg(arg),
  154. _phy(this,false,true),
  155. _unixListenSocket((PhySocket *)0),
  156. _mac(mac),
  157. _homePath(homePath),
  158. _mtu(mtu),
  159. _enabled(true),
  160. _run(true)
  161. {
  162. char sockPath[4096],lwipPath[4096];
  163. rpc_counter = -1;
  164. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",_nwid,ZT_PATH_SEPARATOR_S,(unsigned long long)nwid);
  165. _dev = sockPath; // in netcon mode, set device to be just the network ID
  166. Utils::snprintf(lwipPath,sizeof(lwipPath),"%s%sliblwip.so",homePath,ZT_PATH_SEPARATOR_S);
  167. lwipstack = new LWIPStack(lwipPath);
  168. if(!lwipstack)
  169. throw std::runtime_error("unable to dynamically load a new instance of liblwip.so (searched ZeroTier home path)");
  170. lwipstack->lwip_init();
  171. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  172. dwr(MSG_INFO, " NetconEthernetTap initialized!\n", _phy.getDescriptor(_unixListenSocket));
  173. if (!_unixListenSocket)
  174. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  175. _thread = Thread::start(this);
  176. }
  177. NetconEthernetTap::~NetconEthernetTap()
  178. {
  179. _run = false;
  180. _phy.whack();
  181. _phy.whack();
  182. Thread::join(_thread);
  183. _phy.close(_unixListenSocket,false);
  184. delete lwipstack;
  185. }
  186. void NetconEthernetTap::setEnabled(bool en)
  187. {
  188. _enabled = en;
  189. }
  190. bool NetconEthernetTap::enabled() const
  191. {
  192. return _enabled;
  193. }
  194. bool NetconEthernetTap::addIp(const InetAddress &ip)
  195. {
  196. Mutex::Lock _l(_ips_m);
  197. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  198. _ips.push_back(ip);
  199. std::sort(_ips.begin(),_ips.end());
  200. if (ip.isV4()) {
  201. // Set IP
  202. static ip_addr_t ipaddr, netmask, gw;
  203. IP4_ADDR(&gw,192,168,0,1);
  204. ipaddr.addr = *((u32_t *)ip.rawIpData());
  205. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  206. // Set up the lwip-netif for LWIP's sake
  207. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  208. interface.state = this;
  209. interface.output = lwipstack->_etharp_output;
  210. _mac.copyTo(interface.hwaddr, 6);
  211. interface.mtu = _mtu;
  212. interface.name[0] = 't';
  213. interface.name[1] = 'p';
  214. interface.linkoutput = low_level_output;
  215. interface.hwaddr_len = 6;
  216. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  217. lwipstack->netif_set_default(&interface);
  218. lwipstack->netif_set_up(&interface);
  219. }
  220. }
  221. return true;
  222. }
  223. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  224. {
  225. Mutex::Lock _l(_ips_m);
  226. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  227. if (i == _ips.end())
  228. return false;
  229. _ips.erase(i);
  230. if (ip.isV4()) {
  231. // TODO: dealloc from LWIP
  232. }
  233. return true;
  234. }
  235. std::vector<InetAddress> NetconEthernetTap::ips() const
  236. {
  237. Mutex::Lock _l(_ips_m);
  238. return _ips;
  239. }
  240. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  241. {
  242. struct pbuf *p,*q;
  243. if (!_enabled)
  244. return;
  245. struct eth_hdr ethhdr;
  246. from.copyTo(ethhdr.src.addr, 6);
  247. to.copyTo(ethhdr.dest.addr, 6);
  248. ethhdr.type = Utils::hton((uint16_t)etherType);
  249. // We allocate a pbuf chain of pbufs from the pool.
  250. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  251. if (p != NULL) {
  252. const char *dataptr = reinterpret_cast<const char *>(data);
  253. // First pbuf gets ethernet header at start
  254. q = p;
  255. if (q->len < sizeof(ethhdr)) {
  256. dwr(MSG_ERROR, "_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  257. return;
  258. }
  259. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  260. memcpy((char*)q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  261. dataptr += q->len - sizeof(ethhdr);
  262. // Remaining pbufs (if any) get rest of data
  263. while ((q = q->next)) {
  264. memcpy(q->payload,dataptr,q->len);
  265. dataptr += q->len;
  266. }
  267. } else {
  268. dwr(MSG_ERROR, "put(): Dropped packet: no pbufs available\n");
  269. return;
  270. }
  271. {
  272. Mutex::Lock _l2(lwipstack->_lock);
  273. if(interface.input(p, &interface) != ERR_OK) {
  274. dwr(MSG_ERROR, "put(): Error while RXing packet (netif->input)\n");
  275. }
  276. }
  277. }
  278. std::string NetconEthernetTap::deviceName() const
  279. {
  280. return _dev;
  281. }
  282. void NetconEthernetTap::setFriendlyName(const char *friendlyName) {
  283. }
  284. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  285. {
  286. std::vector<MulticastGroup> newGroups;
  287. Mutex::Lock _l(_multicastGroups_m);
  288. // TODO: get multicast subscriptions from LWIP
  289. std::vector<InetAddress> allIps(ips());
  290. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  291. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  292. std::sort(newGroups.begin(),newGroups.end());
  293. std::unique(newGroups.begin(),newGroups.end());
  294. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  295. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  296. added.push_back(*m);
  297. }
  298. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  299. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  300. removed.push_back(*m);
  301. }
  302. _multicastGroups.swap(newGroups);
  303. }
  304. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(PhySocket *sock, int fd)
  305. {
  306. for(size_t i=0; i<tcp_connections.size(); i++) {
  307. if(tcp_connections[i]->perceived_fd == fd && tcp_connections[i]->rpcSock == sock)
  308. return tcp_connections[i];
  309. }
  310. return NULL;
  311. }
  312. /*
  313. * Dumps service state in 80x25 when debug mode is off
  314. */
  315. void NetconEthernetTap::compact_dump()
  316. {
  317. /*
  318. clearscreen();
  319. gotoxy(0,0);
  320. fprintf(stderr, "ZeroTier - Network Containers Service [State Dump]\n\r");
  321. fprintf(stderr, " RPC Sockets = %d\n\r", rpc_sockets.size());
  322. fprintf(stderr, " TCP Connections = %d\n\r", tcp_connections.size());
  323. for(size_t i=0; i<rpc_sockets.size(); i++) {
  324. int rpc_fd = _phy.getDescriptor(rpc_sockets[i]);
  325. char buf[80];
  326. int pid = pidmap[rpc_sockets[i]];
  327. memset(&buf, '\0', 80);
  328. get_path_from_pid(buf, pid);
  329. fprintf(stderr, "\n Client(addr=0x%x, rpc=%d, pid=%d) %s\n", rpc_sockets[i], rpc_fd, pid, buf);
  330. for(size_t j=0; j<tcp_connections.size(); j++) {
  331. memset(&buf, '\0', 80);
  332. get_path_from_pid(buf, tcp_connections[j]->pid);
  333. if(tcp_connections[j]->rpcSock==rpc_sockets[i]) {
  334. fprintf(stderr, "\t\tpath\t\t= %s\n", buf);
  335. }
  336. }
  337. }
  338. */
  339. for(size_t i=0; i<rpc_sockets.size(); i++) {
  340. fprintf(stderr, "\n\n\nrpc(%d)\n", _phy.getDescriptor(rpc_sockets[i]));
  341. for(size_t j=0; j<tcp_connections.size(); j++) {
  342. if(_phy.getDescriptor(tcp_connections[j]->rpcSock) == _phy.getDescriptor(rpc_sockets[i]))
  343. fprintf(stderr, "\t(%d) ----> (%d)\n\n", _phy.getDescriptor(tcp_connections[j]->dataSock), tcp_connections[j]->perceived_fd);
  344. }
  345. }
  346. }
  347. /*
  348. * Dumps service state
  349. */
  350. void NetconEthernetTap::dump()
  351. {
  352. fprintf(stderr, "\n\n---\n\ndie(): BEGIN SERVICE STATE DUMP\n");
  353. fprintf(stderr, "*** IF YOU SEE THIS, EMAIL THE DUMP TEXT TO [email protected] ***\n");
  354. fprintf(stderr, " tcp_conns = %lu, rpc_socks = %lu\n", tcp_connections.size(), rpc_sockets.size());
  355. // TODO: Add logic to detect bad mapping conditions
  356. for(size_t i=0; i<rpc_sockets.size(); i++) {
  357. for(size_t j=0; j<rpc_sockets.size(); j++) {
  358. if(j != i && rpc_sockets[i] == rpc_sockets[j]) {
  359. fprintf(stderr, "Duplicate PhySockets found! (0x%p)\n", rpc_sockets[i]);
  360. }
  361. }
  362. }
  363. // Dump the state of the service mapping
  364. for(size_t i=0; i<rpc_sockets.size(); i++) {
  365. int rpc_fd = _phy.getDescriptor(rpc_sockets[i]);
  366. char buf[80];
  367. int pid = pidmap[rpc_sockets[i]];
  368. get_path_from_pid(buf, pid);
  369. fprintf(stderr, "\nClient(addr=0x%p, rpc=%d, pid=%d) %s\n", rpc_sockets[i], rpc_fd, pid, buf);
  370. for(size_t j=0; j<tcp_connections.size(); j++) {
  371. get_path_from_pid(buf, tcp_connections[j]->pid);
  372. if(tcp_connections[j]->rpcSock==rpc_sockets[i]){
  373. fprintf(stderr, " |\n");
  374. fprintf(stderr, " |-Connection(0x%p):\n", tcp_connections[j]);
  375. fprintf(stderr, " | path\t\t\t= %s\n", buf);
  376. fprintf(stderr, " | perceived_fd\t\t= %d\t(fd)\n", tcp_connections[j]->perceived_fd);
  377. fprintf(stderr, " | their_fd\t\t= %d\t(fd)\n", tcp_connections[j]->their_fd);
  378. fprintf(stderr, " | dataSock(0x%p)\t= %d\t(fd)\n", tcp_connections[j]->dataSock, _phy.getDescriptor(tcp_connections[j]->dataSock));
  379. fprintf(stderr, " | rpcSock(0x%p)\t= %d\t(fd)\n", tcp_connections[j]->rpcSock, _phy.getDescriptor(tcp_connections[j]->rpcSock));
  380. fprintf(stderr, " | pending\t\t= %d\n", tcp_connections[j]->pending);
  381. fprintf(stderr, " | listening\t\t= %d\n", tcp_connections[j]->listening);
  382. fprintf(stderr, " \\------pcb(0x%p)->state\t= %d\n", tcp_connections[j]->pcb, tcp_connections[j]->pcb->state);
  383. }
  384. }
  385. }
  386. fprintf(stderr, "\n\ndie(): END SERVICE STATE DUMP\n\n---\n\n");
  387. }
  388. /*
  389. * Dumps service state and then exits
  390. */
  391. void NetconEthernetTap::die(int exret) {
  392. dump();
  393. exit(exret);
  394. }
  395. /*
  396. * Closes a TcpConnection and associated LWIP PCB strcuture.
  397. */
  398. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  399. {
  400. if(!conn)
  401. return;
  402. dwr(MSG_DEBUG, " closeConnection(%x, %d)\n", conn->pcb, _phy.getDescriptor(conn->dataSock));
  403. //lwipstack->_tcp_sent(conn->pcb, NULL);
  404. //lwipstack->_tcp_recv(conn->pcb, NULL);
  405. //lwipstack->_tcp_err(conn->pcb, NULL);
  406. //lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  407. //lwipstack->_tcp_arg(conn->pcb, NULL);
  408. if(lwipstack->_tcp_close(conn->pcb) != ERR_OK) {
  409. dwr(MSG_ERROR, " closeConnection(): Error while calling tcp_close()\n");
  410. exit(0);
  411. }
  412. else {
  413. if(conn->dataSock) {
  414. close(_phy.getDescriptor(conn->dataSock));
  415. _phy.close(conn->dataSock,false);
  416. }
  417. /* Eventually we might want to use a map here instead */
  418. for(int i=0; i<tcp_connections.size(); i++) {
  419. if(tcp_connections[i] == conn) {
  420. tcp_connections.erase(tcp_connections.begin() + i);
  421. delete conn;
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. /*
  428. * Close a single RPC connection and associated PhySocket
  429. */
  430. void NetconEthernetTap::closeClient(PhySocket *sock)
  431. {
  432. for(size_t i=0; i<rpc_sockets.size(); i++) {
  433. if(rpc_sockets[i] == sock){
  434. rpc_sockets.erase(rpc_sockets.begin() + i);
  435. break;
  436. }
  437. }
  438. close(_phy.getDescriptor(sock));
  439. _phy.close(sock);
  440. }
  441. /*
  442. * Close all RPC and TCP connections
  443. */
  444. void NetconEthernetTap::closeAll()
  445. {
  446. while(rpc_sockets.size())
  447. closeClient(rpc_sockets.front());
  448. while(tcp_connections.size())
  449. closeConnection(tcp_connections.front());
  450. }
  451. #include <sys/resource.h>
  452. void NetconEthernetTap::threadMain()
  453. throw()
  454. {
  455. uint64_t prev_tcp_time = 0;
  456. uint64_t prev_status_time = 0;
  457. uint64_t prev_etharp_time = 0;
  458. /*
  459. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  460. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  461. fprintf(stderr, "- PBUF_POOL_BUFSIZE = %d\n", PBUF_POOL_BUFSIZE);
  462. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  463. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  464. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  465. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n\n", MEMP_NUM_TCP_SEG);
  466. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  467. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n\n", TCP_SND_QUEUELEN);
  468. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  469. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  470. fprintf(stderr, "- TCP_MAXRTX = %d\n", TCP_MAXRTX);
  471. fprintf(stderr, "- IP_REASSEMBLY = %d\n\n", IP_REASSEMBLY);
  472. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  473. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  474. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  475. */
  476. // Main timer loop
  477. while (_run) {
  478. uint64_t now = OSUtils::now();
  479. uint64_t since_tcp = now - prev_tcp_time;
  480. uint64_t since_etharp = now - prev_etharp_time;
  481. uint64_t since_status = now - prev_status_time;
  482. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  483. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  484. uint64_t status_remaining = STATUS_TMR_INTERVAL;
  485. // Connection prunning
  486. if (since_status >= STATUS_TMR_INTERVAL) {
  487. //compact_dump();
  488. prev_status_time = now;
  489. status_remaining = STATUS_TMR_INTERVAL - since_status;
  490. if(rpc_sockets.size() || tcp_connections.size()) {
  491. // dump();
  492. // Here we will periodically check the list of rpc_sockets for those that
  493. // do not currently have any data connection associated with them. If they are
  494. // unused, then we will try to read from them, if they fail, we can safely assume
  495. // that the client has closed their end and we can close ours
  496. for(size_t i = 0; i<tcp_connections.size(); i++) {
  497. if(tcp_connections[i]->listening) {
  498. char c;
  499. if (read(_phy.getDescriptor(tcp_connections[i]->dataSock), &c, 1) < 0) {
  500. // Still in listening state
  501. }
  502. else {
  503. // Here we should handle the case there there is incoming data (?)
  504. dwr(MSG_DEBUG, " tap_thread(): Listening socketpair closed. Removing RPC connection (%d)\n",
  505. _phy.getDescriptor(tcp_connections[i]->dataSock));
  506. closeConnection(tcp_connections[i]);
  507. }
  508. }
  509. }
  510. }
  511. //dwr(4, " tap_thread(): tcp_conns = %d, rpc_socks = %d\n", tcp_connections.size(), rpc_sockets.size());
  512. for(size_t i=0, associated = 0; i<rpc_sockets.size(); i++, associated = 0) {
  513. for(size_t j=0; j<tcp_connections.size(); j++) {
  514. if (tcp_connections[j]->rpcSock == rpc_sockets[i])
  515. associated++;
  516. }
  517. if(!associated){
  518. // No TCP connections are associated, this is a candidate for removal
  519. int fd = _phy.getDescriptor(rpc_sockets[i]);
  520. fcntl(fd, F_SETFL, O_NONBLOCK);
  521. unsigned char tmpbuf[BUF_SZ];
  522. int n;
  523. if((n = read(fd,&tmpbuf,BUF_SZ)) < 0) {
  524. dwr(MSG_DEBUG, " tap_thread(): closing RPC (%d)\n", _phy.getDescriptor(rpc_sockets[i]));
  525. closeClient(rpc_sockets[i]);
  526. }
  527. // < 0 is failure
  528. // 0 nothing to read, RPC still active
  529. // > 0 RPC data read, handle it
  530. else if (n > 0) {
  531. // Handle RPC call, this is rare
  532. dwr(MSG_DEBUG, " tap_thread(): RPC read during connection check (%d bytes)\n", n);
  533. phyOnUnixData(rpc_sockets[i],_phy.getuptr(rpc_sockets[i]),&tmpbuf,BUF_SZ);
  534. }
  535. }
  536. }
  537. }
  538. // Main TCP/ETHARP timer section
  539. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  540. prev_tcp_time = now;
  541. lwipstack->tcp_tmr();
  542. } else {
  543. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  544. }
  545. if (since_etharp >= ARP_TMR_INTERVAL) {
  546. prev_etharp_time = now;
  547. lwipstack->etharp_tmr();
  548. } else {
  549. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  550. }
  551. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  552. }
  553. closeAll();
  554. dlclose(lwipstack->_libref);
  555. }
  556. // Unused -- no UDP or TCP from this thread/Phy<>
  557. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  558. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  559. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  560. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  561. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  562. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  563. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr) {
  564. dwr(MSG_DEBUG, " phyOnUnixClose(sock=0x%x, uptr=0x%x): fd = %d\n", sock, uptr, _phy.getDescriptor(sock));
  565. TcpConnection *conn = (TcpConnection*)*uptr;
  566. closeConnection(conn);
  567. }
  568. /*
  569. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  570. */
  571. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  572. {
  573. if(readable) {
  574. TcpConnection *conn = (TcpConnection*)*uptr;
  575. if(conn->dataSock) { // Sometimes a connection may be closed via nc_recved, check first
  576. lwipstack->_lock.lock();
  577. handle_write(conn);
  578. lwipstack->_lock.unlock();
  579. }
  580. }
  581. else {
  582. dwr(MSG_ERROR, "phyOnFileDescriptorActivity(): PhySocket not readable\n");
  583. }
  584. }
  585. /*
  586. * Add a new PhySocket for the client connections
  587. */
  588. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {
  589. dwr(MSG_DEBUG, " phyOnUnixAccept(): accepting new connection\n");
  590. if(find(rpc_sockets.begin(), rpc_sockets.end(), sockN) != rpc_sockets.end()){
  591. dwr(MSG_ERROR, " phyOnUnixAccept(): SockN (0x%x) already exists!\n", sockN);
  592. return;
  593. }
  594. rpc_sockets.push_back(sockN);
  595. }
  596. /*
  597. * Processes incoming data on a client-specific RPC connection
  598. */
  599. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  600. {
  601. pid_t pid, tid;
  602. int rpc_count;
  603. char cmd, timestamp[20];
  604. void *payload;
  605. unload_rpc(data, pid, tid, rpc_count, timestamp, cmd, payload);
  606. dwr(MSG_DEBUG, "\n\nRPC: (pid=%d, tid=%d, rpc_count=%d, timestamp=%s, cmd=%d\n", pid, tid, rpc_count, timestamp, cmd);
  607. unsigned char *buf = (unsigned char*)data;
  608. switch(cmd)
  609. {
  610. case RPC_SOCKET:
  611. dwr(MSG_DEBUG, "RPC_SOCKET\n");
  612. struct socket_st socket_rpc;
  613. memcpy(&socket_rpc, &buf[IDX_PAYLOAD+1], sizeof(struct socket_st));
  614. if(rpc_count==rpc_counter) {
  615. dwr(MSG_ERROR, "Detected repeat RPC.\n");
  616. //return;
  617. }
  618. else {
  619. rpc_counter = rpc_count;
  620. }
  621. TcpConnection * new_conn;
  622. if((new_conn = handle_socket(sock, uptr, &socket_rpc))) {
  623. pidmap[sock] = pid;
  624. new_conn->pid = pid;
  625. }
  626. break;
  627. case RPC_LISTEN:
  628. dwr(MSG_DEBUG, "RPC_LISTEN\n");
  629. struct listen_st listen_rpc;
  630. memcpy(&listen_rpc, &buf[IDX_PAYLOAD+1], sizeof(struct listen_st));
  631. handle_listen(sock, uptr, &listen_rpc);
  632. break;
  633. case RPC_BIND:
  634. dwr(MSG_DEBUG, "RPC_BIND\n");
  635. struct bind_st bind_rpc;
  636. memcpy(&bind_rpc, &buf[IDX_PAYLOAD+1], sizeof(struct bind_st));
  637. handle_bind(sock, uptr, &bind_rpc);
  638. break;
  639. case RPC_CONNECT:
  640. dwr(MSG_DEBUG, "RPC_CONNECT\n");
  641. struct connect_st connect_rpc;
  642. memcpy(&connect_rpc, &buf[IDX_PAYLOAD+1], sizeof(struct connect_st));
  643. handle_connect(sock, uptr, &connect_rpc);
  644. break;
  645. case RPC_MAP:
  646. dwr(MSG_DEBUG, "RPC_MAP (len = %d)\n", len);
  647. int newfd;
  648. memcpy(&newfd, &buf[IDX_PAYLOAD+1], sizeof(int));
  649. handle_retval(sock, uptr, rpc_count, newfd);
  650. break;
  651. case RPC_MAP_REQ:
  652. dwr(MSG_DEBUG, "RPC_MAP_REQ\n");
  653. handle_map_request(sock, uptr, buf);
  654. break;
  655. default:
  656. break;
  657. }
  658. }
  659. /*
  660. * Send a 'retval' and 'errno' to the client for an RPC over connection->rpcSock
  661. */
  662. int NetconEthernetTap::send_return_value(TcpConnection *conn, int retval, int _errno = 0)
  663. {
  664. if(conn) {
  665. int n = send_return_value(_phy.getDescriptor(conn->rpcSock), retval, _errno);
  666. if(n > 0)
  667. conn->pending = false;
  668. else {
  669. dwr(MSG_ERROR, " Unable to send return value to the intercept. Closing connection\n");
  670. closeConnection(conn);
  671. }
  672. return n;
  673. }
  674. return -1;
  675. }
  676. int NetconEthernetTap::send_return_value(int fd, int retval, int _errno = 0)
  677. {
  678. dwr(MSG_DEBUG, " send_return_value(): fd = %d, retval = %d, errno = %d\n", fd, retval, _errno);
  679. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  680. char retmsg[sz];
  681. memset(&retmsg, '\0', sizeof(retmsg));
  682. retmsg[0]=RPC_RETVAL;
  683. memcpy(&retmsg[1], &retval, sizeof(retval));
  684. memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
  685. return write(fd, &retmsg, sz);
  686. }
  687. /*------------------------------------------------------------------------------
  688. --------------------------------- LWIP callbacks -------------------------------
  689. ------------------------------------------------------------------------------*/
  690. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  691. // locked in this case!
  692. /*
  693. * Callback from LWIP for when a connection has been accepted and the PCB has been
  694. * put into an ACCEPT state.
  695. *
  696. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  697. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  698. * is then required to tell the service what new file descriptor it has allocated
  699. * for this connection. After the mapping is complete, the accepted socket can be
  700. * used.
  701. *
  702. * @param associated service state object
  703. * @param newly allocated PCB
  704. * @param error code
  705. * @return ERR_OK if everything is ok, -1 otherwise
  706. i := should be implemented in intercept lib
  707. I := is implemented in intercept lib
  708. X := is implemented in service
  709. ? := required treatment Unknown
  710. - := Not needed
  711. [ ] EAGAIN or EWOULDBLOCK - The socket is marked nonblocking and no connections are present
  712. to be accepted. POSIX.1-2001 allows either error to be returned for
  713. this case, and does not require these constants to have the same value,
  714. so a portable application should check for both possibilities.
  715. [I] EBADF - The descriptor is invalid.
  716. [I] ECONNABORTED - A connection has been aborted.
  717. [i] EFAULT - The addr argument is not in a writable part of the user address space.
  718. [-] EINTR - The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).
  719. [I] EINVAL - Socket is not listening for connections, or addrlen is invalid (e.g., is negative).
  720. [I] EINVAL - (accept4()) invalid value in flags.
  721. [I] EMFILE - The per-process limit of open file descriptors has been reached.
  722. [ ] ENFILE - The system limit on the total number of open files has been reached.
  723. [ ] ENOBUFS, ENOMEM - Not enough free memory. This often means that the memory allocation is
  724. limited by the socket buffer limits, not by the system memory.
  725. [I] ENOTSOCK - The descriptor references a file, not a socket.
  726. [I] EOPNOTSUPP - The referenced socket is not of type SOCK_STREAM.
  727. [ ] EPROTO - Protocol error.
  728. *
  729. */
  730. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  731. {
  732. dwr(MSG_DEBUG, " nc_accept()\n");
  733. Larg *l = (Larg*)arg;
  734. TcpConnection *conn = l->conn;
  735. NetconEthernetTap *tap = l->tap;
  736. int listening_fd = tap->_phy.getDescriptor(conn->dataSock);
  737. if(conn) {
  738. ZT_PHY_SOCKFD_TYPE fds[2];
  739. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  740. if(errno < 0) {
  741. l->tap->send_return_value(conn, -1, errno);
  742. dwr(MSG_ERROR, " nc_accept(): unable to create socketpair\n");
  743. return ERR_MEM;
  744. }
  745. }
  746. TcpConnection *new_tcp_conn = new TcpConnection();
  747. new_tcp_conn->dataSock = tap->_phy.wrapSocket(fds[0], new_tcp_conn);
  748. new_tcp_conn->rpcSock = conn->rpcSock;
  749. new_tcp_conn->pcb = newpcb;
  750. new_tcp_conn->their_fd = fds[1];
  751. tap->tcp_connections.push_back(new_tcp_conn);
  752. dwr(MSG_DEBUG, " nc_accept(): socketpair = {%d, %d}\n", fds[0], fds[1]);
  753. int n, send_fd = tap->_phy.getDescriptor(conn->rpcSock);
  754. if((n = send(listening_fd, "z", 1, MSG_NOSIGNAL)) < 0) {
  755. dwr(MSG_ERROR, " nc_accept(): Error: [send(listening_fd,...) = MSG_NOSIGNAL].\n");
  756. return -1;
  757. }
  758. else if(n > 0) {
  759. if(sock_fd_write(send_fd, fds[1]) > 0) {
  760. close(fds[1]); // close other end of socketpair
  761. new_tcp_conn->pending = true;
  762. }
  763. else {
  764. dwr(MSG_ERROR, " nc_accept(%d): unable to send fd to client\n", listening_fd);
  765. }
  766. }
  767. else {
  768. dwr(MSG_ERROR, " nc_accept(%d): error writing signal byte (send_fd = %d, perceived_fd = %d)\n", listening_fd, send_fd, fds[1]);
  769. return -1;
  770. }
  771. tap->lwipstack->_tcp_arg(newpcb, new Larg(tap, new_tcp_conn));
  772. tap->lwipstack->_tcp_recv(newpcb, nc_recved);
  773. tap->lwipstack->_tcp_err(newpcb, nc_err);
  774. tap->lwipstack->_tcp_sent(newpcb, nc_sent);
  775. tap->lwipstack->_tcp_poll(newpcb, nc_poll, 1);
  776. tcp_accepted(conn->pcb); // Let lwIP know that it can queue additional incoming connections
  777. return ERR_OK;
  778. }
  779. else {
  780. dwr(MSG_ERROR, " nc_accept(%d): can't locate Connection object for PCB.\n", listening_fd);
  781. }
  782. return -1;
  783. }
  784. /*
  785. * Callback from LWIP for when data is available to be read from the network.
  786. *
  787. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  788. * send to the client over the associated unix socket.
  789. *
  790. * @param associated service state object
  791. * @param allocated PCB
  792. * @param chain of pbufs
  793. * @param error code
  794. * @return ERR_OK if everything is ok, -1 otherwise
  795. *
  796. */
  797. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  798. {
  799. dwr(MSG_DEBUG, " nc_recved()\n");
  800. Larg *l = (Larg*)arg;
  801. int n;
  802. struct pbuf* q = p;
  803. if(!l->conn) {
  804. dwr(MSG_ERROR, " nc_recved(): no connection object\n");
  805. return ERR_OK; // ?
  806. }
  807. if(p == NULL) {
  808. if(l->conn) {
  809. dwr(MSG_INFO, " nc_recved(): closing connection\n");
  810. l->tap->closeConnection(l->conn);
  811. return ERR_ABRT;
  812. }
  813. else {
  814. dwr(MSG_ERROR, " nc_recved(): can't locate connection via (arg)\n");
  815. }
  816. return err;
  817. }
  818. q = p;
  819. while(p != NULL) { // Cycle through pbufs and write them to the socket
  820. if(p->len <= 0)
  821. break; // ?
  822. if((n = l->tap->_phy.streamSend(l->conn->dataSock,p->payload, p->len)) > 0) {
  823. if(n < p->len) {
  824. dwr(MSG_INFO, " nc_recved(): unable to write entire pbuf to buffer\n");
  825. }
  826. l->tap->lwipstack->_tcp_recved(tpcb, n); // TODO: would it be more efficient to call this once at the end?
  827. dwr(MSG_DEBUG, " nc_recved(): wrote %d bytes to (%d)\n", n, l->tap->_phy.getDescriptor(l->conn->dataSock));
  828. }
  829. else {
  830. dwr(MSG_INFO, " nc_recved(): No data written to intercept buffer (%d)\n", l->tap->_phy.getDescriptor(l->conn->dataSock));
  831. }
  832. p = p->next;
  833. }
  834. l->tap->lwipstack->_pbuf_free(q); // free pbufs
  835. return ERR_OK;
  836. }
  837. /*
  838. * Callback from LWIP when an internal error is associtated with the given (arg)
  839. *
  840. * Since the PCB related to this error might no longer exist, only its perviously
  841. * associated (arg) is provided to us.
  842. *
  843. * @param associated service state object
  844. * @param error code
  845. *
  846. */
  847. void NetconEthernetTap::nc_err(void *arg, err_t err)
  848. {
  849. dwr(MSG_DEBUG, "nc_err()\n");
  850. Larg *l = (Larg*)arg;
  851. if(!l->conn)
  852. dwr(MSG_ERROR, "nc_err(): Connection is NULL!\n");
  853. switch(err)
  854. {
  855. case ERR_MEM:
  856. dwr(MSG_ERROR, "nc_err(): ERR_MEM->ENOMEM\n");
  857. l->tap->send_return_value(l->conn, -1, ENOMEM);
  858. break;
  859. case ERR_BUF:
  860. dwr(MSG_ERROR, "nc_err(): ERR_BUF->ENOBUFS\n");
  861. l->tap->send_return_value(l->conn, -1, ENOBUFS);
  862. break;
  863. case ERR_TIMEOUT:
  864. dwr(MSG_ERROR, "nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  865. l->tap->send_return_value(l->conn, -1, ETIMEDOUT);
  866. break;
  867. case ERR_RTE:
  868. dwr(MSG_ERROR, "nc_err(): ERR_RTE->ENETUNREACH\n");
  869. l->tap->send_return_value(l->conn, -1, ENETUNREACH);
  870. break;
  871. case ERR_INPROGRESS:
  872. dwr(MSG_ERROR, "nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  873. l->tap->send_return_value(l->conn, -1, EINPROGRESS);
  874. break;
  875. case ERR_VAL:
  876. dwr(MSG_ERROR, "nc_err(): ERR_VAL->EINVAL\n");
  877. l->tap->send_return_value(l->conn, -1, EINVAL);
  878. break;
  879. case ERR_WOULDBLOCK:
  880. dwr(MSG_ERROR, "nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  881. l->tap->send_return_value(l->conn, -1, EWOULDBLOCK);
  882. break;
  883. case ERR_USE:
  884. dwr(MSG_ERROR, "nc_err(): ERR_USE->EADDRINUSE\n");
  885. l->tap->send_return_value(l->conn, -1, EADDRINUSE);
  886. break;
  887. case ERR_ISCONN:
  888. dwr(MSG_ERROR, "nc_err(): ERR_ISCONN->EISCONN\n");
  889. l->tap->send_return_value(l->conn, -1, EISCONN);
  890. break;
  891. case ERR_ABRT:
  892. dwr(MSG_ERROR, "nc_err(): ERR_ABRT->ECONNREFUSED\n");
  893. l->tap->send_return_value(l->conn, -1, ECONNREFUSED);
  894. break;
  895. // FIXME: Below are errors which don't have a standard errno correlate
  896. case ERR_RST:
  897. l->tap->send_return_value(l->conn, -1, -1);
  898. break;
  899. case ERR_CLSD:
  900. l->tap->send_return_value(l->conn, -1, -1);
  901. break;
  902. case ERR_CONN:
  903. l->tap->send_return_value(l->conn, -1, -1);
  904. break;
  905. case ERR_ARG:
  906. l->tap->send_return_value(l->conn, -1, -1);
  907. break;
  908. case ERR_IF:
  909. l->tap->send_return_value(l->conn, -1, -1);
  910. break;
  911. default:
  912. break;
  913. }
  914. dwr(MSG_ERROR, "nc_err(): closing connection\n");
  915. l->tap->closeConnection(l->conn);
  916. }
  917. /*
  918. * Callback from LWIP to do whatever work we might need to do.
  919. *
  920. * @param associated service state object
  921. * @param PCB we're polling on
  922. * @return ERR_OK if everything is ok, -1 otherwise
  923. *
  924. */
  925. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  926. {
  927. //Larg *l = (Larg*)arg;
  928. /*
  929. Larg *l = (Larg*)arg;
  930. TcpConnection *conn = l->conn;
  931. NetconEthernetTap *tap = l->tap;
  932. if(conn && conn->idx) // if valid connection and non-zero index (indicating data present)
  933. tap->handle_write(conn);
  934. */
  935. return ERR_OK;
  936. }
  937. /*
  938. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  939. * As a result, we should put our socket back into a notify-on-readability state
  940. * since there is now room on the PCB buffer to write to.
  941. *
  942. * NOTE: This could be used to track the amount of data sent by a connection.
  943. *
  944. * @param associated service state object
  945. * @param relevant PCB
  946. * @param length of data sent
  947. * @return ERR_OK if everything is ok, -1 otherwise
  948. *
  949. */
  950. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  951. {
  952. //dwr(5, " nc_sent()\n");
  953. Larg *l = (Larg*)arg;
  954. if(len) {
  955. l->conn->acked+=len;
  956. //dwr("W = %d, A = %d\n", l->conn->written, l->conn->acked);
  957. //dwr("ACK = %d\n", len);
  958. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  959. l->tap->_phy.whack();
  960. }
  961. return ERR_OK;
  962. }
  963. /*
  964. * Callback from LWIP which sends a return value to the client to signal that
  965. * a connection was established for this PCB
  966. *
  967. * @param associated service state object
  968. * @param relevant PCB
  969. * @param error code
  970. * @return ERR_OK if everything is ok, -1 otherwise
  971. *
  972. */
  973. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  974. {
  975. dwr(MSG_DEBUG, " nc_connected()\n");
  976. Larg *l = (Larg*)arg;
  977. l->tap->send_return_value(l->conn, ERR_OK);
  978. return ERR_OK;
  979. }
  980. /*------------------------------------------------------------------------------
  981. ----------------------------- RPC Handler functions ----------------------------
  982. ------------------------------------------------------------------------------*/
  983. /* Unpacks the buffer from an RPC command */
  984. void NetconEthernetTap::unload_rpc(void *data, pid_t &pid, pid_t &tid, int &rpc_count, char (timestamp[20]), char &cmd, void* &payload)
  985. {
  986. unsigned char *buf = (unsigned char*)data;
  987. memcpy(&pid, &buf[IDX_PID], sizeof(pid_t));
  988. memcpy(&tid, &buf[IDX_TID], sizeof(pid_t));
  989. memcpy(&rpc_count, &buf[IDX_COUNT], sizeof(int));
  990. memcpy(timestamp, &buf[IDX_TIME], 20);
  991. memcpy(&cmd, &buf[IDX_PAYLOAD], sizeof(char));
  992. }
  993. /*
  994. Responds to a request from the [intercept] to determine whether a local socket is
  995. mapped to this service. In other words, how do the intercept's overridden calls
  996. tell the difference between regular AF_LOCAL sockets and one of our socketpairs
  997. that is used to communicate over the network?
  998. */
  999. void NetconEthernetTap::handle_map_request(PhySocket *sock, void **uptr, unsigned char* buf)
  1000. {
  1001. dwr(4, " handle_map_request()\n");
  1002. TcpConnection *conn = (TcpConnection*)*uptr;
  1003. int req_fd;
  1004. memcpy(&req_fd, &buf[IDX_PAYLOAD+1], sizeof(req_fd));
  1005. for(size_t i=0; i<tcp_connections.size(); i++) {
  1006. if(tcp_connections[i]->rpcSock == conn->rpcSock && tcp_connections[i]->perceived_fd == req_fd){
  1007. send_return_value(conn, 1, ERR_OK); // True
  1008. dwr(MSG_DEBUG, " handle_map_request(their=%d): MAPPED (to %d)\n", req_fd,
  1009. _phy.getDescriptor(tcp_connections[i]->dataSock));
  1010. return;
  1011. }
  1012. }
  1013. send_return_value(conn, 0, ERR_OK); // False
  1014. dwr(MSG_DEBUG, " handle_map_request(their=%d): NOT MAPPED\n", req_fd);
  1015. }
  1016. /**
  1017. * Handles a return value (client's perceived fd) and completes a mapping
  1018. * so that we know what connection an RPC call should be associated with.
  1019. *
  1020. * @param PhySocket associated with this RPC connection
  1021. * @param structure containing the data and parameters for this client's RPC
  1022. *
  1023. */
  1024. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, int rpc_count, int newfd)
  1025. {
  1026. dwr(MSG_DEBUG, " handle_retval()\n");
  1027. TcpConnection *conn = (TcpConnection*)*uptr;
  1028. if(!conn->pending)
  1029. return;
  1030. conn->pending = false;
  1031. conn->perceived_fd = newfd;
  1032. if(rpc_count==rpc_counter) {
  1033. dwr(MSG_ERROR, " handle_retval(): Detected repeat RPC.\n");
  1034. //return;
  1035. }
  1036. else
  1037. rpc_counter = rpc_count;
  1038. dwr(MSG_DEBUG, " handle_retval(): CONN:%x - Mapping [our=%d -> their=%d]\n",conn,
  1039. _phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  1040. /* Check for pre-existing connection for this socket ---
  1041. This block is in response to interesting behaviour from redis-server. A
  1042. socket is created, setsockopt is called and the socket is set to IPV6 but fails (for now),
  1043. then it is closed and re-opened and consequently remapped. With two pipes mapped
  1044. to the same socket, makes it possible that we write to the wrong pipe and fail. So
  1045. this block merely searches for a possible duplicate mapping and erases it
  1046. */
  1047. for(size_t i=0; i<tcp_connections.size(); i++) {
  1048. if(tcp_connections[i] == conn)
  1049. continue;
  1050. if(tcp_connections[i]->rpcSock == conn->rpcSock) {
  1051. if(tcp_connections[i]->perceived_fd == conn->perceived_fd) {
  1052. int n;
  1053. if((n = send(_phy.getDescriptor(tcp_connections[i]->dataSock), "z", 1, MSG_NOSIGNAL)) < 0) {
  1054. dwr(MSG_DEBUG, " handle_retval(): CONN:%x - Socket (%d) already mapped (originally CONN:%x)\n", conn, tcp_connections[i]->perceived_fd, tcp_connections[i]);
  1055. closeConnection(tcp_connections[i]);
  1056. }
  1057. else {
  1058. dwr(MSG_ERROR, " handle_retval(): CONN:%x - This socket is mapped to two different pipes (?). Exiting.\n", conn);
  1059. //die(0); // FIXME: Print service mapping state and exit
  1060. }
  1061. }
  1062. }
  1063. }
  1064. }
  1065. /*
  1066. * Handles an RPC to bind an LWIP PCB to a given address and port
  1067. *
  1068. * @param PhySocket associated with this RPC connection
  1069. * @param structure containing the data and parameters for this client's RPC
  1070. *
  1071. i := should be implemented in intercept lib
  1072. I := is implemented in intercept lib
  1073. X := is implemented in service
  1074. ? := required treatment Unknown
  1075. - := Not needed
  1076. [ ] EACCES - The address is protected, and the user is not the superuser.
  1077. [X] EADDRINUSE - The given address is already in use.
  1078. [I] EBADF - sockfd is not a valid descriptor.
  1079. [X] EINVAL - The socket is already bound to an address.
  1080. [I] ENOTSOCK - sockfd is a descriptor for a file, not a socket.
  1081. [X] ENOMEM - Insufficient kernel memory was available.
  1082. - The following errors are specific to UNIX domain (AF_UNIX) sockets:
  1083. [-] EACCES - Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
  1084. [-] EADDRNOTAVAIL - A nonexistent interface was requested or the requested address was not local.
  1085. [-] EFAULT - addr points outside the user's accessible address space.
  1086. [-] EINVAL - The addrlen is wrong, or the socket was not in the AF_UNIX family.
  1087. [-] ELOOP - Too many symbolic links were encountered in resolving addr.
  1088. [-] ENAMETOOLONG - s addr is too long.
  1089. [-] ENOENT - The file does not exist.
  1090. [-] ENOTDIR - A component of the path prefix is not a directory.
  1091. [-] EROFS - The socket inode would reside on a read-only file system.
  1092. */
  1093. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  1094. {
  1095. struct sockaddr_in *connaddr;
  1096. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  1097. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  1098. ip_addr_t conn_addr;
  1099. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  1100. TcpConnection *conn = getConnectionByTheirFD(sock, bind_rpc->sockfd);
  1101. dwr(MSG_DEBUG, " handle_bind(%d)\n", bind_rpc->sockfd);
  1102. if(conn) {
  1103. if(conn->pcb->state == CLOSED){
  1104. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  1105. if(err != ERR_OK) {
  1106. int ip = connaddr->sin_addr.s_addr;
  1107. unsigned char d[4];
  1108. d[0] = ip & 0xFF;
  1109. d[1] = (ip >> 8) & 0xFF;
  1110. d[2] = (ip >> 16) & 0xFF;
  1111. d[3] = (ip >> 24) & 0xFF;
  1112. dwr(MSG_ERROR, " handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  1113. dwr(MSG_ERROR, " handle_bind(): err = %d\n", err);
  1114. if(err == ERR_USE)
  1115. send_return_value(conn, -1, EADDRINUSE);
  1116. if(err == ERR_MEM)
  1117. send_return_value(conn, -1, ENOMEM);
  1118. if(err == ERR_BUF)
  1119. send_return_value(conn, -1, ENOMEM); // FIXME: Closest match
  1120. }
  1121. else
  1122. send_return_value(conn, ERR_OK, ERR_OK); // Success
  1123. }
  1124. else {
  1125. dwr(MSG_ERROR, " handle_bind(): PCB (%x) not in CLOSED state. Ignoring BIND request.\n", conn->pcb);
  1126. send_return_value(conn, -1, EINVAL);
  1127. }
  1128. }
  1129. else {
  1130. dwr(MSG_ERROR, " handle_bind(): can't locate connection for PCB\n");
  1131. send_return_value(conn, -1, EBADF);
  1132. }
  1133. }
  1134. /*
  1135. * Handles an RPC to put an LWIP PCB into LISTEN mode
  1136. *
  1137. * @param PhySocket associated with this RPC connection
  1138. * @param structure containing the data and parameters for this client's RPC
  1139. *
  1140. i := should be implemented in intercept lib
  1141. I := is implemented in intercept lib
  1142. X := is implemented in service
  1143. ? := required treatment Unknown
  1144. - := Not needed
  1145. [?] EADDRINUSE - Another socket is already listening on the same port.
  1146. [IX] EBADF - The argument sockfd is not a valid descriptor.
  1147. [I] ENOTSOCK - The argument sockfd is not a socket.
  1148. [I] EOPNOTSUPP - The socket is not of a type that supports the listen() operation.
  1149. */
  1150. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  1151. {
  1152. dwr(3, " handle_listen(their=%d):\n", listen_rpc->sockfd);
  1153. TcpConnection *conn = getConnectionByTheirFD(sock, listen_rpc->sockfd);
  1154. if(!conn){
  1155. dwr(MSG_ERROR, " handle_listen(): unable to locate connection object\n");
  1156. // ? send_return_value(conn, -1, EBADF);
  1157. return;
  1158. }
  1159. dwr(3, " handle_listen(our=%d -> their=%d)\n", _phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  1160. if(conn->pcb->state == LISTEN) {
  1161. dwr(MSG_ERROR, " handle_listen(): PCB is already in listening state.\n");
  1162. return;
  1163. }
  1164. struct tcp_pcb* listening_pcb;
  1165. #ifdef TCP_LISTEN_BACKLOG
  1166. listening_pcb = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  1167. #else
  1168. listening_pcb = lwipstack->tcp_listen(conn->pcb);
  1169. #endif
  1170. if(listening_pcb != NULL) {
  1171. conn->pcb = listening_pcb;
  1172. lwipstack->tcp_accept(listening_pcb, nc_accept);
  1173. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  1174. /* we need to wait for the client to send us the fd allocated on their end
  1175. for this listening socket */
  1176. fcntl(_phy.getDescriptor(conn->dataSock), F_SETFL, O_NONBLOCK);
  1177. conn->listening = true;
  1178. conn->pending = true;
  1179. send_return_value(conn, ERR_OK, ERR_OK);
  1180. }
  1181. else {
  1182. /*
  1183. dwr"handle_listen(): unable to allocate memory for new listening PCB\n");
  1184. // FIXME: This does not have an equivalent errno value
  1185. // lwip will reclaim space with a tcp_listen call since a PCB in a LISTEN
  1186. // state takes up less space. If something goes wrong during the creation of a
  1187. // new listening socket we should return an error that implies we can't use this
  1188. // socket, even if the reason isn't describing what really happened internally.
  1189. // See: http://lwip.wikia.com/wiki/Raw/TCP
  1190. send_return_value(conn, -1, EBADF);
  1191. */
  1192. }
  1193. }
  1194. /*
  1195. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  1196. *
  1197. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  1198. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  1199. * is then required to tell the service what new file descriptor it has allocated
  1200. * for this connection. After the mapping is complete, the socket can be used.
  1201. *
  1202. * @param PhySocket associated with this RPC connection
  1203. * @param structure containing the data and parameters for this client's RPC
  1204. *
  1205. i := should be implemented in intercept lib
  1206. I := is implemented in intercept lib
  1207. X := is implemented in service
  1208. ? := required treatment Unknown
  1209. - := Not needed
  1210. [-] EACCES - Permission to create a socket of the specified type and/or protocol is denied.
  1211. [I] EAFNOSUPPORT - The implementation does not support the specified address family.
  1212. [I] EINVAL - Unknown protocol, or protocol family not available.
  1213. [I] EINVAL - Invalid flags in type.
  1214. [I] EMFILE - Process file table overflow.
  1215. [?] ENFILE - The system limit on the total number of open files has been reached.
  1216. [X] ENOBUFS or ENOMEM - Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
  1217. [?] EPROTONOSUPPORT - The protocol type or the specified protocol is not supported within this domain.
  1218. */
  1219. TcpConnection * NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  1220. {
  1221. int rpc_fd = _phy.getDescriptor(sock);
  1222. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  1223. dwr(MSG_DEBUG, " handle_socket(): pcb=%x\n", newpcb);
  1224. if(newpcb != NULL) {
  1225. ZT_PHY_SOCKFD_TYPE fds[2];
  1226. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  1227. if(errno < 0) {
  1228. send_return_value(rpc_fd, -1, errno);
  1229. return NULL;
  1230. }
  1231. }
  1232. dwr(MSG_DEBUG, " handle_socket(): socketpair = {%d, %d}\n", fds[0], fds[1]);
  1233. TcpConnection *new_conn = new TcpConnection();
  1234. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  1235. *uptr = new_conn;
  1236. new_conn->rpcSock = sock;
  1237. new_conn->pcb = newpcb;
  1238. new_conn->their_fd = fds[1];
  1239. tcp_connections.push_back(new_conn);
  1240. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  1241. close(fds[1]); // close other end of socketpair
  1242. // Once the client tells us what its fd is on the other end, we can then complete the mapping
  1243. new_conn->pending = true;
  1244. return new_conn;
  1245. }
  1246. else {
  1247. sock_fd_write(rpc_fd, -1); // Send a bad fd, to signal error
  1248. dwr(MSG_ERROR, " handle_socket(): Memory not available for new PCB\n");
  1249. send_return_value(rpc_fd, -1, ENOMEM);
  1250. return NULL;
  1251. }
  1252. }
  1253. /*
  1254. * Handles an RPC to connect to a given address and port
  1255. *
  1256. * @param PhySocket associated with this RPC connection
  1257. * @param structure containing the data and parameters for this client's RPC
  1258. --- Error handling in this method will only catch problems which are immedately
  1259. apprent. Some errors will need to be caught in the nc_connected(0 callback
  1260. i := should be implemented in intercept lib
  1261. I := is implemented in intercept lib
  1262. X := is implemented in service
  1263. ? := required treatment Unknown
  1264. - := Not needed
  1265. [-] EACCES - For UNIX domain sockets, which are identified by pathname: Write permission is denied ...
  1266. [?] EACCES, EPERM - The user tried to connect to a broadcast address without having the socket broadcast flag enabled ...
  1267. [X] EADDRINUSE - Local address is already in use.
  1268. [I] EAFNOSUPPORT - The passed address didn't have the correct address family in its sa_family field.
  1269. [X] EAGAIN - No more free local ports or insufficient entries in the routing cache.
  1270. [ ] EALREADY - The socket is nonblocking and a previous connection attempt has not yet been completed.
  1271. [IX] EBADF - The file descriptor is not a valid index in the descriptor table.
  1272. [ ] ECONNREFUSED - No-one listening on the remote address.
  1273. [i] EFAULT - The socket structure address is outside the user's address space.
  1274. [ ] EINPROGRESS - The socket is nonblocking and the connection cannot be completed immediately.
  1275. [-] EINTR - The system call was interrupted by a signal that was caught.
  1276. [X] EISCONN - The socket is already connected.
  1277. [X] ENETUNREACH - Network is unreachable.
  1278. [I] ENOTSOCK - The file descriptor is not associated with a socket.
  1279. [X] ETIMEDOUT - Timeout while attempting connection.
  1280. [X] EINVAL - Invalid argument, SVr4, generally makes sense to set this
  1281. *
  1282. */
  1283. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  1284. {
  1285. dwr(MSG_DEBUG, " handle_connect()\n");
  1286. TcpConnection *conn = (TcpConnection*)*uptr;
  1287. struct sockaddr_in *connaddr;
  1288. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  1289. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  1290. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  1291. if(conn != NULL) {
  1292. lwipstack->tcp_sent(conn->pcb, nc_sent);
  1293. lwipstack->tcp_recv(conn->pcb, nc_recved);
  1294. lwipstack->tcp_err(conn->pcb, nc_err);
  1295. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  1296. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  1297. int err = 0;
  1298. if((err = lwipstack->tcp_connect(conn->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  1299. {
  1300. if(err == ERR_ISCONN) {
  1301. send_return_value(conn, -1, EISCONN); // Already in connected state
  1302. return;
  1303. }
  1304. if(err == ERR_USE) {
  1305. send_return_value(conn, -1, EADDRINUSE); // Already in use
  1306. return;
  1307. }
  1308. if(err == ERR_VAL) {
  1309. send_return_value(conn, -1, EINVAL); // Invalid ipaddress parameter
  1310. return;
  1311. }
  1312. if(err == ERR_RTE) {
  1313. send_return_value(conn, -1, ENETUNREACH); // No route to host
  1314. return;
  1315. }
  1316. if(err == ERR_BUF) {
  1317. send_return_value(conn, -1, EAGAIN); // No more ports available
  1318. return;
  1319. }
  1320. if(err == ERR_MEM)
  1321. {
  1322. /* Can occur for the following reasons: tcp_enqueue_flags()
  1323. 1) tcp_enqueue_flags is always called with either SYN or FIN in flags.
  1324. We need one available snd_buf byte to do that.
  1325. This means we can't send FIN while snd_buf==0. A better fix would be to
  1326. not include SYN and FIN sequence numbers in the snd_buf count.
  1327. 2) Cannot allocate new pbuf
  1328. 3) Cannot allocate new TCP segment
  1329. */
  1330. send_return_value(conn, -1, EAGAIN); // FIXME: Doesn't describe the problem well, but closest match
  1331. return;
  1332. }
  1333. // We should only return a value if failure happens immediately
  1334. // Otherwise, we still need to wait for a callback from lwIP.
  1335. // - This is because an ERR_OK from tcp_connect() only verifies
  1336. // that the SYN packet was enqueued onto the stack properly,
  1337. // that's it!
  1338. // - Most instances of a retval for a connect() should happen
  1339. // in the nc_connect() and nc_err() callbacks!
  1340. dwr(MSG_ERROR, " handle_connect(): unable to connect\n");
  1341. send_return_value(conn, -1, EAGAIN);
  1342. }
  1343. // Everything seems to be ok, but we don't have enough info to retval
  1344. conn->pending=true;
  1345. }
  1346. else {
  1347. dwr(MSG_ERROR, " handle_connect(): could not locate PCB based on their fd\n");
  1348. send_return_value(conn, -1, EBADF);
  1349. }
  1350. }
  1351. void NetconEthernetTap::handle_write(TcpConnection *conn)
  1352. {
  1353. //dwr(MSG_DEBUG, " handle_write()\n");
  1354. float max = (float)TCP_SND_BUF;
  1355. int r;
  1356. if(!conn) {
  1357. dwr(MSG_ERROR, " handle_write(): could not locate connection for this fd\n");
  1358. return;
  1359. }
  1360. if(conn->idx < max) {
  1361. if(!conn->pcb) {
  1362. dwr(MSG_ERROR, " handle_write(): conn->pcb == NULL. Failed to write.\n");
  1363. return;
  1364. }
  1365. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  1366. /* PCB send buffer is full,turn off readability notifications for the
  1367. corresponding PhySocket until nc_sent() is called and confirms that there is
  1368. now space on the buffer */
  1369. if(sndbuf == 0) {
  1370. _phy.setNotifyReadable(conn->dataSock, false);
  1371. return;
  1372. }
  1373. if(!conn->listening)
  1374. lwipstack->_tcp_output(conn->pcb);
  1375. if(conn->dataSock) {
  1376. int read_fd = _phy.getDescriptor(conn->dataSock);
  1377. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  1378. conn->idx += r;
  1379. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  1380. * data to LWIP to be enqueued and eventually sent to the network. */
  1381. if(r > 0) {
  1382. int sz;
  1383. // NOTE: this assumes that lwipstack->_lock is locked, either
  1384. // because we are in a callback or have locked it manually.
  1385. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  1386. lwipstack->_tcp_output(conn->pcb);
  1387. if(err != ERR_OK) {
  1388. dwr(MSG_ERROR, " handle_write(): error while writing to PCB, (err = %d)\n", err);
  1389. return;
  1390. }
  1391. else {
  1392. sz = (conn->idx)-r;
  1393. if(sz) {
  1394. memmove(&conn->buf, (conn->buf+r), sz);
  1395. }
  1396. conn->idx -= r;
  1397. conn->written+=r;
  1398. return;
  1399. }
  1400. }
  1401. else {
  1402. dwr(MSG_INFO, " handle_write(): LWIP stack full\n");
  1403. return;
  1404. }
  1405. }
  1406. }
  1407. }
  1408. }
  1409. } // namespace ZeroTier
  1410. #endif // ZT_ENABLE_NETCON