2 * Alternate Getty (agetty) 'agetty' is a versatile, portable, easy to use
3 * replacement for getty on SunOS 4.1.x or the SAC ttymon/ttyadm/sacadm/pmadm
4 * suite on Solaris and other SVR4 systems. 'agetty' was written by Wietse
5 * Venema, enhanced by John DiMarco, and further enhanced by Dennis Cronin.
7 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
8 * Adopt the mingetty features for a better support
9 * of virtual consoles by Werner Fink <werner@suse.de>
11 * This program is freely distributable.
21 #include <sys/ioctl.h>
22 #include <sys/types.h>
31 #include <sys/socket.h>
35 #include <arpa/inet.h>
39 #include <sys/utsname.h>
44 #include "pathnames.h"
49 #include "color-names.h"
52 #include "fileutils.h"
54 #include "logindefs.h"
56 #ifdef USE_PLYMOUTH_SUPPORT
57 # include "plymouth-ctrl.h"
60 #ifdef HAVE_SYS_PARAM_H
61 # include <sys/param.h>
68 #if defined(__FreeBSD_kernel__)
73 # ifdef HAVE_LIBUTIL_H
79 # include <systemd/sd-daemon.h>
80 # include <systemd/sd-login.h>
86 #elif defined(__GNU__)
90 #ifdef __FreeBSD_kernel__
94 /* If USE_SYSLOG is undefined all diagnostics go to /dev/console. */
100 * Some heuristics to find out what environment we are in: if it is not
101 * System V, assume it is SunOS 4. The LOGIN_PROCESS is defined in System V
102 * utmp.h, which will select System V style getty.
109 * Things you may want to modify.
111 * If ISSUE_SUPPORT is not defined, agetty will never display the contents of
112 * the /etc/issue file. You will not want to spit out large "issue" files at
113 * the wrong baud rate. Relevant for System V only.
115 * You may disagree with the default line-editing etc. characters defined
116 * below. Note, however, that DEL cannot be used for interrupt generation
117 * and for line editing at the same time.
120 /* Displayed before the login prompt. */
122 # define ISSUE_SUPPORT
123 # if defined(HAVE_SCANDIRAT) && defined(HAVE_OPENAT)
125 # define ISSUEDIR_SUPPORT
126 # define ISSUEDIR_EXT ".issue"
127 # define ISSUEDIR_EXTSIZ (sizeof(ISSUEDIR_EXT) - 1)
132 #define LOGIN_PROMPT "login: "
134 /* Numbers of args for login(1) */
135 #define LOGIN_ARGV_MAX 16
141 # include <sys/inotify.h>
142 # include <linux/netlink.h>
143 # include <linux/rtnetlink.h>
144 # define AGETTY_RELOAD_FILENAME "/run/agetty.reload" /* trigger file */
145 # define AGETTY_RELOAD_FDNONE -2 /* uninitialized fd */
146 static int inotify_fd
= AGETTY_RELOAD_FDNONE
;
147 static int netlink_fd
= AGETTY_RELOAD_FDNONE
;
148 static uint32_t netlink_groups
;
159 unsigned int do_tcsetattr
: 1,
164 * When multiple baud rates are specified on the command line, the first one
165 * we will try is the first one specified.
167 #define FIRST_SPEED 0
169 /* Storage for command-line options. */
170 #define MAX_SPEED 10 /* max. nr. of baud rates */
173 int flags
; /* toggle switches, see below */
174 unsigned int timeout
; /* time-out period */
175 char *autolog
; /* login the user automatically */
176 char *chdir
; /* Chdir before the login */
177 char *chroot
; /* Chroot before the login */
178 char *login
; /* login program */
179 char *logopt
; /* options for login program */
180 const char *tty
; /* name of tty */
181 const char *vcline
; /* line of virtual console */
182 char *term
; /* terminal type */
183 char *initstring
; /* modem init string */
184 char *issue
; /* alternative issue file or directory */
185 char *erasechars
; /* string with erase chars */
186 char *killchars
; /* string with kill chars */
187 char *osrelease
; /* /etc/os-release data */
188 unsigned int delay
; /* Sleep seconds before prompt */
189 int nice
; /* Run login with this priority */
190 int numspeed
; /* number of baud rates to try */
191 int clocal
; /* CLOCAL_MODE_* */
192 int kbmode
; /* Keyboard mode if virtual console */
193 int tty_is_stdin
; /* is the tty the standard input stream */
194 speed_t speeds
[MAX_SPEED
]; /* baud rates to be tried */
198 CLOCAL_MODE_AUTO
= 0,
203 #define F_PARSE (1<<0) /* process modem status messages */
204 #define F_ISSUE (1<<1) /* display /etc/issue or /etc/issue.d */
205 #define F_RTSCTS (1<<2) /* enable RTS/CTS flow control */
207 #define F_INITSTRING (1<<4) /* initstring is set */
208 #define F_WAITCRLF (1<<5) /* wait for CR or LF */
210 #define F_NOPROMPT (1<<7) /* do not ask for login name! */
211 #define F_LCUC (1<<8) /* support for *LCUC stty modes */
212 #define F_KEEPSPEED (1<<9) /* follow baud rate from kernel */
213 #define F_KEEPCFLAGS (1<<10) /* reuse c_cflags setup from kernel */
214 #define F_EIGHTBITS (1<<11) /* Assume 8bit-clean tty */
215 #define F_VCONSOLE (1<<12) /* This is a virtual console */
216 #define F_HANGUP (1<<13) /* Do call vhangup(2) */
217 #define F_UTF8 (1<<14) /* We can do UTF8 */
218 #define F_LOGINPAUSE (1<<15) /* Wait for any key before dropping login prompt */
219 #define F_NOCLEAR (1<<16) /* Do not clear the screen before prompting */
220 #define F_NONL (1<<17) /* No newline before issue */
221 #define F_NOHOSTNAME (1<<18) /* Do not show the hostname */
222 #define F_LONGHNAME (1<<19) /* Show Full qualified hostname */
223 #define F_NOHINTS (1<<20) /* Don't print hints */
224 #define F_REMOTE (1<<21) /* Add '-h fakehost' to login(1) command line */
226 #define serial_tty_option(opt, flag) \
227 (((opt)->flags & (F_VCONSOLE|(flag))) == (flag))
234 static const struct Speedtab speedtab
[] = {
306 static void init_special_char(char* arg
, struct options
*op
);
307 static void parse_args(int argc
, char **argv
, struct options
*op
);
308 static void parse_speeds(struct options
*op
, char *arg
);
309 static void update_utmp(struct options
*op
);
310 static void open_tty(const char *tty
, struct termios
*tp
, struct options
*op
);
311 static void termio_init(struct options
*op
, struct termios
*tp
);
312 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
);
313 static void auto_baud(struct termios
*tp
);
314 static void list_speeds(void);
315 static void output_special_char (struct issue
*ie
, unsigned char c
, struct options
*op
,
316 struct termios
*tp
, FILE *fp
);
317 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
318 static void next_speed(struct options
*op
, struct termios
*tp
);
319 static char *get_logname(struct issue
*ie
, struct options
*op
,
320 struct termios
*tp
, struct chardata
*cp
);
321 static void termio_final(struct options
*op
,
322 struct termios
*tp
, struct chardata
*cp
);
323 static int caps_lock(char *s
);
324 static speed_t
bcode(char *s
);
325 static void usage(void) __attribute__((__noreturn__
));
326 static void exit_slowly(int code
) __attribute__((__noreturn__
));
327 static void log_err(const char *, ...) __attribute__((__noreturn__
))
328 __attribute__((__format__(printf
, 1, 2)));
329 static void log_warn (const char *, ...)
330 __attribute__((__format__(printf
, 1, 2)));
331 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
);
332 static void check_username (const char* nm
);
333 static void login_options_to_argv(char *argv
[], int *argc
, char *str
, char *username
);
334 static void reload_agettys(void);
335 static void print_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
336 static void eval_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
337 static void show_issue(struct options
*op
);
338 static void load_credentials(struct options
*op
);
341 /* Fake hostname for ut_host specified on command line. */
342 static char *fakehost
;
345 # include "closestream.h"
346 # ifndef DEBUG_OUTPUT
347 # define DEBUG_OUTPUT "/dev/tty10"
349 # define debug(s) do { fprintf(dbf,s); fflush(dbf); } while (0)
352 # define debug(s) do { ; } while (0)
355 int main(int argc
, char **argv
)
357 char *username
= NULL
; /* login name, given to /bin/login */
358 struct chardata chardata
; /* will be set by get_logname() */
359 struct termios termios
; /* terminal mode bits */
360 struct options options
= {
361 .flags
= F_ISSUE
, /* show /etc/issue (SYSV_STYLE) */
362 .login
= _PATH_LOGIN
, /* default login program */
363 .tty
= "tty1" /* default tty line */
365 struct issue issue
= {
368 char *login_argv
[LOGIN_ARGV_MAX
+ 1];
370 struct sigaction sa
, sa_hup
, sa_quit
, sa_int
;
373 setlocale(LC_ALL
, "");
374 bindtextdomain(PACKAGE
, LOCALEDIR
);
377 /* In case vhangup(2) has to called */
378 sa
.sa_handler
= SIG_IGN
;
379 sa
.sa_flags
= SA_RESTART
;
380 sigemptyset (&sa
.sa_mask
);
381 sigaction(SIGHUP
, &sa
, &sa_hup
);
382 sigaction(SIGQUIT
, &sa
, &sa_quit
);
383 sigaction(SIGINT
, &sa
, &sa_int
);
389 dbf
= fopen(DEBUG_OUTPUT
, "w");
390 for (i
= 1; i
< argc
; i
++) {
397 #endif /* DEBUGGING */
399 /* Load systemd credentials. */
400 load_credentials(&options
);
402 /* Parse command-line arguments. */
403 parse_args(argc
, argv
, &options
);
405 login_argv
[login_argc
++] = options
.login
; /* set login program name */
407 /* Update the utmp file. */
409 update_utmp(&options
);
412 sleep(options
.delay
);
414 debug("calling open_tty\n");
416 /* Open the tty as standard { input, output, error }. */
417 open_tty(options
.tty
, &termios
, &options
);
419 /* Unmask SIGHUP if inherited */
421 sigaddset(&set
, SIGHUP
);
422 sigprocmask(SIG_UNBLOCK
, &set
, NULL
);
423 sigaction(SIGHUP
, &sa_hup
, NULL
);
425 tcsetpgrp(STDIN_FILENO
, getpid());
427 /* Default is to follow the current line speed and then default to 9600 */
428 if ((options
.flags
& F_VCONSOLE
) == 0 && options
.numspeed
== 0) {
429 options
.speeds
[options
.numspeed
++] = bcode("9600");
430 options
.flags
|= F_KEEPSPEED
;
433 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
434 debug("calling termio_init\n");
435 termio_init(&options
, &termios
);
437 /* Write the modem init string and DO NOT flush the buffers. */
438 if (options
.flags
& F_INITSTRING
&&
439 options
.initstring
&& *options
.initstring
!= '\0') {
440 debug("writing init string\n");
441 write_all(STDOUT_FILENO
, options
.initstring
,
442 strlen(options
.initstring
));
445 if (options
.flags
& F_VCONSOLE
|| options
.clocal
!= CLOCAL_MODE_ALWAYS
)
446 /* Go to blocking mode unless -L is specified, this change
447 * affects stdout, stdin and stderr as all the file descriptors
448 * are created by dup(). */
449 fcntl(STDOUT_FILENO
, F_SETFL
,
450 fcntl(STDOUT_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
452 /* Optionally detect the baud rate from the modem status message. */
453 debug("before autobaud\n");
454 if (serial_tty_option(&options
, F_PARSE
))
457 /* Set the optional timer. */
459 alarm(options
.timeout
);
461 /* Optionally wait for CR or LF before writing /etc/issue */
462 if (serial_tty_option(&options
, F_WAITCRLF
)) {
465 debug("waiting for cr-lf\n");
466 while (read(STDIN_FILENO
, &ch
, 1) == 1) {
467 /* Strip "parity bit". */
470 fprintf(dbf
, "read %c\n", ch
);
472 if (ch
== '\n' || ch
== '\r')
477 INIT_CHARDATA(&chardata
);
479 if (options
.autolog
) {
480 debug("doing auto login\n");
481 username
= options
.autolog
;
484 if (options
.flags
& F_NOPROMPT
) { /* --skip-login */
485 eval_issue_file(&issue
, &options
, &termios
);
486 print_issue_file(&issue
, &options
, &termios
);
488 } else { /* regular (auto)login */
489 if ((options
.flags
& F_NOHOSTNAME
) == 0 &&
490 getlogindefs_bool("LOGIN_PLAIN_PROMPT", 0) == 1)
491 /* /etc/login.defs enbles --nohostname too */
492 options
.flags
|= F_NOHOSTNAME
;
494 if (options
.autolog
) {
495 /* Autologin prompt */
496 eval_issue_file(&issue
, &options
, &termios
);
497 do_prompt(&issue
, &options
, &termios
);
498 printf(_("%s%s (automatic login)\n"), LOGIN_PROMPT
,
501 /* Read the login name. */
502 debug("reading login name\n");
504 get_logname(&issue
, &options
, &termios
, &chardata
)) == NULL
)
505 if ((options
.flags
& F_VCONSOLE
) == 0 && options
.numspeed
)
506 next_speed(&options
, &termios
);
514 /* Finalize the termios settings. */
515 if ((options
.flags
& F_VCONSOLE
) == 0)
516 termio_final(&options
, &termios
, &chardata
);
518 reset_vc(&options
, &termios
, 1);
520 /* Now the newline character should be properly written. */
521 write_all(STDOUT_FILENO
, "\r\n", 2);
523 sigaction(SIGQUIT
, &sa_quit
, NULL
);
524 sigaction(SIGINT
, &sa_int
, NULL
);
527 check_username(username
);
529 if (options
.logopt
) {
531 * The --login-options completely overwrites the default
532 * way how agetty composes login(1) command line.
534 login_options_to_argv(login_argv
, &login_argc
,
535 options
.logopt
, username
);
537 if (options
.flags
& F_REMOTE
) {
539 login_argv
[login_argc
++] = "-h";
540 login_argv
[login_argc
++] = fakehost
;
541 } else if (options
.flags
& F_NOHOSTNAME
)
542 login_argv
[login_argc
++] = "-H";
546 login_argv
[login_argc
++] = "-f";
547 login_argv
[login_argc
++] = "--";
548 login_argv
[login_argc
++] = username
;
552 login_argv
[login_argc
] = NULL
; /* last login argv */
554 if (options
.chroot
&& chroot(options
.chroot
) < 0)
555 log_err(_("%s: can't change root directory %s: %m"),
556 options
.tty
, options
.chroot
);
557 if (options
.chdir
&& chdir(options
.chdir
) < 0)
558 log_err(_("%s: can't change working directory %s: %m"),
559 options
.tty
, options
.chdir
);
560 if (options
.nice
&& nice(options
.nice
) < 0)
561 log_warn(_("%s: can't change process priority: %m"),
565 if (close_stream(dbf
) != 0)
566 log_err("write failed: %s", DEBUG_OUTPUT
);
569 /* Let the login program take care of password validation. */
570 execv(options
.login
, login_argv
);
572 free(options
.osrelease
);
573 free(options
.autolog
);
575 log_err(_("%s: can't exec %s: %m"), options
.tty
, login_argv
[0]);
579 * Returns : @str if \u not found
580 * : @username if @str equal to "\u"
581 * : newly allocated string if \u mixed with something other
583 static char *replace_u(char *str
, char *username
)
585 char *entry
= NULL
, *p
= str
;
586 size_t usz
= username
? strlen(username
) : 0;
590 char *tp
, *old
= entry
;
592 if (memcmp(p
, "\\u", 2) != 0) {
594 continue; /* no \u */
598 if (p
== str
&& sz
== 2) {
599 /* 'str' contains only '\u' */
604 tp
= entry
= malloc(sz
+ usz
);
606 log_err(_("failed to allocate memory: %m"));
609 /* copy chars before \u */
610 tp
= mempcpy(tp
, str
, p
- str
);
613 tp
= mempcpy(tp
, username
, usz
);
616 /* copy chars after \u + \0 */
617 memcpy(tp
, p
+ 2, sz
- (p
- str
) - 1);
626 return entry
? entry
: str
;
629 static void login_options_to_argv(char *argv
[], int *argc
,
630 char *str
, char *username
)
635 while (str
&& isspace(*str
))
639 while (p
&& *p
&& i
< LOGIN_ARGV_MAX
) {
642 while (isspace(*++p
))
645 argv
[i
++] = replace_u(str
, username
);
651 if (str
&& *str
&& i
< LOGIN_ARGV_MAX
)
652 argv
[i
++] = replace_u(str
, username
);
656 static void output_version(void)
658 static const char *features
[] = {
671 #ifdef ISSUEDIR_SUPPORT
677 #ifdef USE_PLYMOUTH_SUPPORT
693 printf( _("%s from %s"), program_invocation_short_name
, PACKAGE_STRING
);
695 for (i
= 0; features
[i
]; i
++) {
698 printf("%s", features
[i
]);
700 fputs(")\n", stdout
);
703 #define is_speed(str) (strlen((str)) == strspn((str), "0123456789,"))
705 /* Parse command-line arguments. */
706 static void parse_args(int argc
, char **argv
, struct options
*op
)
709 int opt_show_issue
= 0;
712 VERSION_OPTION
= CHAR_MAX
+ 1,
723 const struct option longopts
[] = {
724 { "8bits", no_argument
, NULL
, '8' },
725 { "autologin", required_argument
, NULL
, 'a' },
726 { "noreset", no_argument
, NULL
, 'c' },
727 { "chdir", required_argument
, NULL
, 'C' },
728 { "delay", required_argument
, NULL
, 'd' },
729 { "remote", no_argument
, NULL
, 'E' },
730 { "issue-file", required_argument
, NULL
, 'f' },
731 { "show-issue", no_argument
, NULL
, ISSUE_SHOW_OPTION
},
732 { "flow-control", no_argument
, NULL
, 'h' },
733 { "host", required_argument
, NULL
, 'H' },
734 { "noissue", no_argument
, NULL
, 'i' },
735 { "init-string", required_argument
, NULL
, 'I' },
736 { "noclear", no_argument
, NULL
, 'J' },
737 { "login-program", required_argument
, NULL
, 'l' },
738 { "local-line", optional_argument
, NULL
, 'L' },
739 { "extract-baud", no_argument
, NULL
, 'm' },
740 { "list-speeds", no_argument
, NULL
, LIST_SPEEDS_OPTION
},
741 { "skip-login", no_argument
, NULL
, 'n' },
742 { "nonewline", no_argument
, NULL
, 'N' },
743 { "login-options", required_argument
, NULL
, 'o' },
744 { "login-pause", no_argument
, NULL
, 'p' },
745 { "nice", required_argument
, NULL
, 'P' },
746 { "chroot", required_argument
, NULL
, 'r' },
747 { "hangup", no_argument
, NULL
, 'R' },
748 { "keep-baud", no_argument
, NULL
, 's' },
749 { "timeout", required_argument
, NULL
, 't' },
750 { "detect-case", no_argument
, NULL
, 'U' },
751 { "wait-cr", no_argument
, NULL
, 'w' },
752 { "nohints", no_argument
, NULL
, NOHINTS_OPTION
},
753 { "nohostname", no_argument
, NULL
, NOHOSTNAME_OPTION
},
754 { "long-hostname", no_argument
, NULL
, LONGHOSTNAME_OPTION
},
755 { "reload", no_argument
, NULL
, RELOAD_OPTION
},
756 { "version", no_argument
, NULL
, VERSION_OPTION
},
757 { "help", no_argument
, NULL
, HELP_OPTION
},
758 { "erase-chars", required_argument
, NULL
, ERASE_CHARS_OPTION
},
759 { "kill-chars", required_argument
, NULL
, KILL_CHARS_OPTION
},
763 while ((c
= getopt_long(argc
, argv
,
764 "8a:cC:d:Ef:hH:iI:Jl:L::mnNo:pP:r:Rst:Uw", longopts
,
768 op
->flags
|= F_EIGHTBITS
;
772 op
->autolog
= strdup(optarg
);
774 log_err(_("failed to allocate memory: %m"));
777 op
->flags
|= F_KEEPCFLAGS
;
783 op
->delay
= strtou32_or_err(optarg
, _("invalid delay argument"));
786 op
->flags
|= F_REMOTE
;
792 op
->flags
|= F_RTSCTS
;
798 op
->flags
&= ~F_ISSUE
;
801 init_special_char(optarg
, op
);
802 op
->flags
|= F_INITSTRING
;
805 op
->flags
|= F_NOCLEAR
;
811 /* -L and -L=always have the same meaning */
812 op
->clocal
= CLOCAL_MODE_ALWAYS
;
814 if (strcmp(optarg
, "=always") == 0)
815 op
->clocal
= CLOCAL_MODE_ALWAYS
;
816 else if (strcmp(optarg
, "=never") == 0)
817 op
->clocal
= CLOCAL_MODE_NEVER
;
818 else if (strcmp(optarg
, "=auto") == 0)
819 op
->clocal
= CLOCAL_MODE_AUTO
;
821 log_err(_("invalid argument of --local-line"));
825 op
->flags
|= F_PARSE
;
828 op
->flags
|= F_NOPROMPT
;
837 op
->flags
|= F_LOGINPAUSE
;
840 op
->nice
= strtos32_or_err(optarg
, _("invalid nice argument"));
846 op
->flags
|= F_HANGUP
;
849 op
->flags
|= F_KEEPSPEED
;
852 op
->timeout
= strtou32_or_err(optarg
, _("invalid timeout argument"));
858 op
->flags
|= F_WAITCRLF
;
861 op
->flags
|= F_NOHINTS
;
863 case NOHOSTNAME_OPTION
:
864 op
->flags
|= F_NOHOSTNAME
;
866 case LONGHOSTNAME_OPTION
:
867 op
->flags
|= F_LONGHNAME
;
869 case ERASE_CHARS_OPTION
:
870 op
->erasechars
= optarg
;
872 case KILL_CHARS_OPTION
:
873 op
->killchars
= optarg
;
878 case LIST_SPEEDS_OPTION
:
881 case ISSUE_SHOW_OPTION
:
890 errtryhelp(EXIT_FAILURE
);
894 if (opt_show_issue
) {
899 debug("after getopt loop\n");
901 if (argc
< optind
+ 1) {
902 log_warn(_("not enough arguments"));
903 errx(EXIT_FAILURE
, _("not enough arguments"));
906 /* Accept "tty", "baudrate tty", and "tty baudrate". */
907 if (is_speed(argv
[optind
])) {
908 /* Assume BSD style speed. */
909 parse_speeds(op
, argv
[optind
++]);
910 if (argc
< optind
+ 1) {
911 log_warn(_("not enough arguments"));
912 errx(EXIT_FAILURE
, _("not enough arguments"));
914 op
->tty
= argv
[optind
++];
916 op
->tty
= argv
[optind
++];
918 char *v
= argv
[optind
];
926 /* resolve the tty path in case it was provided as stdin */
927 if (strcmp(op
->tty
, "-") == 0) {
928 op
->tty_is_stdin
= 1;
929 int fd
= get_terminal_name(NULL
, &op
->tty
, NULL
);
931 log_warn(_("could not get terminal name: %d"), fd
);
935 /* On virtual console remember the line which is used for */
936 if (strncmp(op
->tty
, "tty", 3) == 0 &&
937 strspn(op
->tty
+ 3, "0123456789") == strlen(op
->tty
+3))
938 op
->vcline
= op
->tty
+3;
940 if (argc
> optind
&& argv
[optind
])
941 op
->term
= argv
[optind
];
943 debug("exiting parseargs\n");
946 /* Parse alternate baud rates. */
947 static void parse_speeds(struct options
*op
, char *arg
)
950 char *str
= strdup(arg
);
953 log_err(_("failed to allocate memory: %m"));
955 debug("entered parse_speeds:\n");
956 for (cp
= strtok(str
, ","); cp
!= NULL
; cp
= strtok((char *)0, ",")) {
957 if ((op
->speeds
[op
->numspeed
++] = bcode(cp
)) <= 0)
958 log_err(_("bad speed: %s"), cp
);
959 if (op
->numspeed
>= MAX_SPEED
)
960 log_err(_("too many alternate speeds"));
962 debug("exiting parsespeeds\n");
968 /* Update our utmp entry. */
969 static void update_utmp(struct options
*op
)
973 pid_t pid
= getpid();
974 pid_t sid
= getsid(0);
975 const char *vcline
= op
->vcline
;
976 const char *line
= op
->tty
;
980 * The utmp file holds miscellaneous information about things started by
981 * /sbin/init and other system-related events. Our purpose is to update
982 * the utmp entry for the current process, in particular the process type
983 * and the tty line we are listening to. Return successfully only if the
984 * utmp file can be opened for update, and if we are able to find our
985 * entry in the utmp file.
987 utmpxname(_PATH_UTMP
);
991 * Find my pid in utmp.
993 * FIXME: Earlier (when was that?) code here tested only utp->ut_type !=
994 * INIT_PROCESS, so maybe the >= here should be >.
996 * FIXME: The present code is taken from login.c, so if this is changed,
997 * maybe login has to be changed as well (is this true?).
999 while ((utp
= getutxent()))
1000 if (utp
->ut_pid
== pid
1001 && utp
->ut_type
>= INIT_PROCESS
1002 && utp
->ut_type
<= DEAD_PROCESS
)
1006 memcpy(&ut
, utp
, sizeof(ut
));
1008 /* Some inits do not initialize utmp. */
1009 memset(&ut
, 0, sizeof(ut
));
1010 if (vcline
&& *vcline
)
1011 /* Standard virtual console devices */
1012 str2memcpy(ut
.ut_id
, vcline
, sizeof(ut
.ut_id
));
1014 size_t len
= strlen(line
);
1016 if (len
>= sizeof(ut
.ut_id
))
1017 ptr
= line
+ len
- sizeof(ut
.ut_id
);
1020 str2memcpy(ut
.ut_id
, ptr
, sizeof(ut
.ut_id
));
1024 str2memcpy(ut
.ut_user
, "LOGIN", sizeof(ut
.ut_user
));
1025 str2memcpy(ut
.ut_line
, line
, sizeof(ut
.ut_line
));
1027 str2memcpy(ut
.ut_host
, fakehost
, sizeof(ut
.ut_host
));
1029 ut
.ut_tv
.tv_sec
= t
;
1030 ut
.ut_type
= LOGIN_PROCESS
;
1032 ut
.ut_session
= sid
;
1037 updwtmpx(_PATH_WTMP
, &ut
);
1040 #endif /* SYSV_STYLE */
1042 /* Set up tty as stdin, stdout & stderr. */
1043 static void open_tty(const char *tty
, struct termios
*tp
, struct options
*op
)
1045 const pid_t pid
= getpid();
1051 /* Set up new standard input, unless we are given an already opened port. */
1053 if (!op
->tty_is_stdin
) {
1054 char buf
[PATH_MAX
+1];
1055 struct group
*gr
= NULL
;
1061 /* Use tty group if available */
1062 if ((gr
= getgrnam("tty")))
1065 len
= snprintf(buf
, sizeof(buf
), "/dev/%s", tty
);
1066 if (len
< 0 || (size_t)len
>= sizeof(buf
))
1067 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1069 /* Open the tty as standard input. */
1070 if ((fd
= open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0)) < 0)
1071 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1074 * There is always a race between this reset and the call to
1075 * vhangup() that s.o. can use to get access to your tty.
1076 * Linux login(1) will change tty permissions. Use root owner and group
1077 * with permission -rw------- for the period between getty and login.
1079 if (fchown(fd
, 0, gid
) || fchmod(fd
, (gid
? 0620 : 0600))) {
1081 log_warn("%s: %m", buf
);
1083 log_err("%s: %m", buf
);
1086 /* Sanity checks... */
1087 if (fstat(fd
, &st
) < 0)
1088 log_err("%s: %m", buf
);
1089 if ((st
.st_mode
& S_IFMT
) != S_IFCHR
)
1090 log_err(_("/dev/%s: not a character device"), tty
);
1092 log_err(_("/dev/%s: not a tty"), tty
);
1094 if (((tid
= tcgetsid(fd
)) < 0) || (pid
!= tid
)) {
1095 if (ioctl(fd
, TIOCSCTTY
, 1) == -1)
1096 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1099 close(STDIN_FILENO
);
1102 if (op
->flags
& F_HANGUP
) {
1104 if (ioctl(fd
, TIOCNOTTY
))
1105 debug("TIOCNOTTY ioctl failed\n");
1108 * Let's close all file descriptors before vhangup
1109 * https://lkml.org/lkml/2012/6/5/145
1112 close(STDOUT_FILENO
);
1113 close(STDERR_FILENO
);
1118 log_err(_("/dev/%s: vhangup() failed: %m"), tty
);
1123 if (open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0) != 0)
1124 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1126 if (((tid
= tcgetsid(STDIN_FILENO
)) < 0) || (pid
!= tid
)) {
1127 if (ioctl(STDIN_FILENO
, TIOCSCTTY
, 1) == -1)
1128 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1134 * Standard input should already be connected to an open port. Make
1135 * sure it is open for read/write.
1138 if ((fcntl(STDIN_FILENO
, F_GETFL
, 0) & O_RDWR
) != O_RDWR
)
1139 log_err(_("%s: not open for read/write"), tty
);
1143 if (tcsetpgrp(STDIN_FILENO
, pid
))
1144 log_warn(_("/dev/%s: cannot set process group: %m"), tty
);
1146 /* Get rid of the present outputs. */
1148 close(STDOUT_FILENO
);
1149 close(STDERR_FILENO
);
1153 /* Set up standard output and standard error file descriptors. */
1156 /* set up stdout and stderr */
1157 if (dup(STDIN_FILENO
) != 1 || dup(STDIN_FILENO
) != 2)
1158 log_err(_("%s: dup problem: %m"), tty
);
1160 /* make stdio unbuffered for slow modem lines */
1161 setvbuf(stdout
, NULL
, _IONBF
, 0);
1164 * The following ioctl will fail if stdin is not a tty, but also when
1165 * there is noise on the modem control lines. In the latter case, the
1166 * common course of action is (1) fix your cables (2) give the modem
1167 * more time to properly reset after hanging up.
1169 * SunOS users can achieve (2) by patching the SunOS kernel variable
1170 * "zsadtrlow" to a larger value; 5 seconds seems to be a good value.
1171 * http://www.sunmanagers.org/archives/1993/0574.html
1173 memset(tp
, 0, sizeof(struct termios
));
1174 if (tcgetattr(STDIN_FILENO
, tp
) < 0)
1175 log_err(_("%s: failed to get terminal attributes: %m"), tty
);
1177 #if defined(__FreeBSD_kernel__)
1182 * Detect if this is a virtual console or serial/modem line.
1183 * In case of a virtual console the ioctl KDGKBMODE succeeds
1184 * whereas on other lines it will fails.
1187 if (ioctl(STDIN_FILENO
, KDGKBMODE
, &op
->kbmode
) == 0)
1189 if (ioctl(STDIN_FILENO
, TIOCMGET
, &serial
) < 0 && (errno
== EINVAL
))
1192 op
->flags
|= F_VCONSOLE
;
1200 op
->term
= get_terminal_default_type(op
->tty
, !(op
->flags
& F_VCONSOLE
));
1202 log_err(_("failed to allocate memory: %m"));
1204 if (setenv("TERM", op
->term
, 1) != 0)
1205 log_err(_("failed to set the %s environment variable"), "TERM");
1208 /* Initialize termios settings. */
1209 static void termio_clear(int fd
)
1212 * Do not write a full reset (ESC c) because this destroys
1213 * the unicode mode again if the terminal was in unicode
1214 * mode. Also it clears the CONSOLE_MAGIC features which
1215 * are required for some languages/console-fonts.
1216 * Just put the cursor to the home position (ESC [ H),
1217 * erase everything below the cursor (ESC [ J), and set the
1218 * scrolling region to the full window (ESC [ r)
1220 write_all(fd
, "\033[r\033[H\033[J", 9);
1223 /* Initialize termios settings. */
1224 static void termio_init(struct options
*op
, struct termios
*tp
)
1226 speed_t ispeed
, ospeed
;
1228 #ifdef USE_PLYMOUTH_SUPPORT
1229 struct termios lock
;
1230 int i
= (plymouth_command(MAGIC_PING
) == 0) ? PLYMOUTH_TERMIOS_FLAGS_DELAY
: 0;
1232 plymouth_command(MAGIC_QUIT
);
1235 * Even with TTYReset=no it seems with systemd or plymouth
1236 * the termios flags become changed from under the first
1237 * agetty on a serial system console as the flags are locked.
1239 memset(&lock
, 0, sizeof(struct termios
));
1240 if (ioctl(STDIN_FILENO
, TIOCGLCKTRMIOS
, &lock
) < 0)
1242 if (!lock
.c_iflag
&& !lock
.c_oflag
&& !lock
.c_cflag
&& !lock
.c_lflag
)
1244 debug("termios locked\n");
1247 memset(&lock
, 0, sizeof(struct termios
));
1248 ioctl(STDIN_FILENO
, TIOCSLCKTRMIOS
, &lock
);
1251 if (op
->flags
& F_VCONSOLE
) {
1252 #if defined(IUTF8) && defined(KDGKBMODE)
1253 switch(op
->kbmode
) {
1255 setlocale(LC_CTYPE
, "C.UTF-8");
1256 op
->flags
|= F_UTF8
;
1262 setlocale(LC_CTYPE
, "POSIX");
1263 op
->flags
&= ~F_UTF8
;
1267 setlocale(LC_CTYPE
, "POSIX");
1268 op
->flags
&= ~F_UTF8
;
1270 reset_vc(op
, tp
, 0);
1272 if ((tp
->c_cflag
& (CS8
|PARODD
|PARENB
)) == CS8
)
1273 op
->flags
|= F_EIGHTBITS
;
1275 if ((op
->flags
& F_NOCLEAR
) == 0)
1276 termio_clear(STDOUT_FILENO
);
1284 if (op
->flags
& F_KEEPSPEED
|| !op
->numspeed
) {
1285 /* Save the original setting. */
1286 ispeed
= cfgetispeed(tp
);
1287 ospeed
= cfgetospeed(tp
);
1289 /* Save also the original speed to array of the speeds to make
1290 * it possible to return the original after unexpected BREAKs.
1293 op
->speeds
[op
->numspeed
++] = ispeed
? ispeed
:
1297 ispeed
= TTYDEF_SPEED
;
1299 ospeed
= TTYDEF_SPEED
;
1301 ospeed
= ispeed
= op
->speeds
[FIRST_SPEED
];
1305 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
1306 * Special characters are set after we have read the login name; all
1307 * reads will be done in raw mode anyway. Errors will be dealt with
1311 /* The default is set c_iflag in termio_final() according to chardata.
1312 * Unfortunately, the chardata are not set according to the serial line
1313 * if --autolog is enabled. In this case we do not read from the line
1314 * at all. The best what we can do in this case is to keep c_iflag
1315 * unmodified for --autolog.
1319 tp
->c_iflag
= tp
->c_iflag
& IUTF8
;
1320 if (tp
->c_iflag
& IUTF8
)
1321 op
->flags
|= F_UTF8
;
1328 tp
->c_oflag
&= OPOST
| ONLCR
;
1330 if ((op
->flags
& F_KEEPCFLAGS
) == 0)
1331 tp
->c_cflag
= CS8
| HUPCL
| CREAD
| (tp
->c_cflag
& CLOCAL
);
1334 * Note that the speed is stored in the c_cflag termios field, so we have
1335 * set the speed always when the cflag is reset.
1337 cfsetispeed(tp
, ispeed
);
1338 cfsetospeed(tp
, ospeed
);
1340 /* The default is to follow setting from kernel, but it's possible
1341 * to explicitly remove/add CLOCAL flag by -L[=<mode>]*/
1342 switch (op
->clocal
) {
1343 case CLOCAL_MODE_ALWAYS
:
1344 tp
->c_cflag
|= CLOCAL
; /* -L or -L=always */
1346 case CLOCAL_MODE_NEVER
:
1347 tp
->c_cflag
&= ~CLOCAL
; /* -L=never */
1349 case CLOCAL_MODE_AUTO
: /* -L=auto */
1353 #ifdef HAVE_STRUCT_TERMIOS_C_LINE
1357 tp
->c_cc
[VTIME
] = 0;
1359 /* Check for terminal size and if not found set default */
1360 if (ioctl(STDIN_FILENO
, TIOCGWINSZ
, &ws
) == 0) {
1365 if (ioctl(STDIN_FILENO
, TIOCSWINSZ
, &ws
))
1366 debug("TIOCSWINSZ ioctl failed\n");
1369 /* Optionally enable hardware flow control. */
1371 if (op
->flags
& F_RTSCTS
)
1372 tp
->c_cflag
|= CRTSCTS
;
1374 /* Flush input and output queues, important for modems! */
1375 tcflush(STDIN_FILENO
, TCIOFLUSH
);
1377 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
))
1378 log_warn(_("setting terminal attributes failed: %m"));
1380 /* Go to blocking input even in local mode. */
1381 fcntl(STDIN_FILENO
, F_SETFL
,
1382 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1384 debug("term_io 2\n");
1387 /* Reset virtual console on stdin to its defaults */
1388 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
)
1392 fl
|= (op
->flags
& F_KEEPCFLAGS
) == 0 ? 0 : UL_TTY_KEEPCFLAGS
;
1393 fl
|= (op
->flags
& F_UTF8
) == 0 ? 0 : UL_TTY_UTF8
;
1395 reset_virtual_console(tp
, fl
);
1397 #ifdef AGETTY_RELOAD
1399 * Discard all the flags that makes the line go canonical with echoing.
1400 * We need to know when the user starts typing.
1406 if (tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
))
1407 log_warn(_("setting terminal attributes failed: %m"));
1409 /* Go to blocking input even in local mode. */
1410 fcntl(STDIN_FILENO
, F_SETFL
,
1411 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1414 /* Extract baud rate from modem status message. */
1415 static void auto_baud(struct termios
*tp
)
1425 * This works only if the modem produces its status code AFTER raising
1426 * the DCD line, and if the computer is fast enough to set the proper
1427 * baud rate before the message has gone by. We expect a message of the
1430 * <junk><number><junk>
1432 * The number is interpreted as the baud rate of the incoming call. If the
1433 * modem does not tell us the baud rate within one second, we will keep
1434 * using the current baud rate. It is advisable to enable BREAK
1435 * processing (comma-separated list of baud rates) if the processing of
1436 * modem status messages is enabled.
1440 * Use 7-bit characters, don't block if input queue is empty. Errors will
1441 * be dealt with later on.
1443 iflag
= tp
->c_iflag
;
1444 /* Enable 8th-bit stripping. */
1445 tp
->c_iflag
|= ISTRIP
;
1446 vmin
= tp
->c_cc
[VMIN
];
1447 /* Do not block when queue is empty. */
1449 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1452 * Wait for a while, then read everything the modem has said so far and
1453 * try to extract the speed of the dial-in call.
1456 if ((nread
= read(STDIN_FILENO
, buf
, sizeof(buf
) - 1)) > 0) {
1458 for (bp
= buf
; bp
< buf
+ nread
; bp
++)
1459 if (c_isascii(*bp
) && isdigit(*bp
)) {
1460 if ((speed
= bcode(bp
))) {
1461 cfsetispeed(tp
, speed
);
1462 cfsetospeed(tp
, speed
);
1468 /* Restore terminal settings. Errors will be dealt with later on. */
1469 tp
->c_iflag
= iflag
;
1470 tp
->c_cc
[VMIN
] = vmin
;
1471 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1474 static char *xgethostname(void)
1477 size_t sz
= get_hostname_max() + 1;
1479 name
= malloc(sizeof(char) * sz
);
1481 log_err(_("failed to allocate memory: %m"));
1483 if (gethostname(name
, sz
) != 0) {
1487 name
[sz
- 1] = '\0';
1491 static char *xgetdomainname(void)
1493 #ifdef HAVE_GETDOMAINNAME
1495 const size_t sz
= get_hostname_max() + 1;
1497 name
= malloc(sizeof(char) * sz
);
1499 log_err(_("failed to allocate memory: %m"));
1501 if (getdomainname(name
, sz
) != 0) {
1505 name
[sz
- 1] = '\0';
1513 static char *read_os_release(struct options
*op
, const char *varname
)
1517 size_t varsz
= strlen(varname
);
1518 char *p
, *buf
= NULL
, *ret
= NULL
;
1520 /* read the file only once */
1521 if (!op
->osrelease
) {
1522 fd
= open(_PATH_OS_RELEASE_ETC
, O_RDONLY
);
1524 fd
= open(_PATH_OS_RELEASE_USR
, O_RDONLY
);
1526 log_warn(_("cannot open os-release file"));
1531 if (fstat(fd
, &st
) < 0 || st
.st_size
> 4 * 1024 * 1024)
1534 op
->osrelease
= malloc(st
.st_size
+ 1);
1536 log_err(_("failed to allocate memory: %m"));
1537 if (read_all(fd
, op
->osrelease
, st
.st_size
) != (ssize_t
) st
.st_size
) {
1538 free(op
->osrelease
);
1539 op
->osrelease
= NULL
;
1542 op
->osrelease
[st
.st_size
] = 0;
1544 buf
= strdup(op
->osrelease
);
1546 log_err(_("failed to allocate memory: %m"));
1552 p
+= strspn(p
, "\n\r");
1553 p
+= strspn(p
, " \t\n\r");
1556 if (strspn(p
, "#;\n") != 0) {
1557 p
+= strcspn(p
, "\n\r");
1560 if (strncmp(p
, varname
, varsz
) != 0) {
1561 p
+= strcspn(p
, "\n\r");
1565 p
+= strspn(p
, " \t\n\r");
1570 p
+= strspn(p
, " \t\n\r=\"");
1571 eol
= p
+ strcspn(p
, "\n\r");
1575 if (*eon
== '\t' || *eon
== ' ') {
1588 log_err(_("failed to allocate memory: %m"));
1598 #ifdef AGETTY_RELOAD
1599 static void open_netlink(void)
1601 struct sockaddr_nl addr
= { 0, };
1604 if (netlink_fd
!= AGETTY_RELOAD_FDNONE
)
1607 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
1609 addr
.nl_family
= AF_NETLINK
;
1610 addr
.nl_pid
= getpid();
1611 addr
.nl_groups
= netlink_groups
;
1612 if (bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) < 0)
1619 static int process_netlink_msg(int *triggered
)
1622 struct sockaddr_nl snl
;
1626 struct iovec iov
= {
1628 .iov_len
= sizeof(buf
)
1630 struct msghdr msg
= {
1632 .msg_namelen
= sizeof(snl
),
1635 .msg_control
= NULL
,
1636 .msg_controllen
= 0,
1640 rc
= recvmsg(netlink_fd
, &msg
, MSG_DONTWAIT
);
1642 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1645 /* Failure, just stop listening for changes */
1647 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1651 for (h
= (struct nlmsghdr
*)buf
; NLMSG_OK(h
, (unsigned int)rc
); h
= NLMSG_NEXT(h
, rc
)) {
1652 if (h
->nlmsg_type
== NLMSG_DONE
||
1653 h
->nlmsg_type
== NLMSG_ERROR
) {
1655 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1666 static int process_netlink(void)
1669 while (process_netlink_msg(&triggered
));
1673 static int wait_for_term_input(int fd
)
1675 char buffer
[sizeof(struct inotify_event
) + NAME_MAX
+ 1];
1678 if (inotify_fd
== AGETTY_RELOAD_FDNONE
) {
1679 /* make sure the reload trigger file exists */
1680 int reload_fd
= open(AGETTY_RELOAD_FILENAME
,
1681 O_CREAT
|O_CLOEXEC
|O_RDONLY
,
1684 /* initialize reload trigger inotify stuff */
1685 if (reload_fd
>= 0) {
1686 inotify_fd
= inotify_init1(IN_NONBLOCK
| IN_CLOEXEC
);
1688 inotify_add_watch(inotify_fd
, AGETTY_RELOAD_FILENAME
,
1689 IN_ATTRIB
| IN_MODIFY
);
1693 log_warn(_("failed to create reload file: %s: %m"),
1694 AGETTY_RELOAD_FILENAME
);
1703 if (inotify_fd
>= 0) {
1704 FD_SET(inotify_fd
, &rfds
);
1705 nfds
= max(nfds
, inotify_fd
);
1707 if (netlink_fd
>= 0) {
1708 FD_SET(netlink_fd
, &rfds
);
1709 nfds
= max(nfds
, netlink_fd
);
1712 /* If waiting fails, just fall through, presumably reading input will fail */
1713 if (select(nfds
+ 1, &rfds
, NULL
, NULL
, NULL
) < 0)
1716 if (FD_ISSET(fd
, &rfds
)) {
1721 if (netlink_fd
>= 0 && FD_ISSET(netlink_fd
, &rfds
)) {
1722 if (!process_netlink())
1725 /* Just drain the inotify buffer */
1726 } else if (inotify_fd
>= 0 && FD_ISSET(inotify_fd
, &rfds
)) {
1727 while (read(inotify_fd
, buffer
, sizeof (buffer
)) > 0);
1733 #endif /* AGETTY_RELOAD */
1735 #ifdef ISSUEDIR_SUPPORT
1736 static int issuedir_filter(const struct dirent
*d
)
1740 #ifdef _DIRENT_HAVE_D_TYPE
1741 if (d
->d_type
!= DT_UNKNOWN
&& d
->d_type
!= DT_REG
&&
1742 d
->d_type
!= DT_LNK
)
1745 if (*d
->d_name
== '.')
1748 namesz
= strlen(d
->d_name
);
1749 if (!namesz
|| namesz
< ISSUEDIR_EXTSIZ
+ 1 ||
1750 strcmp(d
->d_name
+ (namesz
- ISSUEDIR_EXTSIZ
), ISSUEDIR_EXT
) != 0)
1758 static int issuefile_read_stream(struct issue
*ie
, FILE *f
, struct options
*op
, struct termios
*tp
);
1760 /* returns: 0 on success, 1 cannot open, <0 on error
1762 static int issuedir_read(struct issue
*ie
, const char *dirname
,
1763 struct options
*op
, struct termios
*tp
)
1766 struct dirent
**namelist
= NULL
;
1768 dd
= open(dirname
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
1772 nfiles
= scandirat(dd
, ".", &namelist
, issuedir_filter
, versionsort
);
1776 ie
->do_tcsetattr
= 1;
1778 for (i
= 0; i
< nfiles
; i
++) {
1779 struct dirent
*d
= namelist
[i
];
1782 f
= fopen_at(dd
, d
->d_name
, O_RDONLY
|O_CLOEXEC
, "r" UL_CLOEXECSTR
);
1784 issuefile_read_stream(ie
, f
, op
, tp
);
1789 for (i
= 0; i
< nfiles
; i
++)
1797 #else /* !ISSUEDIR_SUPPORT */
1798 static int issuedir_read(struct issue
*ie
__attribute__((__unused__
)),
1799 const char *dirname
__attribute__((__unused__
)),
1800 struct options
*op
__attribute__((__unused__
)),
1801 struct termios
*tp
__attribute__((__unused__
)))
1805 #endif /* ISSUEDIR_SUPPORT */
1807 #ifndef ISSUE_SUPPORT
1808 static void print_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1810 struct termios
*tp
__attribute__((__unused__
)))
1812 if ((op
->flags
& F_NONL
) == 0) {
1813 /* Issue not in use, start with a new line. */
1814 write_all(STDOUT_FILENO
, "\r\n", 2);
1818 static void eval_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1819 struct options
*op
__attribute__((__unused__
)),
1820 struct termios
*tp
__attribute__((__unused__
)))
1824 static void show_issue(struct options
*op
__attribute__((__unused__
)))
1828 #else /* ISSUE_SUPPORT */
1830 static int issuefile_read_stream(
1831 struct issue
*ie
, FILE *f
,
1832 struct options
*op
, struct termios
*tp
)
1837 if (fstat(fileno(f
), &st
) || !S_ISREG(st
.st_mode
))
1844 ie
->output
= open_memstream(&ie
->mem
, &ie
->mem_sz
);
1847 while ((c
= fgetc(f
)) != EOF
) {
1849 output_special_char(ie
, fgetc(f
), op
, tp
, f
);
1851 putc(c
, ie
->output
);
1857 static int issuefile_read(
1858 struct issue
*ie
, const char *filename
,
1859 struct options
*op
, struct termios
*tp
)
1861 FILE *f
= fopen(filename
, "r" UL_CLOEXECSTR
);
1865 rc
= issuefile_read_stream(ie
, f
, op
, tp
);
1872 #ifdef AGETTY_RELOAD
1873 static int issue_is_changed(struct issue
*ie
)
1875 if (ie
->mem_old
&& ie
->mem
1876 && strcmp(ie
->mem_old
, ie
->mem
) == 0) {
1878 ie
->mem_old
= ie
->mem
;
1887 static void print_issue_file(struct issue
*ie
,
1891 int oflag
= tp
->c_oflag
; /* Save current setting. */
1893 if ((op
->flags
& F_NONL
) == 0) {
1894 /* Issue not in use, start with a new line. */
1895 write_all(STDOUT_FILENO
, "\r\n", 2);
1898 if (ie
->do_tcsetattr
) {
1899 if ((op
->flags
& F_VCONSOLE
) == 0) {
1900 /* Map new line in output to carriage return & new line. */
1901 tp
->c_oflag
|= (ONLCR
| OPOST
);
1902 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1907 write_all(STDOUT_FILENO
, ie
->mem
, ie
->mem_sz
);
1909 if (ie
->do_tcrestore
) {
1910 /* Restore settings. */
1911 tp
->c_oflag
= oflag
;
1912 /* Wait till output is gone. */
1913 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1916 #ifdef AGETTY_RELOAD
1918 ie
->mem_old
= ie
->mem
;
1928 static void eval_issue_file(struct issue
*ie
,
1934 #ifdef AGETTY_RELOAD
1937 if (!(op
->flags
& F_ISSUE
))
1940 * The custom issue file or directory list specified by:
1941 * agetty --isue-file <path[:path]...>
1942 * Note that nothing is printed if the file/dir does not exist.
1945 char *list
= strdup(op
->issue
);
1949 log_err(_("failed to allocate memory: %m"));
1951 for (file
= strtok(list
, ":"); file
; file
= strtok(NULL
, ":")) {
1954 if (stat(file
, &st
) < 0)
1956 if (S_ISDIR(st
.st_mode
))
1957 issuedir_read(ie
, file
, op
, tp
);
1959 issuefile_read(ie
, file
, op
, tp
);
1965 /* The default /etc/issue and optional /etc/issue.d directory as
1966 * extension to the file. The /etc/issue.d directory is ignored if
1967 * there is no /etc/issue file. The file may be empty or symlink.
1969 if (access(_PATH_ISSUE
, F_OK
|R_OK
) == 0) {
1970 issuefile_read(ie
, _PATH_ISSUE
, op
, tp
);
1971 issuedir_read(ie
, _PATH_ISSUEDIR
, op
, tp
);
1975 /* Fallback @runstatedir (usually /run) -- the file is not required to
1978 if (issuefile_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
) == 0)
1980 if (issuedir_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
) == 0)
1985 /* Fallback @sysconfstaticdir (usually /usr/lib) -- the file is not
1986 * required to read the dir
1988 issuefile_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
);
1989 issuedir_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
);
1993 #ifdef AGETTY_RELOAD
1994 if (netlink_groups
!= 0)
2003 /* This is --show-issue backend, executed by normal user on the current
2006 static void show_issue(struct options
*op
)
2008 struct issue ie
= { .output
= NULL
};
2011 memset(&tp
, 0, sizeof(struct termios
));
2012 if (tcgetattr(STDIN_FILENO
, &tp
) < 0)
2013 err(EXIT_FAILURE
, _("failed to get terminal attributes: %m"));
2015 eval_issue_file(&ie
, op
, &tp
);
2018 write_all(STDOUT_FILENO
, ie
.mem
, ie
.mem_sz
);
2024 #endif /* ISSUE_SUPPORT */
2026 /* Show login prompt, optionally preceded by /etc/issue contents. */
2027 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
)
2029 #ifdef AGETTY_RELOAD
2032 print_issue_file(ie
, op
, tp
);
2034 if (op
->flags
& F_LOGINPAUSE
) {
2035 puts(_("[press ENTER to login]"));
2036 #ifdef AGETTY_RELOAD
2038 if (!wait_for_term_input(STDIN_FILENO
)) {
2039 eval_issue_file(ie
, op
, tp
);
2040 if (issue_is_changed(ie
)) {
2041 if ((op
->flags
& F_VCONSOLE
)
2042 && (op
->flags
& F_NOCLEAR
) == 0)
2043 termio_clear(STDOUT_FILENO
);
2051 if (!(op
->flags
& F_NOHINTS
) && !op
->autolog
&&
2052 (op
->flags
& F_VCONSOLE
)) {
2055 if (ioctl(STDIN_FILENO
, KDGKBLED
, &kb
) == 0) {
2056 char hint
[256] = { '\0' };
2059 if (access(_PATH_NUMLOCK_ON
, F_OK
) == 0)
2062 if (nl
&& (kb
& 0x02) == 0)
2063 append(hint
, sizeof(hint
), NULL
, _("Num Lock off"));
2065 else if (nl
== 0 && (kb
& 2) && (kb
& 0x20) == 0)
2066 append(hint
, sizeof(hint
), NULL
, _("Num Lock on"));
2068 if ((kb
& 0x04) && (kb
& 0x40) == 0)
2069 append(hint
, sizeof(hint
), ", ", _("Caps Lock on"));
2071 if ((kb
& 0x01) && (kb
& 0x10) == 0)
2072 append(hint
, sizeof(hint
), ", ", _("Scroll Lock on"));
2075 printf(_("Hint: %s\n\n"), hint
);
2078 #endif /* KDGKBLED */
2079 if ((op
->flags
& F_NOHOSTNAME
) == 0) {
2080 char *hn
= xgethostname();
2083 char *dot
= strchr(hn
, '.');
2085 struct addrinfo
*res
= NULL
;
2087 if ((op
->flags
& F_LONGHNAME
) == 0) {
2091 } else if (dot
== NULL
) {
2092 struct addrinfo hints
;
2094 memset(&hints
, 0, sizeof(hints
));
2095 hints
.ai_flags
= AI_CANONNAME
;
2097 if (!getaddrinfo(hn
, NULL
, &hints
, &res
)
2098 && res
&& res
->ai_canonname
)
2099 cn
= res
->ai_canonname
;
2102 write_all(STDOUT_FILENO
, cn
, strlen(cn
));
2103 write_all(STDOUT_FILENO
, " ", 1);
2111 /* Always show login prompt. */
2112 write_all(STDOUT_FILENO
, LOGIN_PROMPT
,
2113 sizeof(LOGIN_PROMPT
) - 1);
2117 /* Select next baud rate. */
2118 static void next_speed(struct options
*op
, struct termios
*tp
)
2120 static int baud_index
= -1;
2122 if (baud_index
== -1)
2124 * If the F_KEEPSPEED flags is set then the FIRST_SPEED is not
2125 * tested yet (see termio_init()).
2128 (op
->flags
& F_KEEPSPEED
) ? FIRST_SPEED
: 1 % op
->numspeed
;
2130 baud_index
= (baud_index
+ 1) % op
->numspeed
;
2132 cfsetispeed(tp
, op
->speeds
[baud_index
]);
2133 cfsetospeed(tp
, op
->speeds
[baud_index
]);
2134 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
2137 /* Get user name, establish parity, speed, erase, kill & eol. */
2138 static char *get_logname(struct issue
*ie
, struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2140 static char logname
[BUFSIZ
];
2142 char c
; /* input character, full eight bits */
2143 char ascval
; /* low 7 bits of input character */
2145 static char *erase
[] = { /* backspace-space-backspace */
2146 "\010\040\010", /* space parity */
2147 "\010\040\010", /* odd parity */
2148 "\210\240\210", /* even parity */
2149 "\210\240\210", /* no parity */
2152 /* Initialize kill, erase, parity etc. (also after switching speeds). */
2156 * Flush pending input (especially important after parsing or switching
2159 if ((op
->flags
& F_VCONSOLE
) == 0)
2161 tcflush(STDIN_FILENO
, TCIFLUSH
);
2163 eightbit
= (op
->flags
& (F_EIGHTBITS
|F_UTF8
));
2167 eval_issue_file(ie
, op
, tp
);
2168 while (*logname
== '\0') {
2169 /* Write issue file and prompt */
2170 do_prompt(ie
, op
, tp
);
2173 #ifdef AGETTY_RELOAD
2174 if (!wait_for_term_input(STDIN_FILENO
)) {
2175 /* refresh prompt -- discard input data, clear terminal
2176 * and call do_prompt() again
2178 if ((op
->flags
& F_VCONSOLE
) == 0)
2180 eval_issue_file(ie
, op
, tp
);
2181 if (!issue_is_changed(ie
))
2183 tcflush(STDIN_FILENO
, TCIFLUSH
);
2184 if ((op
->flags
& F_VCONSOLE
)
2185 && (op
->flags
& F_NOCLEAR
) == 0)
2186 termio_clear(STDOUT_FILENO
);
2194 /* Read name, watch for break and end-of-line. */
2195 while (cp
->eol
== '\0') {
2200 debug("read from FD\n");
2201 readres
= read(STDIN_FILENO
, &c
, 1);
2203 debug("read failed\n");
2205 /* The terminal could be open with O_NONBLOCK when
2206 * -L (force CLOCAL) is specified... */
2207 if (errno
== EINTR
|| errno
== EAGAIN
) {
2217 exit_slowly(EXIT_SUCCESS
);
2219 log_err(_("%s: read: %m"), op
->tty
);
2226 /* Do parity bit handling. */
2229 else if (c
!= (ascval
= (c
& 0177))) {
2230 uint32_t bits
; /* # of "1" bits per character */
2231 uint32_t mask
; /* mask with 1 bit up */
2232 for (bits
= 1, mask
= 1; mask
& 0177; mask
<<= 1) {
2236 cp
->parity
|= ((bits
& 1) ? 1 : 2);
2239 if (op
->killchars
&& strchr(op
->killchars
, ascval
))
2241 else if (op
->erasechars
&& strchr(op
->erasechars
, ascval
))
2246 /* Do erase, kill and end-of-line processing. */
2250 if (op
->numspeed
> 1 && !(op
->flags
& F_VCONSOLE
))
2253 exit_slowly(EXIT_SUCCESS
);
2257 *bp
= 0; /* terminate logname */
2258 cp
->eol
= ascval
; /* set end-of-line char */
2262 cp
->erase
= ascval
; /* set erase character */
2264 if ((tp
->c_lflag
& ECHO
) == 0)
2265 write_all(1, erase
[cp
->parity
], 3);
2270 cp
->kill
= ascval
; /* set kill character */
2273 if (key
== CTL('C') && !(op
->flags
& F_VCONSOLE
))
2274 /* Ignore CTRL+C on serial line */
2276 while (bp
> logname
) {
2277 if ((tp
->c_lflag
& ECHO
) == 0)
2278 write_all(1, erase
[cp
->parity
], 3);
2285 if ((size_t)(bp
- logname
) >= sizeof(logname
) - 1)
2286 log_err(_("%s: input overrun"), op
->tty
);
2287 if ((tp
->c_lflag
& ECHO
) == 0)
2288 write_all(1, &c
, 1); /* echo the character */
2289 *bp
++ = ascval
; /* and store it */
2292 /* Everything was erased. */
2293 if (bp
== logname
&& cp
->eol
== '\0')
2298 #ifdef HAVE_WIDECHAR
2299 if ((op
->flags
& (F_EIGHTBITS
|F_UTF8
)) == (F_EIGHTBITS
|F_UTF8
)) {
2300 /* Check out UTF-8 multibyte characters */
2304 len
= mbstowcs((wchar_t *)0, logname
, 0);
2306 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2308 wcs
= malloc((len
+ 1) * sizeof(wchar_t));
2310 log_err(_("failed to allocate memory: %m"));
2312 len
= mbstowcs(wcs
, logname
, len
+ 1);
2314 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2318 const wint_t wc
= *wcp
++;
2320 log_err(_("%s: invalid character 0x%x in login name"), op
->tty
, wc
);
2325 if ((op
->flags
& F_LCUC
) && (cp
->capslock
= caps_lock(logname
))) {
2327 /* Handle names with upper case and no lower case. */
2328 for (bp
= logname
; *bp
; bp
++)
2330 *bp
= tolower(*bp
); /* map name to lower case */
2336 /* Set the final tty mode bits. */
2337 static void termio_final(struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2339 /* General terminal-independent stuff. */
2341 /* 2-way flow control */
2342 tp
->c_iflag
|= IXON
| IXOFF
;
2343 tp
->c_lflag
|= ICANON
| ISIG
| ECHO
| ECHOE
| ECHOK
| ECHOKE
;
2344 /* no longer| ECHOCTL | ECHOPRT */
2345 tp
->c_oflag
|= OPOST
;
2346 /* tp->c_cflag = 0; */
2347 tp
->c_cc
[VINTR
] = DEF_INTR
;
2348 tp
->c_cc
[VQUIT
] = DEF_QUIT
;
2349 tp
->c_cc
[VEOF
] = DEF_EOF
;
2350 tp
->c_cc
[VEOL
] = DEF_EOL
;
2352 tp
->c_cc
[VSWTC
] = DEF_SWITCH
;
2353 #elif defined(VSWTCH)
2354 tp
->c_cc
[VSWTCH
] = DEF_SWITCH
;
2355 #endif /* __linux__ */
2357 /* Account for special characters seen in input. */
2358 if (cp
->eol
== CR
) {
2359 tp
->c_iflag
|= ICRNL
;
2360 tp
->c_oflag
|= ONLCR
;
2362 tp
->c_cc
[VERASE
] = cp
->erase
;
2363 tp
->c_cc
[VKILL
] = cp
->kill
;
2365 /* Account for the presence or absence of parity bits in input. */
2366 switch (cp
->parity
) {
2368 /* space (always 0) parity */
2372 tp
->c_cflag
|= PARODD
;
2376 tp
->c_cflag
|= PARENB
;
2377 tp
->c_iflag
|= INPCK
| ISTRIP
;
2381 tp
->c_cflag
&= ~CSIZE
;
2385 /* Account for upper case without lower case. */
2388 tp
->c_iflag
|= IUCLC
;
2391 tp
->c_lflag
|= XCASE
;
2394 tp
->c_oflag
|= OLCUC
;
2397 /* Optionally enable hardware flow control. */
2399 if (op
->flags
& F_RTSCTS
)
2400 tp
->c_cflag
|= CRTSCTS
;
2403 /* Finally, make the new settings effective. */
2404 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
) < 0)
2405 log_err(_("%s: failed to set terminal attributes: %m"), op
->tty
);
2409 * String contains upper case without lower case.
2410 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=52940
2411 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=156242
2413 static int caps_lock(char *s
)
2417 for (capslock
= 0; *s
; s
++) {
2419 return EXIT_SUCCESS
;
2421 capslock
= isupper(*s
);
2426 /* Convert speed string to speed code; return 0 on failure. */
2427 static speed_t
bcode(char *s
)
2429 const struct Speedtab
*sp
;
2434 speed
= strtol(s
, &end
, 10);
2436 if (errno
|| !end
|| end
== s
)
2439 for (sp
= speedtab
; sp
->speed
; sp
++)
2440 if (sp
->speed
== speed
)
2445 static void __attribute__((__noreturn__
)) usage(void)
2449 fputs(USAGE_HEADER
, out
);
2450 fprintf(out
, _(" %1$s [options] <line> [<baud_rate>,...] [<termtype>]\n"
2451 " %1$s [options] <baud_rate>,... <line> [<termtype>]\n"), program_invocation_short_name
);
2453 fputs(USAGE_SEPARATOR
, out
);
2454 fputs(_("Open a terminal and set its mode.\n"), out
);
2456 fputs(USAGE_OPTIONS
, out
);
2457 fputs(_(" -8, --8bits assume 8-bit tty\n"), out
);
2458 fputs(_(" -a, --autologin <user> login the specified user automatically\n"), out
);
2459 fputs(_(" -c, --noreset do not reset control mode\n"), out
);
2460 fputs(_(" -E, --remote use -r <hostname> for login(1)\n"), out
);
2461 fputs(_(" -f, --issue-file <list> display issue files or directories\n"), out
);
2462 fputs(_(" --show-issue display issue file and exit\n"), out
);
2463 fputs(_(" -h, --flow-control enable hardware flow control\n"), out
);
2464 fputs(_(" -H, --host <hostname> specify login host\n"), out
);
2465 fputs(_(" -i, --noissue do not display issue file\n"), out
);
2466 fputs(_(" -I, --init-string <string> set init string\n"), out
);
2467 fputs(_(" -J, --noclear do not clear the screen before prompt\n"), out
);
2468 fputs(_(" -l, --login-program <file> specify login program\n"), out
);
2469 fputs(_(" -L, --local-line[=<mode>] control the local line flag\n"), out
);
2470 fputs(_(" -m, --extract-baud extract baud rate during connect\n"), out
);
2471 fputs(_(" -n, --skip-login do not prompt for login\n"), out
);
2472 fputs(_(" -N, --nonewline do not print a newline before issue\n"), out
);
2473 fputs(_(" -o, --login-options <opts> options that are passed to login\n"), out
);
2474 fputs(_(" -p, --login-pause wait for any key before the login\n"), out
);
2475 fputs(_(" -r, --chroot <dir> change root to the directory\n"), out
);
2476 fputs(_(" -R, --hangup do virtually hangup on the tty\n"), out
);
2477 fputs(_(" -s, --keep-baud try to keep baud rate after break\n"), out
);
2478 fputs(_(" -t, --timeout <number> login process timeout\n"), out
);
2479 fputs(_(" -U, --detect-case detect uppercase terminal\n"), out
);
2480 fputs(_(" -w, --wait-cr wait carriage-return\n"), out
);
2481 fputs(_(" --nohints do not print hints\n"), out
);
2482 fputs(_(" --nohostname no hostname at all will be shown\n"), out
);
2483 fputs(_(" --long-hostname show full qualified hostname\n"), out
);
2484 fputs(_(" --erase-chars <string> additional backspace chars\n"), out
);
2485 fputs(_(" --kill-chars <string> additional kill chars\n"), out
);
2486 fputs(_(" --chdir <directory> chdir before the login\n"), out
);
2487 fputs(_(" --delay <number> sleep seconds before prompt\n"), out
);
2488 fputs(_(" --nice <number> run login with this priority\n"), out
);
2489 fputs(_(" --reload reload prompts on running agetty instances\n"), out
);
2490 fputs(_(" --list-speeds display supported baud rates\n"), out
);
2491 fprintf(out
, " --help %s\n", USAGE_OPTSTR_HELP
);
2492 fprintf(out
, " --version %s\n", USAGE_OPTSTR_VERSION
);
2493 fprintf(out
, USAGE_MAN_TAIL("agetty(8)"));
2498 static void list_speeds(void)
2500 const struct Speedtab
*sp
;
2502 for (sp
= speedtab
; sp
->speed
; sp
++)
2503 printf("%10ld\n", sp
->speed
);
2507 * Helper function reports errors to console or syslog.
2508 * Will be used by log_err() and log_warn() therefore
2509 * it takes a format as well as va_list.
2511 static void dolog(int priority
2513 __attribute__((__unused__
))
2515 , const char *fmt
, va_list ap
)
2519 * If the diagnostic is reported via syslog(3), the process name is
2520 * automatically prepended to the message. If we write directly to
2521 * /dev/console, we must prepend the process name ourselves.
2523 openlog("agetty", LOG_PID
, LOG_AUTHPRIV
);
2524 vsyslog(priority
, fmt
, ap
);
2528 * Write the diagnostic directly to /dev/console if we do not use
2529 * the syslog(3) facility.
2532 char new_fmt
[BUFSIZ
];
2535 snprintf(new_fmt
, sizeof(new_fmt
), "%s: %s\r\n",
2536 program_invocation_short_name
, fmt
);
2537 /* Terminate with CR-LF since the console mode is unknown. */
2538 vsnprintf(buf
, sizeof(buf
), new_fmt
, ap
);
2540 if ((fd
= open("/dev/console", 1)) >= 0) {
2541 write_all(fd
, buf
, strlen(buf
));
2544 #endif /* USE_SYSLOG */
2547 static void exit_slowly(int code
)
2549 /* Be kind to init(8). */
2554 static void log_err(const char *fmt
, ...)
2559 dolog(LOG_ERR
, fmt
, ap
);
2562 exit_slowly(EXIT_FAILURE
);
2565 static void log_warn(const char *fmt
, ...)
2570 dolog(LOG_WARNING
, fmt
, ap
);
2574 static void print_addr(struct issue
*ie
, sa_family_t family
, void *addr
)
2576 char buff
[INET6_ADDRSTRLEN
+ 1];
2578 inet_ntop(family
, addr
, buff
, sizeof(buff
));
2579 fprintf(ie
->output
, "%s", buff
);
2583 * Prints IP for the specified interface (@iface), if the interface is not
2584 * specified then prints the "best" one (UP, RUNNING, non-LOOPBACK). If not
2585 * found the "best" interface then prints at least host IP.
2587 static void output_iface_ip(struct issue
*ie
,
2588 struct ifaddrs
*addrs
,
2593 struct addrinfo hints
, *info
= NULL
;
2600 for (p
= addrs
; p
; p
= p
->ifa_next
) {
2604 p
->ifa_addr
->sa_family
!= family
)
2608 /* Filter out by interface name */
2609 if (strcmp(p
->ifa_name
, iface
) != 0)
2612 /* Select the "best" interface */
2613 if ((p
->ifa_flags
& IFF_LOOPBACK
) ||
2614 !(p
->ifa_flags
& IFF_UP
) ||
2615 !(p
->ifa_flags
& IFF_RUNNING
))
2620 switch (p
->ifa_addr
->sa_family
) {
2622 addr
= &((struct sockaddr_in
*) p
->ifa_addr
)->sin_addr
;
2625 addr
= &((struct sockaddr_in6
*) p
->ifa_addr
)->sin6_addr
;
2630 print_addr(ie
, family
, addr
);
2638 /* Hmm.. not found the best interface, print host IP at least */
2639 memset(&hints
, 0, sizeof(hints
));
2640 hints
.ai_family
= family
;
2641 if (family
== AF_INET6
)
2642 hints
.ai_flags
= AI_V4MAPPED
;
2644 host
= xgethostname();
2645 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2646 switch (info
->ai_family
) {
2648 addr
= &((struct sockaddr_in
*) info
->ai_addr
)->sin_addr
;
2651 addr
= &((struct sockaddr_in6
*) info
->ai_addr
)->sin6_addr
;
2655 print_addr(ie
, family
, addr
);
2663 * parses \x{argument}, if not argument specified then returns NULL, the @fd
2664 * has to point to one char after the sequence (it means '{').
2666 static char *get_escape_argument(FILE *fd
, char *buf
, size_t bufsz
)
2671 if (c
== EOF
|| (unsigned char) c
!= '{') {
2680 if ((unsigned char) c
!= '}' && i
< bufsz
- 1)
2681 buf
[i
++] = (unsigned char) c
;
2683 } while ((unsigned char) c
!= '}');
2689 static void output_special_char(struct issue
*ie
,
2700 char escname
[UL_COLORNAME_MAXSZ
];
2702 if (get_escape_argument(fp
, escname
, sizeof(escname
))) {
2703 char *esc
= color_get_sequence(escname
);
2706 fputs(esc
, ie
->output
);
2710 fputs("\033", ie
->output
);
2715 fprintf(ie
->output
, "%s", uts
.sysname
);
2719 fprintf(ie
->output
, "%s", uts
.nodename
);
2723 fprintf(ie
->output
, "%s", uts
.release
);
2727 fprintf(ie
->output
, "%s", uts
.version
);
2731 fprintf(ie
->output
, "%s", uts
.machine
);
2735 char *dom
= xgetdomainname();
2737 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2744 char *host
= xgethostname();
2745 struct addrinfo hints
, *info
= NULL
;
2747 memset(&hints
, 0, sizeof(hints
));
2748 hints
.ai_flags
= AI_CANONNAME
;
2750 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2753 if (info
->ai_canonname
&&
2754 (canon
= strchr(info
->ai_canonname
, '.')))
2757 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2770 localtime_r(&now
, &tm
);
2772 if (c
== 'd') /* ISO 8601 */
2773 fprintf(ie
->output
, "%s %s %2d %d",
2774 nl_langinfo(ABDAY_1
+ tm
.tm_wday
),
2775 nl_langinfo(ABMON_1
+ tm
.tm_mon
),
2777 tm
.tm_year
< 70 ? tm
.tm_year
+ 2000 :
2780 fprintf(ie
->output
, "%02d:%02d:%02d",
2781 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
2785 fprintf (ie
->output
, "%s", op
->tty
);
2789 const speed_t speed
= cfgetispeed(tp
);
2792 for (i
= 0; speedtab
[i
].speed
; i
++) {
2793 if (speedtab
[i
].code
== speed
) {
2794 fprintf(ie
->output
, "%ld", speedtab
[i
].speed
);
2802 char *var
= NULL
, varname
[64];
2805 if (get_escape_argument(fp
, varname
, sizeof(varname
))) {
2806 var
= read_os_release(op
, varname
);
2808 if (strcmp(varname
, "ANSI_COLOR") == 0)
2809 fprintf(ie
->output
, "\033[%sm", var
);
2811 fputs(var
, ie
->output
);
2814 } else if ((var
= read_os_release(op
, "PRETTY_NAME"))) {
2815 fputs(var
, ie
->output
);
2817 /* \S and PRETTY_NAME not found */
2820 fputs(uts
.sysname
, ie
->output
);
2832 if (sd_booted() > 0) {
2833 users
= sd_get_sessions(NULL
);
2841 while ((ut
= getutxent()))
2842 if (ut
->ut_type
== USER_PROCESS
)
2849 fprintf(ie
->output
, P_("%d user", "%d users", users
), users
);
2851 fprintf (ie
->output
, "%d ", users
);
2854 #if defined(RTMGRP_IPV4_IFADDR) && defined(RTMGRP_IPV6_IFADDR)
2858 sa_family_t family
= c
== '4' ? AF_INET
: AF_INET6
;
2859 struct ifaddrs
*addrs
= NULL
;
2862 if (getifaddrs(&addrs
))
2865 if (get_escape_argument(fp
, iface
, sizeof(iface
)))
2866 output_iface_ip(ie
, addrs
, iface
, family
);
2868 output_iface_ip(ie
, addrs
, NULL
, family
);
2873 netlink_groups
|= RTMGRP_IPV4_IFADDR
;
2875 netlink_groups
|= RTMGRP_IPV6_IFADDR
;
2880 putc(c
, ie
->output
);
2885 static void init_special_char(char* arg
, struct options
*op
)
2890 op
->initstring
= malloc(strlen(arg
) + 1);
2891 if (!op
->initstring
)
2892 log_err(_("failed to allocate memory: %m"));
2895 * Copy optarg into op->initstring decoding \ddd octal
2901 /* The \\ is converted to \ */
2908 /* Handle \000 - \177. */
2910 for (i
= 1; i
<= 3; i
++) {
2911 if (*p
>= '0' && *p
<= '7') {
2928 * Appends @str to @dest and if @dest is not empty then use @sep as a
2929 * separator. The maximal final length of the @dest is @len.
2931 * Returns the final @dest length or -1 in case of error.
2933 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
)
2935 size_t dsz
= 0, ssz
= 0, sz
;
2938 if (!dest
|| !len
|| !src
)
2947 if (dsz
+ ssz
+ sz
+ 1 > len
)
2952 p
= mempcpy(p
, sep
, ssz
);
2957 return dsz
+ ssz
+ sz
;
2961 * Do not allow the user to pass an option as a user name
2962 * To be more safe: Use `--' to make sure the rest is
2963 * interpreted as non-options by the program, if it supports it.
2965 static void check_username(const char* nm
)
2970 if (strlen(nm
) > 42)
2979 log_err(_("checkname failed: %m"));
2982 static void reload_agettys(void)
2984 #ifdef AGETTY_RELOAD
2985 int fd
= open(AGETTY_RELOAD_FILENAME
, O_CREAT
|O_CLOEXEC
|O_WRONLY
,
2988 err(EXIT_FAILURE
, _("cannot open %s"), AGETTY_RELOAD_FILENAME
);
2990 if (futimens(fd
, NULL
) < 0 || close(fd
) < 0)
2991 err(EXIT_FAILURE
, _("cannot touch file %s"),
2992 AGETTY_RELOAD_FILENAME
);
2995 errx(EXIT_FAILURE
, _("--reload is unsupported on your system"));
2999 static void load_credentials(struct options
*op
) {
3003 struct path_cxt
*pc
;
3005 env
= safe_getenv("CREDENTIALS_DIRECTORY");
3009 pc
= ul_new_path("%s", env
);
3011 log_warn(_("failed to initialize path context"));
3015 dir
= ul_path_opendir(pc
, NULL
);
3017 log_warn(_("failed to open credentials directory"));
3021 while ((d
= xreaddir(dir
))) {
3024 if (strcmp(d
->d_name
, "agetty.autologin") == 0) {
3025 ul_path_read_string(pc
, &str
, d
->d_name
);