NetconEthernetTap.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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. #define APPLICATION_POLL_FREQ 20
  46. #define ZT_LWIP_TCP_TIMER_INTERVAL 5
  47. #define STATUS_TMR_INTERVAL 3000 // How often we check connection statuses
  48. namespace ZeroTier {
  49. // ---------------------------------------------------------------------------
  50. // Gets the process/path name associated with a pid
  51. static void get_path_from_pid(char* dest, int pid)
  52. {
  53. char ppath[80];
  54. sprintf(ppath, "/proc/%d/exe", pid);
  55. if (readlink (ppath, dest, 80) != -1){
  56. }
  57. }
  58. static err_t tapif_init(struct netif *netif)
  59. {
  60. // Actual init functionality is in addIp() of tap
  61. return ERR_OK;
  62. }
  63. static err_t low_level_output(struct netif *netif, struct pbuf *p)
  64. {
  65. struct pbuf *q;
  66. char buf[ZT_MAX_MTU+32];
  67. char *bufptr;
  68. int tot_len = 0;
  69. ZeroTier::NetconEthernetTap *tap = (ZeroTier::NetconEthernetTap*)netif->state;
  70. /* initiate transfer(); */
  71. bufptr = buf;
  72. for(q = p; q != NULL; q = q->next) {
  73. /* Send the data from the pbuf to the interface, one pbuf at a
  74. time. The size of the data in each pbuf is kept in the ->len
  75. variable. */
  76. /* send data from(q->payload, q->len); */
  77. memcpy(bufptr, q->payload, q->len);
  78. bufptr += q->len;
  79. tot_len += q->len;
  80. }
  81. // [Send packet to network]
  82. // Split ethernet header and feed into handler
  83. struct eth_hdr *ethhdr;
  84. ethhdr = (struct eth_hdr *)buf;
  85. ZeroTier::MAC src_mac;
  86. ZeroTier::MAC dest_mac;
  87. src_mac.setTo(ethhdr->src.addr, 6);
  88. dest_mac.setTo(ethhdr->dest.addr, 6);
  89. tap->_handler(tap->_arg,tap->_nwid,src_mac,dest_mac,
  90. Utils::ntoh((uint16_t)ethhdr->type),0,buf + sizeof(struct eth_hdr),tot_len - sizeof(struct eth_hdr));
  91. return ERR_OK;
  92. }
  93. /*
  94. * TCP connection administered by service
  95. */
  96. class TcpConnection
  97. {
  98. public:
  99. int perceived_fd;
  100. int their_fd;
  101. bool pending;
  102. bool listening;
  103. int pid;
  104. unsigned long written;
  105. unsigned long acked;
  106. PhySocket *rpcSock;
  107. PhySocket *dataSock;
  108. struct tcp_pcb *pcb;
  109. struct sockaddr_storage *addr;
  110. unsigned char buf[DEFAULT_READ_BUFFER_SIZE];
  111. int idx;
  112. };
  113. /*
  114. * A helper class for passing a reference to _phy to LWIP callbacks as a "state"
  115. */
  116. class Larg
  117. {
  118. public:
  119. NetconEthernetTap *tap;
  120. TcpConnection *conn;
  121. Larg(NetconEthernetTap *_tap, TcpConnection *conn) : tap(_tap), conn(conn) {}
  122. };
  123. // ---------------------------------------------------------------------------
  124. NetconEthernetTap::NetconEthernetTap(
  125. const char *homePath,
  126. const MAC &mac,
  127. unsigned int mtu,
  128. unsigned int metric,
  129. uint64_t nwid,
  130. const char *friendlyName,
  131. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  132. void *arg) :
  133. _nwid(nwid),
  134. _handler(handler),
  135. _arg(arg),
  136. _phy(this,false,true),
  137. _unixListenSocket((PhySocket *)0),
  138. _mac(mac),
  139. _homePath(homePath),
  140. _mtu(mtu),
  141. _enabled(true),
  142. _run(true)
  143. {
  144. char sockPath[4096],lwipPath[4096];
  145. rpc_counter = -1;
  146. Utils::snprintf(sockPath,sizeof(sockPath),"%s%snc_%.16llx",homePath,ZT_PATH_SEPARATOR_S,_nwid,ZT_PATH_SEPARATOR_S,(unsigned long long)nwid);
  147. _dev = sockPath; // in netcon mode, set device to be just the network ID
  148. Utils::snprintf(lwipPath,sizeof(lwipPath),"%s%sliblwip.so",homePath,ZT_PATH_SEPARATOR_S);
  149. lwipstack = new LWIPStack(lwipPath);
  150. if(!lwipstack)
  151. throw std::runtime_error("unable to dynamically load a new instance of liblwip.so (searched ZeroTier home path)");
  152. lwipstack->lwip_init();
  153. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  154. dwr(MSG_INFO, " NetconEthernetTap initialized!\n", _phy.getDescriptor(_unixListenSocket));
  155. if (!_unixListenSocket)
  156. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  157. _thread = Thread::start(this);
  158. }
  159. NetconEthernetTap::~NetconEthernetTap()
  160. {
  161. _run = false;
  162. _phy.whack();
  163. _phy.whack();
  164. Thread::join(_thread);
  165. _phy.close(_unixListenSocket,false);
  166. delete lwipstack;
  167. }
  168. void NetconEthernetTap::setEnabled(bool en)
  169. {
  170. _enabled = en;
  171. }
  172. bool NetconEthernetTap::enabled() const
  173. {
  174. return _enabled;
  175. }
  176. bool NetconEthernetTap::addIp(const InetAddress &ip)
  177. {
  178. Mutex::Lock _l(_ips_m);
  179. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  180. _ips.push_back(ip);
  181. std::sort(_ips.begin(),_ips.end());
  182. if (ip.isV4()) {
  183. // Set IP
  184. static ip_addr_t ipaddr, netmask, gw;
  185. IP4_ADDR(&gw,192,168,0,1);
  186. ipaddr.addr = *((u32_t *)ip.rawIpData());
  187. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  188. // Set up the lwip-netif for LWIP's sake
  189. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  190. interface.state = this;
  191. interface.output = lwipstack->_etharp_output;
  192. _mac.copyTo(interface.hwaddr, 6);
  193. interface.mtu = _mtu;
  194. interface.name[0] = 't';
  195. interface.name[1] = 'p';
  196. interface.linkoutput = low_level_output;
  197. interface.hwaddr_len = 6;
  198. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  199. lwipstack->netif_set_default(&interface);
  200. lwipstack->netif_set_up(&interface);
  201. }
  202. }
  203. return true;
  204. }
  205. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  206. {
  207. Mutex::Lock _l(_ips_m);
  208. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  209. if (i == _ips.end())
  210. return false;
  211. _ips.erase(i);
  212. if (ip.isV4()) {
  213. // TODO: dealloc from LWIP
  214. }
  215. return true;
  216. }
  217. std::vector<InetAddress> NetconEthernetTap::ips() const
  218. {
  219. Mutex::Lock _l(_ips_m);
  220. return _ips;
  221. }
  222. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  223. {
  224. struct pbuf *p,*q;
  225. if (!_enabled)
  226. return;
  227. struct eth_hdr ethhdr;
  228. from.copyTo(ethhdr.src.addr, 6);
  229. to.copyTo(ethhdr.dest.addr, 6);
  230. ethhdr.type = Utils::hton((uint16_t)etherType);
  231. // We allocate a pbuf chain of pbufs from the pool.
  232. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  233. if (p != NULL) {
  234. const char *dataptr = reinterpret_cast<const char *>(data);
  235. // First pbuf gets ethernet header at start
  236. q = p;
  237. if (q->len < sizeof(ethhdr)) {
  238. dwr(MSG_ERROR, "_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  239. return;
  240. }
  241. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  242. memcpy((char*)q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  243. dataptr += q->len - sizeof(ethhdr);
  244. // Remaining pbufs (if any) get rest of data
  245. while ((q = q->next)) {
  246. memcpy(q->payload,dataptr,q->len);
  247. dataptr += q->len;
  248. }
  249. } else {
  250. dwr(MSG_ERROR, "put(): Dropped packet: no pbufs available\n");
  251. return;
  252. }
  253. {
  254. Mutex::Lock _l2(lwipstack->_lock);
  255. if(interface.input(p, &interface) != ERR_OK) {
  256. dwr(MSG_ERROR, "put(): Error while RXing packet (netif->input)\n");
  257. }
  258. }
  259. }
  260. std::string NetconEthernetTap::deviceName() const
  261. {
  262. return _dev;
  263. }
  264. void NetconEthernetTap::setFriendlyName(const char *friendlyName) {
  265. }
  266. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  267. {
  268. std::vector<MulticastGroup> newGroups;
  269. Mutex::Lock _l(_multicastGroups_m);
  270. // TODO: get multicast subscriptions from LWIP
  271. std::vector<InetAddress> allIps(ips());
  272. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  273. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  274. std::sort(newGroups.begin(),newGroups.end());
  275. std::unique(newGroups.begin(),newGroups.end());
  276. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  277. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  278. added.push_back(*m);
  279. }
  280. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  281. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  282. removed.push_back(*m);
  283. }
  284. _multicastGroups.swap(newGroups);
  285. }
  286. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(PhySocket *sock, int fd)
  287. {
  288. for(size_t i=0; i<tcp_connections.size(); i++) {
  289. if(tcp_connections[i]->perceived_fd == fd && tcp_connections[i]->rpcSock == sock)
  290. return tcp_connections[i];
  291. }
  292. return NULL;
  293. }
  294. /*
  295. * Dumps service state in 80x25 when debug mode is off
  296. */
  297. void NetconEthernetTap::compact_dump()
  298. {
  299. /*
  300. clearscreen();
  301. gotoxy(0,0);
  302. fprintf(stderr, "ZeroTier - Network Containers Service [State Dump]\n\r");
  303. fprintf(stderr, " RPC Sockets = %d\n\r", rpc_sockets.size());
  304. fprintf(stderr, " TCP Connections = %d\n\r", tcp_connections.size());
  305. for(size_t i=0; i<rpc_sockets.size(); i++) {
  306. int rpc_fd = _phy.getDescriptor(rpc_sockets[i]);
  307. char buf[80];
  308. int pid = pidmap[rpc_sockets[i]];
  309. memset(&buf, '\0', 80);
  310. get_path_from_pid(buf, pid);
  311. fprintf(stderr, "\n Client(addr=0x%x, rpc=%d, pid=%d) %s\n", rpc_sockets[i], rpc_fd, pid, buf);
  312. for(size_t j=0; j<tcp_connections.size(); j++) {
  313. memset(&buf, '\0', 80);
  314. get_path_from_pid(buf, tcp_connections[j]->pid);
  315. if(tcp_connections[j]->rpcSock==rpc_sockets[i]) {
  316. fprintf(stderr, "\t\tpath\t\t= %s\n", buf);
  317. }
  318. }
  319. }
  320. */
  321. for(size_t i=0; i<rpc_sockets.size(); i++) {
  322. fprintf(stderr, "\n\n\nrpc(%d)\n", _phy.getDescriptor(rpc_sockets[i]));
  323. for(size_t j=0; j<tcp_connections.size(); j++) {
  324. if(_phy.getDescriptor(tcp_connections[j]->rpcSock) == _phy.getDescriptor(rpc_sockets[i]))
  325. fprintf(stderr, "\t(%d) ----> (%d)\n\n", _phy.getDescriptor(tcp_connections[j]->dataSock), tcp_connections[j]->perceived_fd);
  326. }
  327. }
  328. }
  329. /*
  330. * Dumps service state
  331. */
  332. void NetconEthernetTap::dump()
  333. {
  334. fprintf(stderr, "\n\n---\n\ndie(): BEGIN SERVICE STATE DUMP\n");
  335. fprintf(stderr, "*** IF YOU SEE THIS, EMAIL THE DUMP TEXT TO [email protected] ***\n");
  336. fprintf(stderr, " tcp_conns = %lu, rpc_socks = %lu\n", tcp_connections.size(), rpc_sockets.size());
  337. // TODO: Add logic to detect bad mapping conditions
  338. for(size_t i=0; i<rpc_sockets.size(); i++) {
  339. for(size_t j=0; j<rpc_sockets.size(); j++) {
  340. if(j != i && rpc_sockets[i] == rpc_sockets[j]) {
  341. fprintf(stderr, "Duplicate PhySockets found! (0x%p)\n", rpc_sockets[i]);
  342. }
  343. }
  344. }
  345. // Dump the state of the service mapping
  346. for(size_t i=0; i<rpc_sockets.size(); i++) {
  347. int rpc_fd = _phy.getDescriptor(rpc_sockets[i]);
  348. char buf[80];
  349. int pid = pidmap[rpc_sockets[i]];
  350. get_path_from_pid(buf, pid);
  351. fprintf(stderr, "\nClient(addr=0x%p, rpc=%d, pid=%d) %s\n", rpc_sockets[i], rpc_fd, pid, buf);
  352. for(size_t j=0; j<tcp_connections.size(); j++) {
  353. get_path_from_pid(buf, tcp_connections[j]->pid);
  354. if(tcp_connections[j]->rpcSock==rpc_sockets[i]){
  355. fprintf(stderr, " |\n");
  356. fprintf(stderr, " |-Connection(0x%p):\n", tcp_connections[j]);
  357. fprintf(stderr, " | path\t\t\t= %s\n", buf);
  358. fprintf(stderr, " | perceived_fd\t\t= %d\t(fd)\n", tcp_connections[j]->perceived_fd);
  359. fprintf(stderr, " | their_fd\t\t= %d\t(fd)\n", tcp_connections[j]->their_fd);
  360. fprintf(stderr, " | dataSock(0x%p)\t= %d\t(fd)\n", tcp_connections[j]->dataSock, _phy.getDescriptor(tcp_connections[j]->dataSock));
  361. fprintf(stderr, " | rpcSock(0x%p)\t= %d\t(fd)\n", tcp_connections[j]->rpcSock, _phy.getDescriptor(tcp_connections[j]->rpcSock));
  362. fprintf(stderr, " | pending\t\t= %d\n", tcp_connections[j]->pending);
  363. fprintf(stderr, " | listening\t\t= %d\n", tcp_connections[j]->listening);
  364. fprintf(stderr, " \\------pcb(0x%p)->state\t= %d\n", tcp_connections[j]->pcb, tcp_connections[j]->pcb->state);
  365. }
  366. }
  367. }
  368. fprintf(stderr, "\n\ndie(): END SERVICE STATE DUMP\n\n---\n\n");
  369. }
  370. /*
  371. * Dumps service state and then exits
  372. */
  373. void NetconEthernetTap::die(int exret) {
  374. dump();
  375. exit(exret);
  376. }
  377. /*
  378. * Closes a TcpConnection and associated LWIP PCB strcuture.
  379. */
  380. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  381. {
  382. if(!conn)
  383. return;
  384. dwr(MSG_DEBUG, " closeConnection(%x, %d)\n", conn->pcb, _phy.getDescriptor(conn->dataSock));
  385. //lwipstack->_tcp_sent(conn->pcb, NULL);
  386. //lwipstack->_tcp_recv(conn->pcb, NULL);
  387. //lwipstack->_tcp_err(conn->pcb, NULL);
  388. //lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  389. //lwipstack->_tcp_arg(conn->pcb, NULL);
  390. if(lwipstack->_tcp_close(conn->pcb) != ERR_OK) {
  391. dwr(MSG_ERROR, " closeConnection(): Error while calling tcp_close()\n");
  392. exit(0);
  393. }
  394. else {
  395. if(conn->dataSock) {
  396. close(_phy.getDescriptor(conn->dataSock));
  397. _phy.close(conn->dataSock,false);
  398. }
  399. /* Eventually we might want to use a map here instead */
  400. for(int i=0; i<tcp_connections.size(); i++) {
  401. if(tcp_connections[i] == conn) {
  402. tcp_connections.erase(tcp_connections.begin() + i);
  403. delete conn;
  404. break;
  405. }
  406. }
  407. }
  408. }
  409. /*
  410. * Close a single RPC connection and associated PhySocket
  411. */
  412. void NetconEthernetTap::closeClient(PhySocket *sock)
  413. {
  414. for(size_t i=0; i<rpc_sockets.size(); i++) {
  415. if(rpc_sockets[i] == sock){
  416. rpc_sockets.erase(rpc_sockets.begin() + i);
  417. break;
  418. }
  419. }
  420. close(_phy.getDescriptor(sock));
  421. _phy.close(sock);
  422. }
  423. /*
  424. * Close all RPC and TCP connections
  425. */
  426. void NetconEthernetTap::closeAll()
  427. {
  428. while(rpc_sockets.size())
  429. closeClient(rpc_sockets.front());
  430. while(tcp_connections.size())
  431. closeConnection(tcp_connections.front());
  432. }
  433. #include <sys/resource.h>
  434. void NetconEthernetTap::threadMain()
  435. throw()
  436. {
  437. uint64_t prev_tcp_time = 0;
  438. uint64_t prev_status_time = 0;
  439. uint64_t prev_etharp_time = 0;
  440. /*
  441. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  442. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  443. fprintf(stderr, "- PBUF_POOL_BUFSIZE = %d\n", PBUF_POOL_BUFSIZE);
  444. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  445. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  446. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  447. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n\n", MEMP_NUM_TCP_SEG);
  448. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  449. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n\n", TCP_SND_QUEUELEN);
  450. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  451. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  452. fprintf(stderr, "- TCP_MAXRTX = %d\n", TCP_MAXRTX);
  453. fprintf(stderr, "- IP_REASSEMBLY = %d\n\n", IP_REASSEMBLY);
  454. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  455. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  456. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  457. */
  458. // Main timer loop
  459. while (_run) {
  460. uint64_t now = OSUtils::now();
  461. uint64_t since_tcp = now - prev_tcp_time;
  462. uint64_t since_etharp = now - prev_etharp_time;
  463. uint64_t since_status = now - prev_status_time;
  464. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  465. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  466. uint64_t status_remaining = STATUS_TMR_INTERVAL;
  467. // Connection prunning
  468. if (since_status >= STATUS_TMR_INTERVAL) {
  469. //compact_dump();
  470. prev_status_time = now;
  471. status_remaining = STATUS_TMR_INTERVAL - since_status;
  472. if(rpc_sockets.size() || tcp_connections.size()) {
  473. // dump();
  474. // Here we will periodically check the list of rpc_sockets for those that
  475. // do not currently have any data connection associated with them. If they are
  476. // unused, then we will try to read from them, if they fail, we can safely assume
  477. // that the client has closed their end and we can close ours
  478. for(size_t i = 0; i<tcp_connections.size(); i++) {
  479. if(tcp_connections[i]->listening) {
  480. char c;
  481. if (read(_phy.getDescriptor(tcp_connections[i]->dataSock), &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. switch(err)
  834. {
  835. case ERR_MEM:
  836. dwr(MSG_ERROR, "nc_err(): ERR_MEM->ENOMEM\n");
  837. l->tap->send_return_value(l->conn, -1, ENOMEM);
  838. break;
  839. case ERR_BUF:
  840. dwr(MSG_ERROR, "nc_err(): ERR_BUF->ENOBUFS\n");
  841. l->tap->send_return_value(l->conn, -1, ENOBUFS);
  842. break;
  843. case ERR_TIMEOUT:
  844. dwr(MSG_ERROR, "nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  845. l->tap->send_return_value(l->conn, -1, ETIMEDOUT);
  846. break;
  847. case ERR_RTE:
  848. dwr(MSG_ERROR, "nc_err(): ERR_RTE->ENETUNREACH\n");
  849. l->tap->send_return_value(l->conn, -1, ENETUNREACH);
  850. break;
  851. case ERR_INPROGRESS:
  852. dwr(MSG_ERROR, "nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  853. l->tap->send_return_value(l->conn, -1, EINPROGRESS);
  854. break;
  855. case ERR_VAL:
  856. dwr(MSG_ERROR, "nc_err(): ERR_VAL->EINVAL\n");
  857. l->tap->send_return_value(l->conn, -1, EINVAL);
  858. break;
  859. case ERR_WOULDBLOCK:
  860. dwr(MSG_ERROR, "nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  861. l->tap->send_return_value(l->conn, -1, EWOULDBLOCK);
  862. break;
  863. case ERR_USE:
  864. dwr(MSG_ERROR, "nc_err(): ERR_USE->EADDRINUSE\n");
  865. l->tap->send_return_value(l->conn, -1, EADDRINUSE);
  866. break;
  867. case ERR_ISCONN:
  868. dwr(MSG_ERROR, "nc_err(): ERR_ISCONN->EISCONN\n");
  869. l->tap->send_return_value(l->conn, -1, EISCONN);
  870. break;
  871. case ERR_ABRT:
  872. dwr(MSG_ERROR, "nc_err(): ERR_ABRT->ECONNREFUSED\n");
  873. l->tap->send_return_value(l->conn, -1, ECONNREFUSED);
  874. break;
  875. // FIXME: Below are errors which don't have a standard errno correlate
  876. case ERR_RST:
  877. l->tap->send_return_value(l->conn, -1, -1);
  878. break;
  879. case ERR_CLSD:
  880. l->tap->send_return_value(l->conn, -1, -1);
  881. break;
  882. case ERR_CONN:
  883. l->tap->send_return_value(l->conn, -1, -1);
  884. break;
  885. case ERR_ARG:
  886. l->tap->send_return_value(l->conn, -1, -1);
  887. break;
  888. case ERR_IF:
  889. l->tap->send_return_value(l->conn, -1, -1);
  890. break;
  891. default:
  892. break;
  893. }
  894. dwr(MSG_ERROR, "nc_err(): closing connection\n");
  895. l->tap->closeConnection(l->conn);
  896. }
  897. /*
  898. * Callback from LWIP to do whatever work we might need to do.
  899. *
  900. * @param associated service state object
  901. * @param PCB we're polling on
  902. * @return ERR_OK if everything is ok, -1 otherwise
  903. *
  904. */
  905. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  906. {
  907. return ERR_OK;
  908. }
  909. /*
  910. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  911. * As a result, we should put our socket back into a notify-on-readability state
  912. * since there is now room on the PCB buffer to write to.
  913. *
  914. * NOTE: This could be used to track the amount of data sent by a connection.
  915. *
  916. * @param associated service state object
  917. * @param relevant PCB
  918. * @param length of data sent
  919. * @return ERR_OK if everything is ok, -1 otherwise
  920. *
  921. */
  922. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  923. {
  924. //dwr(5, " nc_sent()\n");
  925. Larg *l = (Larg*)arg;
  926. if(len) {
  927. l->conn->acked+=len;
  928. //dwr("W = %d, A = %d\n", l->conn->written, l->conn->acked);
  929. //dwr("ACK = %d\n", len);
  930. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  931. l->tap->_phy.whack();
  932. }
  933. return ERR_OK;
  934. }
  935. /*
  936. * Callback from LWIP which sends a return value to the client to signal that
  937. * a connection was established for this PCB
  938. *
  939. * @param associated service state object
  940. * @param relevant PCB
  941. * @param error code
  942. * @return ERR_OK if everything is ok, -1 otherwise
  943. *
  944. */
  945. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  946. {
  947. dwr(MSG_DEBUG, " nc_connected()\n");
  948. Larg *l = (Larg*)arg;
  949. l->tap->send_return_value(l->conn, ERR_OK);
  950. return ERR_OK;
  951. }
  952. /*------------------------------------------------------------------------------
  953. ----------------------------- RPC Handler functions ----------------------------
  954. ------------------------------------------------------------------------------*/
  955. /* Unpacks the buffer from an RPC command */
  956. void NetconEthernetTap::unload_rpc(void *data, pid_t &pid, pid_t &tid, int &rpc_count, char (timestamp[20]), char &cmd, void* &payload)
  957. {
  958. unsigned char *buf = (unsigned char*)data;
  959. memcpy(&pid, &buf[IDX_PID], sizeof(pid_t));
  960. memcpy(&tid, &buf[IDX_TID], sizeof(pid_t));
  961. memcpy(&rpc_count, &buf[IDX_COUNT], sizeof(int));
  962. memcpy(timestamp, &buf[IDX_TIME], 20);
  963. memcpy(&cmd, &buf[IDX_PAYLOAD], sizeof(char));
  964. }
  965. /*
  966. Responds to a request from the [intercept] to determine whether a local socket is
  967. mapped to this service. In other words, how do the intercept's overridden calls
  968. tell the difference between regular AF_LOCAL sockets and one of our socketpairs
  969. that is used to communicate over the network?
  970. */
  971. void NetconEthernetTap::handle_map_request(PhySocket *sock, void **uptr, unsigned char* buf)
  972. {
  973. dwr(4, " handle_map_request()\n");
  974. TcpConnection *conn = (TcpConnection*)*uptr;
  975. int req_fd;
  976. memcpy(&req_fd, &buf[IDX_PAYLOAD+1], sizeof(req_fd));
  977. for(size_t i=0; i<tcp_connections.size(); i++) {
  978. if(tcp_connections[i]->rpcSock == conn->rpcSock && tcp_connections[i]->perceived_fd == req_fd){
  979. send_return_value(conn, 1, ERR_OK); // True
  980. dwr(MSG_DEBUG, " handle_map_request(their=%d): MAPPED (to %d)\n", req_fd,
  981. _phy.getDescriptor(tcp_connections[i]->dataSock));
  982. return;
  983. }
  984. }
  985. send_return_value(conn, 0, ERR_OK); // False
  986. dwr(MSG_DEBUG, " handle_map_request(their=%d): NOT MAPPED\n", req_fd);
  987. }
  988. /**
  989. * Handles a return value (client's perceived fd) and completes a mapping
  990. * so that we know what connection an RPC call should be associated with.
  991. *
  992. * @param PhySocket associated with this RPC connection
  993. * @param structure containing the data and parameters for this client's RPC
  994. *
  995. */
  996. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, int rpc_count, int newfd)
  997. {
  998. dwr(MSG_DEBUG, " handle_retval()\n");
  999. TcpConnection *conn = (TcpConnection*)*uptr;
  1000. if(!conn->pending){
  1001. send_return_value(conn, -1, -1);
  1002. return;
  1003. }
  1004. conn->pending = false;
  1005. conn->perceived_fd = newfd;
  1006. if(rpc_count==rpc_counter) {
  1007. dwr(MSG_ERROR, " handle_retval(): Detected repeat RPC.\n");
  1008. send_return_value(conn, -1, -1);
  1009. //return;
  1010. }
  1011. else
  1012. rpc_counter = rpc_count;
  1013. dwr(MSG_DEBUG, " handle_retval(): CONN:%x - Mapping [our=%d -> their=%d]\n",conn,
  1014. _phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  1015. /* Check for pre-existing connection for this socket ---
  1016. This block is in response to interesting behaviour from redis-server. A
  1017. socket is created, setsockopt is called and the socket is set to IPV6 but fails (for now),
  1018. then it is closed and re-opened and consequently remapped. With two pipes mapped
  1019. to the same socket, makes it possible that we write to the wrong pipe and fail. So
  1020. this block merely searches for a possible duplicate mapping and erases it
  1021. */
  1022. for(size_t i=0; i<tcp_connections.size(); i++) {
  1023. if(tcp_connections[i] == conn)
  1024. continue;
  1025. if(tcp_connections[i]->rpcSock == conn->rpcSock) {
  1026. if(tcp_connections[i]->perceived_fd == conn->perceived_fd) {
  1027. int n;
  1028. if((n = send(_phy.getDescriptor(tcp_connections[i]->dataSock), "z", 1, MSG_NOSIGNAL)) < 0) {
  1029. dwr(MSG_DEBUG, " handle_retval(): CONN:%x - Socket (%d) already mapped (originally CONN:%x)\n", conn, tcp_connections[i]->perceived_fd, tcp_connections[i]);
  1030. closeConnection(tcp_connections[i]);
  1031. }
  1032. else {
  1033. dwr(MSG_ERROR, " handle_retval(): CONN:%x - This socket is mapped to two different pipes (?). Exiting.\n", conn);
  1034. //die(0); // FIXME: Print service mapping state and exit
  1035. }
  1036. }
  1037. }
  1038. }
  1039. send_return_value(conn, ERR_OK, ERR_OK); // Success
  1040. }
  1041. /* Return the address that the socket is bound to */
  1042. void NetconEthernetTap::handle_getsockname(PhySocket *sock, void **uptr, struct getsockname_st *getsockname_rpc)
  1043. {
  1044. TcpConnection *conn = getConnectionByTheirFD(sock, getsockname_rpc->sockfd);
  1045. dwr(MSG_DEBUG, " handle_getsockname(): sockfd = %d\n", getsockname_rpc->sockfd);
  1046. dwr(MSG_DEBUG, " handle_getsockname(): conn = 0x%x\n", conn);
  1047. /*
  1048. if(!conn){
  1049. return;
  1050. }
  1051. struct sockaddr_in * myaddr = (struct sockaddr_in*)conn->addr;
  1052. int port = myaddr->sin_port;
  1053. int ip = myaddr->sin_addr.s_addr;
  1054. unsigned char d[4];
  1055. d[0] = ip & 0xFF;
  1056. d[1] = (ip >> 8) & 0xFF;
  1057. d[2] = (ip >> 16) & 0xFF;
  1058. d[3] = (ip >> 24) & 0xFF;
  1059. dwr(MSG_ERROR, " handle_getsockname(): addr = %d.%d.%d.%d: %d\n", d[0],d[1],d[2],d[3], lwipstack->ntohs(port));
  1060. */
  1061. // Assemble address "command" to send to intercept
  1062. char retmsg[sizeof(struct sockaddr_storage)];
  1063. memset(&retmsg, 0, sizeof(retmsg));
  1064. if ((conn)&&(conn->addr))
  1065. memcpy(&retmsg, conn->addr, sizeof(struct sockaddr_storage));
  1066. int n = write(_phy.getDescriptor(conn->rpcSock), &retmsg, sizeof(struct sockaddr_storage));
  1067. dwr(MSG_DEBUG, " handle_getsockname(): wrote %d bytes\n", n);
  1068. }
  1069. /*
  1070. * Handles an RPC to bind an LWIP PCB to a given address and port
  1071. *
  1072. * @param PhySocket associated with this RPC connection
  1073. * @param structure containing the data and parameters for this client's RPC
  1074. *
  1075. i := should be implemented in intercept lib
  1076. I := is implemented in intercept lib
  1077. X := is implemented in service
  1078. ? := required treatment Unknown
  1079. - := Not needed
  1080. [ ] EACCES - The address is protected, and the user is not the superuser.
  1081. [X] EADDRINUSE - The given address is already in use.
  1082. [I] EBADF - sockfd is not a valid descriptor.
  1083. [X] EINVAL - The socket is already bound to an address.
  1084. [I] ENOTSOCK - sockfd is a descriptor for a file, not a socket.
  1085. [X] ENOMEM - Insufficient kernel memory was available.
  1086. - The following errors are specific to UNIX domain (AF_UNIX) sockets:
  1087. [-] EACCES - Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
  1088. [-] EADDRNOTAVAIL - A nonexistent interface was requested or the requested address was not local.
  1089. [-] EFAULT - addr points outside the user's accessible address space.
  1090. [-] EINVAL - The addrlen is wrong, or the socket was not in the AF_UNIX family.
  1091. [-] ELOOP - Too many symbolic links were encountered in resolving addr.
  1092. [-] ENAMETOOLONG - s addr is too long.
  1093. [-] ENOENT - The file does not exist.
  1094. [-] ENOTDIR - A component of the path prefix is not a directory.
  1095. [-] EROFS - The socket inode would reside on a read-only file system.
  1096. */
  1097. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  1098. {
  1099. struct sockaddr_in *connaddr;
  1100. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  1101. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  1102. ip_addr_t conn_addr;
  1103. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  1104. TcpConnection *conn = getConnectionByTheirFD(sock, bind_rpc->sockfd);
  1105. dwr(MSG_DEBUG, " handle_bind(%d)\n", bind_rpc->sockfd);
  1106. if(conn) {
  1107. if(conn->pcb->state == CLOSED){
  1108. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  1109. int ip = connaddr->sin_addr.s_addr;
  1110. unsigned char d[4];
  1111. d[0] = ip & 0xFF;
  1112. d[1] = (ip >> 8) & 0xFF;
  1113. d[2] = (ip >> 16) & 0xFF;
  1114. d[3] = (ip >> 24) & 0xFF;
  1115. dwr(MSG_DEBUG, " handle_bind(): %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  1116. if(err != ERR_OK) {
  1117. dwr(MSG_ERROR, " handle_bind(): err = %d\n", err);
  1118. if(err == ERR_USE)
  1119. send_return_value(conn, -1, EADDRINUSE);
  1120. if(err == ERR_MEM)
  1121. send_return_value(conn, -1, ENOMEM);
  1122. if(err == ERR_BUF)
  1123. send_return_value(conn, -1, ENOMEM); // FIXME: Closest match
  1124. }
  1125. else {
  1126. conn->addr = (struct sockaddr_storage *) &bind_rpc->addr;
  1127. send_return_value(conn, ERR_OK, ERR_OK); // Success
  1128. }
  1129. }
  1130. else {
  1131. dwr(MSG_ERROR, " handle_bind(): PCB (%x) not in CLOSED state. Ignoring BIND request.\n", conn->pcb);
  1132. send_return_value(conn, -1, EINVAL);
  1133. }
  1134. }
  1135. else {
  1136. dwr(MSG_ERROR, " handle_bind(): can't locate connection for PCB\n");
  1137. send_return_value(conn, -1, EBADF);
  1138. }
  1139. }
  1140. /*
  1141. * Handles an RPC to put an LWIP PCB into LISTEN mode
  1142. *
  1143. * @param PhySocket associated with this RPC connection
  1144. * @param structure containing the data and parameters for this client's RPC
  1145. *
  1146. i := should be implemented in intercept lib
  1147. I := is implemented in intercept lib
  1148. X := is implemented in service
  1149. ? := required treatment Unknown
  1150. - := Not needed
  1151. [?] EADDRINUSE - Another socket is already listening on the same port.
  1152. [IX] EBADF - The argument sockfd is not a valid descriptor.
  1153. [I] ENOTSOCK - The argument sockfd is not a socket.
  1154. [I] EOPNOTSUPP - The socket is not of a type that supports the listen() operation.
  1155. */
  1156. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  1157. {
  1158. dwr(3, " handle_listen(their=%d):\n", listen_rpc->sockfd);
  1159. TcpConnection *conn = getConnectionByTheirFD(sock, listen_rpc->sockfd);
  1160. if(!conn){
  1161. dwr(MSG_ERROR, " handle_listen(): unable to locate connection object\n");
  1162. send_return_value(conn, -1, EBADF);
  1163. return;
  1164. }
  1165. dwr(3, " handle_listen(our=%d -> their=%d)\n", _phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  1166. if(conn->pcb->state == LISTEN) {
  1167. dwr(MSG_ERROR, " handle_listen(): PCB is already in listening state.\n");
  1168. send_return_value(conn, ERR_OK, ERR_OK);
  1169. return;
  1170. }
  1171. struct tcp_pcb* listening_pcb;
  1172. #ifdef TCP_LISTEN_BACKLOG
  1173. listening_pcb = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  1174. #else
  1175. listening_pcb = lwipstack->tcp_listen(conn->pcb);
  1176. #endif
  1177. if(listening_pcb != NULL) {
  1178. conn->pcb = listening_pcb;
  1179. lwipstack->tcp_accept(listening_pcb, nc_accept);
  1180. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  1181. /* we need to wait for the client to send us the fd allocated on their end
  1182. for this listening socket */
  1183. fcntl(_phy.getDescriptor(conn->dataSock), F_SETFL, O_NONBLOCK);
  1184. conn->listening = true;
  1185. conn->pending = true;
  1186. send_return_value(conn, ERR_OK, ERR_OK);
  1187. return;
  1188. }
  1189. send_return_value(conn, -1, -1);
  1190. }
  1191. /*
  1192. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  1193. *
  1194. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  1195. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  1196. * is then required to tell the service what new file descriptor it has allocated
  1197. * for this connection. After the mapping is complete, the socket can be used.
  1198. *
  1199. * @param PhySocket associated with this RPC connection
  1200. * @param structure containing the data and parameters for this client's RPC
  1201. *
  1202. i := should be implemented in intercept lib
  1203. I := is implemented in intercept lib
  1204. X := is implemented in service
  1205. ? := required treatment Unknown
  1206. - := Not needed
  1207. [-] EACCES - Permission to create a socket of the specified type and/or protocol is denied.
  1208. [I] EAFNOSUPPORT - The implementation does not support the specified address family.
  1209. [I] EINVAL - Unknown protocol, or protocol family not available.
  1210. [I] EINVAL - Invalid flags in type.
  1211. [I] EMFILE - Process file table overflow.
  1212. [?] ENFILE - The system limit on the total number of open files has been reached.
  1213. [X] ENOBUFS or ENOMEM - Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
  1214. [?] EPROTONOSUPPORT - The protocol type or the specified protocol is not supported within this domain.
  1215. */
  1216. TcpConnection * NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  1217. {
  1218. int rpc_fd = _phy.getDescriptor(sock);
  1219. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  1220. dwr(MSG_DEBUG, " handle_socket(): pcb=%x\n", newpcb);
  1221. if(newpcb != NULL) {
  1222. ZT_PHY_SOCKFD_TYPE fds[2];
  1223. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  1224. if(errno < 0) {
  1225. send_return_value(rpc_fd, -1, errno);
  1226. return NULL;
  1227. }
  1228. }
  1229. dwr(MSG_DEBUG, " handle_socket(): socketpair = {%d, %d}\n", fds[0], fds[1]);
  1230. TcpConnection *new_conn = new TcpConnection();
  1231. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  1232. *uptr = new_conn;
  1233. new_conn->rpcSock = sock;
  1234. new_conn->pcb = newpcb;
  1235. new_conn->their_fd = fds[1];
  1236. tcp_connections.push_back(new_conn);
  1237. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  1238. close(fds[1]); // close other end of socketpair
  1239. // Once the client tells us what its fd is on the other end, we can then complete the mapping
  1240. new_conn->pending = true;
  1241. return new_conn;
  1242. }
  1243. sock_fd_write(rpc_fd, -1); // Send a bad fd, to signal error
  1244. dwr(MSG_ERROR, " handle_socket(): Memory not available for new PCB\n");
  1245. send_return_value(rpc_fd, -1, ENOMEM);
  1246. return NULL;
  1247. }
  1248. /*
  1249. * Handles an RPC to connect to a given address and port
  1250. *
  1251. * @param PhySocket associated with this RPC connection
  1252. * @param structure containing the data and parameters for this client's RPC
  1253. --- Error handling in this method will only catch problems which are immedately
  1254. apprent. Some errors will need to be caught in the nc_connected(0 callback
  1255. i := should be implemented in intercept lib
  1256. I := is implemented in intercept lib
  1257. X := is implemented in service
  1258. ? := required treatment Unknown
  1259. - := Not needed
  1260. [-] EACCES - For UNIX domain sockets, which are identified by pathname: Write permission is denied ...
  1261. [?] EACCES, EPERM - The user tried to connect to a broadcast address without having the socket broadcast flag enabled ...
  1262. [X] EADDRINUSE - Local address is already in use.
  1263. [I] EAFNOSUPPORT - The passed address didn't have the correct address family in its sa_family field.
  1264. [X] EAGAIN - No more free local ports or insufficient entries in the routing cache.
  1265. [ ] EALREADY - The socket is nonblocking and a previous connection attempt has not yet been completed.
  1266. [IX] EBADF - The file descriptor is not a valid index in the descriptor table.
  1267. [ ] ECONNREFUSED - No-one listening on the remote address.
  1268. [i] EFAULT - The socket structure address is outside the user's address space.
  1269. [ ] EINPROGRESS - The socket is nonblocking and the connection cannot be completed immediately.
  1270. [-] EINTR - The system call was interrupted by a signal that was caught.
  1271. [X] EISCONN - The socket is already connected.
  1272. [X] ENETUNREACH - Network is unreachable.
  1273. [I] ENOTSOCK - The file descriptor is not associated with a socket.
  1274. [X] ETIMEDOUT - Timeout while attempting connection.
  1275. [X] EINVAL - Invalid argument, SVr4, generally makes sense to set this
  1276. *
  1277. */
  1278. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  1279. {
  1280. dwr(MSG_DEBUG, " handle_connect()\n");
  1281. TcpConnection *conn = (TcpConnection*)*uptr;
  1282. struct sockaddr_in *connaddr;
  1283. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  1284. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  1285. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  1286. if(conn != NULL) {
  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. }
  1341. else {
  1342. dwr(MSG_ERROR, " handle_connect(): could not locate PCB based on their fd\n");
  1343. send_return_value(conn, -1, EBADF);
  1344. }
  1345. }
  1346. void NetconEthernetTap::handle_write(TcpConnection *conn)
  1347. {
  1348. float max = (float)TCP_SND_BUF;
  1349. int r;
  1350. if(!conn) {
  1351. dwr(MSG_ERROR, " handle_write(): could not locate connection for this fd\n");
  1352. return;
  1353. }
  1354. if(conn->idx < max) {
  1355. if(!conn->pcb) {
  1356. dwr(MSG_ERROR, " handle_write(): conn->pcb == NULL. Failed to write.\n");
  1357. return;
  1358. }
  1359. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  1360. /* PCB send buffer is full,turn off readability notifications for the
  1361. corresponding PhySocket until nc_sent() is called and confirms that there is
  1362. now space on the buffer */
  1363. if(sndbuf == 0) {
  1364. _phy.setNotifyReadable(conn->dataSock, false);
  1365. return;
  1366. }
  1367. if(!conn->listening)
  1368. lwipstack->_tcp_output(conn->pcb);
  1369. if(conn->dataSock) {
  1370. int read_fd = _phy.getDescriptor(conn->dataSock);
  1371. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  1372. conn->idx += r;
  1373. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  1374. * data to LWIP to be enqueued and eventually sent to the network. */
  1375. if(r > 0) {
  1376. int sz;
  1377. // NOTE: this assumes that lwipstack->_lock is locked, either
  1378. // because we are in a callback or have locked it manually.
  1379. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  1380. lwipstack->_tcp_output(conn->pcb);
  1381. if(err != ERR_OK) {
  1382. dwr(MSG_ERROR, " handle_write(): error while writing to PCB, (err = %d)\n", err);
  1383. return;
  1384. }
  1385. else {
  1386. sz = (conn->idx)-r;
  1387. if(sz) {
  1388. memmove(&conn->buf, (conn->buf+r), sz);
  1389. }
  1390. conn->idx -= r;
  1391. conn->written+=r;
  1392. return;
  1393. }
  1394. }
  1395. else {
  1396. dwr(MSG_INFO, " handle_write(): LWIP stack full\n");
  1397. return;
  1398. }
  1399. }
  1400. }
  1401. }
  1402. }
  1403. } // namespace ZeroTier