+ assert_not_reached("Unknown error type");
+ }
+}
+
+static int chown_terminal(int fd, uid_t uid) {
+ struct stat st;
+
+ assert(fd >= 0);
+
+ /* This might fail. What matters are the results. */
+ fchown(fd, uid, -1);
+ fchmod(fd, TTY_MODE);
+
+ if (fstat(fd, &st) < 0)
+ return -errno;
+
+ if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
+ return -EPERM;
+
+ return 0;
+}
+
+static int setup_confirm_stdio(const ExecContext *context,
+ int *_saved_stdin,
+ int *_saved_stdout) {
+ int fd = -1, saved_stdin, saved_stdout = -1, r;
+
+ assert(context);
+ assert(_saved_stdin);
+ assert(_saved_stdout);
+
+ /* This returns positive EXIT_xxx return values instead of
+ * negative errno style values! */
+
+ if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
+ return EXIT_STDIN;
+
+ if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
+ r = EXIT_STDOUT;
+ goto fail;
+ }
+
+ if ((fd = acquire_terminal(
+ tty_path(context),
+ context->std_input == EXEC_INPUT_TTY_FAIL,
+ context->std_input == EXEC_INPUT_TTY_FORCE)) < 0) {
+ r = EXIT_STDIN;
+ goto fail;
+ }
+
+ if (chown_terminal(fd, getuid()) < 0) {
+ r = EXIT_STDIN;
+ goto fail;
+ }
+
+ if (dup2(fd, STDIN_FILENO) < 0) {
+ r = EXIT_STDIN;
+ goto fail;
+ }
+
+ if (dup2(fd, STDOUT_FILENO) < 0) {
+ r = EXIT_STDOUT;
+ goto fail;
+ }
+
+ if (fd >= 2)
+ close_nointr_nofail(fd);
+
+ *_saved_stdin = saved_stdin;
+ *_saved_stdout = saved_stdout;
+
+ return 0;
+
+fail:
+ if (saved_stdout >= 0)
+ close_nointr_nofail(saved_stdout);
+
+ if (saved_stdin >= 0)
+ close_nointr_nofail(saved_stdin);
+
+ if (fd >= 0)
+ close_nointr_nofail(fd);
+
+ return r;
+}
+
+static int restore_conform_stdio(const ExecContext *context,
+ int *saved_stdin,
+ int *saved_stdout,
+ bool *keep_stdin,
+ bool *keep_stdout) {
+
+ assert(context);
+ assert(saved_stdin);
+ assert(*saved_stdin >= 0);
+ assert(saved_stdout);
+ assert(*saved_stdout >= 0);
+
+ /* This returns positive EXIT_xxx return values instead of
+ * negative errno style values! */
+
+ if (is_terminal_input(context->std_input)) {
+
+ /* The service wants terminal input. */
+
+ *keep_stdin = true;
+ *keep_stdout =
+ context->std_output == EXEC_OUTPUT_INHERIT ||
+ context->std_output == EXEC_OUTPUT_TTY;
+
+ } else {
+ /* If the service doesn't want a controlling terminal,
+ * then we need to get rid entirely of what we have
+ * already. */
+
+ if (release_terminal() < 0)
+ return EXIT_STDIN;
+
+ if (dup2(*saved_stdin, STDIN_FILENO) < 0)
+ return EXIT_STDIN;
+
+ if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
+ return EXIT_STDOUT;
+
+ *keep_stdout = *keep_stdin = false;