NetconEthernetTap.cpp 45 KB

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