NetconEthernetTap.cpp 44 KB

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