Intercept.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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.c"
  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 (*realclose)(CLOSE_SIG);
  76. //static int (*realclone)(CLONE_SIG);
  77. //static int (*realpoll)(POLL_SIG);
  78. static int (*realdup2)(DUP2_SIG);
  79. static int (*realdup3)(DUP3_SIG);
  80. /* Exported Function Prototypes */
  81. void my_init(void);
  82. int connect(CONNECT_SIG);
  83. int select(SELECT_SIG);
  84. int bind(BIND_SIG);
  85. int accept(ACCEPT_SIG);
  86. int listen(LISTEN_SIG);
  87. int socket(SOCKET_SIG);
  88. int setsockopt(SETSOCKOPT_SIG);
  89. int getsockopt(GETSOCKOPT_SIG);
  90. int accept4(ACCEPT4_SIG);
  91. long syscall(SYSCALL_SIG);
  92. int close(CLOSE_SIG);
  93. //int clone(CLONE_SIG);
  94. //int poll(POLL_SIG);
  95. int dup2(DUP2_SIG);
  96. int dup3(DUP3_SIG);
  97. #ifdef USE_SOCKS_DNS
  98. int res_init(void);
  99. #endif
  100. int connect_to_service(void);
  101. int init_service_connection();
  102. //void dwr(const char *fmt, ...);
  103. void load_symbols(void);
  104. void set_up_intercept();
  105. int checkpid();
  106. #define SERVICE_CONNECT_ATTEMPTS 30
  107. #define RPC_FD 1023
  108. ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd);
  109. /* threading */
  110. pthread_mutex_t lock;
  111. pthread_mutex_t loglock;
  112. void handle_error(char *name, char *info, int err)
  113. {
  114. #ifdef ERRORS_ARE_FATAL
  115. if(err < 0) {
  116. dwr(MSG_DEBUG,"handle_error(%s)=%d: FATAL: %s\n", name, err, info);
  117. //exit(-1);
  118. }
  119. #endif
  120. #ifdef VERBOSE
  121. dwr(MSG_DEBUG,"%s()=%d\n", name, err);
  122. #endif
  123. }
  124. static unsigned long rpc_count = 0;
  125. /*------------------------------------------------------------------------------
  126. ------------------- Intercept<--->Service Comm mechanisms-----------------------
  127. ------------------------------------------------------------------------------*/
  128. static int is_initialized = 0;
  129. static int fdret_sock; // used for fd-transfers
  130. static int newfd; // used for "this_end" socket
  131. static int thispid;
  132. static char* af_sock_name = "/tmp/.ztnc_e5cd7a9e1c5311ab";
  133. /*
  134. * Check for forking
  135. */
  136. int checkpid() {
  137. if(thispid != getpid()) {
  138. printf("clone/fork detected. re-initializing this instance.\n");
  139. set_up_intercept();
  140. fdret_sock = init_service_connection();
  141. thispid = getpid();
  142. }
  143. return 0;
  144. }
  145. /*
  146. * Sends an RPC command to the service
  147. */
  148. int send_command(int rpc_fd, char *cmd)
  149. {
  150. #ifdef DEBUG_RPC
  151. /*
  152. #define IDX_PID 0
  153. #define IDX_TID sizeof(pid_t)
  154. #define IDX_COUNT IDX_TID + sizeof(pid_t)
  155. #define IDX_TIME IDX_COUNT + sizeof(int)
  156. #define IDX_CMD IDX_TIME + 20 // 20 being the length of the timestamp string
  157. #define IDX_PAYLOAD IDX_TIME + sizeof(char)
  158. */
  159. // [pid_t] [pid_t] [rpc_count] [int] [...]
  160. char metabuf[BUF_SZ]; // portion of buffer which contains RPC meta-data for debugging
  161. memset(metabuf, '\0', BUF_SZ);
  162. pid_t pid = syscall(SYS_getpid);
  163. pid_t tid = syscall(SYS_gettid);
  164. rpc_count++;
  165. char timestring[20];
  166. time_t timestamp;
  167. timestamp = time(NULL);
  168. strftime(timestring, sizeof(timestring), "%H:%M:%S", localtime(&timestamp));
  169. memcpy(&metabuf[IDX_PID], &pid, sizeof(pid_t) ); // pid
  170. memcpy(&metabuf[IDX_TID], &tid, sizeof(pid_t) ); // tid
  171. memcpy(&metabuf[IDX_COUNT], &rpc_count, sizeof(rpc_count) ); // rpc_count
  172. memcpy(&metabuf[IDX_TIME], &timestring, 20 ); // timestamp
  173. #endif
  174. // copy payload into final command buffer
  175. memcpy(&metabuf[IDX_PAYLOAD], cmd, PAYLOAD_SZ);
  176. //dwr(MSG_DEBUG," RX: (pid=%d, tid=%d, rpc_count=%d, timestamp=%s, cmd=%d\n", pid, tid, rpc_count, timestring, cmd[0]);
  177. int n_write = write(rpc_fd, &metabuf, BUF_SZ);
  178. if(n_write < 0){
  179. dwr(MSG_DEBUG,"Error writing command to service (CMD = %d)\n", cmd[0]);
  180. errno = 0;
  181. return -1;
  182. }
  183. return 0;
  184. }
  185. /*
  186. * Reads a return value from the service and sets errno (if applicable)
  187. */
  188. int get_retval()
  189. {
  190. dwr(MSG_DEBUG,"get_retval()\n");
  191. if(fdret_sock >= 0) {
  192. int retval;
  193. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  194. char retbuf[BUF_SZ];
  195. memset(&retbuf, '\0', sz);
  196. int n_read = read(fdret_sock, &retbuf, sz);
  197. if(n_read > 0) {
  198. memcpy(&retval, &retbuf[1], sizeof(retval));
  199. memcpy(&errno, &retbuf[1+sizeof(retval)], sizeof(errno));
  200. return retval;
  201. }
  202. }
  203. dwr(MSG_DEBUG,"unable to read return value\n");
  204. return -1;
  205. }
  206. /* Check whether the socket is mapped to the service or not. We
  207. need to know if this is a regular AF_LOCAL socket or an end of a socketpair
  208. that the service uses. We don't want to keep state in the intercept, so
  209. we simply ask the service via an RPC */
  210. int is_mapped_to_service(int sockfd)
  211. {
  212. dwr(MSG_DEBUG,"is_mapped_to_service()\n");
  213. char cmd[BUF_SZ];
  214. memset(cmd, '\0', BUF_SZ);
  215. cmd[0] = RPC_MAP_REQ;
  216. memcpy(&cmd[1], &sockfd, sizeof(sockfd));
  217. pthread_mutex_lock(&lock);
  218. if(send_command(fdret_sock, cmd) < 0)
  219. return -1;
  220. int err = get_retval();
  221. pthread_mutex_unlock(&lock);
  222. return err;
  223. }
  224. /*------------------------------------------------------------------------------
  225. ---------- Unix-domain socket lazy initializer (for fd-transfers)--------------
  226. ------------------------------------------------------------------------------*/
  227. /* Sets up the connection pipes and sockets to the service */
  228. int init_service_connection()
  229. {
  230. dwr(MSG_DEBUG,"init_service_connection()\n");
  231. if(!is_initialized) {
  232. struct sockaddr_un addr;
  233. int tfd = -1, attempts = 0, conn_err = -1;
  234. memset(&addr, 0, sizeof(addr));
  235. addr.sun_family = AF_UNIX;
  236. strncpy(addr.sun_path, af_sock_name, sizeof(addr.sun_path)-1);
  237. if ( (tfd = realsocket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  238. perror("socket error");
  239. exit(-1);
  240. }
  241. while(conn_err < 0 && attempts < SERVICE_CONNECT_ATTEMPTS) {
  242. conn_err = realconnect(tfd, (struct sockaddr*)&addr, sizeof(addr));
  243. if(conn_err < 0) {
  244. dwr(MSG_DEBUG,"re-attempting connection in %ds\n", 1+attempts);
  245. sleep(1);
  246. }
  247. else {
  248. dwr(MSG_DEBUG,"AF_UNIX connection established: %d\n", tfd);
  249. is_initialized = 1;
  250. int newtfd = realdup2(tfd, 1023);
  251. dwr(MSG_DEBUG,"dup'd to rpc_fd = %d\n", newtfd);
  252. close(tfd);
  253. return newtfd;
  254. }
  255. attempts++;
  256. }
  257. }
  258. return -1;
  259. }
  260. /*------------------------------------------------------------------------------
  261. ------------------------ ctors and dtors (and friends)-------------------------
  262. ------------------------------------------------------------------------------*/
  263. void my_dest(void) __attribute__ ((destructor));
  264. void my_dest(void) {
  265. //dwr(MSG_DEBUG,"closing connections to service...\n");
  266. close(fdret_sock);
  267. pthread_mutex_destroy(&lock);
  268. }
  269. void load_symbols(void)
  270. {
  271. #ifdef USE_OLD_DLSYM
  272. void *lib;
  273. #endif
  274. /* possibly add check to beginning of each method to avoid needing to cll the constructor */
  275. if(thispid == getpid()) {
  276. dwr(MSG_DEBUG,"detected duplicate call to global ctor (pid=%d).\n", thispid);
  277. }
  278. //dwr(MSG_DEBUG," -- pid = %d\n", getpid());
  279. //dwr(MSG_DEBUG," -- uid = %d\n", getuid());
  280. thispid = getpid();
  281. //thistid = gettid();
  282. #ifndef USE_OLD_DLSYM
  283. realconnect = dlsym(RTLD_NEXT, "connect");
  284. realbind = dlsym(RTLD_NEXT, "bind");
  285. realaccept = dlsym(RTLD_NEXT, "accept");
  286. reallisten = dlsym(RTLD_NEXT, "listen");
  287. realsocket = dlsym(RTLD_NEXT, "socket");
  288. realbind = dlsym(RTLD_NEXT, "bind");
  289. realselect = dlsym(RTLD_NEXT, "select");
  290. realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
  291. realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
  292. realaccept4 = dlsym(RTLD_NEXT, "accept4");
  293. //realclone = dlsym(RTLD_NEXT, "clone");
  294. realclose = dlsym(RTLD_NEXT, "close");
  295. realsyscall = dlsym(RTLD_NEXT, "syscall");
  296. //realsyscall = dlsym(RTLD_NEXT, "poll");
  297. realdup2 = dlsym(RTLD_NEXT, "dup2");
  298. realdup3 = dlsym(RTLD_NEXT, "dup3");
  299. #ifdef USE_SOCKS_DNS
  300. realresinit = dlsym(RTLD_NEXT, "res_init");
  301. #endif
  302. #else
  303. lib = dlopen(LIBCONNECT, RTLD_LAZY);
  304. realconnect = dlsym(lib, "connect");
  305. realbind = dlsym(lib, "bind");
  306. realaccept = dlsym(lib, "accept");
  307. reallisten = dlsym(lib, "listen");
  308. realsocket = dlsym(lib, "socket");
  309. realselect = dlsym(lib, "select");
  310. realsetsockopt = dlsym(lib, "setsockopt");
  311. realgetsockopt = dlsym(lib, "getsockopt");
  312. realaccept4 = dlsym(lib), "accept4");
  313. //realclone = dlsym(lib, "clone");
  314. realclose = dlsym(lib, "close");
  315. realsyscall = dlsym(lib, "syscall");
  316. //realsyscall = dlsym(lib, "poll");
  317. realdup2 = dlsym(RTLD_NEXT, "dup2");
  318. realdup3 = dlsym(RTLD_NEXT, "dup3");
  319. #ifdef USE_SOCKS_DNS
  320. realresinit = dlsym(lib, "res_init");
  321. #endif
  322. dlclose(lib);
  323. lib = dlopen(LIBC, RTLD_LAZY);
  324. dlclose(lib);
  325. #endif
  326. }
  327. /* Private Function Prototypes */
  328. void _init(void) __attribute__ ((constructor));
  329. void _init(void) {
  330. set_up_intercept();
  331. }
  332. /* get symbols and initialize mutexes */
  333. void set_up_intercept()
  334. {
  335. load_symbols();
  336. if(pthread_mutex_init(&lock, NULL) != 0) {
  337. printf("error while initializing service call mutex\n");
  338. }
  339. if(pthread_mutex_init(&loglock, NULL) != 0) {
  340. printf("error while initializing log mutex mutex\n");
  341. }
  342. }
  343. /*------------------------------------------------------------------------------
  344. --------------------------------- setsockopt() ---------------------------------
  345. ------------------------------------------------------------------------------*/
  346. /* int socket, int level, int option_name, const void *option_value, socklen_t option_len */
  347. int setsockopt(SETSOCKOPT_SIG)
  348. {
  349. dwr(MSG_DEBUG,"\n\nsetsockopt(%d)\n", socket);
  350. /*
  351. if(is_mapped_to_service(socket) < 0) { // First, check if the service manages this
  352. return realsetsockopt(socket, level, option_name, option_value, option_len);
  353. }
  354. */
  355. //return(realsetsockopt(socket, level, option_name, option_value, option_len));
  356. if(level == SOL_IPV6 && option_name == IPV6_V6ONLY)
  357. return 0;
  358. if(level == SOL_IP && option_name == IP_TTL)
  359. return 0;
  360. if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE))
  361. return 0;
  362. /* make sure we don't touch any standard outputs */
  363. if(socket == STDIN_FILENO || socket == STDOUT_FILENO || socket == STDERR_FILENO)
  364. return(realsetsockopt(socket, level, option_name, option_value, option_len));
  365. int err = realsetsockopt(socket, level, option_name, option_value, option_len);
  366. if(err < 0){
  367. //perror("setsockopt():\n");
  368. }
  369. return 0;
  370. }
  371. /*------------------------------------------------------------------------------
  372. --------------------------------- getsockopt() ---------------------------------
  373. ------------------------------------------------------------------------------*/
  374. /* int sockfd, int level, int optname, void *optval, socklen_t *optlen */
  375. int getsockopt(GETSOCKOPT_SIG)
  376. {
  377. dwr(MSG_DEBUG,"\n\ngetsockopt(%d)\n", sockfd);
  378. /*
  379. if(is_mapped_to_service(sockfd) < 0) { // First, check if the service manages this
  380. return realgetsockopt(sockfd, level, optname, optval, optlen);
  381. }
  382. */
  383. int err = realgetsockopt(sockfd, level, optname, optval, optlen);
  384. // FIXME: this condition will need a little more intelligence later on
  385. // -- we will need to know if this fd is a local we are spoofing, or a true local
  386. if(optname == SO_TYPE)
  387. {
  388. int* val = (int*)optval;
  389. *val = 2;
  390. optval = (void*)val;
  391. }
  392. if(err < 0){
  393. //perror("setsockopt():\n");
  394. }
  395. return 0;
  396. }
  397. /*------------------------------------------------------------------------------
  398. ----------------------------------- socket() -----------------------------------
  399. ------------------------------------------------------------------------------*/
  400. /* int socket_family, int socket_type, int protocol
  401. socket() intercept function */
  402. int socket(SOCKET_SIG)
  403. {
  404. dwr(MSG_DEBUG,"\n\nsocket():\n");
  405. int err;
  406. #ifdef CHECKS
  407. /* Check that type makes sense */
  408. int flags = socket_type & ~SOCK_TYPE_MASK;
  409. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  410. errno = EINVAL;
  411. handle_error("socket1", "", -1);
  412. return -1;
  413. }
  414. socket_type &= SOCK_TYPE_MASK;
  415. /* Check protocol is in range */
  416. if (socket_family < 0 || socket_family >= NPROTO){
  417. errno = EAFNOSUPPORT;
  418. handle_error("socket2", "", -1);
  419. return -1;
  420. }
  421. if (socket_type < 0 || socket_type >= SOCK_MAX) {
  422. errno = EINVAL;
  423. handle_error("socket3", "", -1);
  424. return -1;
  425. }
  426. /* Check that we haven't hit the soft-limit file descriptors allowed */
  427. /* FIXME: Find number of open fds
  428. struct rlimit rl;
  429. getrlimit(RLIMIT_NOFILE, &rl);
  430. if(sockfd >= rl.rlim_cur){
  431. errno = EMFILE;
  432. return -1;
  433. }
  434. */
  435. /* FIXME: detect ENFILE condition */
  436. #endif
  437. char cmd[BUF_SZ];
  438. fdret_sock = !is_initialized ? init_service_connection() : fdret_sock;
  439. if(fdret_sock < 0) {
  440. dwr(MSG_DEBUG,"BAD service connection. exiting.\n");
  441. handle_error("socket4", "", -1);
  442. exit(-1);
  443. }
  444. if(socket_family == AF_LOCAL
  445. || socket_family == AF_NETLINK
  446. || socket_family == AF_UNIX) {
  447. int err = realsocket(socket_family, socket_type, protocol);
  448. dwr(MSG_DEBUG,"realsocket, err = %d\n", err);
  449. handle_error("socket5", "", err);
  450. return err;
  451. }
  452. /* Assemble and send RPC */
  453. struct socket_st rpc_st;
  454. rpc_st.socket_family = socket_family;
  455. rpc_st.socket_type = socket_type;
  456. rpc_st.protocol = protocol;
  457. rpc_st.__tid = syscall(SYS_gettid);
  458. memset(cmd, '\0', BUF_SZ);
  459. cmd[0] = RPC_SOCKET;
  460. dwr(MSG_DEBUG,"pid = %d\n", thispid);
  461. memcpy(&cmd[1]+sizeof(pid_t), &rpc_st, sizeof(struct socket_st));
  462. pthread_mutex_lock(&lock);
  463. send_command(fdret_sock, cmd);
  464. /* get new fd */
  465. char rbuf[16];
  466. ssize_t sz = sock_fd_read(fdret_sock, rbuf, sizeof(rbuf), &newfd);
  467. dwr(MSG_DEBUG,"read %d bytes (%s)\n", sz, &rbuf);
  468. if(sz > 0)
  469. {
  470. dwr(MSG_DEBUG,"sending fd = %d to Service over (%d)\n", newfd, fdret_sock);
  471. /* send our local-fd number back to service so
  472. it can complete its mapping table entry */
  473. memset(cmd, '\0', BUF_SZ);
  474. cmd[0] = RPC_MAP;
  475. memcpy(&cmd[1], &newfd, sizeof(newfd));
  476. if(newfd > -1) { // FIXME: check logic
  477. send_command(fdret_sock, cmd);
  478. pthread_mutex_unlock(&lock);
  479. errno = ERR_OK; // OK
  480. handle_error("socket6", "", newfd);
  481. return newfd;
  482. }
  483. else { // Try to read retval+errno since we RXed a bad fd
  484. dwr(MSG_DEBUG,"Error, service sent bad fd.\n");
  485. err = get_retval();
  486. pthread_mutex_unlock(&lock);
  487. handle_error("socket7", "", -1);
  488. return err;
  489. }
  490. }
  491. else {
  492. dwr(MSG_DEBUG,"Error while receiving new FD.\n");
  493. err = get_retval();
  494. pthread_mutex_unlock(&lock);
  495. handle_error("socket8", "", -1);
  496. return err;
  497. }
  498. }
  499. /*------------------------------------------------------------------------------
  500. ---------------------------------- connect() -----------------------------------
  501. ------------------------------------------------------------------------------*/
  502. /* int __fd, const struct sockaddr * __addr, socklen_t __len
  503. connect() intercept function */
  504. int connect(CONNECT_SIG)
  505. {
  506. dwr(MSG_DEBUG,"\n\nconnect(%d):\n", __fd);
  507. print_addr(__addr);
  508. struct sockaddr_in *connaddr;
  509. connaddr = (struct sockaddr_in *) __addr;
  510. #ifdef CHECKS
  511. /* Check that this is a valid fd */
  512. if(fcntl(__fd, F_GETFD) < 0) {
  513. errno = EBADF;
  514. handle_error("connect", "EBADF", -1);
  515. return -1;
  516. }
  517. /* Check that it is a socket */
  518. int sock_type;
  519. socklen_t sock_type_len = sizeof(sock_type);
  520. if(getsockopt(__fd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  521. errno = ENOTSOCK;
  522. handle_error("connect", "ENOTSOCK", -1);
  523. return -1;
  524. }
  525. /* Check family */
  526. if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
  527. errno = EAFNOSUPPORT;
  528. handle_error("connect", "EAFNOSUPPORT", -1);
  529. return -1;
  530. }
  531. /* FIXME: Check that address is in user space, return EFAULT ? */
  532. #endif
  533. /* make sure we don't touch any standard outputs */
  534. if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO){
  535. if (realconnect == NULL) {
  536. handle_error("connect", "Unresolved symbol [connect]", -1);
  537. exit(-1);
  538. }
  539. return(realconnect(__fd, __addr, __len));
  540. }
  541. if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
  542. || connaddr->sin_family == PF_NETLINK
  543. || connaddr->sin_family == AF_NETLINK
  544. || connaddr->sin_family == AF_UNIX)) {
  545. int err = realconnect(__fd, __addr, __len);
  546. perror("connect():");
  547. //handle_error("connect", "Cannot connect to local socket", err);
  548. return err;
  549. }
  550. /* Assemble and send RPC */
  551. int err;
  552. char cmd[BUF_SZ];
  553. memset(cmd, '\0', BUF_SZ);
  554. struct connect_st rpc_st;
  555. rpc_st.__tid = syscall(SYS_gettid);
  556. rpc_st.__fd = __fd;
  557. memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr));
  558. memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
  559. cmd[0] = RPC_CONNECT;
  560. memcpy(&cmd[1], &rpc_st, sizeof(struct connect_st));
  561. pthread_mutex_lock(&lock);
  562. send_command(fdret_sock, cmd);
  563. /*
  564. if(sock_type && O_NONBLOCK) {
  565. //pthread_mutex_unlock(&lock);
  566. //return EINPROGRESS;
  567. }
  568. */
  569. err = get_retval();
  570. pthread_mutex_unlock(&lock);
  571. //handle_error("connect", "", err);
  572. return err;
  573. }
  574. /*------------------------------------------------------------------------------
  575. ---------------------------------- select() ------------------------------------
  576. ------------------------------------------------------------------------------*/
  577. /* int n, fd_set *readfds, fd_set *writefds,
  578. fd_set *exceptfds, struct timeval *timeout */
  579. int select(SELECT_SIG)
  580. {
  581. //dwr(MSG_DEBUG,"select():\n");
  582. return realselect(n, readfds, writefds, exceptfds, timeout);
  583. }
  584. /*------------------------------------------------------------------------------
  585. ------------------------------------ bind() ------------------------------------
  586. ------------------------------------------------------------------------------*/
  587. /* int sockfd, const struct sockaddr *addr, socklen_t addrlen
  588. bind() intercept function */
  589. int bind(BIND_SIG)
  590. {
  591. dwr(MSG_DEBUG,"\n\nbind(%d):\n", sockfd);
  592. print_addr(addr);
  593. #ifdef CHECKS
  594. /* Check that this is a valid fd */
  595. if(fcntl(sockfd, F_GETFD) < 0) {
  596. errno = EBADF;
  597. handle_error("bind", "EBADF", -1);
  598. return -1;
  599. }
  600. /* Check that it is a socket */
  601. int opt = -1;
  602. socklen_t opt_len;
  603. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  604. errno = ENOTSOCK;
  605. handle_error("bind", "ENOTSOCK", -1);
  606. return -1;
  607. }
  608. #endif
  609. int err;
  610. /* make sure we don't touch any standard outputs */
  611. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  612. return(realbind(sockfd, addr, addrlen));
  613. /* If local, just use normal syscall */
  614. struct sockaddr_in *connaddr;
  615. connaddr = (struct sockaddr_in *)addr;
  616. if(connaddr->sin_family == AF_LOCAL
  617. || connaddr->sin_family == AF_NETLINK
  618. || connaddr->sin_family == AF_UNIX) {
  619. int err = realbind(sockfd, addr, addrlen);
  620. dwr(MSG_DEBUG,"realbind, err = %d\n", err);
  621. return err;
  622. }
  623. /* Assemble and send RPC */
  624. char cmd[BUF_SZ];
  625. struct bind_st rpc_st;
  626. rpc_st.sockfd = sockfd;
  627. rpc_st.__tid = syscall(SYS_gettid);
  628. memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr));
  629. memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
  630. cmd[0]=RPC_BIND;
  631. memcpy(&cmd[1], &rpc_st, sizeof(struct bind_st));
  632. pthread_mutex_lock(&lock);
  633. send_command(fdret_sock, cmd);
  634. err = get_retval();
  635. pthread_mutex_unlock(&lock);
  636. errno = ERR_OK;
  637. handle_error("bind", "", err);
  638. return err;
  639. }
  640. /*------------------------------------------------------------------------------
  641. ----------------------------------- accept4() ----------------------------------
  642. ------------------------------------------------------------------------------*/
  643. /* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
  644. int accept4(ACCEPT4_SIG)
  645. {
  646. dwr(MSG_DEBUG,"\n\naccept4(%d):\n", sockfd);
  647. #ifdef CHECKS
  648. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  649. errno = EINVAL;
  650. return -1;
  651. }
  652. #endif
  653. int newfd = accept(sockfd, addr, addrlen);
  654. if(newfd > 0) {
  655. if(flags & SOCK_CLOEXEC)
  656. fcntl(newfd, F_SETFL, FD_CLOEXEC);
  657. if(flags & SOCK_NONBLOCK)
  658. fcntl(newfd, F_SETFL, O_NONBLOCK);
  659. }
  660. handle_error("accept4", "", newfd);
  661. return newfd;
  662. }
  663. /*------------------------------------------------------------------------------
  664. ----------------------------------- accept() -----------------------------------
  665. ------------------------------------------------------------------------------*/
  666. /* int sockfd struct sockaddr *addr, socklen_t *addrlen
  667. accept() intercept function */
  668. int accept(ACCEPT_SIG)
  669. {
  670. dwr(MSG_DEBUG,"\n\naccept(%d):\n", sockfd);
  671. #ifdef CHECKS
  672. /* Check that this is a valid fd */
  673. if(fcntl(sockfd, F_GETFD) < 0) {
  674. return -1;
  675. errno = EBADF;
  676. dwr(MSG_DEBUG,"EBADF\n");
  677. handle_error("accept", "EBADF", -1);
  678. return -1;
  679. }
  680. /* Check that it is a socket */
  681. int opt;
  682. socklen_t opt_len;
  683. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  684. errno = ENOTSOCK;
  685. dwr(MSG_DEBUG,"ENOTSOCK\n");
  686. handle_error("accept", "ENOTSOCK", -1);
  687. return -1;
  688. }
  689. /* Check that this socket supports accept() */
  690. if(!(opt && (SOCK_STREAM | SOCK_SEQPACKET))) {
  691. errno = EOPNOTSUPP;
  692. dwr(MSG_DEBUG,"EOPNOTSUPP\n");
  693. handle_error("accept", "EOPNOTSUPP", -1);
  694. return -1;
  695. }
  696. /* Check that we haven't hit the soft-limit file descriptors allowed */
  697. struct rlimit rl;
  698. getrlimit(RLIMIT_NOFILE, &rl);
  699. if(sockfd >= rl.rlim_cur){
  700. errno = EMFILE;
  701. dwr(MSG_DEBUG,"EMFILE\n");
  702. handle_error("accept", "EMFILE", -1);
  703. return -1;
  704. }
  705. /* Check address length */
  706. if(addrlen < 0) {
  707. errno = EINVAL;
  708. dwr(MSG_DEBUG,"EINVAL\n");
  709. handle_error("accept", "EINVAL", -1);
  710. return -1;
  711. }
  712. #endif
  713. /* redirect calls for standard I/O descriptors to kernel */
  714. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO){
  715. dwr(MSG_DEBUG,"realaccept():\n");
  716. return(realaccept(sockfd, addr, addrlen));
  717. }
  718. if(addr)
  719. addr->sa_family = AF_INET;
  720. /* TODO: also get address info */
  721. char cmd[BUF_SZ];
  722. if(realaccept == NULL) {
  723. handle_error("accept", "Unresolved symbol [accept]", -1);
  724. return -1;
  725. }
  726. //if(opt & O_NONBLOCK)
  727. //fcntl(sockfd, F_SETFL, O_NONBLOCK);
  728. char rbuf[16], c[1];
  729. int new_conn_socket;
  730. int n = read(sockfd, c, sizeof(c)); // Read signal byte
  731. if(n > 0)
  732. {
  733. ssize_t size = sock_fd_read(fdret_sock, rbuf, sizeof(rbuf), &new_conn_socket);
  734. if(size > 0) {
  735. /* Send our local-fd number back to service so it can complete its mapping table */
  736. memset(cmd, '\0', BUF_SZ);
  737. cmd[0] = RPC_MAP;
  738. memcpy(&cmd[1], &new_conn_socket, sizeof(new_conn_socket));
  739. pthread_mutex_lock(&lock);
  740. int n_write = write(fdret_sock, cmd, BUF_SZ);
  741. if(n_write < 0) {
  742. errno = ECONNABORTED; // FIXME: Closest match, service unreachable
  743. handle_error("accept", "ECONNABORTED - Error sending perceived FD to service", -1);
  744. return -1;
  745. }
  746. pthread_mutex_unlock(&lock);
  747. errno = ERR_OK;
  748. dwr(MSG_DEBUG,"*accept()=%d\n", new_conn_socket);
  749. handle_error("accept", "", new_conn_socket);
  750. return new_conn_socket; // OK
  751. }
  752. else {
  753. errno = ECONNABORTED; // FIXME: Closest match, service unreachable
  754. handle_error("accept", "ECONNABORTED - Error receiving new FD from service", -1);
  755. return -1;
  756. }
  757. }
  758. errno = EBADF;
  759. handle_error("accept", "EBADF - Error reading signal byte from service", -1);
  760. return -1;
  761. }
  762. /*------------------------------------------------------------------------------
  763. ------------------------------------- listen()----------------------------------
  764. ------------------------------------------------------------------------------*/
  765. /* int sockfd, int backlog
  766. listen() intercept function */
  767. int listen(LISTEN_SIG)
  768. {
  769. dwr(MSG_DEBUG,"\n\nlisten(%d):\n", sockfd);
  770. int sock_type;
  771. socklen_t sock_type_len = sizeof(sock_type);
  772. #ifdef CHECKS
  773. /* Check that this is a valid fd */
  774. if(fcntl(sockfd, F_GETFD) < 0) {
  775. errno = EBADF;
  776. handle_error("listen", "EBADF", -1);
  777. return -1;
  778. }
  779. /* Check that it is a socket */
  780. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  781. errno = ENOTSOCK;
  782. handle_error("listen", "ENOTSOCK", -1);
  783. return -1;
  784. }
  785. /* Check that this socket supports accept() */
  786. if(!(sock_type && (SOCK_STREAM | SOCK_SEQPACKET))) {
  787. errno = EOPNOTSUPP;
  788. handle_error("listen", "EOPNOTSUPP", -1);
  789. return -1;
  790. }
  791. #endif
  792. /* make sure we don't touch any standard outputs */
  793. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  794. return(reallisten(sockfd, backlog));
  795. if(is_mapped_to_service(sockfd) < 0) {
  796. // We now know this socket is not one of our socketpairs
  797. int err = reallisten(sockfd, backlog);
  798. dwr(MSG_DEBUG,"reallisten()=%d\n", err);
  799. return err;
  800. }
  801. /* Assemble and send RPC */
  802. char cmd[BUF_SZ];
  803. memset(cmd, '\0', BUF_SZ);
  804. struct listen_st rpc_st;
  805. rpc_st.sockfd = sockfd;
  806. rpc_st.backlog = backlog;
  807. rpc_st.__tid = syscall(SYS_gettid);
  808. cmd[0] = RPC_LISTEN;
  809. memcpy(&cmd[1], &rpc_st, sizeof(struct listen_st));
  810. pthread_mutex_lock(&lock);
  811. send_command(fdret_sock, cmd);
  812. /*int err = */get_retval();
  813. pthread_mutex_unlock(&lock);
  814. handle_error("listen", "", ERR_OK);
  815. return ERR_OK;
  816. }
  817. /*------------------------------------------------------------------------------
  818. -------------------------------------- clone()----------------------------------
  819. ------------------------------------------------------------------------------*/
  820. // int (*fn)(void *), void *child_stack, int flags, void *arg, ...
  821. /*
  822. int clone(CLONE_SIG)
  823. {
  824. dwr(MSG_DEBUG,"clone()\n");
  825. return realclone(fn, child_stack, flags, arg);
  826. }
  827. */
  828. /*------------------------------------------------------------------------------
  829. -------------------------------------- poll()-----------------------------------
  830. ------------------------------------------------------------------------------*/
  831. // struct pollfd *fds, nfds_t nfds, int timeout
  832. /*
  833. int poll(POLL_SIG)
  834. {
  835. dwr(MSG_DEBUG,"poll()\n");
  836. return realpoll(fds, nfds, timeout);
  837. //return ERESTART_RESTARTBLOCK;
  838. }
  839. */
  840. /*------------------------------------------------------------------------------
  841. -------------------------------------- close()-----------------------------------
  842. ------------------------------------------------------------------------------*/
  843. // int fd
  844. int close(CLOSE_SIG)
  845. {
  846. dwr(MSG_DEBUG,"close(%d)\n", fd);
  847. if(fd == fdret_sock)
  848. return 0; // FIXME: Ignore request to shut down our rpc fd, this is *almost always* safe
  849. if(fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
  850. return realclose(fd);
  851. return -1;
  852. }
  853. /*------------------------------------------------------------------------------
  854. -------------------------------------- dup2()-----------------------------------
  855. ------------------------------------------------------------------------------*/
  856. // int oldfd, int newfd
  857. int dup2(DUP2_SIG)
  858. {
  859. dwr(MSG_DEBUG,"dup2(%d, %d)\n", oldfd, newfd);
  860. if(oldfd == fdret_sock) {
  861. dwr(MSG_DEBUG,"client application attempted to dup2 RPC socket (%d). This is not allowed.\n", oldfd);
  862. errno = EBADF;
  863. return -1;
  864. }
  865. if(oldfd != STDIN_FILENO && oldfd != STDOUT_FILENO && oldfd != STDERR_FILENO)
  866. return realdup2(oldfd, newfd);
  867. return -1;
  868. }
  869. /*------------------------------------------------------------------------------
  870. -------------------------------------- dup3()-----------------------------------
  871. ------------------------------------------------------------------------------*/
  872. // int oldfd, int newfd, int flags
  873. int dup3(DUP3_SIG)
  874. {
  875. dwr(MSG_DEBUG,"dup3(%d, %d, %d)\n", oldfd, newfd, flags);
  876. #ifdef DEBUG
  877. // Only do this check if we want to debug the intercept, otherwise, dont mess with
  878. // the client application's logging methods
  879. if(newfd == STDIN_FILENO || newfd == STDOUT_FILENO || newfd == STDERR_FILENO)
  880. return newfd; // FIXME: This is to prevent httpd from dup'ing over our stderr
  881. //and preventing us from debugging
  882. else
  883. #endif
  884. return realdup3(oldfd, newfd, flags);
  885. }
  886. /*------------------------------------------------------------------------------
  887. ------------------------------------ syscall()----------------------------------
  888. ------------------------------------------------------------------------------*/
  889. long syscall(SYSCALL_SIG)
  890. {
  891. dwr(MSG_DEBUG,"syscall(%u, ...):\n", number);
  892. va_list ap;
  893. uintptr_t a,b,c,d,e,f;
  894. va_start(ap, number);
  895. a=va_arg(ap, uintptr_t);
  896. b=va_arg(ap, uintptr_t);
  897. c=va_arg(ap, uintptr_t);
  898. d=va_arg(ap, uintptr_t);
  899. e=va_arg(ap, uintptr_t);
  900. f=va_arg(ap, uintptr_t);
  901. va_end(ap);
  902. #if defined(__i386__)
  903. /* TODO: Implement for 32-bit systems: syscall(__NR_socketcall, 18, args);
  904. args[0] = (unsigned long) fd;
  905. args[1] = (unsigned long) addr;
  906. args[2] = (unsigned long) addrlen;
  907. args[3] = (unsigned long) flags;
  908. */
  909. #else
  910. if(number == __NR_accept4) {
  911. int sockfd = a;
  912. struct sockaddr * addr = (struct sockaddr*)b;
  913. socklen_t * addrlen = (socklen_t*)c;
  914. int flags = d;
  915. int old_errno = errno;
  916. int err = accept4(sockfd, addr, addrlen, flags);
  917. errno = old_errno;
  918. if(err == -EBADF) {
  919. //errno = EAGAIN;
  920. err = -EAGAIN;
  921. //exit(0);
  922. }
  923. return err;
  924. }
  925. #endif
  926. return realsyscall(number,a,b,c,d,e,f);
  927. }