NetconEthernetTap.cpp 51 KB

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