qrexec-agent.c 26 KB

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