qrexec-agent.c 25 KB

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