Intercept.c 33 KB

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