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 "logindefs.h"
54 #ifdef USE_PLYMOUTH_SUPPORT
55 # include "plymouth-ctrl.h"
58 #ifdef HAVE_SYS_PARAM_H
59 # include <sys/param.h>
66 #if defined(__FreeBSD_kernel__)
71 # ifdef HAVE_LIBUTIL_H
79 # ifndef DEFAULT_VCTERM
80 # define DEFAULT_VCTERM "linux"
82 # if defined (__s390__) || defined (__s390x__)
83 # define DEFAULT_TTYS0 "dumb"
84 # define DEFAULT_TTY32 "ibm327x"
85 # define DEFAULT_TTYS1 "vt220"
87 # ifndef DEFAULT_STERM
88 # define DEFAULT_STERM "vt102"
90 #elif defined(__GNU__)
92 # ifndef DEFAULT_VCTERM
93 # define DEFAULT_VCTERM "hurd"
95 # ifndef DEFAULT_STERM
96 # define DEFAULT_STERM "vt102"
99 # ifndef DEFAULT_VCTERM
100 # define DEFAULT_VCTERM "vt100"
102 # ifndef DEFAULT_STERM
103 # define DEFAULT_STERM "vt100"
107 #ifdef __FreeBSD_kernel__
111 /* If USE_SYSLOG is undefined all diagnostics go to /dev/console. */
117 * Some heuristics to find out what environment we are in: if it is not
118 * System V, assume it is SunOS 4. The LOGIN_PROCESS is defined in System V
119 * utmp.h, which will select System V style getty.
126 * Things you may want to modify.
128 * If ISSUE_SUPPORT is not defined, agetty will never display the contents of
129 * the /etc/issue file. You will not want to spit out large "issue" files at
130 * the wrong baud rate. Relevant for System V only.
132 * You may disagree with the default line-editing etc. characters defined
133 * below. Note, however, that DEL cannot be used for interrupt generation
134 * and for line editing at the same time.
137 /* Displayed before the login prompt. */
139 # define ISSUE_SUPPORT
140 # if defined(HAVE_SCANDIRAT) && defined(HAVE_OPENAT)
142 # include "fileutils.h"
143 # define ISSUEDIR_SUPPORT
144 # define ISSUEDIR_EXT ".issue"
145 # define ISSUEDIR_EXTSIZ (sizeof(ISSUEDIR_EXT) - 1)
150 #define LOGIN_PROMPT "login: "
152 /* Numbers of args for login(1) */
153 #define LOGIN_ARGV_MAX 16
159 # include <sys/inotify.h>
160 # include <linux/netlink.h>
161 # include <linux/rtnetlink.h>
162 # define AGETTY_RELOAD_FILENAME "/run/agetty.reload" /* trigger file */
163 # define AGETTY_RELOAD_FDNONE -2 /* uninitialized fd */
164 static int inotify_fd
= AGETTY_RELOAD_FDNONE
;
165 static int netlink_fd
= AGETTY_RELOAD_FDNONE
;
166 static uint32_t netlink_groups
;
177 unsigned int do_tcsetattr
: 1,
182 * When multiple baud rates are specified on the command line, the first one
183 * we will try is the first one specified.
185 #define FIRST_SPEED 0
187 /* Storage for command-line options. */
188 #define MAX_SPEED 10 /* max. nr. of baud rates */
191 int flags
; /* toggle switches, see below */
192 unsigned int timeout
; /* time-out period */
193 char *autolog
; /* login the user automatically */
194 char *chdir
; /* Chdir before the login */
195 char *chroot
; /* Chroot before the login */
196 char *login
; /* login program */
197 char *logopt
; /* options for login program */
198 const char *tty
; /* name of tty */
199 const char *vcline
; /* line of virtual console */
200 char *term
; /* terminal type */
201 char *initstring
; /* modem init string */
202 char *issue
; /* alternative issue file or directory */
203 char *erasechars
; /* string with erase chars */
204 char *killchars
; /* string with kill chars */
205 char *osrelease
; /* /etc/os-release data */
206 unsigned int delay
; /* Sleep seconds before prompt */
207 int nice
; /* Run login with this priority */
208 int numspeed
; /* number of baud rates to try */
209 int clocal
; /* CLOCAL_MODE_* */
210 int kbmode
; /* Keyboard mode if virtual console */
211 int tty_is_stdin
; /* is the tty the standard input stream */
212 speed_t speeds
[MAX_SPEED
]; /* baud rates to be tried */
216 CLOCAL_MODE_AUTO
= 0,
221 #define F_PARSE (1<<0) /* process modem status messages */
222 #define F_ISSUE (1<<1) /* display /etc/issue or /etc/issue.d */
223 #define F_RTSCTS (1<<2) /* enable RTS/CTS flow control */
225 #define F_INITSTRING (1<<4) /* initstring is set */
226 #define F_WAITCRLF (1<<5) /* wait for CR or LF */
228 #define F_NOPROMPT (1<<7) /* do not ask for login name! */
229 #define F_LCUC (1<<8) /* support for *LCUC stty modes */
230 #define F_KEEPSPEED (1<<9) /* follow baud rate from kernel */
231 #define F_KEEPCFLAGS (1<<10) /* reuse c_cflags setup from kernel */
232 #define F_EIGHTBITS (1<<11) /* Assume 8bit-clean tty */
233 #define F_VCONSOLE (1<<12) /* This is a virtual console */
234 #define F_HANGUP (1<<13) /* Do call vhangup(2) */
235 #define F_UTF8 (1<<14) /* We can do UTF8 */
236 #define F_LOGINPAUSE (1<<15) /* Wait for any key before dropping login prompt */
237 #define F_NOCLEAR (1<<16) /* Do not clear the screen before prompting */
238 #define F_NONL (1<<17) /* No newline before issue */
239 #define F_NOHOSTNAME (1<<18) /* Do not show the hostname */
240 #define F_LONGHNAME (1<<19) /* Show Full qualified hostname */
241 #define F_NOHINTS (1<<20) /* Don't print hints */
242 #define F_REMOTE (1<<21) /* Add '-h fakehost' to login(1) command line */
244 #define serial_tty_option(opt, flag) \
245 (((opt)->flags & (F_VCONSOLE|(flag))) == (flag))
252 static const struct Speedtab speedtab
[] = {
324 static void init_special_char(char* arg
, struct options
*op
);
325 static void parse_args(int argc
, char **argv
, struct options
*op
);
326 static void parse_speeds(struct options
*op
, char *arg
);
327 static void update_utmp(struct options
*op
);
328 static void open_tty(const char *tty
, struct termios
*tp
, struct options
*op
);
329 static void termio_init(struct options
*op
, struct termios
*tp
);
330 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
);
331 static void auto_baud(struct termios
*tp
);
332 static void list_speeds(void);
333 static void output_special_char (struct issue
*ie
, unsigned char c
, struct options
*op
,
334 struct termios
*tp
, FILE *fp
);
335 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
336 static void next_speed(struct options
*op
, struct termios
*tp
);
337 static char *get_logname(struct issue
*ie
, struct options
*op
,
338 struct termios
*tp
, struct chardata
*cp
);
339 static void termio_final(struct options
*op
,
340 struct termios
*tp
, struct chardata
*cp
);
341 static int caps_lock(char *s
);
342 static speed_t
bcode(char *s
);
343 static void usage(void) __attribute__((__noreturn__
));
344 static void exit_slowly(int code
) __attribute__((__noreturn__
));
345 static void log_err(const char *, ...) __attribute__((__noreturn__
))
346 __attribute__((__format__(printf
, 1, 2)));
347 static void log_warn (const char *, ...)
348 __attribute__((__format__(printf
, 1, 2)));
349 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
);
350 static void check_username (const char* nm
);
351 static void login_options_to_argv(char *argv
[], int *argc
, char *str
, char *username
);
352 static void reload_agettys(void);
353 static void print_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
354 static void eval_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
355 static void show_issue(struct options
*op
);
358 /* Fake hostname for ut_host specified on command line. */
359 static char *fakehost
;
362 # include "closestream.h"
363 # ifndef DEBUG_OUTPUT
364 # define DEBUG_OUTPUT "/dev/tty10"
366 # define debug(s) do { fprintf(dbf,s); fflush(dbf); } while (0)
369 # define debug(s) do { ; } while (0)
372 int main(int argc
, char **argv
)
374 char *username
= NULL
; /* login name, given to /bin/login */
375 struct chardata chardata
; /* will be set by get_logname() */
376 struct termios termios
; /* terminal mode bits */
377 struct options options
= {
378 .flags
= F_ISSUE
, /* show /etc/issue (SYSV_STYLE) */
379 .login
= _PATH_LOGIN
, /* default login program */
380 .tty
= "tty1" /* default tty line */
382 struct issue issue
= {
385 char *login_argv
[LOGIN_ARGV_MAX
+ 1];
387 struct sigaction sa
, sa_hup
, sa_quit
, sa_int
;
390 setlocale(LC_ALL
, "");
391 bindtextdomain(PACKAGE
, LOCALEDIR
);
394 /* In case vhangup(2) has to called */
395 sa
.sa_handler
= SIG_IGN
;
396 sa
.sa_flags
= SA_RESTART
;
397 sigemptyset (&sa
.sa_mask
);
398 sigaction(SIGHUP
, &sa
, &sa_hup
);
399 sigaction(SIGQUIT
, &sa
, &sa_quit
);
400 sigaction(SIGINT
, &sa
, &sa_int
);
406 dbf
= fopen(DEBUG_OUTPUT
, "w");
407 for (i
= 1; i
< argc
; i
++) {
414 #endif /* DEBUGGING */
416 /* Parse command-line arguments. */
417 parse_args(argc
, argv
, &options
);
419 login_argv
[login_argc
++] = options
.login
; /* set login program name */
421 /* Update the utmp file. */
423 update_utmp(&options
);
426 sleep(options
.delay
);
428 debug("calling open_tty\n");
430 /* Open the tty as standard { input, output, error }. */
431 open_tty(options
.tty
, &termios
, &options
);
433 /* Unmask SIGHUP if inherited */
435 sigaddset(&set
, SIGHUP
);
436 sigprocmask(SIG_UNBLOCK
, &set
, NULL
);
437 sigaction(SIGHUP
, &sa_hup
, NULL
);
439 tcsetpgrp(STDIN_FILENO
, getpid());
441 /* Default is to follow the current line speed and then default to 9600 */
442 if ((options
.flags
& F_VCONSOLE
) == 0 && options
.numspeed
== 0) {
443 options
.speeds
[options
.numspeed
++] = bcode("9600");
444 options
.flags
|= F_KEEPSPEED
;
447 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
448 debug("calling termio_init\n");
449 termio_init(&options
, &termios
);
451 /* Write the modem init string and DO NOT flush the buffers. */
452 if (options
.flags
& F_INITSTRING
&&
453 options
.initstring
&& *options
.initstring
!= '\0') {
454 debug("writing init string\n");
455 write_all(STDOUT_FILENO
, options
.initstring
,
456 strlen(options
.initstring
));
459 if (options
.flags
& F_VCONSOLE
|| options
.clocal
!= CLOCAL_MODE_ALWAYS
)
460 /* Go to blocking mode unless -L is specified, this change
461 * affects stdout, stdin and stderr as all the file descriptors
462 * are created by dup(). */
463 fcntl(STDOUT_FILENO
, F_SETFL
,
464 fcntl(STDOUT_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
466 /* Optionally detect the baud rate from the modem status message. */
467 debug("before autobaud\n");
468 if (serial_tty_option(&options
, F_PARSE
))
471 /* Set the optional timer. */
473 alarm(options
.timeout
);
475 /* Optionally wait for CR or LF before writing /etc/issue */
476 if (serial_tty_option(&options
, F_WAITCRLF
)) {
479 debug("waiting for cr-lf\n");
480 while (read(STDIN_FILENO
, &ch
, 1) == 1) {
481 /* Strip "parity bit". */
484 fprintf(dbf
, "read %c\n", ch
);
486 if (ch
== '\n' || ch
== '\r')
491 INIT_CHARDATA(&chardata
);
493 if (options
.autolog
) {
494 debug("doing auto login\n");
495 username
= options
.autolog
;
498 if (options
.flags
& F_NOPROMPT
) { /* --skip-login */
499 eval_issue_file(&issue
, &options
, &termios
);
500 print_issue_file(&issue
, &options
, &termios
);
502 } else { /* regular (auto)login */
503 if ((options
.flags
& F_NOHOSTNAME
) == 0 &&
504 getlogindefs_bool("LOGIN_PLAIN_PROMPT", 0) == 1)
505 /* /etc/login.defs enbles --nohostname too */
506 options
.flags
|= F_NOHOSTNAME
;
508 if (options
.autolog
) {
509 /* Autologin prompt */
510 eval_issue_file(&issue
, &options
, &termios
);
511 do_prompt(&issue
, &options
, &termios
);
512 printf(_("%s%s (automatic login)\n"), LOGIN_PROMPT
,
515 /* Read the login name. */
516 debug("reading login name\n");
518 get_logname(&issue
, &options
, &termios
, &chardata
)) == NULL
)
519 if ((options
.flags
& F_VCONSOLE
) == 0 && options
.numspeed
)
520 next_speed(&options
, &termios
);
528 /* Finalize the termios settings. */
529 if ((options
.flags
& F_VCONSOLE
) == 0)
530 termio_final(&options
, &termios
, &chardata
);
532 reset_vc(&options
, &termios
, 1);
534 /* Now the newline character should be properly written. */
535 write_all(STDOUT_FILENO
, "\r\n", 2);
537 sigaction(SIGQUIT
, &sa_quit
, NULL
);
538 sigaction(SIGINT
, &sa_int
, NULL
);
541 check_username(username
);
543 if (options
.logopt
) {
545 * The --login-options completely overwrites the default
546 * way how agetty composes login(1) command line.
548 login_options_to_argv(login_argv
, &login_argc
,
549 options
.logopt
, username
);
551 if (options
.flags
& F_REMOTE
) {
553 login_argv
[login_argc
++] = "-h";
554 login_argv
[login_argc
++] = fakehost
;
555 } else if (options
.flags
& F_NOHOSTNAME
)
556 login_argv
[login_argc
++] = "-H";
560 login_argv
[login_argc
++] = "-f";
562 login_argv
[login_argc
++] = "--";
563 login_argv
[login_argc
++] = username
;
567 login_argv
[login_argc
] = NULL
; /* last login argv */
569 if (options
.chroot
&& chroot(options
.chroot
) < 0)
570 log_err(_("%s: can't change root directory %s: %m"),
571 options
.tty
, options
.chroot
);
572 if (options
.chdir
&& chdir(options
.chdir
) < 0)
573 log_err(_("%s: can't change working directory %s: %m"),
574 options
.tty
, options
.chdir
);
575 if (options
.nice
&& nice(options
.nice
) < 0)
576 log_warn(_("%s: can't change process priority: %m"),
579 free(options
.osrelease
);
581 if (close_stream(dbf
) != 0)
582 log_err("write failed: %s", DEBUG_OUTPUT
);
585 /* Let the login program take care of password validation. */
586 execv(options
.login
, login_argv
);
587 log_err(_("%s: can't exec %s: %m"), options
.tty
, login_argv
[0]);
591 * Returns : @str if \u not found
592 * : @username if @str equal to "\u"
593 * : newly allocated string if \u mixed with something other
595 static char *replace_u(char *str
, char *username
)
597 char *entry
= NULL
, *p
= str
;
598 size_t usz
= username
? strlen(username
) : 0;
602 char *tp
, *old
= entry
;
604 if (memcmp(p
, "\\u", 2) != 0) {
606 continue; /* no \u */
610 if (p
== str
&& sz
== 2) {
611 /* 'str' contains only '\u' */
616 tp
= entry
= malloc(sz
+ usz
);
618 log_err(_("failed to allocate memory: %m"));
621 /* copy chars before \u */
622 memcpy(tp
, str
, p
- str
);
627 memcpy(tp
, username
, usz
);
631 /* copy chars after \u + \0 */
632 memcpy(tp
, p
+ 2, sz
- (p
- str
) - 1);
641 return entry
? entry
: str
;
644 static void login_options_to_argv(char *argv
[], int *argc
,
645 char *str
, char *username
)
650 while (str
&& isspace(*str
))
654 while (p
&& *p
&& i
< LOGIN_ARGV_MAX
) {
657 while (isspace(*++p
))
660 argv
[i
++] = replace_u(str
, username
);
666 if (str
&& *str
&& i
< LOGIN_ARGV_MAX
)
667 argv
[i
++] = replace_u(str
, username
);
671 static void output_version(void)
673 static const char *features
[] = {
686 #ifdef ISSUEDIR_SUPPORT
692 #ifdef USE_PLYMOUTH_SUPPORT
708 printf( _("%s from %s"), program_invocation_short_name
, PACKAGE_STRING
);
710 for (i
= 0; features
[i
]; i
++) {
713 printf("%s", features
[i
]);
715 fputs(")\n", stdout
);
718 #define is_speed(str) (strlen((str)) == strspn((str), "0123456789,"))
720 /* Parse command-line arguments. */
721 static void parse_args(int argc
, char **argv
, struct options
*op
)
724 int opt_show_issue
= 0;
727 VERSION_OPTION
= CHAR_MAX
+ 1,
738 const struct option longopts
[] = {
739 { "8bits", no_argument
, NULL
, '8' },
740 { "autologin", required_argument
, NULL
, 'a' },
741 { "noreset", no_argument
, NULL
, 'c' },
742 { "chdir", required_argument
, NULL
, 'C' },
743 { "delay", required_argument
, NULL
, 'd' },
744 { "remote", no_argument
, NULL
, 'E' },
745 { "issue-file", required_argument
, NULL
, 'f' },
746 { "show-issue", no_argument
, NULL
, ISSUE_SHOW_OPTION
},
747 { "flow-control", no_argument
, NULL
, 'h' },
748 { "host", required_argument
, NULL
, 'H' },
749 { "noissue", no_argument
, NULL
, 'i' },
750 { "init-string", required_argument
, NULL
, 'I' },
751 { "noclear", no_argument
, NULL
, 'J' },
752 { "login-program", required_argument
, NULL
, 'l' },
753 { "local-line", optional_argument
, NULL
, 'L' },
754 { "extract-baud", no_argument
, NULL
, 'm' },
755 { "list-speeds", no_argument
, NULL
, LIST_SPEEDS_OPTION
},
756 { "skip-login", no_argument
, NULL
, 'n' },
757 { "nonewline", no_argument
, NULL
, 'N' },
758 { "login-options", required_argument
, NULL
, 'o' },
759 { "login-pause", no_argument
, NULL
, 'p' },
760 { "nice", required_argument
, NULL
, 'P' },
761 { "chroot", required_argument
, NULL
, 'r' },
762 { "hangup", no_argument
, NULL
, 'R' },
763 { "keep-baud", no_argument
, NULL
, 's' },
764 { "timeout", required_argument
, NULL
, 't' },
765 { "detect-case", no_argument
, NULL
, 'U' },
766 { "wait-cr", no_argument
, NULL
, 'w' },
767 { "nohints", no_argument
, NULL
, NOHINTS_OPTION
},
768 { "nohostname", no_argument
, NULL
, NOHOSTNAME_OPTION
},
769 { "long-hostname", no_argument
, NULL
, LONGHOSTNAME_OPTION
},
770 { "reload", no_argument
, NULL
, RELOAD_OPTION
},
771 { "version", no_argument
, NULL
, VERSION_OPTION
},
772 { "help", no_argument
, NULL
, HELP_OPTION
},
773 { "erase-chars", required_argument
, NULL
, ERASE_CHARS_OPTION
},
774 { "kill-chars", required_argument
, NULL
, KILL_CHARS_OPTION
},
778 while ((c
= getopt_long(argc
, argv
,
779 "8a:cC:d:Ef:hH:iI:Jl:L::mnNo:pP:r:Rst:Uw", longopts
,
783 op
->flags
|= F_EIGHTBITS
;
786 op
->autolog
= optarg
;
789 op
->flags
|= F_KEEPCFLAGS
;
795 op
->delay
= strtou32_or_err(optarg
, _("invalid delay argument"));
798 op
->flags
|= F_REMOTE
;
804 op
->flags
|= F_RTSCTS
;
810 op
->flags
&= ~F_ISSUE
;
813 init_special_char(optarg
, op
);
814 op
->flags
|= F_INITSTRING
;
817 op
->flags
|= F_NOCLEAR
;
823 /* -L and -L=always have the same meaning */
824 op
->clocal
= CLOCAL_MODE_ALWAYS
;
826 if (strcmp(optarg
, "=always") == 0)
827 op
->clocal
= CLOCAL_MODE_ALWAYS
;
828 else if (strcmp(optarg
, "=never") == 0)
829 op
->clocal
= CLOCAL_MODE_NEVER
;
830 else if (strcmp(optarg
, "=auto") == 0)
831 op
->clocal
= CLOCAL_MODE_AUTO
;
833 log_err(_("invalid argument of --local-line"));
837 op
->flags
|= F_PARSE
;
840 op
->flags
|= F_NOPROMPT
;
849 op
->flags
|= F_LOGINPAUSE
;
852 op
->nice
= strtos32_or_err(optarg
, _("invalid nice argument"));
858 op
->flags
|= F_HANGUP
;
861 op
->flags
|= F_KEEPSPEED
;
864 op
->timeout
= strtou32_or_err(optarg
, _("invalid timeout argument"));
870 op
->flags
|= F_WAITCRLF
;
873 op
->flags
|= F_NOHINTS
;
875 case NOHOSTNAME_OPTION
:
876 op
->flags
|= F_NOHOSTNAME
;
878 case LONGHOSTNAME_OPTION
:
879 op
->flags
|= F_LONGHNAME
;
881 case ERASE_CHARS_OPTION
:
882 op
->erasechars
= optarg
;
884 case KILL_CHARS_OPTION
:
885 op
->killchars
= optarg
;
890 case LIST_SPEEDS_OPTION
:
893 case ISSUE_SHOW_OPTION
:
902 errtryhelp(EXIT_FAILURE
);
906 if (opt_show_issue
) {
911 debug("after getopt loop\n");
913 if (argc
< optind
+ 1) {
914 log_warn(_("not enough arguments"));
915 errx(EXIT_FAILURE
, _("not enough arguments"));
918 /* Accept "tty", "baudrate tty", and "tty baudrate". */
919 if (is_speed(argv
[optind
])) {
920 /* Assume BSD style speed. */
921 parse_speeds(op
, argv
[optind
++]);
922 if (argc
< optind
+ 1) {
923 log_warn(_("not enough arguments"));
924 errx(EXIT_FAILURE
, _("not enough arguments"));
926 op
->tty
= argv
[optind
++];
928 op
->tty
= argv
[optind
++];
930 char *v
= argv
[optind
];
938 /* resolve the tty path in case it was provided as stdin */
939 if (strcmp(op
->tty
, "-") == 0) {
940 op
->tty_is_stdin
= 1;
941 int fd
= get_terminal_name(NULL
, &op
->tty
, NULL
);
943 log_warn(_("could not get terminal name: %d"), fd
);
947 /* On virtual console remember the line which is used for */
948 if (strncmp(op
->tty
, "tty", 3) == 0 &&
949 strspn(op
->tty
+ 3, "0123456789") == strlen(op
->tty
+3))
950 op
->vcline
= op
->tty
+3;
952 if (argc
> optind
&& argv
[optind
])
953 op
->term
= argv
[optind
];
955 debug("exiting parseargs\n");
958 /* Parse alternate baud rates. */
959 static void parse_speeds(struct options
*op
, char *arg
)
962 char *str
= strdup(arg
);
965 log_err(_("failed to allocate memory: %m"));
967 debug("entered parse_speeds:\n");
968 for (cp
= strtok(str
, ","); cp
!= NULL
; cp
= strtok((char *)0, ",")) {
969 if ((op
->speeds
[op
->numspeed
++] = bcode(cp
)) <= 0)
970 log_err(_("bad speed: %s"), cp
);
971 if (op
->numspeed
>= MAX_SPEED
)
972 log_err(_("too many alternate speeds"));
974 debug("exiting parsespeeds\n");
980 /* Update our utmp entry. */
981 static void update_utmp(struct options
*op
)
985 pid_t pid
= getpid();
986 pid_t sid
= getsid(0);
987 const char *vcline
= op
->vcline
;
988 const char *line
= op
->tty
;
992 * The utmp file holds miscellaneous information about things started by
993 * /sbin/init and other system-related events. Our purpose is to update
994 * the utmp entry for the current process, in particular the process type
995 * and the tty line we are listening to. Return successfully only if the
996 * utmp file can be opened for update, and if we are able to find our
997 * entry in the utmp file.
999 utmpxname(_PATH_UTMP
);
1003 * Find my pid in utmp.
1005 * FIXME: Earlier (when was that?) code here tested only utp->ut_type !=
1006 * INIT_PROCESS, so maybe the >= here should be >.
1008 * FIXME: The present code is taken from login.c, so if this is changed,
1009 * maybe login has to be changed as well (is this true?).
1011 while ((utp
= getutxent()))
1012 if (utp
->ut_pid
== pid
1013 && utp
->ut_type
>= INIT_PROCESS
1014 && utp
->ut_type
<= DEAD_PROCESS
)
1018 memcpy(&ut
, utp
, sizeof(ut
));
1020 /* Some inits do not initialize utmp. */
1021 memset(&ut
, 0, sizeof(ut
));
1022 if (vcline
&& *vcline
)
1023 /* Standard virtual console devices */
1024 str2memcpy(ut
.ut_id
, vcline
, sizeof(ut
.ut_id
));
1026 size_t len
= strlen(line
);
1028 if (len
>= sizeof(ut
.ut_id
))
1029 ptr
= line
+ len
- sizeof(ut
.ut_id
);
1032 str2memcpy(ut
.ut_id
, ptr
, sizeof(ut
.ut_id
));
1036 str2memcpy(ut
.ut_user
, "LOGIN", sizeof(ut
.ut_user
));
1037 str2memcpy(ut
.ut_line
, line
, sizeof(ut
.ut_line
));
1039 str2memcpy(ut
.ut_host
, fakehost
, sizeof(ut
.ut_host
));
1041 ut
.ut_tv
.tv_sec
= t
;
1042 ut
.ut_type
= LOGIN_PROCESS
;
1044 ut
.ut_session
= sid
;
1049 updwtmpx(_PATH_WTMP
, &ut
);
1052 #endif /* SYSV_STYLE */
1054 /* Set up tty as stdin, stdout & stderr. */
1055 static void open_tty(const char *tty
, struct termios
*tp
, struct options
*op
)
1057 const pid_t pid
= getpid();
1063 /* Set up new standard input, unless we are given an already opened port. */
1065 if (!op
->tty_is_stdin
) {
1066 char buf
[PATH_MAX
+1];
1067 struct group
*gr
= NULL
;
1073 /* Use tty group if available */
1074 if ((gr
= getgrnam("tty")))
1077 len
= snprintf(buf
, sizeof(buf
), "/dev/%s", tty
);
1078 if (len
< 0 || (size_t)len
>= sizeof(buf
))
1079 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1081 /* Open the tty as standard input. */
1082 if ((fd
= open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0)) < 0)
1083 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1086 * There is always a race between this reset and the call to
1087 * vhangup() that s.o. can use to get access to your tty.
1088 * Linux login(1) will change tty permissions. Use root owner and group
1089 * with permission -rw------- for the period between getty and login.
1091 if (fchown(fd
, 0, gid
) || fchmod(fd
, (gid
? 0620 : 0600))) {
1093 log_warn("%s: %m", buf
);
1095 log_err("%s: %m", buf
);
1098 /* Sanity checks... */
1099 if (fstat(fd
, &st
) < 0)
1100 log_err("%s: %m", buf
);
1101 if ((st
.st_mode
& S_IFMT
) != S_IFCHR
)
1102 log_err(_("/dev/%s: not a character device"), tty
);
1104 log_err(_("/dev/%s: not a tty"), tty
);
1106 if (((tid
= tcgetsid(fd
)) < 0) || (pid
!= tid
)) {
1107 if (ioctl(fd
, TIOCSCTTY
, 1) == -1)
1108 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1111 close(STDIN_FILENO
);
1114 if (op
->flags
& F_HANGUP
) {
1116 if (ioctl(fd
, TIOCNOTTY
))
1117 debug("TIOCNOTTY ioctl failed\n");
1120 * Let's close all file descriptors before vhangup
1121 * https://lkml.org/lkml/2012/6/5/145
1124 close(STDOUT_FILENO
);
1125 close(STDERR_FILENO
);
1130 log_err(_("/dev/%s: vhangup() failed: %m"), tty
);
1135 if (open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0) != 0)
1136 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1138 if (((tid
= tcgetsid(STDIN_FILENO
)) < 0) || (pid
!= tid
)) {
1139 if (ioctl(STDIN_FILENO
, TIOCSCTTY
, 1) == -1)
1140 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1146 * Standard input should already be connected to an open port. Make
1147 * sure it is open for read/write.
1150 if ((fcntl(STDIN_FILENO
, F_GETFL
, 0) & O_RDWR
) != O_RDWR
)
1151 log_err(_("%s: not open for read/write"), tty
);
1155 if (tcsetpgrp(STDIN_FILENO
, pid
))
1156 log_warn(_("/dev/%s: cannot set process group: %m"), tty
);
1158 /* Get rid of the present outputs. */
1160 close(STDOUT_FILENO
);
1161 close(STDERR_FILENO
);
1165 /* Set up standard output and standard error file descriptors. */
1168 /* set up stdout and stderr */
1169 if (dup(STDIN_FILENO
) != 1 || dup(STDIN_FILENO
) != 2)
1170 log_err(_("%s: dup problem: %m"), tty
);
1172 /* make stdio unbuffered for slow modem lines */
1173 setvbuf(stdout
, NULL
, _IONBF
, 0);
1176 * The following ioctl will fail if stdin is not a tty, but also when
1177 * there is noise on the modem control lines. In the latter case, the
1178 * common course of action is (1) fix your cables (2) give the modem
1179 * more time to properly reset after hanging up.
1181 * SunOS users can achieve (2) by patching the SunOS kernel variable
1182 * "zsadtrlow" to a larger value; 5 seconds seems to be a good value.
1183 * http://www.sunmanagers.org/archives/1993/0574.html
1185 memset(tp
, 0, sizeof(struct termios
));
1186 if (tcgetattr(STDIN_FILENO
, tp
) < 0)
1187 log_err(_("%s: failed to get terminal attributes: %m"), tty
);
1189 #ifdef HAVE_GETTTYNAM
1191 struct ttyent
*ent
= getttynam(tty
);
1192 /* a bit nasty as it's never freed */
1193 if (ent
&& ent
->ty_type
) {
1194 op
->term
= strdup(ent
->ty_type
);
1196 log_err(_("failed to allocate memory: %m"));
1201 #if defined (__s390__) || defined (__s390x__)
1204 * Special terminal on first serial line on a S/390(x) which
1205 * is due legacy reasons a block terminal of type 3270 or
1206 * higher. Whereas the second serial line on a S/390(x) is
1207 * a real character terminal which is compatible with VT220.
1209 if (strcmp(op
->tty
, "ttyS0") == 0) /* linux/drivers/s390/char/con3215.c */
1210 op
->term
= DEFAULT_TTYS0
;
1211 else if (strncmp(op
->tty
, "3270/tty", 8) == 0) /* linux/drivers/s390/char/con3270.c */
1212 op
->term
= DEFAULT_TTY32
;
1213 else if (strcmp(op
->tty
, "ttyS1") == 0) /* linux/drivers/s390/char/sclp_vt220.c */
1214 op
->term
= DEFAULT_TTYS1
;
1218 #if defined(__FreeBSD_kernel__)
1223 * Detect if this is a virtual console or serial/modem line.
1224 * In case of a virtual console the ioctl KDGKBMODE succeeds
1225 * whereas on other lines it will fails.
1228 if (ioctl(STDIN_FILENO
, KDGKBMODE
, &op
->kbmode
) == 0)
1230 if (ioctl(STDIN_FILENO
, TIOCMGET
, &serial
) < 0 && (errno
== EINVAL
))
1233 op
->flags
|= F_VCONSOLE
;
1235 op
->term
= DEFAULT_VCTERM
;
1241 op
->term
= DEFAULT_STERM
;
1244 if (setenv("TERM", op
->term
, 1) != 0)
1245 log_err(_("failed to set the %s environment variable"), "TERM");
1248 /* Initialize termios settings. */
1249 static void termio_clear(int fd
)
1252 * Do not write a full reset (ESC c) because this destroys
1253 * the unicode mode again if the terminal was in unicode
1254 * mode. Also it clears the CONSOLE_MAGIC features which
1255 * are required for some languages/console-fonts.
1256 * Just put the cursor to the home position (ESC [ H),
1257 * erase everything below the cursor (ESC [ J), and set the
1258 * scrolling region to the full window (ESC [ r)
1260 write_all(fd
, "\033[r\033[H\033[J", 9);
1263 /* Initialize termios settings. */
1264 static void termio_init(struct options
*op
, struct termios
*tp
)
1266 speed_t ispeed
, ospeed
;
1268 #ifdef USE_PLYMOUTH_SUPPORT
1269 struct termios lock
;
1270 int i
= (plymouth_command(MAGIC_PING
) == 0) ? PLYMOUTH_TERMIOS_FLAGS_DELAY
: 0;
1272 plymouth_command(MAGIC_QUIT
);
1275 * Even with TTYReset=no it seems with systemd or plymouth
1276 * the termios flags become changed from under the first
1277 * agetty on a serial system console as the flags are locked.
1279 memset(&lock
, 0, sizeof(struct termios
));
1280 if (ioctl(STDIN_FILENO
, TIOCGLCKTRMIOS
, &lock
) < 0)
1282 if (!lock
.c_iflag
&& !lock
.c_oflag
&& !lock
.c_cflag
&& !lock
.c_lflag
)
1284 debug("termios locked\n");
1287 memset(&lock
, 0, sizeof(struct termios
));
1288 ioctl(STDIN_FILENO
, TIOCSLCKTRMIOS
, &lock
);
1291 if (op
->flags
& F_VCONSOLE
) {
1292 #if defined(IUTF8) && defined(KDGKBMODE)
1293 switch(op
->kbmode
) {
1295 setlocale(LC_CTYPE
, "C.UTF-8");
1296 op
->flags
|= F_UTF8
;
1302 setlocale(LC_CTYPE
, "POSIX");
1303 op
->flags
&= ~F_UTF8
;
1307 setlocale(LC_CTYPE
, "POSIX");
1308 op
->flags
&= ~F_UTF8
;
1310 reset_vc(op
, tp
, 0);
1312 if ((tp
->c_cflag
& (CS8
|PARODD
|PARENB
)) == CS8
)
1313 op
->flags
|= F_EIGHTBITS
;
1315 if ((op
->flags
& F_NOCLEAR
) == 0)
1316 termio_clear(STDOUT_FILENO
);
1324 if (op
->flags
& F_KEEPSPEED
|| !op
->numspeed
) {
1325 /* Save the original setting. */
1326 ispeed
= cfgetispeed(tp
);
1327 ospeed
= cfgetospeed(tp
);
1329 /* Save also the original speed to array of the speeds to make
1330 * it possible to return the original after unexpected BREAKs.
1333 op
->speeds
[op
->numspeed
++] = ispeed
? ispeed
:
1337 ispeed
= TTYDEF_SPEED
;
1339 ospeed
= TTYDEF_SPEED
;
1341 ospeed
= ispeed
= op
->speeds
[FIRST_SPEED
];
1345 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
1346 * Special characters are set after we have read the login name; all
1347 * reads will be done in raw mode anyway. Errors will be dealt with
1351 /* The default is set c_iflag in termio_final() according to chardata.
1352 * Unfortunately, the chardata are not set according to the serial line
1353 * if --autolog is enabled. In this case we do not read from the line
1354 * at all. The best what we can do in this case is to keep c_iflag
1355 * unmodified for --autolog.
1359 tp
->c_iflag
= tp
->c_iflag
& IUTF8
;
1360 if (tp
->c_iflag
& IUTF8
)
1361 op
->flags
|= F_UTF8
;
1368 tp
->c_oflag
&= OPOST
| ONLCR
;
1370 if ((op
->flags
& F_KEEPCFLAGS
) == 0)
1371 tp
->c_cflag
= CS8
| HUPCL
| CREAD
| (tp
->c_cflag
& CLOCAL
);
1374 * Note that the speed is stored in the c_cflag termios field, so we have
1375 * set the speed always when the cflag is reset.
1377 cfsetispeed(tp
, ispeed
);
1378 cfsetospeed(tp
, ospeed
);
1380 /* The default is to follow setting from kernel, but it's possible
1381 * to explicitly remove/add CLOCAL flag by -L[=<mode>]*/
1382 switch (op
->clocal
) {
1383 case CLOCAL_MODE_ALWAYS
:
1384 tp
->c_cflag
|= CLOCAL
; /* -L or -L=always */
1386 case CLOCAL_MODE_NEVER
:
1387 tp
->c_cflag
&= ~CLOCAL
; /* -L=never */
1389 case CLOCAL_MODE_AUTO
: /* -L=auto */
1393 #ifdef HAVE_STRUCT_TERMIOS_C_LINE
1397 tp
->c_cc
[VTIME
] = 0;
1399 /* Check for terminal size and if not found set default */
1400 if (ioctl(STDIN_FILENO
, TIOCGWINSZ
, &ws
) == 0) {
1405 if (ioctl(STDIN_FILENO
, TIOCSWINSZ
, &ws
))
1406 debug("TIOCSWINSZ ioctl failed\n");
1409 /* Optionally enable hardware flow control. */
1411 if (op
->flags
& F_RTSCTS
)
1412 tp
->c_cflag
|= CRTSCTS
;
1414 /* Flush input and output queues, important for modems! */
1415 tcflush(STDIN_FILENO
, TCIOFLUSH
);
1417 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
))
1418 log_warn(_("setting terminal attributes failed: %m"));
1420 /* Go to blocking input even in local mode. */
1421 fcntl(STDIN_FILENO
, F_SETFL
,
1422 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1424 debug("term_io 2\n");
1427 /* Reset virtual console on stdin to its defaults */
1428 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
)
1432 fl
|= (op
->flags
& F_KEEPCFLAGS
) == 0 ? 0 : UL_TTY_KEEPCFLAGS
;
1433 fl
|= (op
->flags
& F_UTF8
) == 0 ? 0 : UL_TTY_UTF8
;
1435 reset_virtual_console(tp
, fl
);
1437 #ifdef AGETTY_RELOAD
1439 * Discard all the flags that makes the line go canonical with echoing.
1440 * We need to know when the user starts typing.
1446 if (tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
))
1447 log_warn(_("setting terminal attributes failed: %m"));
1449 /* Go to blocking input even in local mode. */
1450 fcntl(STDIN_FILENO
, F_SETFL
,
1451 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1454 /* Extract baud rate from modem status message. */
1455 static void auto_baud(struct termios
*tp
)
1465 * This works only if the modem produces its status code AFTER raising
1466 * the DCD line, and if the computer is fast enough to set the proper
1467 * baud rate before the message has gone by. We expect a message of the
1470 * <junk><number><junk>
1472 * The number is interpreted as the baud rate of the incoming call. If the
1473 * modem does not tell us the baud rate within one second, we will keep
1474 * using the current baud rate. It is advisable to enable BREAK
1475 * processing (comma-separated list of baud rates) if the processing of
1476 * modem status messages is enabled.
1480 * Use 7-bit characters, don't block if input queue is empty. Errors will
1481 * be dealt with later on.
1483 iflag
= tp
->c_iflag
;
1484 /* Enable 8th-bit stripping. */
1485 tp
->c_iflag
|= ISTRIP
;
1486 vmin
= tp
->c_cc
[VMIN
];
1487 /* Do not block when queue is empty. */
1489 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1492 * Wait for a while, then read everything the modem has said so far and
1493 * try to extract the speed of the dial-in call.
1496 if ((nread
= read(STDIN_FILENO
, buf
, sizeof(buf
) - 1)) > 0) {
1498 for (bp
= buf
; bp
< buf
+ nread
; bp
++)
1499 if (c_isascii(*bp
) && isdigit(*bp
)) {
1500 if ((speed
= bcode(bp
))) {
1501 cfsetispeed(tp
, speed
);
1502 cfsetospeed(tp
, speed
);
1508 /* Restore terminal settings. Errors will be dealt with later on. */
1509 tp
->c_iflag
= iflag
;
1510 tp
->c_cc
[VMIN
] = vmin
;
1511 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1514 static char *xgethostname(void)
1517 size_t sz
= get_hostname_max() + 1;
1519 name
= malloc(sizeof(char) * sz
);
1521 log_err(_("failed to allocate memory: %m"));
1523 if (gethostname(name
, sz
) != 0) {
1527 name
[sz
- 1] = '\0';
1531 static char *xgetdomainname(void)
1533 #ifdef HAVE_GETDOMAINNAME
1535 const size_t sz
= get_hostname_max() + 1;
1537 name
= malloc(sizeof(char) * sz
);
1539 log_err(_("failed to allocate memory: %m"));
1541 if (getdomainname(name
, sz
) != 0) {
1545 name
[sz
- 1] = '\0';
1553 static char *read_os_release(struct options
*op
, const char *varname
)
1557 size_t varsz
= strlen(varname
);
1558 char *p
, *buf
= NULL
, *ret
= NULL
;
1560 /* read the file only once */
1561 if (!op
->osrelease
) {
1562 fd
= open(_PATH_OS_RELEASE_ETC
, O_RDONLY
);
1564 fd
= open(_PATH_OS_RELEASE_USR
, O_RDONLY
);
1566 log_warn(_("cannot open os-release file"));
1571 if (fstat(fd
, &st
) < 0 || st
.st_size
> 4 * 1024 * 1024)
1574 op
->osrelease
= malloc(st
.st_size
+ 1);
1576 log_err(_("failed to allocate memory: %m"));
1577 if (read_all(fd
, op
->osrelease
, st
.st_size
) != (ssize_t
) st
.st_size
) {
1578 free(op
->osrelease
);
1579 op
->osrelease
= NULL
;
1582 op
->osrelease
[st
.st_size
] = 0;
1584 buf
= strdup(op
->osrelease
);
1586 log_err(_("failed to allocate memory: %m"));
1592 p
+= strspn(p
, "\n\r");
1593 p
+= strspn(p
, " \t\n\r");
1596 if (strspn(p
, "#;\n") != 0) {
1597 p
+= strcspn(p
, "\n\r");
1600 if (strncmp(p
, varname
, varsz
) != 0) {
1601 p
+= strcspn(p
, "\n\r");
1605 p
+= strspn(p
, " \t\n\r");
1610 p
+= strspn(p
, " \t\n\r=\"");
1611 eol
= p
+ strcspn(p
, "\n\r");
1615 if (*eon
== '\t' || *eon
== ' ') {
1628 log_err(_("failed to allocate memory: %m"));
1638 #ifdef AGETTY_RELOAD
1639 static void open_netlink(void)
1641 struct sockaddr_nl addr
= { 0, };
1644 if (netlink_fd
!= AGETTY_RELOAD_FDNONE
)
1647 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
1649 addr
.nl_family
= AF_NETLINK
;
1650 addr
.nl_pid
= getpid();
1651 addr
.nl_groups
= netlink_groups
;
1652 if (bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) < 0)
1659 static int process_netlink_msg(int *triggered
)
1662 struct sockaddr_nl snl
;
1666 struct iovec iov
= {
1668 .iov_len
= sizeof(buf
)
1670 struct msghdr msg
= {
1672 .msg_namelen
= sizeof(snl
),
1675 .msg_control
= NULL
,
1676 .msg_controllen
= 0,
1680 rc
= recvmsg(netlink_fd
, &msg
, MSG_DONTWAIT
);
1682 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1685 /* Failure, just stop listening for changes */
1687 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1691 for (h
= (struct nlmsghdr
*)buf
; NLMSG_OK(h
, (unsigned int)rc
); h
= NLMSG_NEXT(h
, rc
)) {
1692 if (h
->nlmsg_type
== NLMSG_DONE
||
1693 h
->nlmsg_type
== NLMSG_ERROR
) {
1695 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1706 static int process_netlink(void)
1709 while (process_netlink_msg(&triggered
));
1713 static int wait_for_term_input(int fd
)
1715 char buffer
[sizeof(struct inotify_event
) + NAME_MAX
+ 1];
1718 if (inotify_fd
== AGETTY_RELOAD_FDNONE
) {
1719 /* make sure the reload trigger file exists */
1720 int reload_fd
= open(AGETTY_RELOAD_FILENAME
,
1721 O_CREAT
|O_CLOEXEC
|O_RDONLY
,
1724 /* initialize reload trigger inotify stuff */
1725 if (reload_fd
>= 0) {
1726 inotify_fd
= inotify_init1(IN_NONBLOCK
| IN_CLOEXEC
);
1728 inotify_add_watch(inotify_fd
, AGETTY_RELOAD_FILENAME
,
1729 IN_ATTRIB
| IN_MODIFY
);
1733 log_warn(_("failed to create reload file: %s: %m"),
1734 AGETTY_RELOAD_FILENAME
);
1743 if (inotify_fd
>= 0) {
1744 FD_SET(inotify_fd
, &rfds
);
1745 nfds
= max(nfds
, inotify_fd
);
1747 if (netlink_fd
>= 0) {
1748 FD_SET(netlink_fd
, &rfds
);
1749 nfds
= max(nfds
, netlink_fd
);
1752 /* If waiting fails, just fall through, presumably reading input will fail */
1753 if (select(nfds
+ 1, &rfds
, NULL
, NULL
, NULL
) < 0)
1756 if (FD_ISSET(fd
, &rfds
)) {
1761 if (netlink_fd
>= 0 && FD_ISSET(netlink_fd
, &rfds
)) {
1762 if (!process_netlink())
1765 /* Just drain the inotify buffer */
1766 } else if (inotify_fd
>= 0 && FD_ISSET(inotify_fd
, &rfds
)) {
1767 while (read(inotify_fd
, buffer
, sizeof (buffer
)) > 0);
1773 #endif /* AGETTY_RELOAD */
1775 #ifdef ISSUEDIR_SUPPORT
1776 static int issuedir_filter(const struct dirent
*d
)
1780 #ifdef _DIRENT_HAVE_D_TYPE
1781 if (d
->d_type
!= DT_UNKNOWN
&& d
->d_type
!= DT_REG
&&
1782 d
->d_type
!= DT_LNK
)
1785 if (*d
->d_name
== '.')
1788 namesz
= strlen(d
->d_name
);
1789 if (!namesz
|| namesz
< ISSUEDIR_EXTSIZ
+ 1 ||
1790 strcmp(d
->d_name
+ (namesz
- ISSUEDIR_EXTSIZ
), ISSUEDIR_EXT
) != 0)
1798 static int issuefile_read_stream(struct issue
*ie
, FILE *f
, struct options
*op
, struct termios
*tp
);
1800 /* returns: 0 on success, 1 cannot open, <0 on error
1802 static int issuedir_read(struct issue
*ie
, const char *dirname
,
1803 struct options
*op
, struct termios
*tp
)
1806 struct dirent
**namelist
= NULL
;
1808 dd
= open(dirname
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
1812 nfiles
= scandirat(dd
, ".", &namelist
, issuedir_filter
, versionsort
);
1816 ie
->do_tcsetattr
= 1;
1818 for (i
= 0; i
< nfiles
; i
++) {
1819 struct dirent
*d
= namelist
[i
];
1822 f
= fopen_at(dd
, d
->d_name
, O_RDONLY
|O_CLOEXEC
, "r" UL_CLOEXECSTR
);
1824 issuefile_read_stream(ie
, f
, op
, tp
);
1829 for (i
= 0; i
< nfiles
; i
++)
1837 #else /* !ISSUEDIR_SUPPORT */
1838 static int issuedir_read(struct issue
*ie
__attribute__((__unused__
)),
1839 const char *dirname
__attribute__((__unused__
)),
1840 struct options
*op
__attribute__((__unused__
)),
1841 struct termios
*tp
__attribute__((__unused__
)))
1845 #endif /* ISSUEDIR_SUPPORT */
1847 #ifndef ISSUE_SUPPORT
1848 static void print_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1850 struct termios
*tp
__attribute__((__unused__
)))
1852 if ((op
->flags
& F_NONL
) == 0) {
1853 /* Issue not in use, start with a new line. */
1854 write_all(STDOUT_FILENO
, "\r\n", 2);
1858 static void eval_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1859 struct options
*op
__attribute__((__unused__
)),
1860 struct termios
*tp
__attribute__((__unused__
)))
1864 static void show_issue(struct options
*op
__attribute__((__unused__
)))
1868 #else /* ISSUE_SUPPORT */
1870 static int issuefile_read_stream(
1871 struct issue
*ie
, FILE *f
,
1872 struct options
*op
, struct termios
*tp
)
1877 if (fstat(fileno(f
), &st
) || !S_ISREG(st
.st_mode
))
1884 ie
->output
= open_memstream(&ie
->mem
, &ie
->mem_sz
);
1887 while ((c
= getc(f
)) != EOF
) {
1889 output_special_char(ie
, getc(f
), op
, tp
, f
);
1891 putc(c
, ie
->output
);
1897 static int issuefile_read(
1898 struct issue
*ie
, const char *filename
,
1899 struct options
*op
, struct termios
*tp
)
1901 FILE *f
= fopen(filename
, "r" UL_CLOEXECSTR
);
1905 rc
= issuefile_read_stream(ie
, f
, op
, tp
);
1912 #ifdef AGETTY_RELOAD
1913 static int issue_is_changed(struct issue
*ie
)
1915 if (ie
->mem_old
&& ie
->mem
1916 && strcmp(ie
->mem_old
, ie
->mem
) == 0) {
1918 ie
->mem_old
= ie
->mem
;
1927 static void print_issue_file(struct issue
*ie
,
1931 int oflag
= tp
->c_oflag
; /* Save current setting. */
1933 if ((op
->flags
& F_NONL
) == 0) {
1934 /* Issue not in use, start with a new line. */
1935 write_all(STDOUT_FILENO
, "\r\n", 2);
1938 if (ie
->do_tcsetattr
) {
1939 if ((op
->flags
& F_VCONSOLE
) == 0) {
1940 /* Map new line in output to carriage return & new line. */
1941 tp
->c_oflag
|= (ONLCR
| OPOST
);
1942 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1947 write_all(STDOUT_FILENO
, ie
->mem
, ie
->mem_sz
);
1949 if (ie
->do_tcrestore
) {
1950 /* Restore settings. */
1951 tp
->c_oflag
= oflag
;
1952 /* Wait till output is gone. */
1953 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1956 #ifdef AGETTY_RELOAD
1958 ie
->mem_old
= ie
->mem
;
1968 static void eval_issue_file(struct issue
*ie
,
1974 #ifdef AGETTY_RELOAD
1977 if (!(op
->flags
& F_ISSUE
))
1980 * The custom issue file or directory list specified by:
1981 * agetty --isue-file <path[:path]...>
1982 * Note that nothing is printed if the file/dir does not exist.
1985 char *list
= strdup(op
->issue
);
1989 log_err(_("failed to allocate memory: %m"));
1991 for (file
= strtok(list
, ":"); file
; file
= strtok(NULL
, ":")) {
1994 if (stat(file
, &st
) < 0)
1996 if (S_ISDIR(st
.st_mode
))
1997 issuedir_read(ie
, file
, op
, tp
);
1999 issuefile_read(ie
, file
, op
, tp
);
2005 /* The default /etc/issue and optional /etc/issue.d directory as
2006 * extension to the file. The /etc/issue.d directory is ignored if
2007 * there is no /etc/issue file. The file may be empty or symlink.
2009 if (access(_PATH_ISSUE
, F_OK
|R_OK
) == 0) {
2010 issuefile_read(ie
, _PATH_ISSUE
, op
, tp
);
2011 issuedir_read(ie
, _PATH_ISSUEDIR
, op
, tp
);
2015 /* Fallback @runstatedir (usually /run) -- the file is not required to
2018 if (issuefile_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
) == 0)
2020 if (issuedir_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
) == 0)
2025 /* Fallback @sysconfstaticdir (usually /usr/lib) -- the file is not
2026 * required to read the dir
2028 issuefile_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
);
2029 issuedir_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
);
2033 #ifdef AGETTY_RELOAD
2034 if (netlink_groups
!= 0)
2043 /* This is --show-issue backend, executed by normal user on the current
2046 static void show_issue(struct options
*op
)
2048 struct issue ie
= { .output
= NULL
};
2051 memset(&tp
, 0, sizeof(struct termios
));
2052 if (tcgetattr(STDIN_FILENO
, &tp
) < 0)
2053 err(EXIT_FAILURE
, _("failed to get terminal attributes: %m"));
2055 eval_issue_file(&ie
, op
, &tp
);
2058 write_all(STDOUT_FILENO
, ie
.mem
, ie
.mem_sz
);
2064 #endif /* ISSUE_SUPPORT */
2066 /* Show login prompt, optionally preceded by /etc/issue contents. */
2067 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
)
2069 #ifdef AGETTY_RELOAD
2072 print_issue_file(ie
, op
, tp
);
2074 if (op
->flags
& F_LOGINPAUSE
) {
2075 puts(_("[press ENTER to login]"));
2076 #ifdef AGETTY_RELOAD
2078 if (!wait_for_term_input(STDIN_FILENO
)) {
2079 eval_issue_file(ie
, op
, tp
);
2080 if (issue_is_changed(ie
)) {
2081 if (op
->flags
& F_VCONSOLE
)
2082 termio_clear(STDOUT_FILENO
);
2090 if (!(op
->flags
& F_NOHINTS
) && !op
->autolog
&&
2091 (op
->flags
& F_VCONSOLE
)) {
2094 if (ioctl(STDIN_FILENO
, KDGKBLED
, &kb
) == 0) {
2095 char hint
[256] = { '\0' };
2098 if (access(_PATH_NUMLOCK_ON
, F_OK
) == 0)
2101 if (nl
&& (kb
& 0x02) == 0)
2102 append(hint
, sizeof(hint
), NULL
, _("Num Lock off"));
2104 else if (nl
== 0 && (kb
& 2) && (kb
& 0x20) == 0)
2105 append(hint
, sizeof(hint
), NULL
, _("Num Lock on"));
2107 if ((kb
& 0x04) && (kb
& 0x40) == 0)
2108 append(hint
, sizeof(hint
), ", ", _("Caps Lock on"));
2110 if ((kb
& 0x01) && (kb
& 0x10) == 0)
2111 append(hint
, sizeof(hint
), ", ", _("Scroll Lock on"));
2114 printf(_("Hint: %s\n\n"), hint
);
2117 #endif /* KDGKBLED */
2118 if ((op
->flags
& F_NOHOSTNAME
) == 0) {
2119 char *hn
= xgethostname();
2122 char *dot
= strchr(hn
, '.');
2124 struct addrinfo
*res
= NULL
;
2126 if ((op
->flags
& F_LONGHNAME
) == 0) {
2130 } else if (dot
== NULL
) {
2131 struct addrinfo hints
;
2133 memset(&hints
, 0, sizeof(hints
));
2134 hints
.ai_flags
= AI_CANONNAME
;
2136 if (!getaddrinfo(hn
, NULL
, &hints
, &res
)
2137 && res
&& res
->ai_canonname
)
2138 cn
= res
->ai_canonname
;
2141 write_all(STDOUT_FILENO
, cn
, strlen(cn
));
2142 write_all(STDOUT_FILENO
, " ", 1);
2150 /* Always show login prompt. */
2151 write_all(STDOUT_FILENO
, LOGIN_PROMPT
,
2152 sizeof(LOGIN_PROMPT
) - 1);
2156 /* Select next baud rate. */
2157 static void next_speed(struct options
*op
, struct termios
*tp
)
2159 static int baud_index
= -1;
2161 if (baud_index
== -1)
2163 * If the F_KEEPSPEED flags is set then the FIRST_SPEED is not
2164 * tested yet (see termio_init()).
2167 (op
->flags
& F_KEEPSPEED
) ? FIRST_SPEED
: 1 % op
->numspeed
;
2169 baud_index
= (baud_index
+ 1) % op
->numspeed
;
2171 cfsetispeed(tp
, op
->speeds
[baud_index
]);
2172 cfsetospeed(tp
, op
->speeds
[baud_index
]);
2173 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
2176 /* Get user name, establish parity, speed, erase, kill & eol. */
2177 static char *get_logname(struct issue
*ie
, struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2179 static char logname
[BUFSIZ
];
2181 char c
; /* input character, full eight bits */
2182 char ascval
; /* low 7 bits of input character */
2184 static char *erase
[] = { /* backspace-space-backspace */
2185 "\010\040\010", /* space parity */
2186 "\010\040\010", /* odd parity */
2187 "\210\240\210", /* even parity */
2188 "\210\240\210", /* no parity */
2191 /* Initialize kill, erase, parity etc. (also after switching speeds). */
2195 * Flush pending input (especially important after parsing or switching
2198 if ((op
->flags
& F_VCONSOLE
) == 0)
2200 tcflush(STDIN_FILENO
, TCIFLUSH
);
2202 eightbit
= (op
->flags
& (F_EIGHTBITS
|F_UTF8
));
2206 eval_issue_file(ie
, op
, tp
);
2207 while (*logname
== '\0') {
2208 /* Write issue file and prompt */
2209 do_prompt(ie
, op
, tp
);
2212 #ifdef AGETTY_RELOAD
2213 if (!wait_for_term_input(STDIN_FILENO
)) {
2214 /* refresh prompt -- discard input data, clear terminal
2215 * and call do_prompt() again
2217 if ((op
->flags
& F_VCONSOLE
) == 0)
2219 eval_issue_file(ie
, op
, tp
);
2220 if (!issue_is_changed(ie
))
2222 tcflush(STDIN_FILENO
, TCIFLUSH
);
2223 if (op
->flags
& F_VCONSOLE
)
2224 termio_clear(STDOUT_FILENO
);
2232 /* Read name, watch for break and end-of-line. */
2233 while (cp
->eol
== '\0') {
2238 debug("read from FD\n");
2239 readres
= read(STDIN_FILENO
, &c
, 1);
2241 debug("read failed\n");
2243 /* The terminal could be open with O_NONBLOCK when
2244 * -L (force CLOCAL) is specified... */
2245 if (errno
== EINTR
|| errno
== EAGAIN
) {
2255 exit_slowly(EXIT_SUCCESS
);
2257 log_err(_("%s: read: %m"), op
->tty
);
2264 /* Do parity bit handling. */
2267 else if (c
!= (ascval
= (c
& 0177))) {
2268 uint32_t bits
; /* # of "1" bits per character */
2269 uint32_t mask
; /* mask with 1 bit up */
2270 for (bits
= 1, mask
= 1; mask
& 0177; mask
<<= 1) {
2274 cp
->parity
|= ((bits
& 1) ? 1 : 2);
2277 if (op
->killchars
&& strchr(op
->killchars
, ascval
))
2279 else if (op
->erasechars
&& strchr(op
->erasechars
, ascval
))
2284 /* Do erase, kill and end-of-line processing. */
2288 if (op
->numspeed
> 1 && !(op
->flags
& F_VCONSOLE
))
2291 exit_slowly(EXIT_SUCCESS
);
2295 *bp
= 0; /* terminate logname */
2296 cp
->eol
= ascval
; /* set end-of-line char */
2300 cp
->erase
= ascval
; /* set erase character */
2302 if ((tp
->c_lflag
& ECHO
) == 0)
2303 write_all(1, erase
[cp
->parity
], 3);
2308 cp
->kill
= ascval
; /* set kill character */
2311 if (key
== CTL('C') && !(op
->flags
& F_VCONSOLE
))
2312 /* Ignore CTRL+C on serial line */
2314 while (bp
> logname
) {
2315 if ((tp
->c_lflag
& ECHO
) == 0)
2316 write_all(1, erase
[cp
->parity
], 3);
2323 if ((size_t)(bp
- logname
) >= sizeof(logname
) - 1)
2324 log_err(_("%s: input overrun"), op
->tty
);
2325 if ((tp
->c_lflag
& ECHO
) == 0)
2326 write_all(1, &c
, 1); /* echo the character */
2327 *bp
++ = ascval
; /* and store it */
2330 /* Everything was erased. */
2331 if (bp
== logname
&& cp
->eol
== '\0')
2336 #ifdef HAVE_WIDECHAR
2337 if ((op
->flags
& (F_EIGHTBITS
|F_UTF8
)) == (F_EIGHTBITS
|F_UTF8
)) {
2338 /* Check out UTF-8 multibyte characters */
2342 len
= mbstowcs((wchar_t *)0, logname
, 0);
2344 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2346 wcs
= malloc((len
+ 1) * sizeof(wchar_t));
2348 log_err(_("failed to allocate memory: %m"));
2350 len
= mbstowcs(wcs
, logname
, len
+ 1);
2352 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2356 const wint_t wc
= *wcp
++;
2358 log_err(_("%s: invalid character 0x%x in login name"), op
->tty
, wc
);
2363 if ((op
->flags
& F_LCUC
) && (cp
->capslock
= caps_lock(logname
))) {
2365 /* Handle names with upper case and no lower case. */
2366 for (bp
= logname
; *bp
; bp
++)
2368 *bp
= tolower(*bp
); /* map name to lower case */
2374 /* Set the final tty mode bits. */
2375 static void termio_final(struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2377 /* General terminal-independent stuff. */
2379 /* 2-way flow control */
2380 tp
->c_iflag
|= IXON
| IXOFF
;
2381 tp
->c_lflag
|= ICANON
| ISIG
| ECHO
| ECHOE
| ECHOK
| ECHOKE
;
2382 /* no longer| ECHOCTL | ECHOPRT */
2383 tp
->c_oflag
|= OPOST
;
2384 /* tp->c_cflag = 0; */
2385 tp
->c_cc
[VINTR
] = DEF_INTR
;
2386 tp
->c_cc
[VQUIT
] = DEF_QUIT
;
2387 tp
->c_cc
[VEOF
] = DEF_EOF
;
2388 tp
->c_cc
[VEOL
] = DEF_EOL
;
2390 tp
->c_cc
[VSWTC
] = DEF_SWITCH
;
2391 #elif defined(VSWTCH)
2392 tp
->c_cc
[VSWTCH
] = DEF_SWITCH
;
2393 #endif /* __linux__ */
2395 /* Account for special characters seen in input. */
2396 if (cp
->eol
== CR
) {
2397 tp
->c_iflag
|= ICRNL
;
2398 tp
->c_oflag
|= ONLCR
;
2400 tp
->c_cc
[VERASE
] = cp
->erase
;
2401 tp
->c_cc
[VKILL
] = cp
->kill
;
2403 /* Account for the presence or absence of parity bits in input. */
2404 switch (cp
->parity
) {
2406 /* space (always 0) parity */
2410 tp
->c_cflag
|= PARODD
;
2414 tp
->c_cflag
|= PARENB
;
2415 tp
->c_iflag
|= INPCK
| ISTRIP
;
2419 tp
->c_cflag
&= ~CSIZE
;
2423 /* Account for upper case without lower case. */
2426 tp
->c_iflag
|= IUCLC
;
2429 tp
->c_lflag
|= XCASE
;
2432 tp
->c_oflag
|= OLCUC
;
2435 /* Optionally enable hardware flow control. */
2437 if (op
->flags
& F_RTSCTS
)
2438 tp
->c_cflag
|= CRTSCTS
;
2441 /* Finally, make the new settings effective. */
2442 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
) < 0)
2443 log_err(_("%s: failed to set terminal attributes: %m"), op
->tty
);
2447 * String contains upper case without lower case.
2448 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=52940
2449 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=156242
2451 static int caps_lock(char *s
)
2455 for (capslock
= 0; *s
; s
++) {
2457 return EXIT_SUCCESS
;
2459 capslock
= isupper(*s
);
2464 /* Convert speed string to speed code; return 0 on failure. */
2465 static speed_t
bcode(char *s
)
2467 const struct Speedtab
*sp
;
2472 speed
= strtol(s
, &end
, 10);
2474 if (errno
|| !end
|| end
== s
)
2477 for (sp
= speedtab
; sp
->speed
; sp
++)
2478 if (sp
->speed
== speed
)
2483 static void __attribute__((__noreturn__
)) usage(void)
2487 fputs(USAGE_HEADER
, out
);
2488 fprintf(out
, _(" %1$s [options] <line> [<baud_rate>,...] [<termtype>]\n"
2489 " %1$s [options] <baud_rate>,... <line> [<termtype>]\n"), program_invocation_short_name
);
2491 fputs(USAGE_SEPARATOR
, out
);
2492 fputs(_("Open a terminal and set its mode.\n"), out
);
2494 fputs(USAGE_OPTIONS
, out
);
2495 fputs(_(" -8, --8bits assume 8-bit tty\n"), out
);
2496 fputs(_(" -a, --autologin <user> login the specified user automatically\n"), out
);
2497 fputs(_(" -c, --noreset do not reset control mode\n"), out
);
2498 fputs(_(" -E, --remote use -r <hostname> for login(1)\n"), out
);
2499 fputs(_(" -f, --issue-file <list> display issue files or directories\n"), out
);
2500 fputs(_(" --show-issue display issue file and exit\n"), out
);
2501 fputs(_(" -h, --flow-control enable hardware flow control\n"), out
);
2502 fputs(_(" -H, --host <hostname> specify login host\n"), out
);
2503 fputs(_(" -i, --noissue do not display issue file\n"), out
);
2504 fputs(_(" -I, --init-string <string> set init string\n"), out
);
2505 fputs(_(" -J --noclear do not clear the screen before prompt\n"), out
);
2506 fputs(_(" -l, --login-program <file> specify login program\n"), out
);
2507 fputs(_(" -L, --local-line[=<mode>] control the local line flag\n"), out
);
2508 fputs(_(" -m, --extract-baud extract baud rate during connect\n"), out
);
2509 fputs(_(" -n, --skip-login do not prompt for login\n"), out
);
2510 fputs(_(" -N --nonewline do not print a newline before issue\n"), out
);
2511 fputs(_(" -o, --login-options <opts> options that are passed to login\n"), out
);
2512 fputs(_(" -p, --login-pause wait for any key before the login\n"), out
);
2513 fputs(_(" -r, --chroot <dir> change root to the directory\n"), out
);
2514 fputs(_(" -R, --hangup do virtually hangup on the tty\n"), out
);
2515 fputs(_(" -s, --keep-baud try to keep baud rate after break\n"), out
);
2516 fputs(_(" -t, --timeout <number> login process timeout\n"), out
);
2517 fputs(_(" -U, --detect-case detect uppercase terminal\n"), out
);
2518 fputs(_(" -w, --wait-cr wait carriage-return\n"), out
);
2519 fputs(_(" --nohints do not print hints\n"), out
);
2520 fputs(_(" --nohostname no hostname at all will be shown\n"), out
);
2521 fputs(_(" --long-hostname show full qualified hostname\n"), out
);
2522 fputs(_(" --erase-chars <string> additional backspace chars\n"), out
);
2523 fputs(_(" --kill-chars <string> additional kill chars\n"), out
);
2524 fputs(_(" --chdir <directory> chdir before the login\n"), out
);
2525 fputs(_(" --delay <number> sleep seconds before prompt\n"), out
);
2526 fputs(_(" --nice <number> run login with this priority\n"), out
);
2527 fputs(_(" --reload reload prompts on running agetty instances\n"), out
);
2528 fputs(_(" --list-speeds display supported baud rates\n"), out
);
2529 printf( " --help %s\n", USAGE_OPTSTR_HELP
);
2530 printf( " --version %s\n", USAGE_OPTSTR_VERSION
);
2531 printf(USAGE_MAN_TAIL("agetty(8)"));
2536 static void list_speeds(void)
2538 const struct Speedtab
*sp
;
2540 for (sp
= speedtab
; sp
->speed
; sp
++)
2541 printf("%10ld\n", sp
->speed
);
2545 * Helper function reports errors to console or syslog.
2546 * Will be used by log_err() and log_warn() therefore
2547 * it takes a format as well as va_list.
2549 static void dolog(int priority
2551 __attribute__((__unused__
))
2553 , const char *fmt
, va_list ap
)
2557 * If the diagnostic is reported via syslog(3), the process name is
2558 * automatically prepended to the message. If we write directly to
2559 * /dev/console, we must prepend the process name ourselves.
2561 openlog(program_invocation_short_name
, LOG_PID
, LOG_AUTHPRIV
);
2562 vsyslog(priority
, fmt
, ap
);
2566 * Write the diagnostic directly to /dev/console if we do not use
2567 * the syslog(3) facility.
2570 char new_fmt
[BUFSIZ
];
2573 snprintf(new_fmt
, sizeof(new_fmt
), "%s: %s\r\n",
2574 program_invocation_short_name
, fmt
);
2575 /* Terminate with CR-LF since the console mode is unknown. */
2576 vsnprintf(buf
, sizeof(buf
), new_fmt
, ap
);
2578 if ((fd
= open("/dev/console", 1)) >= 0) {
2579 write_all(fd
, buf
, strlen(buf
));
2582 #endif /* USE_SYSLOG */
2585 static void exit_slowly(int code
)
2587 /* Be kind to init(8). */
2592 static void log_err(const char *fmt
, ...)
2597 dolog(LOG_ERR
, fmt
, ap
);
2600 exit_slowly(EXIT_FAILURE
);
2603 static void log_warn(const char *fmt
, ...)
2608 dolog(LOG_WARNING
, fmt
, ap
);
2612 static void print_addr(struct issue
*ie
, sa_family_t family
, void *addr
)
2614 char buff
[INET6_ADDRSTRLEN
+ 1];
2616 inet_ntop(family
, addr
, buff
, sizeof(buff
));
2617 fprintf(ie
->output
, "%s", buff
);
2621 * Prints IP for the specified interface (@iface), if the interface is not
2622 * specified then prints the "best" one (UP, RUNNING, non-LOOPBACK). If not
2623 * found the "best" interface then prints at least host IP.
2625 static void output_iface_ip(struct issue
*ie
,
2626 struct ifaddrs
*addrs
,
2631 struct addrinfo hints
, *info
= NULL
;
2638 for (p
= addrs
; p
; p
= p
->ifa_next
) {
2642 p
->ifa_addr
->sa_family
!= family
)
2646 /* Filter out by interface name */
2647 if (strcmp(p
->ifa_name
, iface
) != 0)
2650 /* Select the "best" interface */
2651 if ((p
->ifa_flags
& IFF_LOOPBACK
) ||
2652 !(p
->ifa_flags
& IFF_UP
) ||
2653 !(p
->ifa_flags
& IFF_RUNNING
))
2658 switch (p
->ifa_addr
->sa_family
) {
2660 addr
= &((struct sockaddr_in
*) p
->ifa_addr
)->sin_addr
;
2663 addr
= &((struct sockaddr_in6
*) p
->ifa_addr
)->sin6_addr
;
2668 print_addr(ie
, family
, addr
);
2676 /* Hmm.. not found the best interface, print host IP at least */
2677 memset(&hints
, 0, sizeof(hints
));
2678 hints
.ai_family
= family
;
2679 if (family
== AF_INET6
)
2680 hints
.ai_flags
= AI_V4MAPPED
;
2682 host
= xgethostname();
2683 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2684 switch (info
->ai_family
) {
2686 addr
= &((struct sockaddr_in
*) info
->ai_addr
)->sin_addr
;
2689 addr
= &((struct sockaddr_in6
*) info
->ai_addr
)->sin6_addr
;
2693 print_addr(ie
, family
, addr
);
2701 * parses \x{argument}, if not argument specified then returns NULL, the @fd
2702 * has to point to one char after the sequence (it means '{').
2704 static char *get_escape_argument(FILE *fd
, char *buf
, size_t bufsz
)
2709 if (c
== EOF
|| (unsigned char) c
!= '{') {
2718 if ((unsigned char) c
!= '}' && i
< bufsz
- 1)
2719 buf
[i
++] = (unsigned char) c
;
2721 } while ((unsigned char) c
!= '}');
2727 static void output_special_char(struct issue
*ie
,
2738 char escname
[UL_COLORNAME_MAXSZ
];
2740 if (get_escape_argument(fp
, escname
, sizeof(escname
))) {
2741 const char *esc
= color_sequence_from_colorname(escname
);
2743 fputs(esc
, ie
->output
);
2745 fputs("\033", ie
->output
);
2750 fprintf(ie
->output
, "%s", uts
.sysname
);
2754 fprintf(ie
->output
, "%s", uts
.nodename
);
2758 fprintf(ie
->output
, "%s", uts
.release
);
2762 fprintf(ie
->output
, "%s", uts
.version
);
2766 fprintf(ie
->output
, "%s", uts
.machine
);
2770 char *dom
= xgetdomainname();
2772 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2779 char *host
= xgethostname();
2780 struct addrinfo hints
, *info
= NULL
;
2782 memset(&hints
, 0, sizeof(hints
));
2783 hints
.ai_flags
= AI_CANONNAME
;
2785 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2788 if (info
->ai_canonname
&&
2789 (canon
= strchr(info
->ai_canonname
, '.')))
2792 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2805 localtime_r(&now
, &tm
);
2807 if (c
== 'd') /* ISO 8601 */
2808 fprintf(ie
->output
, "%s %s %2d %d",
2809 nl_langinfo(ABDAY_1
+ tm
.tm_wday
),
2810 nl_langinfo(ABMON_1
+ tm
.tm_mon
),
2812 tm
.tm_year
< 70 ? tm
.tm_year
+ 2000 :
2815 fprintf(ie
->output
, "%02d:%02d:%02d",
2816 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
2820 fprintf (ie
->output
, "%s", op
->tty
);
2824 const speed_t speed
= cfgetispeed(tp
);
2827 for (i
= 0; speedtab
[i
].speed
; i
++) {
2828 if (speedtab
[i
].code
== speed
) {
2829 fprintf(ie
->output
, "%ld", speedtab
[i
].speed
);
2837 char *var
= NULL
, varname
[64];
2840 if (get_escape_argument(fp
, varname
, sizeof(varname
))) {
2841 var
= read_os_release(op
, varname
);
2843 if (strcmp(varname
, "ANSI_COLOR") == 0)
2844 fprintf(ie
->output
, "\033[%sm", var
);
2846 fputs(var
, ie
->output
);
2849 } else if ((var
= read_os_release(op
, "PRETTY_NAME"))) {
2850 fputs(var
, ie
->output
);
2852 /* \S and PRETTY_NAME not found */
2855 fputs(uts
.sysname
, ie
->output
);
2868 while ((ut
= getutxent()))
2869 if (ut
->ut_type
== USER_PROCESS
)
2873 fprintf(ie
->output
, P_("%d user", "%d users", users
), users
);
2875 fprintf (ie
->output
, "%d ", users
);
2878 #if defined(RTMGRP_IPV4_IFADDR) && defined(RTMGRP_IPV6_IFADDR)
2882 sa_family_t family
= c
== '4' ? AF_INET
: AF_INET6
;
2883 struct ifaddrs
*addrs
= NULL
;
2886 if (getifaddrs(&addrs
))
2889 if (get_escape_argument(fp
, iface
, sizeof(iface
)))
2890 output_iface_ip(ie
, addrs
, iface
, family
);
2892 output_iface_ip(ie
, addrs
, NULL
, family
);
2897 netlink_groups
|= RTMGRP_IPV4_IFADDR
;
2899 netlink_groups
|= RTMGRP_IPV6_IFADDR
;
2904 putc(c
, ie
->output
);
2909 static void init_special_char(char* arg
, struct options
*op
)
2914 op
->initstring
= malloc(strlen(arg
) + 1);
2915 if (!op
->initstring
)
2916 log_err(_("failed to allocate memory: %m"));
2919 * Copy optarg into op->initstring decoding \ddd octal
2925 /* The \\ is converted to \ */
2932 /* Handle \000 - \177. */
2934 for (i
= 1; i
<= 3; i
++) {
2935 if (*p
>= '0' && *p
<= '7') {
2952 * Appends @str to @dest and if @dest is not empty then use @sep as a
2953 * separator. The maximal final length of the @dest is @len.
2955 * Returns the final @dest length or -1 in case of error.
2957 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
)
2959 size_t dsz
= 0, ssz
= 0, sz
;
2962 if (!dest
|| !len
|| !src
)
2971 if (dsz
+ ssz
+ sz
+ 1 > len
)
2976 memcpy(p
, sep
, ssz
);
2982 return dsz
+ ssz
+ sz
;
2986 * Do not allow the user to pass an option as a user name
2987 * To be more safe: Use `--' to make sure the rest is
2988 * interpreted as non-options by the program, if it supports it.
2990 static void check_username(const char* nm
)
2995 if (strlen(nm
) > 42)
3004 log_err(_("checkname failed: %m"));
3007 static void reload_agettys(void)
3009 #ifdef AGETTY_RELOAD
3010 int fd
= open(AGETTY_RELOAD_FILENAME
, O_CREAT
|O_CLOEXEC
|O_WRONLY
,
3013 err(EXIT_FAILURE
, _("cannot open %s"), AGETTY_RELOAD_FILENAME
);
3015 if (futimens(fd
, NULL
) < 0 || close(fd
) < 0)
3016 err(EXIT_FAILURE
, _("cannot touch file %s"),
3017 AGETTY_RELOAD_FILENAME
);
3020 errx(EXIT_FAILURE
, _("--reload is unsupported on your system"));