qrexec-agent.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. int my_sd_notify(int unset_environment, const char *state) {
  270. struct sockaddr_un addr;
  271. int fd;
  272. int ret = -1;
  273. addr.sun_family = AF_UNIX;
  274. strncpy(addr.sun_path, getenv("NOTIFY_SOCKET"), sizeof(addr.sun_path)-1);
  275. addr.sun_path[sizeof(addr.sun_path)-1] = '\0';
  276. if (addr.sun_path[0] == '@')
  277. addr.sun_path[0] = '\0';
  278. if (unset_environment)
  279. unsetenv("NOTIFY_SOCKET");
  280. fd = socket(AF_UNIX, SOCK_DGRAM, 0);
  281. if (fd == -1) {
  282. perror("sd_notify socket");
  283. return -1;
  284. }
  285. if (connect(fd, &addr, sizeof(addr)) == -1) {
  286. perror("sd_notify connect");
  287. goto out;
  288. }
  289. if (send(fd, state, strlen(state), 0) == -1) {
  290. perror("sd_notify send");
  291. goto out;
  292. }
  293. ret = 0;
  294. out:
  295. close(fd);
  296. return ret;
  297. }
  298. void init()
  299. {
  300. mode_t old_umask;
  301. /* FIXME: This 0 is remote domain ID */
  302. ctrl_vchan = libvchan_server_init(0, VCHAN_BASE_PORT, 4096, 4096);
  303. if (!ctrl_vchan)
  304. handle_vchan_error("server_init");
  305. if (handle_handshake(ctrl_vchan) < 0)
  306. exit(1);
  307. old_umask = umask(0);
  308. trigger_fd = get_server_socket(QREXEC_AGENT_TRIGGER_PATH);
  309. umask(old_umask);
  310. register_exec_func(do_exec);
  311. /* wait for qrexec daemon */
  312. while (!libvchan_is_open(ctrl_vchan))
  313. libvchan_wait(ctrl_vchan);
  314. if (getenv("NOTIFY_SOCKET")) {
  315. my_sd_notify(1, "READY=1");
  316. }
  317. }
  318. void wake_meminfo_writer()
  319. {
  320. FILE *f;
  321. int pid;
  322. if (meminfo_write_started)
  323. /* wake meminfo-writer only once */
  324. return;
  325. f = fopen(MEMINFO_WRITER_PIDFILE, "r");
  326. if (f == NULL) {
  327. /* no meminfo-writer found, ignoring */
  328. return;
  329. }
  330. if (fscanf(f, "%d", &pid) < 1) {
  331. fclose(f);
  332. /* no meminfo-writer found, ignoring */
  333. return;
  334. }
  335. fclose(f);
  336. if (pid <= 1 || pid > 0xffff) {
  337. /* check within acceptable range */
  338. return;
  339. }
  340. if (kill(pid, SIGUSR1) < 0) {
  341. /* Can't send signal */
  342. return;
  343. }
  344. meminfo_write_started = 1;
  345. }
  346. int try_fork_server(int type, int connect_domain, int connect_port,
  347. char *cmdline, int cmdline_len) {
  348. char username[cmdline_len];
  349. char *colon;
  350. char *fork_server_socket_path;
  351. int s, len;
  352. struct sockaddr_un remote;
  353. struct qrexec_cmd_info info;
  354. strncpy(username, cmdline, cmdline_len);
  355. colon = index(username, ':');
  356. if (!colon)
  357. return -1;
  358. *colon = '\0';
  359. if (asprintf(&fork_server_socket_path, QREXEC_FORK_SERVER_SOCKET, username) < 0) {
  360. fprintf(stderr, "Memory allocation failed\n");
  361. return -1;
  362. }
  363. remote.sun_family = AF_UNIX;
  364. strncpy(remote.sun_path, fork_server_socket_path,
  365. sizeof(remote.sun_path) - 1);
  366. free(fork_server_socket_path);
  367. if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  368. perror("socket");
  369. return -1;
  370. }
  371. len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  372. if (connect(s, (struct sockaddr *) &remote, len) == -1) {
  373. if (errno != ECONNREFUSED && errno != ENOENT)
  374. perror("connect");
  375. close(s);
  376. return -1;
  377. }
  378. info.type = type;
  379. info.connect_domain = connect_domain;
  380. info.connect_port = connect_port;
  381. info.cmdline_len = cmdline_len-(strlen(username)+1);
  382. if (!write_all(s, &info, sizeof(info))) {
  383. perror("write");
  384. close(s);
  385. return -1;
  386. }
  387. if (!write_all(s, colon+1, info.cmdline_len)) {
  388. perror("write");
  389. close(s);
  390. return -1;
  391. }
  392. return s;
  393. }
  394. void register_vchan_connection(pid_t pid, int fd, int domain, int port)
  395. {
  396. int i;
  397. for (i = 0; i < MAX_FDS; i++) {
  398. if (connection_info[i].pid == 0) {
  399. connection_info[i].pid = pid;
  400. connection_info[i].fd = fd;
  401. connection_info[i].connect_domain = domain;
  402. connection_info[i].connect_port = port;
  403. return;
  404. }
  405. }
  406. fprintf(stderr, "No free slot for child %d (connection to %d:%d)\n", pid, domain, port);
  407. }
  408. /* Load service configuration from /etc/qubes/rpc-config/
  409. * (QUBES_RPC_CONFIG_DIR), currently only wait-for-session option supported.
  410. *
  411. * Return:
  412. * 1 - config successfuly loaded
  413. * 0 - config not found
  414. * -1 - other error
  415. */
  416. int load_service_config(const char *service_name, int *wait_for_session) {
  417. char filename[256];
  418. char config[MAX_CONFIG_SIZE];
  419. char *config_iter = config;
  420. FILE *config_file;
  421. size_t read_count;
  422. char *current_line;
  423. if (snprintf(filename, sizeof(filename), "%s/%s",
  424. QUBES_RPC_CONFIG_DIR, service_name) >= (int)sizeof(filename)) {
  425. /* buffer too small?! */
  426. return -1;
  427. }
  428. config_file = fopen(filename, "r");
  429. if (!config_file) {
  430. if (errno == ENOENT)
  431. return 0;
  432. else {
  433. fprintf(stderr, "Failed to load %s\n", filename);
  434. return -1;
  435. }
  436. }
  437. read_count = fread(config, 1, sizeof(config)-1, config_file);
  438. if (ferror(config_file)) {
  439. fclose(config_file);
  440. return -1;
  441. }
  442. // config is a text file, should not have \0 inside; but when it has, part
  443. // after it will be ignored
  444. config[read_count] = 0;
  445. while ((current_line = strsep(&config_iter, "\n"))) {
  446. // ignore comments
  447. if (current_line[0] == '#')
  448. continue;
  449. sscanf(current_line, "wait-for-session=%d", wait_for_session);
  450. }
  451. fclose(config_file);
  452. return 1;
  453. }
  454. /* Check if requested command/service require GUI session and if so, initiate
  455. * waiting process.
  456. *
  457. * Return:
  458. * - 1 - waiting is needed, caller should register request to be proceeded
  459. * only after session is started)
  460. * - 0 - waiting is not needed, caller may proceed with request immediately
  461. */
  462. int wait_for_session_maybe(char *cmdline) {
  463. char *realcmd = index(cmdline, ':');
  464. char *user, *service_name, *source_domain, *service_argument;
  465. int stdin_pipe[2];
  466. int wait_for_session = 0;
  467. if (!realcmd)
  468. /* no colon in command line, this will be properly reported later */
  469. return 0;
  470. /* "nogui:" prefix have priority - do not wait for session */
  471. if (strncmp(realcmd, NOGUI_CMD_PREFIX, NOGUI_CMD_PREFIX_LEN) == 0)
  472. return 0;
  473. /* extract username */
  474. user = strndup(cmdline, realcmd - cmdline);
  475. realcmd++;
  476. /* wait for session only for service requests */
  477. if (strncmp(realcmd, RPC_REQUEST_COMMAND " ", RPC_REQUEST_COMMAND_LEN+1) != 0) {
  478. free(user);
  479. return 0;
  480. }
  481. realcmd += RPC_REQUEST_COMMAND_LEN+1;
  482. /* now realcmd contains service name (possibly with argument after '+'
  483. * char) and source domain name, after space */
  484. source_domain = index(realcmd, ' ');
  485. if (!source_domain) {
  486. /* qrexec-rpc-multiplexer will properly report this */
  487. free(user);
  488. return 0;
  489. }
  490. service_name = strndup(realcmd, source_domain - realcmd);
  491. source_domain++;
  492. /* first try to load config for specific argument */
  493. switch (load_service_config(service_name, &wait_for_session)) {
  494. case 0:
  495. /* no config for specific argument, try for bare service name */
  496. service_argument = index(service_name, '+');
  497. if (!service_argument) {
  498. /* there was no argument, so no config at all - do not wait for
  499. * session */
  500. free(user);
  501. return 0;
  502. }
  503. /* cut off the argument */
  504. *service_argument = '\0';
  505. if (load_service_config(service_name, &wait_for_session) != 1) {
  506. /* no config, or load error -> no wait for session */
  507. free(user);
  508. return 0;
  509. }
  510. break;
  511. case 1:
  512. /* config loaded */
  513. break;
  514. case -1:
  515. /* load error -> no wait for session */
  516. free(user);
  517. return 0;
  518. }
  519. if (!wait_for_session) {
  520. /* setting not set, or set to 0 */
  521. free(user);
  522. return 0;
  523. }
  524. /* ok, now we know that service is configured to wait for session */
  525. if (wait_for_session_pid != -1) {
  526. /* we're already waiting */
  527. free(user);
  528. return 1;
  529. }
  530. if (pipe(stdin_pipe) == -1) {
  531. perror("pipe for wait-for-session");
  532. free(user);
  533. return 0;
  534. }
  535. /* start waiting process */
  536. wait_for_session_pid = fork();
  537. switch (wait_for_session_pid) {
  538. case 0:
  539. close(stdin_pipe[1]);
  540. dup2(stdin_pipe[0], 0);
  541. execl("/etc/qubes-rpc/qubes.WaitForSession", "qubes.WaitForSession",
  542. source_domain, (char*)NULL);
  543. exit(1);
  544. case -1:
  545. perror("fork wait-for-session");
  546. free(user);
  547. return 0;
  548. default:
  549. close(stdin_pipe[0]);
  550. if (write(stdin_pipe[1], user, strlen(user)) == -1)
  551. perror("write error");
  552. if (write(stdin_pipe[1], "\n", 1) == -1)
  553. perror("write error");
  554. close(stdin_pipe[1]);
  555. }
  556. free(user);
  557. /* qubes.WaitForSession started, postpone request until it report back */
  558. return 1;
  559. }
  560. /* hdr parameter is received from dom0, so it is trusted */
  561. void handle_server_exec_request_init(struct msg_header *hdr)
  562. {
  563. struct exec_params params;
  564. int buf_len = hdr->len-sizeof(params);
  565. char buf[buf_len];
  566. assert(hdr->len >= sizeof(params));
  567. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  568. handle_vchan_error("read exec params");
  569. if (libvchan_recv(ctrl_vchan, buf, buf_len) < 0)
  570. handle_vchan_error("read exec cmd");
  571. buf[buf_len-1] = 0;
  572. if (hdr->type != MSG_SERVICE_CONNECT && wait_for_session_maybe(buf)) {
  573. /* waiting for session, postpone actual call */
  574. int slot_index;
  575. for (slot_index = 0; slot_index < MAX_FDS; slot_index++)
  576. if (!requests_waiting_for_session[slot_index].cmdline)
  577. break;
  578. if (slot_index == MAX_FDS) {
  579. /* no free slots */
  580. fprintf(stderr, "No free slots for waiting for GUI session, continuing!\n");
  581. } else {
  582. requests_waiting_for_session[slot_index].type = hdr->type;
  583. requests_waiting_for_session[slot_index].connect_domain = params.connect_domain;
  584. requests_waiting_for_session[slot_index].connect_port = params.connect_port;
  585. requests_waiting_for_session[slot_index].cmdline = strdup(buf);
  586. /* nothing to do now, when we get GUI session, we'll continue */
  587. return;
  588. }
  589. }
  590. handle_server_exec_request_do(hdr->type, params.connect_domain, params.connect_port, buf);
  591. }
  592. void handle_server_exec_request_do(int type, int connect_domain, int connect_port, char *cmdline) {
  593. int client_fd;
  594. pid_t child_agent;
  595. int cmdline_len = strlen(cmdline) + 1; // size of cmdline, including \0 at the end
  596. struct exec_params params = {
  597. .connect_domain = connect_domain,
  598. .connect_port = connect_port,
  599. };
  600. if ((type == MSG_EXEC_CMDLINE || type == MSG_JUST_EXEC) &&
  601. !strstr(cmdline, ":nogui:")) {
  602. int child_socket;
  603. child_socket = try_fork_server(type,
  604. params.connect_domain, params.connect_port,
  605. cmdline, cmdline_len);
  606. if (child_socket >= 0) {
  607. register_vchan_connection(-1, child_socket,
  608. params.connect_domain, params.connect_port);
  609. return;
  610. }
  611. }
  612. if (type == MSG_SERVICE_CONNECT && sscanf(cmdline, "SOCKET%d", &client_fd)) {
  613. /* FIXME: Maybe add some check if client_fd is really FD to some
  614. * qrexec-client-vm process; but this data comes from qrexec-daemon
  615. * (which sends back what it got from us earlier), so it isn't critical.
  616. */
  617. if (write(client_fd, &params, sizeof(params)) < 0) {
  618. /* ignore */
  619. }
  620. /* No need to send request_id (buf) - the client don't need it, there
  621. * is only meaningless (for the client) socket FD */
  622. /* Register connection even if there was an error sending params to
  623. * qrexec-client-vm. This way the mainloop will clean the things up
  624. * (close socket, send MSG_CONNECTION_TERMINATED) when qrexec-client-vm
  625. * will close the socket (terminate itself). */
  626. register_vchan_connection(-1, client_fd,
  627. params.connect_domain, params.connect_port);
  628. return;
  629. }
  630. /* No fork server case */
  631. child_agent = handle_new_process(type,
  632. params.connect_domain, params.connect_port,
  633. cmdline, cmdline_len);
  634. register_vchan_connection(child_agent, -1,
  635. params.connect_domain, params.connect_port);
  636. }
  637. void handle_service_refused(struct msg_header *hdr)
  638. {
  639. struct service_params params;
  640. int socket_fd;
  641. if (hdr->len != sizeof(params)) {
  642. fprintf(stderr, "Invalid msg 0x%x length (%d)\n", MSG_SERVICE_REFUSED, hdr->len);
  643. exit(1);
  644. }
  645. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  646. handle_vchan_error("read exec params");
  647. if (sscanf(params.ident, "SOCKET%d", &socket_fd))
  648. close(socket_fd);
  649. else
  650. fprintf(stderr, "Received REFUSED for unknown service request '%s'\n", params.ident);
  651. }
  652. void handle_server_cmd()
  653. {
  654. struct msg_header s_hdr;
  655. if (libvchan_recv(ctrl_vchan, &s_hdr, sizeof(s_hdr)) < 0)
  656. handle_vchan_error("read s_hdr");
  657. // fprintf(stderr, "got %x %x %x\n", s_hdr.type, s_hdr.client_id,
  658. // s_hdr.len);
  659. switch (s_hdr.type) {
  660. case MSG_EXEC_CMDLINE:
  661. case MSG_JUST_EXEC:
  662. case MSG_SERVICE_CONNECT:
  663. wake_meminfo_writer();
  664. handle_server_exec_request_init(&s_hdr);
  665. break;
  666. case MSG_SERVICE_REFUSED:
  667. handle_service_refused(&s_hdr);
  668. break;
  669. default:
  670. fprintf(stderr, "msg type from daemon is %d ?\n",
  671. s_hdr.type);
  672. exit(1);
  673. }
  674. }
  675. volatile int child_exited;
  676. void sigchld_handler(int x __attribute__((__unused__)))
  677. {
  678. child_exited = 1;
  679. signal(SIGCHLD, sigchld_handler);
  680. }
  681. int find_connection(int pid)
  682. {
  683. int i;
  684. for (i = 0; i < MAX_FDS; i++)
  685. if (connection_info[i].pid == pid)
  686. return i;
  687. return -1;
  688. }
  689. void release_connection(int id) {
  690. struct msg_header hdr;
  691. struct exec_params params;
  692. hdr.type = MSG_CONNECTION_TERMINATED;
  693. hdr.len = sizeof(struct exec_params);
  694. params.connect_domain = connection_info[id].connect_domain;
  695. params.connect_port = connection_info[id].connect_port;
  696. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  697. handle_vchan_error("send");
  698. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  699. handle_vchan_error("send");
  700. connection_info[id].pid = 0;
  701. }
  702. void reap_children()
  703. {
  704. int status;
  705. int pid;
  706. int id;
  707. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  708. if (pid == wait_for_session_pid) {
  709. for (id = 0; id < MAX_FDS; id++) {
  710. if (!requests_waiting_for_session[id].cmdline)
  711. continue;
  712. handle_server_exec_request_do(
  713. requests_waiting_for_session[id].type,
  714. requests_waiting_for_session[id].connect_domain,
  715. requests_waiting_for_session[id].connect_port,
  716. requests_waiting_for_session[id].cmdline);
  717. free(requests_waiting_for_session[id].cmdline);
  718. requests_waiting_for_session[id].cmdline = NULL;
  719. }
  720. wait_for_session_pid = -1;
  721. continue;
  722. }
  723. id = find_connection(pid);
  724. if (id < 0)
  725. continue;
  726. release_connection(id);
  727. }
  728. child_exited = 0;
  729. }
  730. int fill_fds_for_select(fd_set * rdset, fd_set * wrset)
  731. {
  732. int max = -1;
  733. int i;
  734. FD_ZERO(rdset);
  735. FD_ZERO(wrset);
  736. FD_SET(trigger_fd, rdset);
  737. if (trigger_fd > max)
  738. max = trigger_fd;
  739. for (i = 0; i < MAX_FDS; i++) {
  740. if (connection_info[i].pid != 0 && connection_info[i].fd != -1) {
  741. FD_SET(connection_info[i].fd, rdset);
  742. if (connection_info[i].fd > max)
  743. max = connection_info[i].fd;
  744. }
  745. }
  746. return max;
  747. }
  748. void handle_trigger_io()
  749. {
  750. struct msg_header hdr;
  751. struct trigger_service_params params;
  752. int ret;
  753. int client_fd;
  754. client_fd = do_accept(trigger_fd);
  755. if (client_fd < 0)
  756. return;
  757. hdr.len = sizeof(params);
  758. ret = read(client_fd, &params, sizeof(params));
  759. if (ret == sizeof(params)) {
  760. hdr.type = MSG_TRIGGER_SERVICE;
  761. snprintf(params.request_id.ident, sizeof(params.request_id), "SOCKET%d", client_fd);
  762. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  763. handle_vchan_error("write hdr");
  764. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  765. handle_vchan_error("write params");
  766. }
  767. if (ret <= 0) {
  768. close(client_fd);
  769. }
  770. /* do not close client_fd - we'll need it to send the connection details
  771. * later (when dom0 accepts the request) */
  772. }
  773. void handle_terminated_fork_client(fd_set *rdset) {
  774. int i, ret;
  775. char buf[2];
  776. for (i = 0; i < MAX_FDS; i++) {
  777. if (connection_info[i].pid && connection_info[i].fd >= 0 &&
  778. FD_ISSET(connection_info[i].fd, rdset)) {
  779. ret = read(connection_info[i].fd, buf, sizeof(buf));
  780. if (ret == 0 || (ret == -1 && errno == ECONNRESET)) {
  781. close(connection_info[i].fd);
  782. release_connection(i);
  783. } else {
  784. fprintf(stderr, "Unexpected read on fork-server connection: %d(%s)\n", ret, strerror(errno));
  785. close(connection_info[i].fd);
  786. release_connection(i);
  787. }
  788. }
  789. }
  790. }
  791. int main()
  792. {
  793. fd_set rdset, wrset;
  794. int max;
  795. sigset_t chld_set;
  796. init();
  797. signal(SIGCHLD, sigchld_handler);
  798. signal(SIGPIPE, SIG_IGN);
  799. sigemptyset(&chld_set);
  800. sigaddset(&chld_set, SIGCHLD);
  801. for (;;) {
  802. sigprocmask(SIG_BLOCK, &chld_set, NULL);
  803. if (child_exited)
  804. reap_children();
  805. max = fill_fds_for_select(&rdset, &wrset);
  806. if (libvchan_buffer_space(ctrl_vchan) <=
  807. (int)sizeof(struct msg_header))
  808. FD_ZERO(&rdset);
  809. wait_for_vchan_or_argfd(ctrl_vchan, max, &rdset, &wrset);
  810. sigprocmask(SIG_UNBLOCK, &chld_set, NULL);
  811. while (libvchan_data_ready(ctrl_vchan))
  812. handle_server_cmd();
  813. if (FD_ISSET(trigger_fd, &rdset))
  814. handle_trigger_io();
  815. handle_terminated_fork_client(&rdset);
  816. }
  817. }