2 * FCRON - periodic command scheduler
4 * Copyright 2000-2013 Thibault Godouet <fcron@free.fr>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * The GNU General Public License can also be found in the file
21 * `LICENSE' that comes with the fcron source distribution.
26 /* read a string (password, etc ...) securely from a tty */
29 #include "read_string.h"
33 extern char debug_opt;
35 /* Derived from Andrew Morgan <morgan@linux.kernel.org> work in Linux PAM misc lib. */
37 /* may be used in fcrondyn without pam : */
39 #define PAM_MAX_MSG_SIZE LINE_LEN
43 read_string(int echo, const char *prompt)
44 /* read a line of input string, giving prompt when appropriate */
46 struct termios term_before, term_tmp;
47 char line[PAM_MAX_MSG_SIZE];
48 int nc, have_term = 0;
50 debug("called with echo='%s', prompt='%s'.", echo ? "ON" : "OFF", prompt);
52 if (isatty(STDIN_FILENO)) { /* terminal state */
54 /* is a terminal so record settings and flush it */
55 if (tcgetattr(STDIN_FILENO, &term_before) != 0) {
56 debug("error: failed to get terminal settings");
59 memcpy(&term_tmp, &term_before, sizeof(term_tmp));
61 term_tmp.c_lflag &= ~(ECHO);
66 debug("warning: cannot turn echo off");
68 /* reading the line */
71 fprintf(stderr, "%s", prompt);
72 /* this may, or may not set echo off -- drop pending input */
74 (void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_tmp);
76 nc = read(STDIN_FILENO, line, sizeof(line) - 1);
78 (void)tcsetattr(STDIN_FILENO, TCSADRAIN, &term_before);
79 if (!echo) /* do we need a newline? */
80 fprintf(stderr, "\n");
82 if (nc > 0) { /* we got some user input */
85 if (nc > 0 && line[nc - 1] == '\n') { /* <NUL> terminate */
91 input = strdup2(line);
94 return input; /* return malloc()ed string */
96 else if (nc == 0) { /* Ctrl-D */
97 debug("user did not want to type anything");
98 fprintf(stderr, "\n");
104 (void)tcsetattr(STDIN_FILENO, TCSADRAIN, &term_before);
106 memset(line, 0, PAM_MAX_MSG_SIZE); /* clean up */