qrexec-agent.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /*
  2. * The Qubes OS Project, http://www.qubes-os.org
  3. *
  4. * Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. *
  20. */
  21. #define _GNU_SOURCE
  22. #define HAVE_PAM
  23. #include <sys/select.h>
  24. #include <sys/socket.h>
  25. #include <sys/un.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <signal.h>
  29. #include <unistd.h>
  30. #include <errno.h>
  31. #include <sys/wait.h>
  32. #include <fcntl.h>
  33. #include <string.h>
  34. #include <pwd.h>
  35. #include <grp.h>
  36. #include <sys/stat.h>
  37. #include <assert.h>
  38. #ifdef HAVE_PAM
  39. #include <security/pam_appl.h>
  40. #endif
  41. #include "qrexec.h"
  42. #include <libvchan.h>
  43. #include "libqrexec-utils.h"
  44. #include "qrexec-agent.h"
  45. struct _connection_info {
  46. int pid; /* pid of child process handling the data */
  47. int fd; /* socket to process handling the data (wait for EOF here) */
  48. int connect_domain;
  49. int connect_port;
  50. };
  51. /* structure describing a single request waiting for qubes.WaitForSession to
  52. * finish */
  53. struct _waiting_request {
  54. int type;
  55. int connect_domain;
  56. int connect_port;
  57. char *cmdline;
  58. };
  59. int max_process_fd = -1;
  60. /* */
  61. struct _connection_info connection_info[MAX_FDS];
  62. struct _waiting_request requests_waiting_for_session[MAX_FDS];
  63. libvchan_t *ctrl_vchan;
  64. pid_t wait_for_session_pid = -1;
  65. int trigger_fd;
  66. int meminfo_write_started = 0;
  67. void handle_server_exec_request_do(int type, int connect_domain, int connect_port, char *cmdline);
  68. void no_colon_in_cmd()
  69. {
  70. fprintf(stderr,
  71. "cmdline is supposed to be in user:command form\n");
  72. exit(1);
  73. }
  74. #ifdef HAVE_PAM
  75. int pam_conv_callback(int num_msg, const struct pam_message **msg,
  76. struct pam_response **resp, void *appdata_ptr __attribute__((__unused__)))
  77. {
  78. int i;
  79. struct pam_response *resp_array =
  80. calloc(sizeof(struct pam_response), num_msg);
  81. if (resp_array == NULL)
  82. return PAM_BUF_ERR;
  83. for (i=0; i<num_msg; i++) {
  84. if (msg[i]->msg_style == PAM_ERROR_MSG)
  85. fprintf(stderr, "%s", msg[i]->msg);
  86. if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF ||
  87. msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
  88. resp_array[i].resp = strdup("");
  89. resp_array[i].resp_retcode = 0;
  90. }
  91. }
  92. *resp = resp_array;
  93. return PAM_SUCCESS;
  94. }
  95. static struct pam_conv conv = {
  96. pam_conv_callback,
  97. NULL
  98. };
  99. #endif
  100. /* Start program requested by dom0 in already prepared process
  101. * (stdin/stdout/stderr already set, etc)
  102. * Called in two cases:
  103. * MSG_JUST_EXEC - from qrexec-agent-data.c:handle_new_process_common->handle_just_exec
  104. * MSG_EXEC_CMDLINE - from
  105. * qrexec-agent-data.c:handle_new_process_common->do_fork_exec (callback
  106. * registerd with register_exec_func in init() here)
  107. *
  108. * cmd parameter came from dom0 (MSG_JUST_EXEC or MSG_EXEC_CMDLINE messages), so
  109. * is trusted. Even in VM-VM service request, the command here is controlled by
  110. * dom0 - it will be in form:
  111. * RPC_REQUEST_COMMAND " " service_name " " source_vm_name
  112. * where service_name is already validated against Qrexec RPC policy
  113. *
  114. * If dom0 sends overly long cmd, it will probably crash qrexec-agent (unless
  115. * process can allocate up to 4GB on both stack and heap), sorry.
  116. */
  117. void do_exec(const char *cmd)
  118. {
  119. char buf[strlen(QUBES_RPC_MULTIPLEXER_PATH) + strlen(cmd) - RPC_REQUEST_COMMAND_LEN + 1];
  120. char *realcmd = index(cmd, ':'), *user;
  121. #ifdef HAVE_PAM
  122. int retval, status;
  123. pam_handle_t *pamh=NULL;
  124. struct passwd *pw;
  125. struct passwd pw_copy;
  126. pid_t child, pid;
  127. char **env;
  128. char pid_s[32];
  129. char *arg0;
  130. char *shell_basename;
  131. #endif
  132. if (!realcmd)
  133. no_colon_in_cmd();
  134. /* mark end of username and move to command */
  135. user=strndup(cmd,realcmd-cmd);
  136. realcmd++;
  137. /* ignore "nogui:" prefix in linux agent */
  138. if (strncmp(realcmd, NOGUI_CMD_PREFIX, NOGUI_CMD_PREFIX_LEN) == 0)
  139. realcmd += NOGUI_CMD_PREFIX_LEN;
  140. /* replace magic RPC cmd with RPC multiplexer path */
  141. if (strncmp(realcmd, RPC_REQUEST_COMMAND " ", RPC_REQUEST_COMMAND_LEN+1)==0) {
  142. strcpy(buf, QUBES_RPC_MULTIPLEXER_PATH);
  143. strcpy(buf + strlen(QUBES_RPC_MULTIPLEXER_PATH), realcmd + RPC_REQUEST_COMMAND_LEN);
  144. realcmd = buf;
  145. }
  146. signal(SIGCHLD, SIG_DFL);
  147. signal(SIGPIPE, SIG_DFL);
  148. #ifdef HAVE_PAM
  149. pw = getpwnam (user);
  150. if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0]
  151. && pw->pw_passwd)) {
  152. fprintf(stderr, "user %s does not exist", user);
  153. exit(1);
  154. }
  155. /* Make a copy of the password information and point pw at the local
  156. * copy instead. Otherwise, some systems (e.g. Linux) would clobber
  157. * the static data through the getlogin call.
  158. */
  159. pw_copy = *pw;
  160. pw = &pw_copy;
  161. pw->pw_name = strdup(pw->pw_name);
  162. pw->pw_passwd = strdup(pw->pw_passwd);
  163. pw->pw_dir = strdup(pw->pw_dir);
  164. pw->pw_shell = strdup(pw->pw_shell);
  165. endpwent();
  166. shell_basename = basename (pw->pw_shell);
  167. /* this process is going to die shortly, so don't care about freeing */
  168. arg0 = malloc (strlen (shell_basename) + 2);
  169. if (!arg0)
  170. goto error;
  171. arg0[0] = '-';
  172. strcpy (arg0 + 1, shell_basename);
  173. retval = pam_start("qrexec", user, &conv, &pamh);
  174. if (retval != PAM_SUCCESS)
  175. goto error;
  176. retval = pam_authenticate(pamh, 0);
  177. if (retval != PAM_SUCCESS)
  178. goto error;
  179. retval = initgroups(pw->pw_name, pw->pw_gid);
  180. if (retval == -1) {
  181. perror("initgroups");
  182. goto error;
  183. }
  184. retval = pam_setcred(pamh, PAM_ESTABLISH_CRED);
  185. if (retval != PAM_SUCCESS)
  186. goto error;
  187. retval = pam_open_session(pamh, 0);
  188. if (retval != PAM_SUCCESS)
  189. goto error;
  190. /* provide this variable to child process */
  191. snprintf(pid_s, sizeof(pid_s), "QREXEC_AGENT_PID=%d", getppid());
  192. retval = pam_putenv(pamh, pid_s);
  193. if (retval != PAM_SUCCESS)
  194. goto error;
  195. /* FORK HERE */
  196. child = fork ();
  197. switch (child) {
  198. case -1:
  199. goto error;
  200. case 0:
  201. /* child */
  202. if (setgid (pw->pw_gid))
  203. exit(126);
  204. if (setuid (pw->pw_uid))
  205. exit(126);
  206. setsid();
  207. /* This is a copy but don't care to free as we exec later anyways. */
  208. env = pam_getenvlist (pamh);
  209. execle(pw->pw_shell, arg0, "-c", realcmd, (char*)NULL, env);
  210. exit(127);
  211. default:
  212. /* parent */
  213. /* close std*, so when child process closes them, qrexec-agent will receive EOF */
  214. /* this is the main purpose of this reimplementation of /bin/su... */
  215. close(0);
  216. close(1);
  217. close(2);
  218. }
  219. /* reachable only in parent */
  220. pid = waitpid (child, &status, 0);
  221. if (pid != (pid_t)-1) {
  222. if (WIFSIGNALED (status))
  223. status = WTERMSIG (status) + 128;
  224. else
  225. status = WEXITSTATUS (status);
  226. } else
  227. status = 1;
  228. retval = pam_close_session (pamh, 0);
  229. retval = pam_setcred (pamh, PAM_DELETE_CRED | PAM_SILENT);
  230. if (pam_end(pamh, retval) != PAM_SUCCESS) { /* close Linux-PAM */
  231. pamh = NULL;
  232. exit(1);
  233. }
  234. exit(status);
  235. error:
  236. pam_end(pamh, PAM_ABORT);
  237. exit(1);
  238. #else
  239. execl("/bin/su", "su", "-", user, "-c", realcmd, NULL);
  240. perror("execl");
  241. exit(1);
  242. #endif
  243. }
  244. void handle_vchan_error(const char *op)
  245. {
  246. fprintf(stderr, "Error while vchan %s, exiting\n", op);
  247. exit(1);
  248. }
  249. void init()
  250. {
  251. mode_t old_umask;
  252. /* FIXME: This 0 is remote domain ID */
  253. ctrl_vchan = libvchan_server_init(0, VCHAN_BASE_PORT, 4096, 4096);
  254. if (!ctrl_vchan)
  255. handle_vchan_error("server_init");
  256. if (handle_handshake(ctrl_vchan) < 0)
  257. exit(1);
  258. old_umask = umask(0);
  259. trigger_fd = get_server_socket(QREXEC_AGENT_TRIGGER_PATH);
  260. umask(old_umask);
  261. register_exec_func(do_exec);
  262. /* wait for qrexec daemon */
  263. while (!libvchan_is_open(ctrl_vchan))
  264. libvchan_wait(ctrl_vchan);
  265. }
  266. void wake_meminfo_writer()
  267. {
  268. FILE *f;
  269. int pid;
  270. if (meminfo_write_started)
  271. /* wake meminfo-writer only once */
  272. return;
  273. f = fopen(MEMINFO_WRITER_PIDFILE, "r");
  274. if (f == NULL) {
  275. /* no meminfo-writer found, ignoring */
  276. return;
  277. }
  278. if (fscanf(f, "%d", &pid) < 1) {
  279. fclose(f);
  280. /* no meminfo-writer found, ignoring */
  281. return;
  282. }
  283. fclose(f);
  284. if (pid <= 1 || pid > 0xffff) {
  285. /* check within acceptable range */
  286. return;
  287. }
  288. if (kill(pid, SIGUSR1) < 0) {
  289. /* Can't send signal */
  290. return;
  291. }
  292. meminfo_write_started = 1;
  293. }
  294. int try_fork_server(int type, int connect_domain, int connect_port,
  295. char *cmdline, int cmdline_len) {
  296. char username[cmdline_len];
  297. char *colon;
  298. char *fork_server_socket_path;
  299. int s, len;
  300. struct sockaddr_un remote;
  301. struct qrexec_cmd_info info;
  302. strncpy(username, cmdline, cmdline_len);
  303. colon = index(username, ':');
  304. if (!colon)
  305. return -1;
  306. *colon = '\0';
  307. if (asprintf(&fork_server_socket_path, QREXEC_FORK_SERVER_SOCKET, username) < 0) {
  308. fprintf(stderr, "Memory allocation failed\n");
  309. return -1;
  310. }
  311. remote.sun_family = AF_UNIX;
  312. strncpy(remote.sun_path, fork_server_socket_path,
  313. sizeof(remote.sun_path));
  314. free(fork_server_socket_path);
  315. if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  316. perror("socket");
  317. return -1;
  318. }
  319. len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  320. if (connect(s, (struct sockaddr *) &remote, len) == -1) {
  321. if (errno != ECONNREFUSED && errno != ENOENT)
  322. perror("connect");
  323. close(s);
  324. return -1;
  325. }
  326. info.type = type;
  327. info.connect_domain = connect_domain;
  328. info.connect_port = connect_port;
  329. info.cmdline_len = cmdline_len-(strlen(username)+1);
  330. if (!write_all(s, &info, sizeof(info))) {
  331. perror("write");
  332. close(s);
  333. return -1;
  334. }
  335. if (!write_all(s, colon+1, info.cmdline_len)) {
  336. perror("write");
  337. close(s);
  338. return -1;
  339. }
  340. return s;
  341. }
  342. void register_vchan_connection(pid_t pid, int fd, int domain, int port)
  343. {
  344. int i;
  345. for (i = 0; i < MAX_FDS; i++) {
  346. if (connection_info[i].pid == 0) {
  347. connection_info[i].pid = pid;
  348. connection_info[i].fd = fd;
  349. connection_info[i].connect_domain = domain;
  350. connection_info[i].connect_port = port;
  351. return;
  352. }
  353. }
  354. fprintf(stderr, "No free slot for child %d (connection to %d:%d)\n", pid, domain, port);
  355. }
  356. /* Load service configuration from /etc/qubes/rpc-config/
  357. * (QUBES_RPC_CONFIG_DIR), currently only wait-for-session option supported.
  358. *
  359. * Return:
  360. * 1 - config successfuly loaded
  361. * 0 - config not found
  362. * -1 - other error
  363. */
  364. int load_service_config(const char *service_name, int *wait_for_session) {
  365. char filename[256];
  366. char config[MAX_CONFIG_SIZE];
  367. char *config_iter = config;
  368. FILE *config_file;
  369. size_t read_count;
  370. char *current_line;
  371. if (snprintf(filename, sizeof(filename), "%s/%s",
  372. QUBES_RPC_CONFIG_DIR, service_name) >= (int)sizeof(filename)) {
  373. /* buffer too small?! */
  374. return -1;
  375. }
  376. config_file = fopen(filename, "r");
  377. if (!config_file) {
  378. if (errno == ENOENT)
  379. return 0;
  380. else {
  381. fprintf(stderr, "Failed to load %s\n", filename);
  382. return -1;
  383. }
  384. }
  385. read_count = fread(config, 1, sizeof(config)-1, config_file);
  386. if (ferror(config_file)) {
  387. fclose(config_file);
  388. return -1;
  389. }
  390. // config is a text file, should not have \0 inside; but when it has, part
  391. // after it will be ignored
  392. config[read_count] = 0;
  393. while ((current_line = strsep(&config_iter, "\n"))) {
  394. // ignore comments
  395. if (current_line[0] == '#')
  396. continue;
  397. sscanf(current_line, "wait-for-session=%d", wait_for_session);
  398. }
  399. fclose(config_file);
  400. return 1;
  401. }
  402. /* Check if requested command/service require GUI session and if so, initiate
  403. * waiting process.
  404. *
  405. * Return:
  406. * - 1 - waiting is needed, caller should register request to be proceeded
  407. * only after session is started)
  408. * - 0 - waiting is not needed, caller may proceed with request immediately
  409. */
  410. int wait_for_session_maybe(char *cmdline) {
  411. char *realcmd = index(cmdline, ':');
  412. char *user, *service_name, *source_domain, *service_argument;
  413. int stdin_pipe[2];
  414. int wait_for_session = 0;
  415. if (!realcmd)
  416. /* no colon in command line, this will be properly reported later */
  417. return 0;
  418. /* "nogui:" prefix have priority - do not wait for session */
  419. if (strncmp(realcmd, NOGUI_CMD_PREFIX, NOGUI_CMD_PREFIX_LEN) == 0)
  420. return 0;
  421. /* extract username */
  422. user = strndup(cmdline, realcmd - cmdline);
  423. realcmd++;
  424. /* wait for session only for service requests */
  425. if (strncmp(realcmd, RPC_REQUEST_COMMAND " ", RPC_REQUEST_COMMAND_LEN+1) != 0) {
  426. free(user);
  427. return 0;
  428. }
  429. realcmd += RPC_REQUEST_COMMAND_LEN+1;
  430. /* now realcmd contains service name (possibly with argument after '+'
  431. * char) and source domain name, after space */
  432. source_domain = index(realcmd, ' ');
  433. if (!source_domain) {
  434. /* qrexec-rpc-multiplexer will properly report this */
  435. free(user);
  436. return 0;
  437. }
  438. service_name = strndup(realcmd, source_domain - realcmd);
  439. source_domain++;
  440. /* first try to load config for specific argument */
  441. switch (load_service_config(service_name, &wait_for_session)) {
  442. case 0:
  443. /* no config for specific argument, try for bare service name */
  444. service_argument = index(service_name, '+');
  445. if (!service_argument) {
  446. /* there was no argument, so no config at all - do not wait for
  447. * session */
  448. free(user);
  449. return 0;
  450. }
  451. /* cut off the argument */
  452. *service_argument = '\0';
  453. if (load_service_config(service_name, &wait_for_session) != 1) {
  454. /* no config, or load error -> no wait for session */
  455. free(user);
  456. return 0;
  457. }
  458. break;
  459. case 1:
  460. /* config loaded */
  461. break;
  462. case -1:
  463. /* load error -> no wait for session */
  464. free(user);
  465. return 0;
  466. }
  467. if (!wait_for_session) {
  468. /* setting not set, or set to 0 */
  469. free(user);
  470. return 0;
  471. }
  472. /* ok, now we know that service is configured to wait for session */
  473. if (wait_for_session_pid != -1) {
  474. /* we're already waiting */
  475. free(user);
  476. return 1;
  477. }
  478. if (pipe(stdin_pipe) == -1) {
  479. perror("pipe for wait-for-session");
  480. free(user);
  481. return 0;
  482. }
  483. /* start waiting process */
  484. wait_for_session_pid = fork();
  485. switch (wait_for_session_pid) {
  486. case 0:
  487. close(stdin_pipe[1]);
  488. dup2(stdin_pipe[0], 0);
  489. execl("/etc/qubes-rpc/qubes.WaitForSession", "qubes.WaitForSession",
  490. source_domain, (char*)NULL);
  491. exit(1);
  492. case -1:
  493. perror("fork wait-for-session");
  494. free(user);
  495. return 0;
  496. default:
  497. close(stdin_pipe[0]);
  498. if (write(stdin_pipe[1], user, strlen(user)) == -1)
  499. perror("write error");
  500. if (write(stdin_pipe[1], "\n", 1) == -1)
  501. perror("write error");
  502. close(stdin_pipe[1]);
  503. }
  504. free(user);
  505. /* qubes.WaitForSession started, postpone request until it report back */
  506. return 1;
  507. }
  508. /* hdr parameter is received from dom0, so it is trusted */
  509. void handle_server_exec_request_init(struct msg_header *hdr)
  510. {
  511. struct exec_params params;
  512. int buf_len = hdr->len-sizeof(params);
  513. char buf[buf_len];
  514. assert(hdr->len >= sizeof(params));
  515. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  516. handle_vchan_error("read exec params");
  517. if (libvchan_recv(ctrl_vchan, buf, buf_len) < 0)
  518. handle_vchan_error("read exec cmd");
  519. buf[buf_len-1] = 0;
  520. if (hdr->type != MSG_SERVICE_CONNECT && wait_for_session_maybe(buf)) {
  521. /* waiting for session, postpone actual call */
  522. int slot_index = 0;
  523. while (slot_index < MAX_FDS)
  524. if (!requests_waiting_for_session[slot_index].cmdline)
  525. break;
  526. if (slot_index == MAX_FDS) {
  527. /* no free slots */
  528. fprintf(stderr, "No free slots for waiting for GUI session, continuing!\n");
  529. } else {
  530. requests_waiting_for_session[slot_index].type = hdr->type;
  531. requests_waiting_for_session[slot_index].connect_domain = params.connect_domain;
  532. requests_waiting_for_session[slot_index].connect_port = params.connect_port;
  533. requests_waiting_for_session[slot_index].cmdline = strdup(buf);
  534. /* nothing to do now, when we get GUI session, we'll continue */
  535. return;
  536. }
  537. }
  538. handle_server_exec_request_do(hdr->type, params.connect_domain, params.connect_port, buf);
  539. }
  540. void handle_server_exec_request_do(int type, int connect_domain, int connect_port, char *cmdline) {
  541. int client_fd;
  542. pid_t child_agent;
  543. int cmdline_len = strlen(cmdline) + 1; // size of cmdline, including \0 at the end
  544. struct exec_params params = {
  545. .connect_domain = connect_domain,
  546. .connect_port = connect_port,
  547. };
  548. if ((type == MSG_EXEC_CMDLINE || type == MSG_JUST_EXEC) &&
  549. !strstr(cmdline, ":nogui:")) {
  550. int child_socket;
  551. child_socket = try_fork_server(type,
  552. params.connect_domain, params.connect_port,
  553. cmdline, cmdline_len);
  554. if (child_socket >= 0) {
  555. register_vchan_connection(-1, child_socket,
  556. params.connect_domain, params.connect_port);
  557. return;
  558. }
  559. }
  560. if (type == MSG_SERVICE_CONNECT && sscanf(cmdline, "SOCKET%d", &client_fd)) {
  561. /* FIXME: Maybe add some check if client_fd is really FD to some
  562. * qrexec-client-vm process; but this data comes from qrexec-daemon
  563. * (which sends back what it got from us earlier), so it isn't critical.
  564. */
  565. if (write(client_fd, &params, sizeof(params)) < 0) {
  566. /* ignore */
  567. }
  568. /* No need to send request_id (buf) - the client don't need it, there
  569. * is only meaningless (for the client) socket FD */
  570. /* Register connection even if there was an error sending params to
  571. * qrexec-client-vm. This way the mainloop will clean the things up
  572. * (close socket, send MSG_CONNECTION_TERMINATED) when qrexec-client-vm
  573. * will close the socket (terminate itself). */
  574. register_vchan_connection(-1, client_fd,
  575. params.connect_domain, params.connect_port);
  576. return;
  577. }
  578. /* No fork server case */
  579. child_agent = handle_new_process(type,
  580. params.connect_domain, params.connect_port,
  581. cmdline, cmdline_len);
  582. register_vchan_connection(child_agent, -1,
  583. params.connect_domain, params.connect_port);
  584. }
  585. void handle_service_refused(struct msg_header *hdr)
  586. {
  587. struct service_params params;
  588. int socket_fd;
  589. if (hdr->len != sizeof(params)) {
  590. fprintf(stderr, "Invalid msg 0x%x length (%d)\n", MSG_SERVICE_REFUSED, hdr->len);
  591. exit(1);
  592. }
  593. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  594. handle_vchan_error("read exec params");
  595. if (sscanf(params.ident, "SOCKET%d", &socket_fd))
  596. close(socket_fd);
  597. else
  598. fprintf(stderr, "Received REFUSED for unknown service request '%s'\n", params.ident);
  599. }
  600. void handle_server_cmd()
  601. {
  602. struct msg_header s_hdr;
  603. if (libvchan_recv(ctrl_vchan, &s_hdr, sizeof(s_hdr)) < 0)
  604. handle_vchan_error("read s_hdr");
  605. // fprintf(stderr, "got %x %x %x\n", s_hdr.type, s_hdr.client_id,
  606. // s_hdr.len);
  607. switch (s_hdr.type) {
  608. case MSG_EXEC_CMDLINE:
  609. case MSG_JUST_EXEC:
  610. case MSG_SERVICE_CONNECT:
  611. wake_meminfo_writer();
  612. handle_server_exec_request_init(&s_hdr);
  613. break;
  614. case MSG_SERVICE_REFUSED:
  615. handle_service_refused(&s_hdr);
  616. break;
  617. default:
  618. fprintf(stderr, "msg type from daemon is %d ?\n",
  619. s_hdr.type);
  620. exit(1);
  621. }
  622. }
  623. volatile int child_exited;
  624. void sigchld_handler(int x __attribute__((__unused__)))
  625. {
  626. child_exited = 1;
  627. signal(SIGCHLD, sigchld_handler);
  628. }
  629. int find_connection(int pid)
  630. {
  631. int i;
  632. for (i = 0; i < MAX_FDS; i++)
  633. if (connection_info[i].pid == pid)
  634. return i;
  635. return -1;
  636. }
  637. void release_connection(int id) {
  638. struct msg_header hdr;
  639. struct exec_params params;
  640. hdr.type = MSG_CONNECTION_TERMINATED;
  641. hdr.len = sizeof(struct exec_params);
  642. params.connect_domain = connection_info[id].connect_domain;
  643. params.connect_port = connection_info[id].connect_port;
  644. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  645. handle_vchan_error("send");
  646. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  647. handle_vchan_error("send");
  648. connection_info[id].pid = 0;
  649. }
  650. void reap_children()
  651. {
  652. int status;
  653. int pid;
  654. int id;
  655. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  656. if (pid == wait_for_session_pid) {
  657. for (id = 0; id < MAX_FDS; id++) {
  658. if (!requests_waiting_for_session[id].cmdline)
  659. continue;
  660. handle_server_exec_request_do(
  661. requests_waiting_for_session[id].type,
  662. requests_waiting_for_session[id].connect_domain,
  663. requests_waiting_for_session[id].connect_port,
  664. requests_waiting_for_session[id].cmdline);
  665. free(requests_waiting_for_session[id].cmdline);
  666. requests_waiting_for_session[id].cmdline = NULL;
  667. }
  668. wait_for_session_pid = -1;
  669. continue;
  670. }
  671. id = find_connection(pid);
  672. if (id < 0)
  673. continue;
  674. release_connection(id);
  675. }
  676. child_exited = 0;
  677. }
  678. int fill_fds_for_select(fd_set * rdset, fd_set * wrset)
  679. {
  680. int max = -1;
  681. int i;
  682. FD_ZERO(rdset);
  683. FD_ZERO(wrset);
  684. FD_SET(trigger_fd, rdset);
  685. if (trigger_fd > max)
  686. max = trigger_fd;
  687. for (i = 0; i < MAX_FDS; i++) {
  688. if (connection_info[i].pid != 0 && connection_info[i].fd != -1) {
  689. FD_SET(connection_info[i].fd, rdset);
  690. if (connection_info[i].fd > max)
  691. max = connection_info[i].fd;
  692. }
  693. }
  694. return max;
  695. }
  696. void handle_trigger_io()
  697. {
  698. struct msg_header hdr;
  699. struct trigger_service_params params;
  700. int ret;
  701. int client_fd;
  702. client_fd = do_accept(trigger_fd);
  703. if (client_fd < 0)
  704. return;
  705. hdr.len = sizeof(params);
  706. ret = read(client_fd, &params, sizeof(params));
  707. if (ret == sizeof(params)) {
  708. hdr.type = MSG_TRIGGER_SERVICE;
  709. snprintf(params.request_id.ident, sizeof(params.request_id), "SOCKET%d", client_fd);
  710. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  711. handle_vchan_error("write hdr");
  712. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  713. handle_vchan_error("write params");
  714. }
  715. if (ret <= 0) {
  716. close(client_fd);
  717. }
  718. /* do not close client_fd - we'll need it to send the connection details
  719. * later (when dom0 accepts the request) */
  720. }
  721. void handle_terminated_fork_client(fd_set *rdset) {
  722. int i, ret;
  723. char buf[2];
  724. for (i = 0; i < MAX_FDS; i++) {
  725. if (connection_info[i].pid && connection_info[i].fd >= 0 &&
  726. FD_ISSET(connection_info[i].fd, rdset)) {
  727. ret = read(connection_info[i].fd, buf, sizeof(buf));
  728. if (ret == 0 || (ret == -1 && errno == ECONNRESET)) {
  729. close(connection_info[i].fd);
  730. release_connection(i);
  731. } else {
  732. fprintf(stderr, "Unexpected read on fork-server connection: %d(%s)\n", ret, strerror(errno));
  733. close(connection_info[i].fd);
  734. release_connection(i);
  735. }
  736. }
  737. }
  738. }
  739. int main()
  740. {
  741. fd_set rdset, wrset;
  742. int max;
  743. sigset_t chld_set;
  744. init();
  745. signal(SIGCHLD, sigchld_handler);
  746. signal(SIGPIPE, SIG_IGN);
  747. sigemptyset(&chld_set);
  748. sigaddset(&chld_set, SIGCHLD);
  749. for (;;) {
  750. sigprocmask(SIG_BLOCK, &chld_set, NULL);
  751. if (child_exited)
  752. reap_children();
  753. max = fill_fds_for_select(&rdset, &wrset);
  754. if (libvchan_buffer_space(ctrl_vchan) <=
  755. (int)sizeof(struct msg_header))
  756. FD_ZERO(&rdset);
  757. wait_for_vchan_or_argfd(ctrl_vchan, max, &rdset, &wrset);
  758. sigprocmask(SIG_UNBLOCK, &chld_set, NULL);
  759. while (libvchan_data_ready(ctrl_vchan))
  760. handle_server_cmd();
  761. if (FD_ISSET(trigger_fd, &rdset))
  762. handle_trigger_io();
  763. handle_terminated_fork_client(&rdset);
  764. }
  765. }