qrexec-agent.c 26 KB

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