NetconEthernetTap.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifdef ZT_ENABLE_NETCON
  28. #include <algorithm>
  29. #include <utility>
  30. #include <dlfcn.h>
  31. #include "NetconEthernetTap.hpp"
  32. #include "../node/Utils.hpp"
  33. #include "../osdep/OSUtils.hpp"
  34. #include "../osdep/Phy.hpp"
  35. #include "lwip/tcp_impl.h"
  36. #include "netif/etharp.h"
  37. #include "lwip/ip.h"
  38. #include "lwip/ip_addr.h"
  39. #include "lwip/ip_frag.h"
  40. #include "lwip/tcp.h"
  41. #include "LWIPStack.hpp"
  42. #include "NetconService.hpp"
  43. #include "Intercept.h"
  44. #include "NetconUtilities.hpp"
  45. #define APPLICATION_POLL_FREQ 1
  46. #define ZT_LWIP_TCP_TIMER_INTERVAL 10
  47. #define STATUS_TMR_INTERVAL 1000
  48. namespace ZeroTier {
  49. NetconEthernetTap::NetconEthernetTap(
  50. const char *homePath,
  51. const MAC &mac,
  52. unsigned int mtu,
  53. unsigned int metric,
  54. uint64_t nwid,
  55. const char *friendlyName,
  56. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  57. void *arg) :
  58. _phy(this,false,true),
  59. _unixListenSocket((PhySocket *)0),
  60. _handler(handler),
  61. _arg(arg),
  62. _nwid(nwid),
  63. _mac(mac),
  64. _homePath(homePath),
  65. _mtu(mtu),
  66. _enabled(true),
  67. _run(true)
  68. {
  69. char sockPath[4096];
  70. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",(unsigned long long)nwid);
  71. _dev = sockPath;
  72. lwipstack = new LWIPStack("ext/bin/lwip/liblwip.so"); // ext/bin/liblwip.so.debug for debug symbols
  73. if(!lwipstack) // TODO double check this check
  74. throw std::runtime_error("unable to load lwip lib.");
  75. lwipstack->lwip_init();
  76. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  77. if (!_unixListenSocket)
  78. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  79. _thread = Thread::start(this);
  80. }
  81. NetconEthernetTap::~NetconEthernetTap()
  82. {
  83. _run = false;
  84. _phy.whack();
  85. _phy.whack();
  86. Thread::join(_thread);
  87. _phy.close(_unixListenSocket,false);
  88. delete lwipstack;
  89. }
  90. void NetconEthernetTap::setEnabled(bool en)
  91. {
  92. _enabled = en;
  93. }
  94. bool NetconEthernetTap::enabled() const
  95. {
  96. return _enabled;
  97. }
  98. bool NetconEthernetTap::addIp(const InetAddress &ip)
  99. {
  100. Mutex::Lock _l(_ips_m);
  101. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  102. _ips.push_back(ip);
  103. std::sort(_ips.begin(),_ips.end());
  104. if (ip.isV4()) {
  105. // Set IP
  106. static ip_addr_t ipaddr, netmask, gw;
  107. IP4_ADDR(&gw,192,168,0,1);
  108. ipaddr.addr = *((u32_t *)ip.rawIpData());
  109. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  110. // Set up the lwip-netif for LWIP's sake
  111. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  112. interface.state = this;
  113. interface.output = lwipstack->_etharp_output;
  114. _mac.copyTo(interface.hwaddr, 6);
  115. interface.mtu = _mtu;
  116. interface.name[0] = 't';
  117. interface.name[1] = 'p';
  118. interface.linkoutput = low_level_output;
  119. interface.hwaddr_len = 6;
  120. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  121. lwipstack->netif_set_default(&interface);
  122. lwipstack->netif_set_up(&interface);
  123. }
  124. }
  125. return true;
  126. }
  127. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  128. {
  129. Mutex::Lock _l(_ips_m);
  130. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  131. if (i == _ips.end())
  132. return false;
  133. _ips.erase(i);
  134. if (ip.isV4()) {
  135. // TODO: dealloc from LWIP
  136. }
  137. return true;
  138. }
  139. std::vector<InetAddress> NetconEthernetTap::ips() const
  140. {
  141. Mutex::Lock _l(_ips_m);
  142. return _ips;
  143. }
  144. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  145. {
  146. struct pbuf *p,*q;
  147. if (!_enabled)
  148. return;
  149. struct eth_hdr ethhdr;
  150. from.copyTo(ethhdr.src.addr, 6);
  151. to.copyTo(ethhdr.dest.addr, 6);
  152. ethhdr.type = Utils::hton((uint16_t)etherType);
  153. // We allocate a pbuf chain of pbufs from the pool.
  154. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  155. if (p != NULL) {
  156. const char *dataptr = reinterpret_cast<const char *>(data);
  157. // First pbuf gets ethernet header at start
  158. q = p;
  159. if (q->len < sizeof(ethhdr)) {
  160. fprintf(stderr,"_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  161. return;
  162. }
  163. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  164. memcpy(q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  165. dataptr += q->len - sizeof(ethhdr);
  166. // Remaining pbufs (if any) get rest of data
  167. while ((q = q->next)) {
  168. memcpy(q->payload,dataptr,q->len);
  169. dataptr += q->len;
  170. }
  171. } else {
  172. fprintf(stderr, "_put(): Dropped packet: no pbufs available\n");
  173. return;
  174. }
  175. {
  176. Mutex::Lock _l2(lwipstack->_lock);
  177. if(interface.input(p, &interface) != ERR_OK) {
  178. fprintf(stderr, "_put(): Error while RXing packet (netif->input)\n");
  179. }
  180. }
  181. }
  182. std::string NetconEthernetTap::deviceName() const
  183. {
  184. return _dev;
  185. }
  186. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  187. {
  188. }
  189. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  190. {
  191. std::vector<MulticastGroup> newGroups;
  192. Mutex::Lock _l(_multicastGroups_m);
  193. // TODO: get multicast subscriptions from LWIP
  194. std::vector<InetAddress> allIps(ips());
  195. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  196. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  197. std::sort(newGroups.begin(),newGroups.end());
  198. std::unique(newGroups.begin(),newGroups.end());
  199. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  200. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  201. added.push_back(*m);
  202. }
  203. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  204. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  205. removed.push_back(*m);
  206. }
  207. _multicastGroups.swap(newGroups);
  208. }
  209. TcpConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  210. {
  211. for(size_t i=0; i<tcp_connections.size(); i++) {
  212. if(tcp_connections[i]->pcb == pcb)
  213. return tcp_connections[i];
  214. }
  215. return NULL;
  216. }
  217. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(PhySocket *sock, int fd)
  218. {
  219. for(size_t i=0; i<tcp_connections.size(); i++) {
  220. if(tcp_connections[i]->perceived_fd == fd && tcp_connections[i]->rpcSock == sock)
  221. return tcp_connections[i];
  222. }
  223. return NULL;
  224. }
  225. /*
  226. * Closes a TcpConnection and associated LWIP PCB strcuture.
  227. */
  228. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  229. {
  230. lwipstack->_tcp_arg(conn->pcb, NULL);
  231. lwipstack->_tcp_sent(conn->pcb, NULL);
  232. lwipstack->_tcp_recv(conn->pcb, NULL);
  233. lwipstack->_tcp_err(conn->pcb, NULL);
  234. lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  235. lwipstack->_tcp_close(conn->pcb);
  236. close(conn->their_fd);
  237. if(conn->dataSock) {
  238. close(_phy.getDescriptor(conn->dataSock));
  239. _phy.close(conn->dataSock);
  240. }
  241. for(int i=0; i<tcp_connections.size(); i++) {
  242. if(tcp_connections[i] == conn) {
  243. tcp_connections.erase(tcp_connections.begin() + i);
  244. break;
  245. }
  246. }
  247. delete conn;
  248. }
  249. /*
  250. * Close a single RPC connection and associated PhySocket
  251. */
  252. void NetconEthernetTap::closeClient(PhySocket *sock)
  253. {
  254. for(int i=0; i<rpc_sockets.size(); i++) {
  255. if(rpc_sockets[i] == sock){
  256. rpc_sockets.erase(rpc_sockets.begin() + i);
  257. break;
  258. }
  259. }
  260. close(_phy.getDescriptor(sock));
  261. _phy.close(sock);
  262. }
  263. /*
  264. * Close all RPC and TCP connections
  265. */
  266. void NetconEthernetTap::closeAll()
  267. {
  268. while(rpc_sockets.size())
  269. closeClient(rpc_sockets.front());
  270. while(tcp_connections.size())
  271. closeConnection(tcp_connections.front());
  272. }
  273. void NetconEthernetTap::threadMain()
  274. throw()
  275. {
  276. fprintf(stderr, "_threadMain()\n");
  277. uint64_t prev_tcp_time = 0;
  278. uint64_t prev_status_time = 0;
  279. uint64_t prev_etharp_time = 0;
  280. /*
  281. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  282. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  283. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  284. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  285. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  286. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n", MEMP_NUM_TCP_SEG);
  287. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  288. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n", TCP_SND_QUEUELEN);
  289. fprintf(stderr, "- TCP_MAXRTX = %d\n", TCP_MAXRTX);
  290. fprintf(stderr, "- IP_REASSEMBLY = %d\n", IP_REASSEMBLY);
  291. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  292. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  293. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  294. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  295. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  296. */
  297. // Main timer loop
  298. while (_run) {
  299. uint64_t now = OSUtils::now();
  300. uint64_t since_tcp = now - prev_tcp_time;
  301. uint64_t since_etharp = now - prev_etharp_time;
  302. uint64_t since_status = now - prev_status_time;
  303. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  304. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  305. uint64_t status_remaining = STATUS_TMR_INTERVAL;
  306. if (since_status >= STATUS_TMR_INTERVAL) {
  307. prev_status_time = now;
  308. fprintf(stderr, "tcp_conns = %d, rpc_socks = %d\n", tcp_connections.size(), rpc_sockets.size());
  309. }
  310. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  311. prev_tcp_time = now;
  312. lwipstack->tcp_tmr();
  313. } else {
  314. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  315. }
  316. if (since_etharp >= ARP_TMR_INTERVAL) {
  317. prev_etharp_time = now;
  318. lwipstack->etharp_tmr();
  319. } else {
  320. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  321. }
  322. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  323. }
  324. closeAll();
  325. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  326. }
  327. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  328. {
  329. // FIXME: What do?
  330. }
  331. /*
  332. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  333. */
  334. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  335. {
  336. if(readable) {
  337. TcpConnection *conn = (TcpConnection*)*uptr;
  338. if(conn->dataSock) // Sometimes a connection may be closed via nc_recved, check first
  339. {
  340. //Mutex::Lock _l(lwipstack->_lock);
  341. lwipstack->_lock.lock();
  342. handle_write(conn);
  343. lwipstack->_lock.unlock();
  344. }
  345. }
  346. else {
  347. fprintf(stderr, "phyOnFileDescriptorActivity(): PhySocket not readable\n");
  348. }
  349. }
  350. // Unused -- no UDP or TCP from this thread/Phy<>
  351. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  352. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  353. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  354. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  355. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  356. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  357. /*
  358. * Add a new PhySocket for the client connection
  359. */
  360. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {
  361. rpc_sockets.push_back(sockN);
  362. }
  363. /*
  364. * Processes incoming data on a client-specific RPC connection
  365. */
  366. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  367. {
  368. unsigned char *buf = (unsigned char*)data;
  369. switch(buf[0])
  370. {
  371. case RPC_SOCKET:
  372. fprintf(stderr, "RPC_SOCKET\n");
  373. struct socket_st socket_rpc;
  374. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  375. handle_socket(sock, uptr, &socket_rpc);
  376. break;
  377. case RPC_LISTEN:
  378. fprintf(stderr, "RPC_LISTEN\n");
  379. struct listen_st listen_rpc;
  380. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  381. handle_listen(sock, uptr, &listen_rpc);
  382. break;
  383. case RPC_BIND:
  384. fprintf(stderr, "RPC_BIND\n");
  385. struct bind_st bind_rpc;
  386. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  387. handle_bind(sock, uptr, &bind_rpc);
  388. break;
  389. case RPC_KILL_INTERCEPT:
  390. fprintf(stderr, "RPC_KILL_INTERCEPT\n");
  391. break;
  392. case RPC_CONNECT:
  393. fprintf(stderr, "RPC_CONNECT\n");
  394. struct connect_st connect_rpc;
  395. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  396. handle_connect(sock, uptr, &connect_rpc);
  397. break;
  398. case RPC_FD_MAP_COMPLETION:
  399. fprintf(stderr, "RPC_FD_MAP_COMPLETION\n");
  400. handle_retval(sock, uptr, buf);
  401. break;
  402. default:
  403. break;
  404. }
  405. }
  406. /*
  407. * Send a 'retval' and 'errno' to the client for an RPC over connection->rpcSock
  408. */
  409. int NetconEthernetTap::send_return_value(TcpConnection *conn, int retval, int _errno = 0)
  410. {
  411. if(conn) {
  412. int n = send_return_value(_phy.getDescriptor(conn->rpcSock), retval, _errno);
  413. if(n > 0)
  414. conn->pending = false;
  415. else {
  416. fprintf(stderr, "Unable to send return value to the intercept. Closing connection\n");
  417. closeConnection(conn);
  418. }
  419. return n;
  420. }
  421. return -1;
  422. }
  423. int NetconEthernetTap::send_return_value(int fd, int retval, int _errno = 0)
  424. {
  425. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  426. char retmsg[sz];
  427. memset(&retmsg, '\0', sizeof(retmsg));
  428. retmsg[0]=RPC_RETVAL;
  429. memcpy(&retmsg[1], &retval, sizeof(retval));
  430. memcpy(&retmsg[1]+sizeof(retval), &_errno, sizeof(_errno));
  431. return write(fd, &retmsg, sz);
  432. }
  433. /*------------------------------------------------------------------------------
  434. --------------------------------- LWIP callbacks -------------------------------
  435. ------------------------------------------------------------------------------*/
  436. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  437. // locked in this case!
  438. /*
  439. * Callback from LWIP for when a connection has been accepted and the PCB has been
  440. * put into an ACCEPT state.
  441. *
  442. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  443. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  444. * is then required to tell the service what new file descriptor it has allocated
  445. * for this connection. After the mapping is complete, the accepted socket can be
  446. * used.
  447. *
  448. * @param associated service state object
  449. * @param newly allocated PCB
  450. * @param error code
  451. * @return ERR_OK if everything is ok, -1 otherwise
  452. i := should be implemented in intercept lib
  453. I := is implemented in intercept lib
  454. X := is implemented in service
  455. ? := required treatment Unknown
  456. - := Not needed
  457. [ ] EAGAIN or EWOULDBLOCK - The socket is marked nonblocking and no connections are present
  458. to be accepted. POSIX.1-2001 allows either error to be returned for
  459. this case, and does not require these constants to have the same value,
  460. so a portable application should check for both possibilities.
  461. [I] EBADF - The descriptor is invalid.
  462. [I] ECONNABORTED - A connection has been aborted.
  463. [i] EFAULT - The addr argument is not in a writable part of the user address space.
  464. [-] EINTR - The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).
  465. [I] EINVAL - Socket is not listening for connections, or addrlen is invalid (e.g., is negative).
  466. [I] EINVAL - (accept4()) invalid value in flags.
  467. [I] EMFILE - The per-process limit of open file descriptors has been reached.
  468. [ ] ENFILE - The system limit on the total number of open files has been reached.
  469. [ ] ENOBUFS, ENOMEM - Not enough free memory. This often means that the memory allocation is
  470. limited by the socket buffer limits, not by the system memory.
  471. [I] ENOTSOCK - The descriptor references a file, not a socket.
  472. [I] EOPNOTSUPP - The referenced socket is not of type SOCK_STREAM.
  473. [ ] EPROTO - Protocol error.
  474. *
  475. */
  476. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  477. {
  478. fprintf(stderr, "nc_accept()\n");
  479. Larg *l = (Larg*)arg;
  480. TcpConnection *conn = l->conn;
  481. NetconEthernetTap *tap = l->tap;
  482. int larg_fd = tap->_phy.getDescriptor(conn->dataSock);
  483. if(conn) {
  484. ZT_PHY_SOCKFD_TYPE fds[2];
  485. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  486. if(errno < 0) {
  487. l->tap->send_return_value(conn, -1, errno);
  488. //fprintf(stderr, "**************\n");
  489. return ERR_MEM;
  490. }
  491. }
  492. TcpConnection *new_tcp_conn = new TcpConnection();
  493. new_tcp_conn->dataSock = tap->_phy.wrapSocket(fds[0], new_tcp_conn);
  494. new_tcp_conn->rpcSock = conn->rpcSock;
  495. new_tcp_conn->pcb = newpcb;
  496. new_tcp_conn->their_fd = fds[1];
  497. tap->tcp_connections.push_back(new_tcp_conn);
  498. int send_fd = tap->_phy.getDescriptor(conn->rpcSock);
  499. int n = write(larg_fd, "z", 1); // accept() in library waits for this byte
  500. if(n > 0) {
  501. if(sock_fd_write(send_fd, fds[1]) > 0) {
  502. new_tcp_conn->pending = true;
  503. }
  504. else {
  505. fprintf(stderr, "nc_accept(%d): unable to send fd to client\n", larg_fd);
  506. }
  507. }
  508. else {
  509. fprintf(stderr, "nc_accept(%d): error writing signal byte (send_fd = %d, perceived_fd = %d)\n", larg_fd, send_fd, fds[1]);
  510. return -1;
  511. }
  512. tap->lwipstack->_tcp_arg(newpcb, new Larg(tap, new_tcp_conn));
  513. tap->lwipstack->_tcp_recv(newpcb, nc_recved);
  514. tap->lwipstack->_tcp_err(newpcb, nc_err);
  515. tap->lwipstack->_tcp_sent(newpcb, nc_sent);
  516. tap->lwipstack->_tcp_poll(newpcb, nc_poll, 0.5);
  517. tcp_accepted(conn->pcb); // Let lwIP know that it can queue additional incoming connections
  518. return ERR_OK;
  519. }
  520. else {
  521. fprintf(stderr, "nc_accept(%d): can't locate Connection object for PCB.\n", larg_fd);
  522. }
  523. return -1;
  524. }
  525. /*
  526. * Callback from LWIP for when data is available to be read from the network.
  527. *
  528. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  529. * send to the client over the associated unix socket.
  530. *
  531. * @param associated service state object
  532. * @param allocated PCB
  533. * @param chain of pbufs
  534. * @param error code
  535. * @return ERR_OK if everything is ok, -1 otherwise
  536. *
  537. */
  538. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  539. {
  540. Larg *l = (Larg*)arg;
  541. int n;
  542. struct pbuf* q = p;
  543. if(!l->conn) {
  544. fprintf(stderr, "nc_recved(): no connection object\n");
  545. return ERR_OK; // ?
  546. }
  547. if(p == NULL) {
  548. if(l->conn) {
  549. fprintf(stderr, "nc_recved(): closing connection\n");
  550. l->tap->closeConnection(l->conn);
  551. }
  552. else {
  553. fprintf(stderr, "nc_recved(): can't locate connection via (arg)\n");
  554. }
  555. return err;
  556. }
  557. q = p;
  558. while(p != NULL) { // Cycle through pbufs and write them to the socket
  559. if(p->len <= 0)
  560. break; // ?
  561. if((n = l->tap->_phy.streamSend(l->conn->dataSock,p->payload, p->len)) > 0) {
  562. if(n < p->len) {
  563. fprintf(stderr, "nc_recved(): unable to write entire pbuf to buffer\n");
  564. }
  565. l->tap->lwipstack->_tcp_recved(tpcb, n); // TODO: would it be more efficient to call this once at the end?
  566. }
  567. else {
  568. fprintf(stderr, "nc_recved(): No data written to intercept buffer\n");
  569. }
  570. p = p->next;
  571. }
  572. l->tap->lwipstack->_pbuf_free(q); // free pbufs
  573. return ERR_OK;
  574. }
  575. /*
  576. * Callback from LWIP when an internal error is associtated with the given (arg)
  577. *
  578. * Since the PCB related to this error might no longer exist, only its perviously
  579. * associated (arg) is provided to us.
  580. *
  581. * @param associated service state object
  582. * @param error code
  583. *
  584. */
  585. void NetconEthernetTap::nc_err(void *arg, err_t err)
  586. {
  587. Larg *l = (Larg*)arg;
  588. //fprintf(stderr, "larg = %x, nc_err() = %d\n", l, err);
  589. if(!l->conn)
  590. fprintf(stderr, "nc_err(): Connection is NULL!\n");
  591. if(l->conn) {
  592. switch(err)
  593. {
  594. case ERR_MEM:
  595. fprintf(stderr, "nc_err(): ERR_MEM->ENOMEM\n");
  596. l->tap->send_return_value(l->conn, -1, ENOMEM);
  597. break;
  598. case ERR_BUF:
  599. fprintf(stderr, "nc_err(): ERR_BUF->ENOBUFS\n");
  600. l->tap->send_return_value(l->conn, -1, ENOBUFS);
  601. break;
  602. case ERR_TIMEOUT:
  603. fprintf(stderr, "nc_err(): ERR_TIMEOUT->ETIMEDOUT\n");
  604. l->tap->send_return_value(l->conn, -1, ETIMEDOUT);
  605. break;
  606. case ERR_RTE:
  607. fprintf(stderr, "nc_err(): ERR_RTE->ENETUNREACH\n");
  608. l->tap->send_return_value(l->conn, -1, ENETUNREACH);
  609. break;
  610. case ERR_INPROGRESS:
  611. fprintf(stderr, "nc_err(): ERR_INPROGRESS->EINPROGRESS\n");
  612. l->tap->send_return_value(l->conn, -1, EINPROGRESS);
  613. break;
  614. case ERR_VAL:
  615. fprintf(stderr, "nc_err(): ERR_VAL->EINVAL\n");
  616. l->tap->send_return_value(l->conn, -1, EINVAL);
  617. break;
  618. case ERR_WOULDBLOCK:
  619. fprintf(stderr, "nc_err(): ERR_WOULDBLOCK->EWOULDBLOCK\n");
  620. l->tap->send_return_value(l->conn, -1, EWOULDBLOCK);
  621. break;
  622. case ERR_USE:
  623. fprintf(stderr, "nc_err(): ERR_USE->EADDRINUSE\n");
  624. l->tap->send_return_value(l->conn, -1, EADDRINUSE);
  625. break;
  626. case ERR_ISCONN:
  627. fprintf(stderr, "nc_err(): ERR_ISCONN->EISCONN\n");
  628. l->tap->send_return_value(l->conn, -1, EISCONN);
  629. break;
  630. case ERR_ABRT:
  631. fprintf(stderr, "nc_err(): ERR_ABRT->ECONNREFUSED\n");
  632. l->tap->send_return_value(l->conn, -1, ECONNREFUSED);
  633. break;
  634. // FIXME: Below are errors which don't have a standard errno correlate
  635. case ERR_RST:
  636. l->tap->send_return_value(l->conn, -1, -1);
  637. break;
  638. case ERR_CLSD:
  639. l->tap->send_return_value(l->conn, -1, -1);
  640. break;
  641. case ERR_CONN:
  642. l->tap->send_return_value(l->conn, -1, -1);
  643. break;
  644. case ERR_ARG:
  645. l->tap->send_return_value(l->conn, -1, -1);
  646. break;
  647. case ERR_IF:
  648. l->tap->send_return_value(l->conn, -1, -1);
  649. break;
  650. default:
  651. break;
  652. }
  653. fprintf(stderr, "nc_err(): closing connection\n");
  654. l->tap->closeConnection(l->conn);
  655. }
  656. else {
  657. fprintf(stderr, "nc_err(): can't locate connection object for PCB\n");
  658. }
  659. }
  660. /*
  661. * Callback from LWIP to do whatever work we might need to do.
  662. *
  663. * @param associated service state object
  664. * @param PCB we're polling on
  665. * @return ERR_OK if everything is ok, -1 otherwise
  666. *
  667. */
  668. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  669. {
  670. /*
  671. Larg *l = (Larg*)arg;
  672. TcpConnection *conn = l->conn;
  673. NetconEthernetTap *tap = l->tap;
  674. if(conn && conn->idx) // if valid connection and non-zero index (indicating data present)
  675. tap->handle_write(conn);
  676. */
  677. return ERR_OK;
  678. }
  679. /*
  680. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  681. * As a result, we should put our socket back into a notify-on-readability state
  682. * since there is now room on the PCB buffer to write to.
  683. *
  684. * NOTE: This could be used to track the amount of data sent by a connection.
  685. *
  686. * @param associated service state object
  687. * @param relevant PCB
  688. * @param length of data sent
  689. * @return ERR_OK if everything is ok, -1 otherwise
  690. *
  691. */
  692. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  693. {
  694. //fprintf(stderr, "nc_sent()\n");
  695. Larg *l = (Larg*)arg;
  696. if(len) {
  697. //fprintf(stderr, "ACKING len = %d, setting read-notify = true, (sndbuf = %d)\n", len, l->conn->pcb->snd_buf);
  698. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  699. //uint64_t now = OSUtils::now();
  700. //fprintf(stderr, "nc_sent(): now = %u\n", now);
  701. l->tap->_phy.whack();
  702. }
  703. return ERR_OK;
  704. }
  705. /*
  706. * Callback from LWIP which sends a return value to the client to signal that
  707. * a connection was established for this PCB
  708. *
  709. * @param associated service state object
  710. * @param relevant PCB
  711. * @param error code
  712. * @return ERR_OK if everything is ok, -1 otherwise
  713. *
  714. */
  715. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  716. {
  717. fprintf(stderr, "nc_connected()\n");
  718. Larg *l = (Larg*)arg;
  719. l->tap->send_return_value(l->conn, ERR_OK);
  720. return ERR_OK;
  721. }
  722. /*------------------------------------------------------------------------------
  723. ----------------------------- RPC Handler functions ----------------------------
  724. ------------------------------------------------------------------------------*/
  725. /**
  726. * Handles a return value (client's perceived fd) and completes a mapping
  727. * so that we know what connection an RPC call should be associated with.
  728. *
  729. * @param PhySocket associated with this RPC connection
  730. * @param structure containing the data and parameters for this client's RPC
  731. *
  732. */
  733. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, unsigned char* buf)
  734. {
  735. TcpConnection *conn = (TcpConnection*)*uptr;
  736. if(conn->pending) {
  737. memcpy(&(conn->perceived_fd), &buf[1], sizeof(int));
  738. //fprintf(stderr, "handle_retval(): Mapping [our=%d -> their=%d]\n",
  739. //_phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  740. conn->pending = false;
  741. }
  742. }
  743. /*
  744. * Handles an RPC to bind an LWIP PCB to a given address and port
  745. *
  746. * @param PhySocket associated with this RPC connection
  747. * @param structure containing the data and parameters for this client's RPC
  748. *
  749. i := should be implemented in intercept lib
  750. I := is implemented in intercept lib
  751. X := is implemented in service
  752. ? := required treatment Unknown
  753. - := Not needed
  754. [ ] EACCES - The address is protected, and the user is not the superuser.
  755. [X] EADDRINUSE - The given address is already in use.
  756. [I] EBADF - sockfd is not a valid descriptor.
  757. [X] EINVAL - The socket is already bound to an address.
  758. [I] ENOTSOCK - sockfd is a descriptor for a file, not a socket.
  759. [X] ENOMEM - Insufficient kernel memory was available.
  760. - The following errors are specific to UNIX domain (AF_UNIX) sockets:
  761. [-] EACCES - Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
  762. [-] EADDRNOTAVAIL - A nonexistent interface was requested or the requested address was not local.
  763. [-] EFAULT - addr points outside the user's accessible address space.
  764. [-] EINVAL - The addrlen is wrong, or the socket was not in the AF_UNIX family.
  765. [-] ELOOP - Too many symbolic links were encountered in resolving addr.
  766. [-] ENAMETOOLONG - s addr is too long.
  767. [-] ENOENT - The file does not exist.
  768. [-] ENOTDIR - A component of the path prefix is not a directory.
  769. [-] EROFS - The socket inode would reside on a read-only file system.
  770. */
  771. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  772. {
  773. struct sockaddr_in *connaddr;
  774. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  775. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  776. ip_addr_t conn_addr;
  777. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  778. TcpConnection *conn = getConnectionByTheirFD(sock, bind_rpc->sockfd);
  779. if(conn) {
  780. if(conn->pcb->state == CLOSED){
  781. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  782. if(err != ERR_OK) {
  783. int ip = connaddr->sin_addr.s_addr;
  784. unsigned char d[4];
  785. d[0] = ip & 0xFF;
  786. d[1] = (ip >> 8) & 0xFF;
  787. d[2] = (ip >> 16) & 0xFF;
  788. d[3] = (ip >> 24) & 0xFF;
  789. fprintf(stderr, "handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  790. if(err == ERR_USE)
  791. send_return_value(conn, -1, EADDRINUSE);
  792. if(err == ERR_MEM)
  793. send_return_value(conn, -1, ENOMEM);
  794. if(err == ERR_BUF)
  795. send_return_value(conn, -1, ENOMEM); // FIXME: Closest match
  796. }
  797. else {
  798. send_return_value(conn, ERR_OK, ERR_OK); // Success
  799. }
  800. }
  801. else {
  802. fprintf(stderr, "handle_bind(): PCB not in CLOSED state. Ignoring BIND request.\n");
  803. send_return_value(conn, -1, EINVAL);
  804. }
  805. }
  806. else {
  807. fprintf(stderr, "handle_bind(): can't locate connection for PCB\n");
  808. send_return_value(conn, -1, EBADF);
  809. }
  810. }
  811. /*
  812. * Handles an RPC to put an LWIP PCB into LISTEN mode
  813. *
  814. * @param PhySocket associated with this RPC connection
  815. * @param structure containing the data and parameters for this client's RPC
  816. *
  817. i := should be implemented in intercept lib
  818. I := is implemented in intercept lib
  819. X := is implemented in service
  820. ? := required treatment Unknown
  821. - := Not needed
  822. [?] EADDRINUSE - Another socket is already listening on the same port.
  823. [IX] EBADF - The argument sockfd is not a valid descriptor.
  824. [I] ENOTSOCK - The argument sockfd is not a socket.
  825. [I] EOPNOTSUPP - The socket is not of a type that supports the listen() operation.
  826. */
  827. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  828. {
  829. TcpConnection *conn = getConnectionByTheirFD(sock, listen_rpc->sockfd);
  830. if(conn) {
  831. if(conn->pcb->state == LISTEN) {
  832. fprintf(stderr, "handle_listen(): PCB is already in listening state.\n");
  833. return;
  834. }
  835. struct tcp_pcb* listening_pcb;
  836. #ifdef TCP_LISTEN_BACKLOG
  837. listening_pcb = lwipstack->tcp_listen_with_backlog(conn->pcb, listen_rpc->backlog);
  838. #else
  839. listening_pcb = lwipstack->tcp_listen(conn->pcb);
  840. #endif
  841. // FIXME: Correct return values from this method, most is handled in intercept lib
  842. if(listening_pcb != NULL) {
  843. conn->pcb = listening_pcb;
  844. lwipstack->tcp_accept(listening_pcb, nc_accept);
  845. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  846. /* we need to wait for the client to send us the fd allocated on their end
  847. for this listening socket */
  848. conn->pending = true;
  849. send_return_value(conn, ERR_OK, ERR_OK);
  850. }
  851. else {
  852. /*
  853. fprintf(stderr, "handle_listen(): unable to allocate memory for new listening PCB\n");
  854. // FIXME: This does not have an equivalent errno value
  855. // lwip will reclaim space with a tcp_listen call since a PCB in a LISTEN
  856. // state takes up less space. If something goes wrong during the creation of a
  857. // new listening socket we should return an error that implies we can't use this
  858. // socket, even if the reason isn't describing what really happened internally.
  859. // See: http://lwip.wikia.com/wiki/Raw/TCP
  860. send_return_value(conn, -1, EBADF);
  861. */
  862. }
  863. }
  864. else {
  865. /*
  866. // We can't find a connection mapped to the socket fd provided
  867. fprintf(stderr, "handle_listen(): can't locate connection for PCB\n");
  868. send_return_value(conn, -1, EBADF);
  869. */
  870. }
  871. }
  872. /*
  873. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  874. *
  875. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  876. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  877. * is then required to tell the service what new file descriptor it has allocated
  878. * for this connection. After the mapping is complete, the socket can be used.
  879. *
  880. * @param PhySocket associated with this RPC connection
  881. * @param structure containing the data and parameters for this client's RPC
  882. *
  883. i := should be implemented in intercept lib
  884. I := is implemented in intercept lib
  885. X := is implemented in service
  886. ? := required treatment Unknown
  887. - := Not needed
  888. [-] EACCES - Permission to create a socket of the specified type and/or protocol is denied.
  889. [I] EAFNOSUPPORT - The implementation does not support the specified address family.
  890. [I] EINVAL - Unknown protocol, or protocol family not available.
  891. [I] EINVAL - Invalid flags in type.
  892. [I] EMFILE - Process file table overflow.
  893. [?] ENFILE - The system limit on the total number of open files has been reached.
  894. [X] ENOBUFS or ENOMEM - Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
  895. [?] EPROTONOSUPPORT - The protocol type or the specified protocol is not supported within this domain.
  896. */
  897. void NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  898. {
  899. int rpc_fd = _phy.getDescriptor(sock);
  900. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  901. if(newpcb != NULL) {
  902. ZT_PHY_SOCKFD_TYPE fds[2];
  903. if(socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
  904. if(errno < 0) {
  905. send_return_value(rpc_fd, -1, errno);
  906. return;
  907. }
  908. }
  909. TcpConnection *new_conn = new TcpConnection();
  910. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  911. *uptr = new_conn;
  912. new_conn->rpcSock = sock;
  913. new_conn->pcb = newpcb;
  914. new_conn->their_fd = fds[1];
  915. tcp_connections.push_back(new_conn);
  916. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  917. // Once the client tells us what its fd is on the other end, we can then complete the mapping
  918. new_conn->pending = true;
  919. }
  920. else {
  921. sock_fd_write(rpc_fd, -1); // Send a bad fd, to signal error
  922. fprintf(stderr, "handle_socket(): Memory not available for new PCB\n");
  923. send_return_value(rpc_fd, -1, ENOMEM);
  924. }
  925. }
  926. /*
  927. * Handles an RPC to connect to a given address and port
  928. *
  929. * @param PhySocket associated with this RPC connection
  930. * @param structure containing the data and parameters for this client's RPC
  931. --- Error handling in this method will only catch problems which are immedately
  932. apprent. Some errors will need to be caught in the nc_connected(0 callback
  933. i := should be implemented in intercept lib
  934. I := is implemented in intercept lib
  935. X := is implemented in service
  936. ? := required treatment Unknown
  937. - := Not needed
  938. [-] EACCES - For UNIX domain sockets, which are identified by pathname: Write permission is denied ...
  939. [?] EACCES, EPERM - The user tried to connect to a broadcast address without having the socket broadcast flag enabled ...
  940. [X] EADDRINUSE - Local address is already in use.
  941. [I] EAFNOSUPPORT - The passed address didn't have the correct address family in its sa_family field.
  942. [X] EAGAIN - No more free local ports or insufficient entries in the routing cache.
  943. [ ] EALREADY - The socket is nonblocking and a previous connection attempt has not yet been completed.
  944. [IX] EBADF - The file descriptor is not a valid index in the descriptor table.
  945. [ ] ECONNREFUSED - No-one listening on the remote address.
  946. [i] EFAULT - The socket structure address is outside the user's address space.
  947. [ ] EINPROGRESS - The socket is nonblocking and the connection cannot be completed immediately.
  948. [-] EINTR - The system call was interrupted by a signal that was caught.
  949. [X] EISCONN - The socket is already connected.
  950. [X] ENETUNREACH - Network is unreachable.
  951. [I] ENOTSOCK - The file descriptor is not associated with a socket.
  952. [X] ETIMEDOUT - Timeout while attempting connection.
  953. [X] EINVAL - Invalid argument, SVr4, generally makes sense to set this
  954. *
  955. */
  956. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  957. {
  958. TcpConnection *conn = (TcpConnection*)*uptr;
  959. struct sockaddr_in *connaddr;
  960. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  961. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  962. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  963. if(conn != NULL) {
  964. lwipstack->tcp_sent(conn->pcb, nc_sent);
  965. lwipstack->tcp_recv(conn->pcb, nc_recved);
  966. lwipstack->tcp_err(conn->pcb, nc_err);
  967. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  968. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  969. int err = 0;
  970. if((err = lwipstack->tcp_connect(conn->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  971. {
  972. if(err == ERR_ISCONN) {
  973. send_return_value(conn, -1, EISCONN); // Already in connected state
  974. return;
  975. }
  976. if(err == ERR_USE) {
  977. send_return_value(conn, -1, EADDRINUSE); // Already in use
  978. return;
  979. }
  980. if(err == ERR_VAL) {
  981. send_return_value(conn, -1, EINVAL); // Invalid ipaddress parameter
  982. return;
  983. }
  984. if(err == ERR_RTE) {
  985. send_return_value(conn, -1, ENETUNREACH); // No route to host
  986. return;
  987. }
  988. if(err == ERR_BUF) {
  989. send_return_value(conn, -1, EAGAIN); // No more ports available
  990. return;
  991. }
  992. if(err == ERR_MEM)
  993. {
  994. /* Can occur for the following reasons: tcp_enqueue_flags()
  995. 1) tcp_enqueue_flags is always called with either SYN or FIN in flags.
  996. We need one available snd_buf byte to do that.
  997. This means we can't send FIN while snd_buf==0. A better fix would be to
  998. not include SYN and FIN sequence numbers in the snd_buf count.
  999. 2) Cannot allocate new pbuf
  1000. 3) Cannot allocate new TCP segment
  1001. */
  1002. send_return_value(conn, -1, EAGAIN); // FIXME: Doesn't describe the problem well, but closest match
  1003. return;
  1004. }
  1005. // We should only return a value if failure happens immediately
  1006. // Otherwise, we still need to wait for a callback from lwIP.
  1007. // - This is because an ERR_OK from tcp_connect() only verifies
  1008. // that the SYN packet was enqueued onto the stack properly,
  1009. // that's it!
  1010. // - Most instances of a retval for a connect() should happen
  1011. // in the nc_connect() and nc_err() callbacks!
  1012. fprintf(stderr, "handle_connect(): unable to connect\n");
  1013. send_return_value(conn, -1, EAGAIN);
  1014. }
  1015. // Everything seems to be ok, but we don't have enough info to retval
  1016. conn->pending=true;
  1017. }
  1018. else {
  1019. fprintf(stderr, "could not locate PCB based on their fd\n");
  1020. send_return_value(conn, -1, EBADF);
  1021. }
  1022. }
  1023. void NetconEthernetTap::handle_write(TcpConnection *conn)
  1024. {
  1025. float max = (float)TCP_SND_BUF;
  1026. int r;
  1027. if(!conn) {
  1028. fprintf(stderr, "handle_write(): could not locate connection for this fd\n");
  1029. return;
  1030. }
  1031. if(conn->idx < max) {
  1032. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  1033. /* PCB send buffer is full,turn off readability notifications for the
  1034. corresponding PhySocket until nc_sent() is called and confirms that there is
  1035. now space on the buffer */
  1036. if(sndbuf == 0) {
  1037. _phy.setNotifyReadable(conn->dataSock, false);
  1038. lwipstack->_tcp_output(conn->pcb);
  1039. return;
  1040. }
  1041. int read_fd = _phy.getDescriptor(conn->dataSock);
  1042. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  1043. conn->idx += r;
  1044. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  1045. * data to LWIP to be enqueued and eventually sent to the network. */
  1046. if(r > 0) {
  1047. int sz;
  1048. // NOTE: this assumes that lwipstack->_lock is locked, either
  1049. // because we are in a callback or have locked it manually.
  1050. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  1051. //lwipstack->_tcp_output(conn->pcb);
  1052. if(err != ERR_OK) {
  1053. fprintf(stderr, "handle_write(): error while writing to PCB, (err = %d)\n", err);
  1054. return;
  1055. }
  1056. else {
  1057. sz = (conn->idx)-r;
  1058. if(sz) {
  1059. memmove(&conn->buf, (conn->buf+r), sz);
  1060. }
  1061. conn->idx -= r;
  1062. return;
  1063. }
  1064. }
  1065. else {
  1066. fprintf(stderr, "handle_write(): LWIP stack full\n");
  1067. return;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. } // namespace ZeroTier
  1073. #endif // ZT_ENABLE_NETCON