NetconEthernetTap.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifdef ZT_ENABLE_NETCON
  28. #include <algorithm>
  29. #include <utility>
  30. #include <dlfcn.h>
  31. //#include <sys/types.h>
  32. #include "NetconEthernetTap.hpp"
  33. #include "../node/Utils.hpp"
  34. #include "../osdep/OSUtils.hpp"
  35. #include "../osdep/Phy.hpp"
  36. #include "lwip/tcp_impl.h"
  37. #include "netif/etharp.h"
  38. #include "lwip/ip.h"
  39. #include "lwip/ip_addr.h"
  40. #include "lwip/ip_frag.h"
  41. #include "lwip/tcp.h"
  42. #include "LWIPStack.hpp"
  43. #include "NetconService.hpp"
  44. #include "Intercept.h"
  45. #include "NetconUtilities.hpp"
  46. #define APPLICATION_POLL_FREQ 1
  47. namespace ZeroTier {
  48. NetconEthernetTap::NetconEthernetTap(
  49. const char *homePath,
  50. const MAC &mac,
  51. unsigned int mtu,
  52. unsigned int metric,
  53. uint64_t nwid,
  54. const char *friendlyName,
  55. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  56. void *arg) :
  57. _phy(this,false,true),
  58. _unixListenSocket((PhySocket *)0),
  59. _handler(handler),
  60. _arg(arg),
  61. _nwid(nwid),
  62. _mac(mac),
  63. _homePath(homePath),
  64. _mtu(mtu),
  65. _enabled(true),
  66. _run(true)
  67. {
  68. char sockPath[4096];
  69. Utils::snprintf(sockPath,sizeof(sockPath),"/tmp/.ztnc_%.16llx",(unsigned long long)nwid);
  70. _dev = sockPath;
  71. lwipstack = new LWIPStack("ext/bin/lwip/liblwip.so"); // ext/bin/liblwip.so.debug for debug symbols
  72. if(!lwipstack) // TODO double check this check
  73. throw std::runtime_error("unable to load lwip lib.");
  74. lwipstack->lwip_init();
  75. _unixListenSocket = _phy.unixListen(sockPath,(void *)this);
  76. if (!_unixListenSocket)
  77. throw std::runtime_error(std::string("unable to bind to ")+sockPath);
  78. _thread = Thread::start(this);
  79. }
  80. NetconEthernetTap::~NetconEthernetTap()
  81. {
  82. _run = false;
  83. _phy.whack();
  84. _phy.whack();
  85. Thread::join(_thread);
  86. _phy.close(_unixListenSocket,false);
  87. delete lwipstack;
  88. }
  89. void NetconEthernetTap::setEnabled(bool en)
  90. {
  91. _enabled = en;
  92. }
  93. bool NetconEthernetTap::enabled() const
  94. {
  95. return _enabled;
  96. }
  97. bool NetconEthernetTap::addIp(const InetAddress &ip)
  98. {
  99. Mutex::Lock _l(_ips_m);
  100. if (std::find(_ips.begin(),_ips.end(),ip) == _ips.end()) {
  101. _ips.push_back(ip);
  102. std::sort(_ips.begin(),_ips.end());
  103. if (ip.isV4()) {
  104. // Set IP
  105. static ip_addr_t ipaddr, netmask, gw;
  106. IP4_ADDR(&gw,192,168,0,1);
  107. ipaddr.addr = *((u32_t *)ip.rawIpData());
  108. netmask.addr = *((u32_t *)ip.netmask().rawIpData());
  109. // Set up the lwip-netif for LWIP's sake
  110. lwipstack->netif_add(&interface,&ipaddr, &netmask, &gw, NULL, tapif_init, lwipstack->_ethernet_input);
  111. interface.state = this;
  112. interface.output = lwipstack->_etharp_output;
  113. _mac.copyTo(interface.hwaddr, 6);
  114. interface.mtu = _mtu;
  115. interface.name[0] = 't';
  116. interface.name[1] = 'p';
  117. interface.linkoutput = low_level_output;
  118. interface.hwaddr_len = 6;
  119. interface.flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP;
  120. lwipstack->netif_set_default(&interface);
  121. lwipstack->netif_set_up(&interface);
  122. }
  123. }
  124. return true;
  125. }
  126. bool NetconEthernetTap::removeIp(const InetAddress &ip)
  127. {
  128. Mutex::Lock _l(_ips_m);
  129. std::vector<InetAddress>::iterator i(std::find(_ips.begin(),_ips.end(),ip));
  130. if (i == _ips.end())
  131. return false;
  132. _ips.erase(i);
  133. if (ip.isV4()) {
  134. // TODO: dealloc from LWIP
  135. }
  136. return true;
  137. }
  138. std::vector<InetAddress> NetconEthernetTap::ips() const
  139. {
  140. Mutex::Lock _l(_ips_m);
  141. return _ips;
  142. }
  143. void NetconEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  144. {
  145. struct pbuf *p,*q;
  146. //fprintf(stderr, "_put(%s,%s,%.4x,[data],%u)\n",from.toString().c_str(),to.toString().c_str(),etherType,len);
  147. if (!_enabled)
  148. return;
  149. //printf(">> %.4x %s\n",etherType,Utils::hex(data,len).c_str());
  150. struct eth_hdr ethhdr;
  151. from.copyTo(ethhdr.src.addr, 6);
  152. to.copyTo(ethhdr.dest.addr, 6);
  153. ethhdr.type = Utils::hton((uint16_t)etherType);
  154. // We allocate a pbuf chain of pbufs from the pool.
  155. p = lwipstack->pbuf_alloc(PBUF_RAW, len+sizeof(struct eth_hdr), PBUF_POOL);
  156. if (p != NULL) {
  157. const char *dataptr = reinterpret_cast<const char *>(data);
  158. // First pbuf gets ethernet header at start
  159. q = p;
  160. if (q->len < sizeof(ethhdr)) {
  161. fprintf(stderr,"_put(): Dropped packet: first pbuf smaller than ethernet header\n");
  162. return;
  163. }
  164. memcpy(q->payload,&ethhdr,sizeof(ethhdr));
  165. memcpy(q->payload + sizeof(ethhdr),dataptr,q->len - sizeof(ethhdr));
  166. dataptr += q->len - sizeof(ethhdr);
  167. // Remaining pbufs (if any) get rest of data
  168. while ((q = q->next)) {
  169. memcpy(q->payload,dataptr,q->len);
  170. dataptr += q->len;
  171. }
  172. } else {
  173. fprintf(stderr, "_put(): Dropped packet: no pbufs available\n");
  174. return;
  175. }
  176. //printf("p->len == %u, p->payload == %s\n",p->len,Utils::hex(p->payload,p->len).c_str());
  177. {
  178. Mutex::Lock _l2(lwipstack->_lock);
  179. if(interface.input(p, &interface) != ERR_OK) {
  180. fprintf(stderr, "_put(): Error while RXing packet (netif->input)\n");
  181. }
  182. }
  183. }
  184. std::string NetconEthernetTap::deviceName() const
  185. {
  186. return _dev;
  187. }
  188. void NetconEthernetTap::setFriendlyName(const char *friendlyName)
  189. {
  190. }
  191. void NetconEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  192. {
  193. std::vector<MulticastGroup> newGroups;
  194. Mutex::Lock _l(_multicastGroups_m);
  195. // TODO: get multicast subscriptions from LWIP
  196. std::vector<InetAddress> allIps(ips());
  197. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  198. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  199. std::sort(newGroups.begin(),newGroups.end());
  200. std::unique(newGroups.begin(),newGroups.end());
  201. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  202. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  203. added.push_back(*m);
  204. }
  205. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  206. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  207. removed.push_back(*m);
  208. }
  209. _multicastGroups.swap(newGroups);
  210. }
  211. TcpConnection *NetconEthernetTap::getConnectionByPCB(struct tcp_pcb *pcb)
  212. {
  213. for(size_t i=0; i<tcp_connections.size(); i++) {
  214. if(tcp_connections[i]->pcb == pcb)
  215. return tcp_connections[i];
  216. }
  217. return NULL;
  218. }
  219. TcpConnection *NetconEthernetTap::getConnectionByTheirFD(int fd)
  220. {
  221. for(size_t i=0; i<tcp_connections.size(); i++) {
  222. if(tcp_connections[i]->perceived_fd == fd)
  223. return tcp_connections[i];
  224. }
  225. return NULL;
  226. }
  227. /*
  228. * Closes a TcpConnection and associated LWIP PCB strcuture.
  229. */
  230. void NetconEthernetTap::closeConnection(TcpConnection *conn)
  231. {
  232. //fprintf(stderr, "closeConnection(): closing: conn->type = %d, fd=%d\n", conn->type, _phy.getDescriptor(conn->sock));
  233. lwipstack->_tcp_arg(conn->pcb, NULL);
  234. lwipstack->_tcp_sent(conn->pcb, NULL);
  235. lwipstack->_tcp_recv(conn->pcb, NULL);
  236. lwipstack->_tcp_err(conn->pcb, NULL);
  237. lwipstack->_tcp_poll(conn->pcb, NULL, 0);
  238. lwipstack->_tcp_close(conn->pcb);
  239. close(_phy.getDescriptor(conn->dataSock));
  240. close(conn->their_fd);
  241. _phy.close(conn->dataSock);
  242. for(int i=0; i<tcp_connections.size(); i++) {
  243. if(tcp_connections[i] == conn) {
  244. tcp_connections.erase(tcp_connections.begin() + i);
  245. }
  246. }
  247. delete conn;
  248. }
  249. void NetconEthernetTap::closeClient(PhySocket *sock)
  250. {
  251. for(int i=0; i<rpc_sockets.size(); i++) {
  252. if(rpc_sockets[i] == sock)
  253. rpc_sockets.erase(rpc_sockets.begin() + i);
  254. }
  255. close(_phy.getDescriptor(sock));
  256. _phy.close(sock);
  257. }
  258. void NetconEthernetTap::closeAll()
  259. {
  260. while(rpc_sockets.size())
  261. closeClient(rpc_sockets.front());
  262. while(tcp_connections.size())
  263. closeConnection(tcp_connections.front());
  264. }
  265. #define ZT_LWIP_TCP_TIMER_INTERVAL 10
  266. void NetconEthernetTap::threadMain()
  267. throw()
  268. {
  269. fprintf(stderr, "_threadMain()\n");
  270. uint64_t prev_tcp_time = 0;
  271. uint64_t prev_etharp_time = 0;
  272. fprintf(stderr, "- MEM_SIZE = %dM\n", MEM_SIZE / (1024*1024));
  273. fprintf(stderr, "- TCP_SND_BUF = %dK\n", TCP_SND_BUF / 1024);
  274. fprintf(stderr, "- MEMP_NUM_PBUF = %d\n", MEMP_NUM_PBUF);
  275. fprintf(stderr, "- MEMP_NUM_TCP_PCB = %d\n", MEMP_NUM_TCP_PCB);
  276. fprintf(stderr, "- MEMP_NUM_TCP_PCB_LISTEN = %d\n", MEMP_NUM_TCP_PCB_LISTEN);
  277. fprintf(stderr, "- MEMP_NUM_TCP_SEG = %d\n", MEMP_NUM_TCP_SEG);
  278. fprintf(stderr, "- PBUF_POOL_SIZE = %d\n", PBUF_POOL_SIZE);
  279. fprintf(stderr, "- TCP_SND_QUEUELEN = %d\n", TCP_SND_QUEUELEN);
  280. fprintf(stderr, "- IP_REASSEMBLY = %d\n", IP_REASSEMBLY);
  281. fprintf(stderr, "- TCP_WND = %d\n", TCP_WND);
  282. fprintf(stderr, "- TCP_MSS = %d\n", TCP_MSS);
  283. fprintf(stderr, "- ARP_TMR_INTERVAL = %d\n", ARP_TMR_INTERVAL);
  284. fprintf(stderr, "- TCP_TMR_INTERVAL = %d\n", TCP_TMR_INTERVAL);
  285. fprintf(stderr, "- IP_TMR_INTERVAL = %d\n", IP_TMR_INTERVAL);
  286. // Main timer loop
  287. while (_run) {
  288. uint64_t now = OSUtils::now();
  289. uint64_t since_tcp = now - prev_tcp_time;
  290. uint64_t since_etharp = now - prev_etharp_time;
  291. uint64_t tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL;
  292. uint64_t etharp_remaining = ARP_TMR_INTERVAL;
  293. if (since_tcp >= ZT_LWIP_TCP_TIMER_INTERVAL) {
  294. prev_tcp_time = now;
  295. lwipstack->tcp_tmr();
  296. //fprintf(stderr, "tcp_tmr\n");
  297. } else {
  298. tcp_remaining = ZT_LWIP_TCP_TIMER_INTERVAL - since_tcp;
  299. }
  300. if (since_etharp >= ARP_TMR_INTERVAL) {
  301. prev_etharp_time = now;
  302. lwipstack->etharp_tmr();
  303. } else {
  304. etharp_remaining = ARP_TMR_INTERVAL - since_etharp;
  305. }
  306. //fprintf(stderr, "poll_wait_time = %d\n", (unsigned long)std::min(tcp_remaining,etharp_remaining));
  307. _phy.poll((unsigned long)std::min(tcp_remaining,etharp_remaining));
  308. }
  309. closeAll();
  310. // TODO: cleanup -- destroy LWIP state, kill any clients, unload .so, etc.
  311. }
  312. void NetconEthernetTap::phyOnUnixClose(PhySocket *sock,void **uptr)
  313. {
  314. //fprintf(stderr, "phyOnUnixClose() CLOSING: %d\n", _phy.getDescriptor(sock));
  315. //closeClient(sock);
  316. // FIXME:
  317. }
  318. /*
  319. * Handles data on a client's data buffer. Data is sent to LWIP to be enqueued.
  320. */
  321. void NetconEthernetTap::phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  322. {
  323. if(readable) {
  324. TcpConnection *conn = (TcpConnection*)*uptr;
  325. Mutex::Lock _l(lwipstack->_lock);
  326. handle_write(conn);
  327. }
  328. else {
  329. fprintf(stderr, "phyOnFileDescriptorActivity(): PhySocket not readable\n");
  330. }
  331. }
  332. // Unused -- no UDP or TCP from this thread/Phy<>
  333. void NetconEthernetTap::phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
  334. void NetconEthernetTap::phyOnTcpConnect(PhySocket *sock,void **uptr,bool success) {}
  335. void NetconEthernetTap::phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  336. void NetconEthernetTap::phyOnTcpClose(PhySocket *sock,void **uptr) {}
  337. void NetconEthernetTap::phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  338. void NetconEthernetTap::phyOnTcpWritable(PhySocket *sock,void **uptr) {}
  339. /*
  340. * Creates a new NetconClient for the accepted RPC connection (unix domain socket)
  341. *
  342. * Subsequent socket connections from this client will be associated with this
  343. * NetconClient object.
  344. */
  345. void NetconEthernetTap::phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  346. {
  347. //fprintf(stderr, "phyOnUnixAccept() NEW CLIENT RPC: %d\n", _phy.getDescriptor(sockN));
  348. rpc_sockets.push_back(sockN);
  349. }
  350. /*
  351. * Processes incoming data on a client-specific RPC connection
  352. */
  353. void NetconEthernetTap::phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  354. {
  355. unsigned char *buf = (unsigned char*)data;
  356. switch(buf[0])
  357. {
  358. case RPC_SOCKET:
  359. fprintf(stderr, "RPC_SOCKET\n");
  360. struct socket_st socket_rpc;
  361. memcpy(&socket_rpc, &buf[1], sizeof(struct socket_st));
  362. handle_socket(sock, uptr, &socket_rpc);
  363. break;
  364. case RPC_LISTEN:
  365. fprintf(stderr, "RPC_LISTEN\n");
  366. struct listen_st listen_rpc;
  367. memcpy(&listen_rpc, &buf[1], sizeof(struct listen_st));
  368. handle_listen(sock, uptr, &listen_rpc);
  369. break;
  370. case RPC_BIND:
  371. fprintf(stderr, "RPC_BIND\n");
  372. struct bind_st bind_rpc;
  373. memcpy(&bind_rpc, &buf[1], sizeof(struct bind_st));
  374. handle_bind(sock, uptr, &bind_rpc);
  375. break;
  376. case RPC_KILL_INTERCEPT:
  377. fprintf(stderr, "RPC_KILL_INTERCEPT\n");
  378. //scloseClient(sock);
  379. break;
  380. case RPC_CONNECT:
  381. fprintf(stderr, "RPC_CONNECT\n");
  382. struct connect_st connect_rpc;
  383. memcpy(&connect_rpc, &buf[1], sizeof(struct connect_st));
  384. handle_connect(sock, uptr, &connect_rpc);
  385. break;
  386. case RPC_FD_MAP_COMPLETION:
  387. fprintf(stderr, "RPC_FD_MAP_COMPLETION\n");
  388. handle_retval(sock, uptr, buf);
  389. break;
  390. default:
  391. break;
  392. }
  393. }
  394. /*
  395. * Send a return value to the client for an RPC
  396. */
  397. int NetconEthernetTap::send_return_value(TcpConnection *conn, int retval)
  398. {
  399. char retmsg[4];
  400. memset(&retmsg, '\0', sizeof(retmsg));
  401. retmsg[0]=RPC_RETVAL;
  402. memcpy(&retmsg[1], &retval, sizeof(retval));
  403. int n = write(_phy.getDescriptor(conn->rpcSock), &retmsg, sizeof(retmsg));
  404. if(n > 0) {
  405. // signal that we've satisfied this requirement
  406. conn->pending = false;
  407. }
  408. else {
  409. fprintf(stderr, "unable to send return value to the intercept\n");
  410. closeConnection(conn);
  411. }
  412. return n;
  413. }
  414. /*------------------------------------------------------------------------------
  415. --------------------------------- LWIP callbacks -------------------------------
  416. ------------------------------------------------------------------------------*/
  417. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  418. // locked in this case!
  419. /*
  420. * Callback from LWIP to do whatever work we might need to do.
  421. *
  422. * @param associated service state object
  423. * @param PCB we're polling on
  424. * @return ERR_OK if everything is ok, -1 otherwise
  425. *
  426. */
  427. err_t NetconEthernetTap::nc_poll(void* arg, struct tcp_pcb *tpcb)
  428. {
  429. //fprintf(stderr, "nc_poll\n");
  430. /*
  431. Larg *l = (Larg*)arg;
  432. TcpConnection *conn = l->conn;
  433. NetconEthernetTap *tap = l->tap;
  434. if(conn && conn->idx) // if valid connection and non-zero index (indicating data present)
  435. tap->handle_write(conn);
  436. */
  437. return ERR_OK;
  438. }
  439. /*
  440. * Callback from LWIP for when a connection has been accepted and the PCB has been
  441. * put into an ACCEPT state.
  442. *
  443. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  444. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  445. * is then required to tell the service what new file descriptor it has allocated
  446. * for this connection. After the mapping is complete, the accepted socket can be
  447. * used.
  448. *
  449. * @param associated service state object
  450. * @param newly allocated PCB
  451. * @param error code
  452. * @return ERR_OK if everything is ok, -1 otherwise
  453. *
  454. */
  455. err_t NetconEthernetTap::nc_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
  456. {
  457. fprintf(stderr, "nc_accept()\n");
  458. Larg *l = (Larg*)arg;
  459. TcpConnection *conn = l->conn;
  460. NetconEthernetTap *tap = l->tap;
  461. int larg_fd = tap->_phy.getDescriptor(conn->dataSock);
  462. if(conn) {
  463. ZT_PHY_SOCKFD_TYPE fds[2];
  464. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  465. TcpConnection *new_tcp_conn = new TcpConnection();
  466. new_tcp_conn->dataSock = tap->_phy.wrapSocket(fds[0], new_tcp_conn);
  467. new_tcp_conn->rpcSock = conn->rpcSock;
  468. new_tcp_conn->pcb = newpcb;
  469. new_tcp_conn->their_fd = fds[1];
  470. tap->tcp_connections.push_back(new_tcp_conn);
  471. int send_fd = tap->_phy.getDescriptor(conn->rpcSock);
  472. int n = write(larg_fd, "z", 1);
  473. if(n > 0) {
  474. if(sock_fd_write(send_fd, fds[1]) > 0) {
  475. new_tcp_conn->pending = true;
  476. fprintf(stderr, "nc_accept(): socketpair = { our=%d, their=%d}\n", fds[0], fds[1]);
  477. }
  478. else {
  479. fprintf(stderr, "nc_accept(%d): unable to send fd to client\n", larg_fd);
  480. }
  481. }
  482. else {
  483. fprintf(stderr, "nc_accept(%d): error writing signal byte (send_fd = %d, perceived_fd = %d)\n", larg_fd, send_fd, fds[1]);
  484. return -1;
  485. }
  486. tap->lwipstack->_tcp_arg(newpcb, new Larg(tap, new_tcp_conn));
  487. tap->lwipstack->_tcp_recv(newpcb, nc_recved);
  488. tap->lwipstack->_tcp_err(newpcb, nc_err);
  489. tap->lwipstack->_tcp_sent(newpcb, nc_sent);
  490. tap->lwipstack->_tcp_poll(newpcb, nc_poll, 1);
  491. tcp_accepted(conn->pcb);
  492. return ERR_OK;
  493. }
  494. else {
  495. fprintf(stderr, "nc_accept(%d): can't locate Connection object for PCB.\n", larg_fd);
  496. }
  497. return -1;
  498. }
  499. /*
  500. * Callback from LWIP for when data is available to be read from the network.
  501. *
  502. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  503. * send to the client over the associated unix socket.
  504. *
  505. * @param associated service state object
  506. * @param allocated PCB
  507. * @param chain of pbufs
  508. * @param error code
  509. * @return ERR_OK if everything is ok, -1 otherwise
  510. *
  511. */
  512. err_t NetconEthernetTap::nc_recved(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  513. {
  514. fprintf(stderr, "nc_recved()\n");
  515. Larg *l = (Larg*)arg;
  516. int n;
  517. struct pbuf* q = p;
  518. if(!l->conn) {
  519. fprintf(stderr, "nc_recved(): no connection object\n");
  520. return ERR_OK; // ?
  521. }
  522. if(p == NULL) {
  523. if(l->conn) {
  524. fprintf(stderr, "nc_recved(): closing connection\n");
  525. l->tap->closeConnection(l->conn);
  526. }
  527. else {
  528. fprintf(stderr, "nc_recved(): can't locate connection via (arg)\n");
  529. }
  530. return err;
  531. }
  532. q = p;
  533. while(p != NULL) { // Cycle through pbufs and write them to the socket
  534. if(p->len <= 0)
  535. break; // ?
  536. if((n = l->tap->_phy.streamSend(l->conn->dataSock,p->payload, p->len)) > 0) {
  537. if(n < p->len) {
  538. fprintf(stderr, "nc_recved(): unable to write entire pbuf to buffer\n");
  539. }
  540. l->tap->lwipstack->_tcp_recved(tpcb, n); // TODO: would it be more efficient to call this once at the end?
  541. }
  542. else {
  543. fprintf(stderr, "nc_recved(): No data written to intercept buffer\n");
  544. }
  545. p = p->next;
  546. }
  547. l->tap->lwipstack->_pbuf_free(q); // free pbufs
  548. return ERR_OK;
  549. }
  550. /*
  551. * Callback from LWIP when an internal error is associtated with the given (arg)
  552. *
  553. * Since the PCB related to this error might no longer exist, only its perviously
  554. * associated (arg) is provided to us.
  555. *
  556. * @param associated service state object
  557. * @param error code
  558. *
  559. */
  560. void NetconEthernetTap::nc_err(void *arg, err_t err)
  561. {
  562. //fprintf(stderr, "nc_err\n");
  563. Larg *l = (Larg*)arg;
  564. if(l->conn) {
  565. fprintf(stderr, "nc_err(): closing connection\n");
  566. l->tap->closeConnection(l->conn);
  567. }
  568. else {
  569. fprintf(stderr, "nc_err(): can't locate connection object for PCB\n");
  570. }
  571. }
  572. /*
  573. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  574. * As a result, we should put our socket back into a notify-on-readability state
  575. * since there is now room on the PCB buffer to write to.
  576. *
  577. * NOTE: This could be used to track the amount of data sent by a connection.
  578. *
  579. * @param associated service state object
  580. * @param relevant PCB
  581. * @param length of data sent
  582. * @return ERR_OK if everything is ok, -1 otherwise
  583. *
  584. */
  585. err_t NetconEthernetTap::nc_sent(void* arg, struct tcp_pcb *tpcb, u16_t len)
  586. {
  587. Larg *l = (Larg*)arg;
  588. if(len) {
  589. //fprintf(stderr, "ACKING len = %d, setting read-notify = true, (sndbuf = %d)\n", len, l->conn->pcb->snd_buf);
  590. l->tap->_phy.setNotifyReadable(l->conn->dataSock, true);
  591. //l->tap->_phy.whack();
  592. //l->tap->handle_write(l->conn);
  593. }
  594. return ERR_OK;
  595. }
  596. /*
  597. * Callback from LWIP which sends a return value to the client to signal that
  598. * a connection was established for this PCB
  599. *
  600. * @param associated service state object
  601. * @param relevant PCB
  602. * @param error code
  603. * @return ERR_OK if everything is ok, -1 otherwise
  604. *
  605. */
  606. err_t NetconEthernetTap::nc_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
  607. {
  608. //fprintf(stderr, "nc_connected\n");
  609. Larg *l = (Larg*)arg;
  610. l->tap->send_return_value(l->conn, err);
  611. return ERR_OK;
  612. }
  613. /*------------------------------------------------------------------------------
  614. ----------------------------- RPC Handler functions ----------------------------
  615. ------------------------------------------------------------------------------*/
  616. /*
  617. * Handles an RPC to bind an LWIP PCB to a given address and port
  618. *
  619. * @param Client that is making the RPC
  620. * @param structure containing the data and parameters for this client's RPC
  621. *
  622. */
  623. void NetconEthernetTap::handle_bind(PhySocket *sock, void **uptr, struct bind_st *bind_rpc)
  624. {
  625. struct sockaddr_in *connaddr;
  626. connaddr = (struct sockaddr_in *) &bind_rpc->addr;
  627. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  628. ip_addr_t conn_addr;
  629. conn_addr.addr = *((u32_t *)_ips[0].rawIpData());
  630. TcpConnection *conn = getConnectionByTheirFD(bind_rpc->sockfd);
  631. if(conn) {
  632. if(conn->pcb->state == CLOSED){
  633. int err = lwipstack->tcp_bind(conn->pcb, &conn_addr, conn_port);
  634. if(err != ERR_OK) {
  635. int ip = connaddr->sin_addr.s_addr;
  636. unsigned char d[4];
  637. d[0] = ip & 0xFF;
  638. d[1] = (ip >> 8) & 0xFF;
  639. d[2] = (ip >> 16) & 0xFF;
  640. d[3] = (ip >> 24) & 0xFF;
  641. fprintf(stderr, "handle_bind(): error binding to %d.%d.%d.%d : %d\n", d[0],d[1],d[2],d[3], conn_port);
  642. }
  643. }
  644. else fprintf(stderr, "handle_bind(): PCB not in CLOSED state. Ignoring BIND request.\n");
  645. }
  646. else fprintf(stderr, "handle_bind(): can't locate connection for PCB\n");
  647. }
  648. /*
  649. * Handles an RPC to put an LWIP PCB into LISTEN mode
  650. *
  651. * @param Client that is making the RPC
  652. * @param structure containing the data and parameters for this client's RPC
  653. *
  654. */
  655. void NetconEthernetTap::handle_listen(PhySocket *sock, void **uptr, struct listen_st *listen_rpc)
  656. {
  657. TcpConnection *conn = getConnectionByTheirFD(listen_rpc->sockfd);
  658. if(conn) {
  659. if(conn->pcb->state == LISTEN) {
  660. fprintf(stderr, "handle_listen(): PCB is already in listening state.\n");
  661. return;
  662. }
  663. struct tcp_pcb* listening_pcb = lwipstack->tcp_listen(conn->pcb);
  664. if(listening_pcb != NULL) {
  665. conn->pcb = listening_pcb;
  666. lwipstack->tcp_accept(listening_pcb, nc_accept);
  667. lwipstack->tcp_arg(listening_pcb, new Larg(this, conn));
  668. /* we need to wait for the client to send us the fd allocated on their end
  669. for this listening socket */
  670. conn->pending = true;
  671. }
  672. else {
  673. fprintf(stderr, "handle_listen(): unable to allocate memory for new listening PCB\n");
  674. }
  675. }
  676. else {
  677. fprintf(stderr, "handle_listen(): can't locate connection for PCB\n");
  678. }
  679. }
  680. /**
  681. * Handles a return value (client's perceived fd) and completes a mapping
  682. * so that we know what connection an RPC call should be associated with.
  683. *
  684. * @param Client that is making the RPC
  685. * @param structure containing the data and parameters for this client's RPC
  686. *
  687. */
  688. void NetconEthernetTap::handle_retval(PhySocket *sock, void **uptr, unsigned char* buf)
  689. {
  690. TcpConnection *conn = (TcpConnection*)*uptr;
  691. if(conn->pending) {
  692. memcpy(&(conn->perceived_fd), &buf[1], sizeof(int));
  693. //fprintf(stderr, "handle_retval(): Mapping [our=%d -> their=%d]\n",
  694. //_phy.getDescriptor(conn->dataSock), conn->perceived_fd);
  695. conn->pending = false;
  696. }
  697. }
  698. /*
  699. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  700. *
  701. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  702. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  703. * is then required to tell the service what new file descriptor it has allocated
  704. * for this connection. After the mapping is complete, the socket can be used.
  705. *
  706. * @param Client that is making the RPC
  707. * @param structure containing the data and parameters for this client's RPC
  708. *
  709. */
  710. void NetconEthernetTap::handle_socket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc)
  711. {
  712. struct tcp_pcb *newpcb = lwipstack->tcp_new();
  713. if(newpcb != NULL) {
  714. ZT_PHY_SOCKFD_TYPE fds[2];
  715. socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
  716. TcpConnection *new_conn = new TcpConnection();
  717. new_conn->dataSock = _phy.wrapSocket(fds[0], new_conn);
  718. *uptr = new_conn;
  719. new_conn->rpcSock = sock;
  720. new_conn->pcb = newpcb;
  721. new_conn->their_fd = fds[1];
  722. tcp_connections.push_back(new_conn);
  723. sock_fd_write(_phy.getDescriptor(sock), fds[1]);
  724. //fprintf(stderr, "handle_socket(): socketpair = { our=%d, their=%d}\n", fds[0], fds[1]);
  725. /* Once the client tells us what its fd is for the other end,
  726. we can then complete the mapping */
  727. new_conn->pending = true;
  728. }
  729. else {
  730. fprintf(stderr, "handle_socket(): Memory not available for new PCB\n");
  731. }
  732. }
  733. /*
  734. * Handles an RPC to connect to a given address and port
  735. *
  736. * @param Client that is making the RPC
  737. * @param structure containing the data and parameters for this client's RPC
  738. *
  739. */
  740. void NetconEthernetTap::handle_connect(PhySocket *sock, void **uptr, struct connect_st* connect_rpc)
  741. {
  742. TcpConnection *conn = (TcpConnection*)*uptr;
  743. struct sockaddr_in *connaddr;
  744. connaddr = (struct sockaddr_in *) &connect_rpc->__addr;
  745. int conn_port = lwipstack->ntohs(connaddr->sin_port);
  746. ip_addr_t conn_addr = convert_ip((struct sockaddr_in *)&connect_rpc->__addr);
  747. if(conn != NULL) {
  748. lwipstack->tcp_sent(conn->pcb, nc_sent); // FIXME: Move?
  749. lwipstack->tcp_recv(conn->pcb, nc_recved);
  750. lwipstack->tcp_err(conn->pcb, nc_err);
  751. lwipstack->tcp_poll(conn->pcb, nc_poll, APPLICATION_POLL_FREQ);
  752. lwipstack->tcp_arg(conn->pcb, new Larg(this, conn));
  753. int err = 0;
  754. if((err = lwipstack->tcp_connect(conn->pcb,&conn_addr,conn_port, nc_connected)) < 0)
  755. {
  756. fprintf(stderr, "handle_connect(): unable to connect\n");
  757. // We should only return a value if failure happens immediately
  758. // Otherwise, we still need to wait for a callback from lwIP.
  759. // - This is because an ERR_OK from tcp_connect() only verifies
  760. // that the SYN packet was enqueued onto the stack properly,
  761. // that's it!
  762. // - Most instances of a retval for a connect() should happen
  763. // in the nc_connect() and nc_err() callbacks!
  764. send_return_value(conn, err);
  765. }
  766. // Everything seems to be ok, but we don't have enough info to retval
  767. conn->pending=true;
  768. }
  769. else {
  770. fprintf(stderr, "could not locate PCB based on their fd\n");
  771. }
  772. }
  773. void NetconEthernetTap::handle_write(TcpConnection *conn)
  774. {
  775. float max = (float)TCP_SND_BUF;
  776. int r;
  777. if(!conn) {
  778. fprintf(stderr, "handle_write(): could not locate connection for this fd\n");
  779. return;
  780. }
  781. if(conn->idx < max) {
  782. int sndbuf = conn->pcb->snd_buf; // How much we are currently allowed to write to the connection
  783. /* PCB send buffer is full,turn off readability notifications for the
  784. corresponding PhySocket until nc_sent() is called and confirms that there is
  785. now space on the buffer */
  786. if(sndbuf == 0) {
  787. //fprintf(stderr, "sndbuf = 0, setting read-notify = false\n");
  788. _phy.setNotifyReadable(conn->dataSock, false);
  789. lwipstack->_tcp_output(conn->pcb);
  790. return;
  791. }
  792. int read_fd = _phy.getDescriptor(conn->dataSock);
  793. if((r = read(read_fd, (&conn->buf)+conn->idx, sndbuf)) > 0) {
  794. //fprintf(stderr, "read = %d\n", r);
  795. conn->idx += r;
  796. /* Writes data pulled from the client's socket buffer to LWIP. This merely sends the
  797. * data to LWIP to be enqueued and eventually sent to the network. */
  798. if(r > 0) {
  799. int sz;
  800. // NOTE: this assumes that lwipstack->_lock is locked, either
  801. // because we are in a callback or have locked it manually.
  802. int err = lwipstack->_tcp_write(conn->pcb, &conn->buf, r, TCP_WRITE_FLAG_COPY);
  803. if(err != ERR_OK) {
  804. fprintf(stderr, "handle_write(): error while writing to PCB\n");
  805. return;
  806. }
  807. else {
  808. sz = (conn->idx)-r;
  809. if(sz) {
  810. memmove(&conn->buf, (conn->buf+r), sz);
  811. }
  812. conn->idx -= r;
  813. return;
  814. }
  815. }
  816. else {
  817. fprintf(stderr, "handle_write(): LWIP stack full\n");
  818. return;
  819. }
  820. }
  821. //else {
  822. // fprintf(stderr, "handle_write(): could not read from PhySocket for this connection\n");
  823. //}
  824. }
  825. }
  826. } // namespace ZeroTier
  827. #endif // ZT_ENABLE_NETCON