Intercept.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifdef USE_GNU_SOURCE
  28. #define _GNU_SOURCE
  29. #endif
  30. /* Name used in err msgs */
  31. char *progname = "";
  32. #include <unistd.h>
  33. #include <stdint.h>
  34. #include <pthread.h>
  35. #include <stdio.h>
  36. #include <dlfcn.h>
  37. #include <strings.h>
  38. #include <netinet/in.h>
  39. #include <sys/time.h>
  40. #include <pwd.h>
  41. #include <errno.h>
  42. #include <linux/errno.h>
  43. #include <stdarg.h>
  44. #include <netdb.h>
  45. #include <string.h>
  46. #include <stdlib.h>
  47. #include <sys/syscall.h>
  48. #include <sys/types.h>
  49. #include <sys/socket.h>
  50. #include <sys/poll.h>
  51. #include <sys/un.h>
  52. #include <arpa/inet.h>
  53. #include "Intercept.h"
  54. #include "Common.h"
  55. #ifdef CHECKS
  56. #include <sys/resource.h>
  57. #include <linux/net.h> /* for NPROTO */
  58. #define SOCK_MAX (SOCK_PACKET + 1)
  59. #define SOCK_TYPE_MASK 0xf
  60. #endif
  61. /* Global Declarations */
  62. #ifdef USE_SOCKS_DNS
  63. static int (*realresinit)(void);
  64. #endif
  65. static int (*realconnect)(CONNECT_SIG);
  66. static int (*realselect)(SELECT_SIG);
  67. static int (*realbind)(BIND_SIG);
  68. static int (*realaccept)(ACCEPT_SIG);
  69. static int (*reallisten)(LISTEN_SIG);
  70. static int (*realsocket)(SOCKET_SIG);
  71. static int (*realsetsockopt)(SETSOCKOPT_SIG);
  72. static int (*realgetsockopt)(GETSOCKOPT_SIG);
  73. static int (*realaccept4)(ACCEPT4_SIG);
  74. static long (*realsyscall)(SYSCALL_SIG);
  75. //static int (*realclone)(CLONE_SIG);
  76. //static int (*realpoll)(POLL_SIG);
  77. /* Exported Function Prototypes */
  78. void my_init(void);
  79. int connect(CONNECT_SIG);
  80. int select(SELECT_SIG);
  81. int close(CLOSE_SIG);
  82. int bind(BIND_SIG);
  83. int accept(ACCEPT_SIG);
  84. int listen(LISTEN_SIG);
  85. int socket(SOCKET_SIG);
  86. int setsockopt(SETSOCKOPT_SIG);
  87. int getsockopt(GETSOCKOPT_SIG);
  88. int accept4(ACCEPT4_SIG);
  89. long syscall(SYSCALL_SIG);
  90. //int clone(CLONE_SIG);
  91. //int poll(POLL_SIG);
  92. #ifdef USE_SOCKS_DNS
  93. int res_init(void);
  94. #endif
  95. int connect_to_service(void);
  96. int init_service_connection();
  97. void dwr(const char *fmt, ...);
  98. void load_symbols(void);
  99. void set_up_intercept();
  100. int checkpid();
  101. #define SERVICE_CONNECT_ATTEMPTS 30
  102. ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd);
  103. /* threading */
  104. pthread_mutex_t lock;
  105. pthread_mutex_t loglock;
  106. void handle_error(char *name, char *info, int err)
  107. {
  108. #ifdef ERRORS_ARE_FATAL
  109. if(err < 0) {
  110. dwr("handle_error(%s)=%d: FATAL: %s\n", name, err, info);
  111. //exit(-1);
  112. }
  113. #endif
  114. #ifdef VERBOSE
  115. dwr("%s()=%d\n", name, err);
  116. #endif
  117. }
  118. /*------------------------------------------------------------------------------
  119. ------------------- Intercept<--->Service Comm mechanisms-----------------------
  120. ------------------------------------------------------------------------------*/
  121. static int is_initialized = 0;
  122. static int fdret_sock; // used for fd-transfers
  123. static int newfd; // used for "this_end" socket
  124. static int thispid;
  125. static char* af_sock_name = "/tmp/.ztnc_e5cd7a9e1c5311ab";
  126. /*
  127. * Check for forking
  128. */
  129. int checkpid() {
  130. if(thispid != getpid()) {
  131. printf("clone/fork detected. re-initializing this instance.\n");
  132. set_up_intercept();
  133. fdret_sock = init_service_connection();
  134. thispid = getpid();
  135. }
  136. return 0;
  137. }
  138. /*
  139. * Sends an RPC command to the service
  140. */
  141. void send_command(int rpc_fd, char *cmd)
  142. {
  143. int n_write = write(rpc_fd, cmd, BUF_SZ);
  144. if(n_write < 0){
  145. dwr("Error writing command to service (CMD = %d)\n", cmd[0]);
  146. errno = 0;
  147. }
  148. }
  149. /*
  150. * Reads a return value from the service and sets errno (if applicable)
  151. */
  152. int get_retval()
  153. {
  154. dwr("get_retval()\n");
  155. if(fdret_sock >= 0) {
  156. int retval;
  157. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  158. char retbuf[BUF_SZ];
  159. memset(&retbuf, '\0', sz);
  160. int n_read = read(fdret_sock, &retbuf, sz);
  161. if(n_read > 0) {
  162. memcpy(&retval, &retbuf[1], sizeof(retval));
  163. memcpy(&errno, &retbuf[1+sizeof(retval)], sizeof(errno));
  164. return retval;
  165. }
  166. }
  167. dwr("unable to read return value\n");
  168. return -1;
  169. }
  170. /* Check whether the socket is mapped to the service or not. We
  171. need to know if this is a regular AF_LOCAL socket or an end of a socketpair
  172. that the service uses. We don't want to keep state in the intercept, so
  173. we simply ask the service via an RPC */
  174. int is_mapped_to_service(int sockfd)
  175. {
  176. dwr("is_mapped_to_service()\n");
  177. char cmd[BUF_SZ];
  178. memset(cmd, '\0', BUF_SZ);
  179. cmd[0] = RPC_MAP_REQ;
  180. memcpy(&cmd[1], &sockfd, sizeof(sockfd));
  181. send_command(fdret_sock, cmd);
  182. return get_retval();
  183. }
  184. /*------------------------------------------------------------------------------
  185. ---------- Unix-domain socket lazy initializer (for fd-transfers)--------------
  186. ------------------------------------------------------------------------------*/
  187. /* Sets up the connection pipes and sockets to the service */
  188. int init_service_connection()
  189. {
  190. dwr("init_service_connection()\n");
  191. if(!is_initialized) {
  192. struct sockaddr_un addr;
  193. int tfd = -1, attempts = 0, conn_err = -1;
  194. memset(&addr, 0, sizeof(addr));
  195. addr.sun_family = AF_UNIX;
  196. strncpy(addr.sun_path, af_sock_name, sizeof(addr.sun_path)-1);
  197. if ( (tfd = realsocket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  198. perror("socket error");
  199. exit(-1);
  200. }
  201. while(conn_err < 0 && attempts < SERVICE_CONNECT_ATTEMPTS) {
  202. conn_err = realconnect(tfd, (struct sockaddr*)&addr, sizeof(addr));
  203. if(conn_err < 0) {
  204. dwr("re-attempting connection in %ds\n", 1+attempts);
  205. sleep(1);
  206. }
  207. else {
  208. dwr("AF_UNIX connection established: %d\n", tfd);
  209. is_initialized = 1;
  210. return tfd;
  211. }
  212. attempts++;
  213. }
  214. }
  215. return -1;
  216. }
  217. /*------------------------------------------------------------------------------
  218. ------------------------ ctors and dtors (and friends)-------------------------
  219. ------------------------------------------------------------------------------*/
  220. void my_dest(void) __attribute__ ((destructor));
  221. void my_dest(void) {
  222. //dwr("closing connections to service...\n");
  223. close(fdret_sock);
  224. pthread_mutex_destroy(&lock);
  225. }
  226. void load_symbols(void)
  227. {
  228. #ifdef USE_OLD_DLSYM
  229. void *lib;
  230. #endif
  231. /* possibly add check to beginning of each method to avoid needing to cll the constructor */
  232. if(thispid == getpid()) {
  233. dwr("detected duplicate call to global ctor (pid=%d).\n", thispid);
  234. }
  235. //dwr(" -- pid = %d\n", getpid());
  236. //dwr(" -- uid = %d\n", getuid());
  237. thispid = getpid();
  238. #ifndef USE_OLD_DLSYM
  239. realconnect = dlsym(RTLD_NEXT, "connect");
  240. realbind = dlsym(RTLD_NEXT, "bind");
  241. realaccept = dlsym(RTLD_NEXT, "accept");
  242. reallisten = dlsym(RTLD_NEXT, "listen");
  243. realsocket = dlsym(RTLD_NEXT, "socket");
  244. realbind = dlsym(RTLD_NEXT, "bind");
  245. realselect = dlsym(RTLD_NEXT, "select");
  246. realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
  247. realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
  248. realaccept4 = dlsym(RTLD_NEXT, "accept4");
  249. //realclone = dlsym(RTLD_NEXT, "clone");
  250. realsyscall = dlsym(RTLD_NEXT, "syscall");
  251. //realsyscall = dlsym(RTLD_NEXT, "poll");
  252. #ifdef USE_SOCKS_DNS
  253. realresinit = dlsym(RTLD_NEXT, "res_init");
  254. #endif
  255. #else
  256. lib = dlopen(LIBCONNECT, RTLD_LAZY);
  257. realconnect = dlsym(lib, "connect");
  258. realbind = dlsym(lib, "bind");
  259. realaccept = dlsym(lib, "accept");
  260. reallisten = dlsym(lib, "listen");
  261. realsocket = dlsym(lib, "socket");
  262. realselect = dlsym(lib, "select");
  263. realsetsockopt = dlsym(lib, "setsockopt");
  264. realgetsockopt = dlsym(lib, "getsockopt");
  265. realaccept4 = dlsym(lib), "accept4");
  266. //realclone = dlsym(lib, "clone");
  267. realsyscall = dlsym(lib, "syscall");
  268. //realsyscall = dlsym(lib, "poll");
  269. #ifdef USE_SOCKS_DNS
  270. realresinit = dlsym(lib, "res_init");
  271. #endif
  272. dlclose(lib);
  273. lib = dlopen(LIBC, RTLD_LAZY);
  274. dlclose(lib);
  275. #endif
  276. }
  277. /* Private Function Prototypes */
  278. void _init(void) __attribute__ ((constructor));
  279. void _init(void) {
  280. set_up_intercept();
  281. }
  282. /* get symbols and initialize mutexes */
  283. void set_up_intercept()
  284. {
  285. load_symbols();
  286. if(pthread_mutex_init(&lock, NULL) != 0) {
  287. printf("error while initializing service call mutex\n");
  288. }
  289. if(pthread_mutex_init(&loglock, NULL) != 0) {
  290. printf("error while initializing log mutex mutex\n");
  291. }
  292. }
  293. /*------------------------------------------------------------------------------
  294. --------------------------------- setsockopt() ---------------------------------
  295. ------------------------------------------------------------------------------*/
  296. /* int socket, int level, int option_name, const void *option_value, socklen_t option_len */
  297. int setsockopt(SETSOCKOPT_SIG)
  298. {
  299. dwr("setsockopt(%d)\n", socket);
  300. //return(realsetsockopt(socket, level, option_name, option_value, option_len));
  301. if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE)){
  302. return 0;
  303. }
  304. /* make sure we don't touch any standard outputs */
  305. if(socket == STDIN_FILENO || socket == STDOUT_FILENO || socket == STDERR_FILENO)
  306. return(realsetsockopt(socket, level, option_name, option_value, option_len));
  307. int err = realsetsockopt(socket, level, option_name, option_value, option_len);
  308. if(err < 0){
  309. //perror("setsockopt():\n");
  310. }
  311. return 0;
  312. }
  313. /*------------------------------------------------------------------------------
  314. --------------------------------- getsockopt() ---------------------------------
  315. ------------------------------------------------------------------------------*/
  316. /* int sockfd, int level, int optname, void *optval, socklen_t *optlen */
  317. int getsockopt(GETSOCKOPT_SIG)
  318. {
  319. dwr("setsockopt(%d)\n", sockfd);
  320. int err = realgetsockopt(sockfd, level, optname, optval, optlen);
  321. // FIXME: this condition will need a little more intelligence later on
  322. // -- we will need to know if this fd is a local we are spoofing, or a true local
  323. if(optname == SO_TYPE)
  324. {
  325. int* val = (int*)optval;
  326. *val = 2;
  327. optval = (void*)val;
  328. }
  329. if(err < 0){
  330. //perror("setsockopt():\n");
  331. }
  332. return 0;
  333. }
  334. /*------------------------------------------------------------------------------
  335. ----------------------------------- socket() -----------------------------------
  336. ------------------------------------------------------------------------------*/
  337. /* int socket_family, int socket_type, int protocol
  338. socket() intercept function */
  339. int socket(SOCKET_SIG)
  340. {
  341. dwr("socket()*:\n");
  342. int err;
  343. #ifdef CHECKS
  344. /* Check that type makes sense */
  345. int flags = socket_type & ~SOCK_TYPE_MASK;
  346. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  347. errno = EINVAL;
  348. handle_error("socket", "", -1);
  349. return -1;
  350. }
  351. socket_type &= SOCK_TYPE_MASK;
  352. /* Check protocol is in range */
  353. if (socket_family < 0 || socket_family >= NPROTO){
  354. errno = EAFNOSUPPORT;
  355. handle_error("socket", "", -1);
  356. return -1;
  357. }
  358. if (socket_type < 0 || socket_type >= SOCK_MAX) {
  359. errno = EINVAL;
  360. handle_error("socket", "", -1);
  361. return -1;
  362. }
  363. /* Check that we haven't hit the soft-limit file descriptors allowed */
  364. /* FIXME: Find number of open fds
  365. struct rlimit rl;
  366. getrlimit(RLIMIT_NOFILE, &rl);
  367. if(sockfd >= rl.rlim_cur){
  368. errno = EMFILE;
  369. return -1;
  370. }
  371. */
  372. /* FIXME: detect ENFILE condition */
  373. #endif
  374. char cmd[BUF_SZ];
  375. fdret_sock = !is_initialized ? init_service_connection() : fdret_sock;
  376. if(fdret_sock < 0) {
  377. dwr("BAD service connection. exiting.\n");
  378. handle_error("socket", "", -1);
  379. exit(-1);
  380. }
  381. if(socket_family == AF_LOCAL
  382. || socket_family == AF_NETLINK
  383. || socket_family == AF_UNIX) {
  384. int err = realsocket(socket_family, socket_type, protocol);
  385. dwr("realsocket, err = %d\n", err);
  386. handle_error("socket", "", err);
  387. return err;
  388. }
  389. /* Assemble and send RPC */
  390. struct socket_st rpc_st;
  391. rpc_st.socket_family = socket_family;
  392. rpc_st.socket_type = socket_type;
  393. rpc_st.protocol = protocol;
  394. rpc_st.__tid = syscall(SYS_gettid);
  395. memset(cmd, '\0', BUF_SZ);
  396. cmd[0] = RPC_SOCKET;
  397. memcpy(&cmd[1], &rpc_st, sizeof(struct socket_st));
  398. pthread_mutex_lock(&lock);
  399. dwr("sending RPC...\n");
  400. send_command(fdret_sock, cmd);
  401. /* get new fd */
  402. char rbuf[16];
  403. ssize_t sz = sock_fd_read(fdret_sock, rbuf, sizeof(rbuf), &newfd);
  404. if(sz > 0)
  405. {
  406. /* send our local-fd number back to service so
  407. it can complete its mapping table entry */
  408. memset(cmd, '\0', BUF_SZ);
  409. cmd[0] = RPC_MAP;
  410. memcpy(&cmd[1], &newfd, sizeof(newfd));
  411. //if(newfd > -1) {
  412. send_command(fdret_sock, cmd);
  413. pthread_mutex_unlock(&lock);
  414. errno = ERR_OK; // OK
  415. handle_error("socket", "", newfd);
  416. return newfd;
  417. //}
  418. /*
  419. else { // Try to read retval+errno since we RXed a bad fd
  420. dwr("Error, service sent bad fd.\n");
  421. err = get_retval();
  422. pthread_mutex_unlock(&lock);
  423. return err;
  424. }
  425. */
  426. }
  427. else {
  428. dwr("Error while receiving new FD.\n");
  429. err = get_retval();
  430. pthread_mutex_unlock(&lock);
  431. handle_error("socket", "", -1);
  432. return err;
  433. }
  434. }
  435. /*------------------------------------------------------------------------------
  436. ---------------------------------- connect() -----------------------------------
  437. ------------------------------------------------------------------------------*/
  438. /* int __fd, const struct sockaddr * __addr, socklen_t __len
  439. connect() intercept function */
  440. int connect(CONNECT_SIG)
  441. {
  442. dwr("connect(%d):\n", __fd);
  443. print_addr(__addr);
  444. struct sockaddr_in *connaddr;
  445. connaddr = (struct sockaddr_in *) __addr;
  446. #ifdef CHECKS
  447. /* Check that this is a valid fd */
  448. if(fcntl(__fd, F_GETFD) < 0) {
  449. errno = EBADF;
  450. handle_error("connect", "EBADF", -1);
  451. return -1;
  452. }
  453. /* Check that it is a socket */
  454. int sock_type;
  455. socklen_t sock_type_len = sizeof(sock_type);
  456. if(getsockopt(__fd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  457. errno = ENOTSOCK;
  458. handle_error("connect", "ENOTSOCK", -1);
  459. return -1;
  460. }
  461. /* Check family */
  462. if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
  463. errno = EAFNOSUPPORT;
  464. handle_error("connect", "EAFNOSUPPORT", -1);
  465. return -1;
  466. }
  467. /* FIXME: Check that address is in user space, return EFAULT ? */
  468. #endif
  469. /* make sure we don't touch any standard outputs */
  470. if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO){
  471. if (realconnect == NULL) {
  472. handle_error("connect", "Unresolved symbol [connect]", -1);
  473. exit(-1);
  474. }
  475. return(realconnect(__fd, __addr, __len));
  476. }
  477. if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
  478. || connaddr->sin_family == PF_NETLINK
  479. || connaddr->sin_family == AF_NETLINK
  480. || connaddr->sin_family == AF_UNIX)) {
  481. int err = realconnect(__fd, __addr, __len);
  482. perror("connect():");
  483. //handle_error("connect", "Cannot connect to local socket", err);
  484. return err;
  485. }
  486. /* Assemble and send RPC */
  487. int err;
  488. char cmd[BUF_SZ];
  489. memset(cmd, '\0', BUF_SZ);
  490. struct connect_st rpc_st;
  491. rpc_st.__tid = syscall(SYS_gettid);
  492. rpc_st.__fd = __fd;
  493. memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr));
  494. memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
  495. cmd[0] = RPC_CONNECT;
  496. memcpy(&cmd[1], &rpc_st, sizeof(struct connect_st));
  497. pthread_mutex_lock(&lock);
  498. send_command(fdret_sock, cmd);
  499. /*
  500. if(sock_type && O_NONBLOCK) {
  501. //pthread_mutex_unlock(&lock);
  502. //return EINPROGRESS;
  503. }
  504. */
  505. err = get_retval();
  506. pthread_mutex_unlock(&lock);
  507. //handle_error("connect", "", err);
  508. return err;
  509. }
  510. /*------------------------------------------------------------------------------
  511. ---------------------------------- select() ------------------------------------
  512. ------------------------------------------------------------------------------*/
  513. /* int n, fd_set *readfds, fd_set *writefds,
  514. fd_set *exceptfds, struct timeval *timeout */
  515. int select(SELECT_SIG)
  516. {
  517. //dwr("select():\n");
  518. return realselect(n, readfds, writefds, exceptfds, timeout);
  519. }
  520. /*------------------------------------------------------------------------------
  521. ------------------------------------ bind() ------------------------------------
  522. ------------------------------------------------------------------------------*/
  523. /* int sockfd, const struct sockaddr *addr, socklen_t addrlen
  524. bind() intercept function */
  525. int bind(BIND_SIG)
  526. {
  527. dwr("bind(%d):\n", sockfd);
  528. print_addr(addr);
  529. #ifdef CHECKS
  530. /* Check that this is a valid fd */
  531. if(fcntl(sockfd, F_GETFD) < 0) {
  532. errno = EBADF;
  533. handle_error("bind", "EBADF", -1);
  534. return -1;
  535. }
  536. /* Check that it is a socket */
  537. int opt = -1;
  538. socklen_t opt_len;
  539. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  540. errno = ENOTSOCK;
  541. handle_error("bind", "ENOTSOCK", -1);
  542. return -1;
  543. }
  544. #endif
  545. int err;
  546. /* make sure we don't touch any standard outputs */
  547. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  548. return(realbind(sockfd, addr, addrlen));
  549. /* If local, just use normal syscall */
  550. struct sockaddr_in *connaddr;
  551. connaddr = (struct sockaddr_in *)addr;
  552. if(connaddr->sin_family == AF_LOCAL
  553. || connaddr->sin_family == AF_NETLINK
  554. || connaddr->sin_family == AF_UNIX) {
  555. int err = realbind(sockfd, addr, addrlen);
  556. dwr("realbind, err = %d\n", err);
  557. return err;
  558. }
  559. /* Assemble and send RPC */
  560. char cmd[BUF_SZ];
  561. struct bind_st rpc_st;
  562. rpc_st.sockfd = sockfd;
  563. rpc_st.__tid = syscall(SYS_gettid);
  564. memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr));
  565. memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
  566. cmd[0]=RPC_BIND;
  567. memcpy(&cmd[1], &rpc_st, sizeof(struct bind_st));
  568. pthread_mutex_lock(&lock);
  569. send_command(fdret_sock, cmd);
  570. err = get_retval();
  571. pthread_mutex_unlock(&lock);
  572. errno = ERR_OK;
  573. handle_error("bind", "", err);
  574. return err;
  575. }
  576. /*------------------------------------------------------------------------------
  577. ----------------------------------- accept4() ----------------------------------
  578. ------------------------------------------------------------------------------*/
  579. /* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
  580. int accept4(ACCEPT4_SIG)
  581. {
  582. dwr("accept4(%d):\n", sockfd);
  583. #ifdef CHECKS
  584. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  585. errno = EINVAL;
  586. return -1;
  587. }
  588. #endif
  589. int newfd = accept(sockfd, addr, addrlen);
  590. if(newfd > 0) {
  591. if(flags & SOCK_CLOEXEC)
  592. fcntl(newfd, F_SETFL, FD_CLOEXEC);
  593. if(flags & SOCK_NONBLOCK)
  594. fcntl(newfd, F_SETFL, O_NONBLOCK);
  595. }
  596. handle_error("accept4", "", newfd);
  597. return newfd;
  598. }
  599. /*------------------------------------------------------------------------------
  600. ----------------------------------- accept() -----------------------------------
  601. ------------------------------------------------------------------------------*/
  602. /* int sockfd struct sockaddr *addr, socklen_t *addrlen
  603. accept() intercept function */
  604. int accept(ACCEPT_SIG)
  605. {
  606. dwr("accept(%d):\n", sockfd);
  607. #ifdef CHECKS
  608. /* Check that this is a valid fd */
  609. if(fcntl(sockfd, F_GETFD) < 0) {
  610. return -1;
  611. errno = EBADF;
  612. dwr("EBADF\n");
  613. handle_error("accept", "EBADF", -1);
  614. return -1;
  615. }
  616. /* Check that it is a socket */
  617. int opt;
  618. socklen_t opt_len;
  619. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  620. errno = ENOTSOCK;
  621. dwr("ENOTSOCK\n");
  622. handle_error("accept", "ENOTSOCK", -1);
  623. return -1;
  624. }
  625. /* Check that this socket supports accept() */
  626. if(!(opt && (SOCK_STREAM | SOCK_SEQPACKET))) {
  627. errno = EOPNOTSUPP;
  628. dwr("EOPNOTSUPP\n");
  629. handle_error("accept", "EOPNOTSUPP", -1);
  630. return -1;
  631. }
  632. /* Check that we haven't hit the soft-limit file descriptors allowed */
  633. struct rlimit rl;
  634. getrlimit(RLIMIT_NOFILE, &rl);
  635. if(sockfd >= rl.rlim_cur){
  636. errno = EMFILE;
  637. dwr("EMFILE\n");
  638. handle_error("accept", "EMFILE", -1);
  639. return -1;
  640. }
  641. /* Check address length */
  642. if(addrlen < 0) {
  643. errno = EINVAL;
  644. dwr("EINVAL\n");
  645. handle_error("accept", "EINVAL", -1);
  646. return -1;
  647. }
  648. #endif
  649. /* redirect calls for standard I/O descriptors to kernel */
  650. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO){
  651. dwr("realaccept():\n");
  652. return(realaccept(sockfd, addr, addrlen));
  653. }
  654. if(addr)
  655. addr->sa_family = AF_INET;
  656. /* TODO: also get address info */
  657. char cmd[BUF_SZ];
  658. if(realaccept == NULL) {
  659. handle_error("accept", "Unresolved symbol [accept]", -1);
  660. return -1;
  661. }
  662. //if(opt & O_NONBLOCK)
  663. //fcntl(sockfd, F_SETFL, O_NONBLOCK);
  664. char rbuf[16], c[1];
  665. int new_conn_socket;
  666. int n = read(sockfd, c, sizeof(c)); // Read signal byte
  667. if(n > 0)
  668. {
  669. ssize_t size = sock_fd_read(fdret_sock, rbuf, sizeof(rbuf), &new_conn_socket);
  670. if(size > 0) {
  671. /* Send our local-fd number back to service so it can complete its mapping table */
  672. memset(cmd, '\0', BUF_SZ);
  673. cmd[0] = RPC_MAP;
  674. memcpy(&cmd[1], &new_conn_socket, sizeof(new_conn_socket));
  675. pthread_mutex_lock(&lock);
  676. int n_write = write(fdret_sock, cmd, BUF_SZ);
  677. if(n_write < 0) {
  678. errno = ECONNABORTED; // FIXME: Closest match, service unreachable
  679. handle_error("accept", "ECONNABORTED - Error sending perceived FD to service", -1);
  680. return -1;
  681. }
  682. pthread_mutex_unlock(&lock);
  683. errno = ERR_OK;
  684. dwr("accept()=%d\n", new_conn_socket);
  685. handle_error("accept", "", new_conn_socket);
  686. return new_conn_socket; // OK
  687. }
  688. else {
  689. errno = ECONNABORTED; // FIXME: Closest match, service unreachable
  690. handle_error("accept", "ECONNABORTED - Error receiving new FD from service", -1);
  691. return -1;
  692. }
  693. }
  694. errno = EAGAIN; /* necessary? */
  695. handle_error("accept", "EAGAIN - Error reading signal byte from service", -1);
  696. return -EAGAIN;
  697. }
  698. /*------------------------------------------------------------------------------
  699. ------------------------------------- listen()----------------------------------
  700. ------------------------------------------------------------------------------*/
  701. /* int sockfd, int backlog
  702. listen() intercept function */
  703. int listen(LISTEN_SIG)
  704. {
  705. dwr("listen(%d):\n", sockfd);
  706. int sock_type;
  707. socklen_t sock_type_len = sizeof(sock_type);
  708. #ifdef CHECKS
  709. /* Check that this is a valid fd */
  710. if(fcntl(sockfd, F_GETFD) < 0) {
  711. errno = EBADF;
  712. handle_error("listen", "EBADF", -1);
  713. return -1;
  714. }
  715. /* Check that it is a socket */
  716. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  717. errno = ENOTSOCK;
  718. handle_error("listen", "ENOTSOCK", -1);
  719. return -1;
  720. }
  721. /* Check that this socket supports accept() */
  722. if(!(sock_type && (SOCK_STREAM | SOCK_SEQPACKET))) {
  723. errno = EOPNOTSUPP;
  724. handle_error("listen", "EOPNOTSUPP", -1);
  725. return -1;
  726. }
  727. #endif
  728. /* make sure we don't touch any standard outputs */
  729. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  730. return(reallisten(sockfd, backlog));
  731. if(!is_mapped_to_service(sockfd)) {
  732. // We now know this socket is not one of our socketpairs
  733. int err = reallisten(sockfd, backlog);
  734. dwr("reallisten()=%d\n", err);
  735. return err;
  736. }
  737. /* Assemble and send RPC */
  738. char cmd[BUF_SZ];
  739. memset(cmd, '\0', BUF_SZ);
  740. struct listen_st rpc_st;
  741. rpc_st.sockfd = sockfd;
  742. rpc_st.backlog = backlog;
  743. rpc_st.__tid = syscall(SYS_gettid);
  744. cmd[0] = RPC_LISTEN;
  745. memcpy(&cmd[1], &rpc_st, sizeof(struct listen_st));
  746. pthread_mutex_lock(&lock);
  747. send_command(fdret_sock, cmd);
  748. //err = get_retval();
  749. pthread_mutex_unlock(&lock);
  750. handle_error("listen", "", ERR_OK);
  751. return ERR_OK;
  752. }
  753. /*------------------------------------------------------------------------------
  754. -------------------------------------- clone()----------------------------------
  755. ------------------------------------------------------------------------------*/
  756. // int (*fn)(void *), void *child_stack, int flags, void *arg, ...
  757. /*
  758. int clone(CLONE_SIG)
  759. {
  760. dwr("clone()\n");
  761. return realclone(fn, child_stack, flags, arg);
  762. }
  763. */
  764. /*------------------------------------------------------------------------------
  765. -------------------------------------- poll()-----------------------------------
  766. ------------------------------------------------------------------------------*/
  767. // struct pollfd *fds, nfds_t nfds, int timeout
  768. /*
  769. int poll(POLL_SIG)
  770. {
  771. dwr("poll()\n");
  772. return realpoll(fds, nfds, timeout);
  773. //return ERESTART_RESTARTBLOCK;
  774. }
  775. */
  776. /*------------------------------------------------------------------------------
  777. ------------------------------------ syscall()----------------------------------
  778. ------------------------------------------------------------------------------*/
  779. long syscall(SYSCALL_SIG)
  780. {
  781. //dwr("syscall(%u, ...):\n", number);
  782. va_list ap;
  783. uintptr_t a,b,c,d,e,f;
  784. va_start(ap, number);
  785. a=va_arg(ap, uintptr_t);
  786. b=va_arg(ap, uintptr_t);
  787. c=va_arg(ap, uintptr_t);
  788. d=va_arg(ap, uintptr_t);
  789. e=va_arg(ap, uintptr_t);
  790. f=va_arg(ap, uintptr_t);
  791. va_end(ap);
  792. #if defined(__i386__)
  793. /* TODO: Implement for 32-bit systems: syscall(__NR_socketcall, 18, args);
  794. args[0] = (unsigned long) fd;
  795. args[1] = (unsigned long) addr;
  796. args[2] = (unsigned long) addrlen;
  797. args[3] = (unsigned long) flags;
  798. */
  799. #else
  800. if(number == __NR_accept4) {
  801. int sockfd = a;
  802. struct sockaddr * addr = (struct sockaddr*)b;
  803. socklen_t * addrlen = (socklen_t*)c;
  804. int flags = d;
  805. return accept4(sockfd, addr, addrlen, flags);
  806. }
  807. #endif
  808. return realsyscall(number,a,b,c,d,e,f);
  809. }