Intercept.c 31 KB

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