NetconEthernetTap.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. #ifndef ZT_NETCONETHERNETTAP_HPP
  28. #define ZT_NETCONETHERNETTAP_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string>
  32. #include <vector>
  33. #include <utility>
  34. #include <stdexcept>
  35. #include <stdint.h>
  36. #include "../node/Constants.hpp"
  37. #include "../node/MulticastGroup.hpp"
  38. #include "../node/Mutex.hpp"
  39. #include "../node/InetAddress.hpp"
  40. #include "../osdep/Thread.hpp"
  41. #include "../osdep/Phy.hpp"
  42. #include "netif/etharp.h"
  43. #include "RPC.h"
  44. struct tcp_pcb;
  45. struct socket_st;
  46. struct listen_st;
  47. struct bind_st;
  48. struct connect_st;
  49. struct getsockname_st;
  50. struct accept_st;
  51. #define APPLICATION_POLL_FREQ 2
  52. #define ZT_LWIP_TCP_TIMER_INTERVAL 5
  53. #define STATUS_TMR_INTERVAL 250 // How often we check connection statuses (in ms)
  54. #define DEFAULT_BUF_SZ 1024 * 1024 * 2
  55. #define DEFAULT_BUF_SOFTMAX DEFAULT_BUF_SZ / 2
  56. namespace ZeroTier {
  57. class NetconEthernetTap;
  58. class LWIPStack;
  59. /*
  60. * TCP connection administered by service
  61. */
  62. struct TcpConnection
  63. {
  64. bool listening, probation;
  65. int pid, txsz, rxsz;
  66. PhySocket *rpcSock, *sock;
  67. struct tcp_pcb *pcb;
  68. struct sockaddr_storage *addr;
  69. unsigned char txbuf[DEFAULT_BUF_SZ];
  70. unsigned char rxbuf[DEFAULT_BUF_SZ];
  71. };
  72. /*
  73. * A helper for passing a reference to _phy to LWIP callbacks as a "state"
  74. */
  75. struct Larg
  76. {
  77. NetconEthernetTap *tap;
  78. TcpConnection *conn;
  79. Larg(NetconEthernetTap *_tap, TcpConnection *conn) : tap(_tap), conn(conn) {}
  80. };
  81. /*
  82. * Network Containers instance -- emulates an Ethernet tap device as far as OneService knows
  83. */
  84. class NetconEthernetTap
  85. {
  86. friend class Phy<NetconEthernetTap *>;
  87. public:
  88. NetconEthernetTap(
  89. const char *homePath,
  90. const MAC &mac,
  91. unsigned int mtu,
  92. unsigned int metric,
  93. uint64_t nwid,
  94. const char *friendlyName,
  95. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  96. void *arg);
  97. ~NetconEthernetTap();
  98. void setEnabled(bool en);
  99. bool enabled() const;
  100. bool addIp(const InetAddress &ip);
  101. bool removeIp(const InetAddress &ip);
  102. std::vector<InetAddress> ips() const;
  103. void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len);
  104. std::string deviceName() const;
  105. void setFriendlyName(const char *friendlyName);
  106. void scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed);
  107. void threadMain()
  108. throw();
  109. LWIPStack *lwipstack;
  110. uint64_t _nwid;
  111. void (*_handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
  112. void *_arg;
  113. private:
  114. // LWIP callbacks
  115. // NOTE: these are called from within LWIP, meaning that lwipstack->_lock is ALREADY
  116. // locked in this case!
  117. /*
  118. * Callback from LWIP for when a connection has been accepted and the PCB has been
  119. * put into an ACCEPT state.
  120. *
  121. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  122. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  123. * is then required to tell the service what new file descriptor it has allocated
  124. * for this connection. After the mapping is complete, the accepted socket can be
  125. * used.
  126. *
  127. * @param associated service state object
  128. * @param newly allocated PCB
  129. * @param error code
  130. * @return ERR_OK if everything is ok, -1 otherwise
  131. *
  132. * i := should be implemented in intercept lib
  133. * I := is implemented in intercept lib
  134. * X := is implemented in service
  135. * ? := required treatment Unknown
  136. * - := Not needed
  137. *
  138. * [ ] EAGAIN or EWOULDBLOCK - The socket is marked nonblocking and no connections are present
  139. * to be accepted. POSIX.1-2001 allows either error to be returned for
  140. * this case, and does not require these constants to have the same value,
  141. * so a portable application should check for both possibilities.
  142. * [I] EBADF - The descriptor is invalid.
  143. * [I] ECONNABORTED - A connection has been aborted.
  144. * [i] EFAULT - The addr argument is not in a writable part of the user address space.
  145. * [-] EINTR - The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).
  146. * [I] EINVAL - Socket is not listening for connections, or addrlen is invalid (e.g., is negative).
  147. * [I] EINVAL - (accept4()) invalid value in flags.
  148. * [I] EMFILE - The per-process limit of open file descriptors has been reached.
  149. * [ ] ENFILE - The system limit on the total number of open files has been reached.
  150. * [ ] ENOBUFS, ENOMEM - Not enough free memory. This often means that the memory allocation is
  151. * limited by the socket buffer limits, not by the system memory.
  152. * [I] ENOTSOCK - The descriptor references a file, not a socket.
  153. * [I] EOPNOTSUPP - The referenced socket is not of type SOCK_STREAM.
  154. * [ ] EPROTO - Protocol error.
  155. *
  156. */
  157. static err_t nc_accept(void *arg, struct tcp_pcb *newPCB, err_t err);
  158. /*
  159. * Callback from LWIP for when data is available to be read from the network.
  160. *
  161. * Data is in the form of a linked list of struct pbufs, it is then recombined and
  162. * send to the client over the associated unix socket.
  163. *
  164. * @param associated service state object
  165. * @param allocated PCB
  166. * @param chain of pbufs
  167. * @param error code
  168. * @return ERR_OK if everything is ok, -1 otherwise
  169. *
  170. */
  171. static err_t nc_recved(void *arg, struct tcp_pcb *PCB, struct pbuf *p, err_t err);
  172. /*
  173. * Callback from LWIP when an internal error is associtated with the given (arg)
  174. *
  175. * Since the PCB related to this error might no longer exist, only its perviously
  176. * associated (arg) is provided to us.
  177. *
  178. * @param associated service state object
  179. * @param error code
  180. *
  181. */
  182. static void nc_err(void *arg, err_t err);
  183. /*
  184. * Callback from LWIP to do whatever work we might need to do.
  185. *
  186. * @param associated service state object
  187. * @param PCB we're polling on
  188. * @return ERR_OK if everything is ok, -1 otherwise
  189. *
  190. */
  191. static err_t nc_poll(void* arg, struct tcp_pcb *PCB);
  192. /*
  193. * Callback from LWIP to signal that 'len' bytes have successfully been sent.
  194. * As a result, we should put our socket back into a notify-on-readability state
  195. * since there is now room on the PCB buffer to write to.
  196. *
  197. * NOTE: This could be used to track the amount of data sent by a connection.
  198. *
  199. * @param associated service state object
  200. * @param relevant PCB
  201. * @param length of data sent
  202. * @return ERR_OK if everything is ok, -1 otherwise
  203. *
  204. */
  205. static err_t nc_sent(void *arg, struct tcp_pcb *PCB, u16_t len);
  206. /*
  207. * Callback from LWIP which sends a return value to the client to signal that
  208. * a connection was established for this PCB
  209. *
  210. * @param associated service state object
  211. * @param relevant PCB
  212. * @param error code
  213. * @return ERR_OK if everything is ok, -1 otherwise
  214. *
  215. */
  216. static err_t nc_connected(void *arg, struct tcp_pcb *PCB, err_t err);
  217. //static void nc_close(struct tcp_pcb *PCB);
  218. //static err_t nc_send(struct tcp_pcb *PCB);
  219. /*
  220. * Handles an RPC to bind an LWIP PCB to a given address and port
  221. *
  222. * @param PhySocket associated with this RPC connection
  223. * @param structure containing the data and parameters for this client's RPC
  224. *
  225. i := should be implemented in intercept lib
  226. I := is implemented in intercept lib
  227. X := is implemented in service
  228. ? := required treatment Unknown
  229. - := Not needed
  230. [ ] EACCES - The address is protected, and the user is not the superuser.
  231. [X] EADDRINUSE - The given address is already in use.
  232. [I] EBADF - sockfd is not a valid descriptor.
  233. [X] EINVAL - The socket is already bound to an address.
  234. [I] ENOTSOCK - sockfd is a descriptor for a file, not a socket.
  235. [X] ENOMEM - Insufficient kernel memory was available.
  236. - The following errors are specific to UNIX domain (AF_UNIX) sockets:
  237. [-] EACCES - Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
  238. [-] EADDRNOTAVAIL - A nonexistent interface was requested or the requested address was not local.
  239. [-] EFAULT - addr points outside the user's accessible address space.
  240. [-] EINVAL - The addrlen is wrong, or the socket was not in the AF_UNIX family.
  241. [-] ELOOP - Too many symbolic links were encountered in resolving addr.
  242. [-] ENAMETOOLONG - s addr is too long.
  243. [-] ENOENT - The file does not exist.
  244. [-] ENOTDIR - A component of the path prefix is not a directory.
  245. [-] EROFS - The socket inode would reside on a read-only file system.
  246. */
  247. void handleBind(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct bind_st *bind_rpc);
  248. /*
  249. * Handles an RPC to put an LWIP PCB into LISTEN mode
  250. *
  251. * @param PhySocket associated with this RPC connection
  252. * @param structure containing the data and parameters for this client's RPC
  253. *
  254. i := should be implemented in intercept lib
  255. I := is implemented in intercept lib
  256. X := is implemented in service
  257. ? := required treatment Unknown
  258. - := Not needed
  259. [?] EADDRINUSE - Another socket is already listening on the same port.
  260. [IX] EBADF - The argument sockfd is not a valid descriptor.
  261. [I] ENOTSOCK - The argument sockfd is not a socket.
  262. [I] EOPNOTSUPP - The socket is not of a type that supports the listen() operation.
  263. */
  264. void handleListen(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct listen_st *listen_rpc);
  265. /*
  266. * Handles an RPC to create a socket (LWIP PCB and associated socketpair)
  267. *
  268. * A socketpair is created, one end is kept and wrapped into a PhySocket object
  269. * for use in the main ZT I/O loop, and one end is sent to the client. The client
  270. * is then required to tell the service what new file descriptor it has allocated
  271. * for this connection. After the mapping is complete, the socket can be used.
  272. *
  273. * @param PhySocket associated with this RPC connection
  274. * @param structure containing the data and parameters for this client's RPC
  275. *
  276. i := should be implemented in intercept lib
  277. I := is implemented in intercept lib
  278. X := is implemented in service
  279. ? := required treatment Unknown
  280. - := Not needed
  281. [-] EACCES - Permission to create a socket of the specified type and/or protocol is denied.
  282. [I] EAFNOSUPPORT - The implementation does not support the specified address family.
  283. [I] EINVAL - Unknown protocol, or protocol family not available.
  284. [I] EINVAL - Invalid flags in type.
  285. [I] EMFILE - Process file table overflow.
  286. [?] ENFILE - The system limit on the total number of open files has been reached.
  287. [X] ENOBUFS or ENOMEM - Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
  288. [?] EPROTONOSUPPORT - The protocol type or the specified protocol is not supported within this domain.
  289. */
  290. TcpConnection * handleSocket(PhySocket *sock, void **uptr, struct socket_st* socket_rpc);
  291. /*
  292. * Handles an RPC to connect to a given address and port
  293. *
  294. * @param PhySocket associated with this RPC connection
  295. * @param structure containing the data and parameters for this client's RPC
  296. --- Error handling in this method will only catch problems which are immedately
  297. apprent. Some errors will need to be caught in the nc_connected(0 callback
  298. i := should be implemented in intercept lib
  299. I := is implemented in intercept lib
  300. X := is implemented in service
  301. ? := required treatment Unknown
  302. - := Not needed
  303. [-] EACCES - For UNIX domain sockets, which are identified by pathname: Write permission is denied ...
  304. [?] EACCES, EPERM - The user tried to connect to a broadcast address without having the socket broadcast flag enabled ...
  305. [X] EADDRINUSE - Local address is already in use.
  306. [I] EAFNOSUPPORT - The passed address didn't have the correct address family in its sa_family field.
  307. [X] EAGAIN - No more free local ports or insufficient entries in the routing cache.
  308. [ ] EALREADY - The socket is nonblocking and a previous connection attempt has not yet been completed.
  309. [IX] EBADF - The file descriptor is not a valid index in the descriptor table.
  310. [ ] ECONNREFUSED - No-one listening on the remote address.
  311. [i] EFAULT - The socket structure address is outside the user's address space.
  312. [ ] EINPROGRESS - The socket is nonblocking and the connection cannot be completed immediately.
  313. [-] EINTR - The system call was interrupted by a signal that was caught.
  314. [X] EISCONN - The socket is already connected.
  315. [X] ENETUNREACH - Network is unreachable.
  316. [I] ENOTSOCK - The file descriptor is not associated with a socket.
  317. [X] ETIMEDOUT - Timeout while attempting connection.
  318. [X] EINVAL - Invalid argument, SVr4, generally makes sense to set this
  319. */
  320. void handleConnect(PhySocket *sock, PhySocket *rpcsock, TcpConnection *conn, struct connect_st* connect_rpc);
  321. /*
  322. * Return the address that the socket is bound to
  323. */
  324. void handleGetsockname(PhySocket *sock, PhySocket *rpcsock, void **uptr, struct getsockname_st *getsockname_rpc);
  325. /*
  326. * Writes data from the application's socket to the LWIP connection
  327. */
  328. void handleWrite(TcpConnection *conn);
  329. /*
  330. * Sends a return value to the intercepted application
  331. */
  332. int sendReturnValue(PhySocket *sock, int retval, int _errno);
  333. int sendReturnValue(int fd, int retval, int _errno);
  334. /*
  335. * Unpacks the buffer from an RPC command
  336. */
  337. void unloadRPC(void *data, pid_t &pid, pid_t &tid,
  338. int &rpc_count, char (timestamp[RPC_TIMESTAMP_SZ]), char (magic[sizeof(uint64_t)]), char &cmd, void* &payload);
  339. // Unused -- no UDP or TCP from this thread/Phy<>
  340. void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len);
  341. void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success);
  342. void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from);
  343. void phyOnTcpClose(PhySocket *sock,void **uptr);
  344. void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len);
  345. void phyOnTcpWritable(PhySocket *sock,void **uptr);
  346. /*
  347. * Signals us to close the TcpConnection associated with this PhySocket
  348. */
  349. void phyOnUnixClose(PhySocket *sock,void **uptr);
  350. /*
  351. * Notifies us that there is data to be read from an application's socket
  352. */
  353. void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len);
  354. /*
  355. * Notifies us that we can write to an application's socket
  356. */
  357. void phyOnUnixWritable(PhySocket *sock,void **uptr,bool lwip_invoked);
  358. /*
  359. * Returns a pointer to a TcpConnection associated with a given PhySocket
  360. */
  361. TcpConnection *getConnection(PhySocket *sock);
  362. /*
  363. * Closes a TcpConnection, associated LWIP PCB strcuture,
  364. * PhySocket, and underlying file descriptor
  365. */
  366. void closeConnection(PhySocket *sock);
  367. ip_addr_t convert_ip(struct sockaddr_in * addr)
  368. {
  369. ip_addr_t conn_addr;
  370. struct sockaddr_in *ipv4 = addr;
  371. short a = ip4_addr1(&(ipv4->sin_addr));
  372. short b = ip4_addr2(&(ipv4->sin_addr));
  373. short c = ip4_addr3(&(ipv4->sin_addr));
  374. short d = ip4_addr4(&(ipv4->sin_addr));
  375. IP4_ADDR(&conn_addr, a,b,c,d);
  376. return conn_addr;
  377. }
  378. Phy<NetconEthernetTap *> _phy;
  379. PhySocket *_unixListenSocket;
  380. std::vector<TcpConnection*> _TcpConnections;
  381. std::map<uint64_t, std::pair<PhySocket*, void*> > jobmap;
  382. pid_t rpcCounter;
  383. netif interface;
  384. MAC _mac;
  385. Thread _thread;
  386. std::string _homePath;
  387. std::string _dev; // path to Unix domain socket
  388. std::vector<MulticastGroup> _multicastGroups;
  389. Mutex _multicastGroups_m;
  390. std::vector<InetAddress> _ips;
  391. Mutex _ips_m, _tcpconns_m, _rx_buf_m;
  392. unsigned int _mtu;
  393. volatile bool _enabled;
  394. volatile bool _run;
  395. };
  396. } // namespace ZeroTier
  397. #endif