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>
34 #include <arpa/inet.h>
38 #include <sys/utsname.h>
43 #include "pathnames.h"
48 #include "color-names.h"
51 #ifdef USE_PLYMOUTH_SUPPORT
52 # include "plymouth-ctrl.h"
55 #ifdef HAVE_SYS_PARAM_H
56 # include <sys/param.h>
59 #if defined(__FreeBSD_kernel__)
64 # ifdef HAVE_LIBUTIL_H
72 # ifndef DEFAULT_VCTERM
73 # define DEFAULT_VCTERM "linux"
75 # if defined (__s390__) || defined (__s390x__)
76 # define DEFAULT_TTYS0 "dumb"
77 # define DEFAULT_TTY32 "ibm327x"
78 # define DEFAULT_TTYS1 "vt220"
80 # ifndef DEFAULT_STERM
81 # define DEFAULT_STERM "vt102"
83 #elif defined(__GNU__)
85 # ifndef DEFAULT_VCTERM
86 # define DEFAULT_VCTERM "hurd"
88 # ifndef DEFAULT_STERM
89 # define DEFAULT_STERM "vt102"
92 # ifndef DEFAULT_VCTERM
93 # define DEFAULT_VCTERM "vt100"
95 # ifndef DEFAULT_STERM
96 # define DEFAULT_STERM "vt100"
100 #ifdef __FreeBSD_kernel__
104 /* If USE_SYSLOG is undefined all diagnostics go to /dev/console. */
110 * Some heuristics to find out what environment we are in: if it is not
111 * System V, assume it is SunOS 4. The LOGIN_PROCESS is defined in System V
112 * utmp.h, which will select System V style getty.
119 * Things you may want to modify.
121 * If ISSUE_SUPPORT is not defined, agetty will never display the contents of
122 * the /etc/issue file. You will not want to spit out large "issue" files at
123 * the wrong baud rate. Relevant for System V only.
125 * You may disagree with the default line-editing etc. characters defined
126 * below. Note, however, that DEL cannot be used for interrupt generation
127 * and for line editing at the same time.
130 /* Displayed before the login prompt. */
132 # define ISSUE_SUPPORT
133 # if defined(HAVE_SCANDIRAT) && defined(HAVE_OPENAT)
135 # include "fileutils.h"
136 # define ISSUEDIR_SUPPORT
137 # define ISSUEDIR_EXT ".issue"
138 # define ISSUEDIR_EXTSIZ (sizeof(ISSUEDIR_EXT) - 1)
143 #define LOGIN "login: "
144 #define LOGIN_ARGV_MAX 16 /* Numbers of args for login */
150 # include <sys/inotify.h>
151 # include <linux/netlink.h>
152 # include <linux/rtnetlink.h>
153 # define AGETTY_RELOAD_FILENAME "/run/agetty.reload" /* trigger file */
154 # define AGETTY_RELOAD_FDNONE -2 /* uninitialized fd */
155 static int inotify_fd
= AGETTY_RELOAD_FDNONE
;
156 static int netlink_fd
= AGETTY_RELOAD_FDNONE
;
157 static uint32_t netlink_groups
;
168 unsigned int do_tcsetattr
: 1,
173 * When multiple baud rates are specified on the command line, the first one
174 * we will try is the first one specified.
176 #define FIRST_SPEED 0
178 /* Storage for command-line options. */
179 #define MAX_SPEED 10 /* max. nr. of baud rates */
182 int flags
; /* toggle switches, see below */
183 unsigned int timeout
; /* time-out period */
184 char *autolog
; /* login the user automatically */
185 char *chdir
; /* Chdir before the login */
186 char *chroot
; /* Chroot before the login */
187 char *login
; /* login program */
188 char *logopt
; /* options for login program */
189 char *tty
; /* name of tty */
190 char *vcline
; /* line of virtual console */
191 char *term
; /* terminal type */
192 char *initstring
; /* modem init string */
193 char *issue
; /* alternative issue file or directory */
194 char *erasechars
; /* string with erase chars */
195 char *killchars
; /* string with kill chars */
196 char *osrelease
; /* /etc/os-release data */
197 unsigned int delay
; /* Sleep seconds before prompt */
198 int nice
; /* Run login with this priority */
199 int numspeed
; /* number of baud rates to try */
200 int clocal
; /* CLOCAL_MODE_* */
201 int kbmode
; /* Keyboard mode if virtual console */
202 speed_t speeds
[MAX_SPEED
]; /* baud rates to be tried */
206 CLOCAL_MODE_AUTO
= 0,
211 #define F_PARSE (1<<0) /* process modem status messages */
212 #define F_ISSUE (1<<1) /* display /etc/issue or /etc/issue.d */
213 #define F_RTSCTS (1<<2) /* enable RTS/CTS flow control */
215 #define F_INITSTRING (1<<4) /* initstring is set */
216 #define F_WAITCRLF (1<<5) /* wait for CR or LF */
218 #define F_NOPROMPT (1<<7) /* do not ask for login name! */
219 #define F_LCUC (1<<8) /* support for *LCUC stty modes */
220 #define F_KEEPSPEED (1<<9) /* follow baud rate from kernel */
221 #define F_KEEPCFLAGS (1<<10) /* reuse c_cflags setup from kernel */
222 #define F_EIGHTBITS (1<<11) /* Assume 8bit-clean tty */
223 #define F_VCONSOLE (1<<12) /* This is a virtual console */
224 #define F_HANGUP (1<<13) /* Do call vhangup(2) */
225 #define F_UTF8 (1<<14) /* We can do UTF8 */
226 #define F_LOGINPAUSE (1<<15) /* Wait for any key before dropping login prompt */
227 #define F_NOCLEAR (1<<16) /* Do not clear the screen before prompting */
228 #define F_NONL (1<<17) /* No newline before issue */
229 #define F_NOHOSTNAME (1<<18) /* Do not show the hostname */
230 #define F_LONGHNAME (1<<19) /* Show Full qualified hostname */
231 #define F_NOHINTS (1<<20) /* Don't print hints */
232 #define F_REMOTE (1<<21) /* Add '-h fakehost' to login(1) command line */
234 #define serial_tty_option(opt, flag) \
235 (((opt)->flags & (F_VCONSOLE|(flag))) == (flag))
242 static const struct Speedtab speedtab
[] = {
314 static void init_special_char(char* arg
, struct options
*op
);
315 static void parse_args(int argc
, char **argv
, struct options
*op
);
316 static void parse_speeds(struct options
*op
, char *arg
);
317 static void update_utmp(struct options
*op
);
318 static void open_tty(char *tty
, struct termios
*tp
, struct options
*op
);
319 static void termio_init(struct options
*op
, struct termios
*tp
);
320 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
);
321 static void auto_baud(struct termios
*tp
);
322 static void list_speeds(void);
323 static void output_special_char (struct issue
*ie
, unsigned char c
, struct options
*op
,
324 struct termios
*tp
, FILE *fp
);
325 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
326 static void next_speed(struct options
*op
, struct termios
*tp
);
327 static char *get_logname(struct issue
*ie
, struct options
*op
,
328 struct termios
*tp
, struct chardata
*cp
);
329 static void termio_final(struct options
*op
,
330 struct termios
*tp
, struct chardata
*cp
);
331 static int caps_lock(char *s
);
332 static speed_t
bcode(char *s
);
333 static void usage(void) __attribute__((__noreturn__
));
334 static void exit_slowly(int code
) __attribute__((__noreturn__
));
335 static void log_err(const char *, ...) __attribute__((__noreturn__
))
336 __attribute__((__format__(printf
, 1, 2)));
337 static void log_warn (const char *, ...)
338 __attribute__((__format__(printf
, 1, 2)));
339 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
);
340 static void check_username (const char* nm
);
341 static void login_options_to_argv(char *argv
[], int *argc
, char *str
, char *username
);
342 static void reload_agettys(void);
343 static void print_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
344 static void eval_issue_file(struct issue
*ie
, struct options
*op
, struct termios
*tp
);
345 static void show_issue(struct options
*op
);
348 /* Fake hostname for ut_host specified on command line. */
349 static char *fakehost
;
352 # include "closestream.h"
353 # ifndef DEBUG_OUTPUT
354 # define DEBUG_OUTPUT "/dev/tty10"
356 # define debug(s) do { fprintf(dbf,s); fflush(dbf); } while (0)
359 # define debug(s) do { ; } while (0)
362 int main(int argc
, char **argv
)
364 char *username
= NULL
; /* login name, given to /bin/login */
365 struct chardata chardata
; /* will be set by get_logname() */
366 struct termios termios
; /* terminal mode bits */
367 struct options options
= {
368 .flags
= F_ISSUE
, /* show /etc/issue (SYSV_STYLE) */
369 .login
= _PATH_LOGIN
, /* default login program */
370 .tty
= "tty1" /* default tty line */
372 struct issue issue
= {
375 char *login_argv
[LOGIN_ARGV_MAX
+ 1];
377 struct sigaction sa
, sa_hup
, sa_quit
, sa_int
;
380 setlocale(LC_ALL
, "");
381 bindtextdomain(PACKAGE
, LOCALEDIR
);
384 /* In case vhangup(2) has to called */
385 sa
.sa_handler
= SIG_IGN
;
386 sa
.sa_flags
= SA_RESTART
;
387 sigemptyset (&sa
.sa_mask
);
388 sigaction(SIGHUP
, &sa
, &sa_hup
);
389 sigaction(SIGQUIT
, &sa
, &sa_quit
);
390 sigaction(SIGINT
, &sa
, &sa_int
);
393 dbf
= fopen(DEBUG_OUTPUT
, "w");
394 for (int i
= 1; i
< argc
; i
++) {
400 #endif /* DEBUGGING */
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 (serial_tty_option(&options
, 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
);
487 } else { /* regular (auto)login */
488 if (options
.autolog
) {
489 /* Autologin prompt */
490 eval_issue_file(&issue
, &options
, &termios
);
491 do_prompt(&issue
, &options
, &termios
);
492 printf(_("%s%s (automatic login)\n"), LOGIN
, options
.autolog
);
494 /* Read the login name. */
495 debug("reading login name\n");
497 get_logname(&issue
, &options
, &termios
, &chardata
)) == NULL
)
498 if ((options
.flags
& F_VCONSOLE
) == 0 && options
.numspeed
)
499 next_speed(&options
, &termios
);
507 /* Finalize the termios settings. */
508 if ((options
.flags
& F_VCONSOLE
) == 0)
509 termio_final(&options
, &termios
, &chardata
);
511 reset_vc(&options
, &termios
, 1);
513 /* Now the newline character should be properly written. */
514 write_all(STDOUT_FILENO
, "\r\n", 2);
516 sigaction(SIGQUIT
, &sa_quit
, NULL
);
517 sigaction(SIGINT
, &sa_int
, NULL
);
520 check_username(username
);
522 if (options
.logopt
) {
524 * The --login-options completely overwrites the default
525 * way how agetty composes login(1) command line.
527 login_options_to_argv(login_argv
, &login_argc
,
528 options
.logopt
, username
);
530 if (options
.flags
& F_REMOTE
) {
532 login_argv
[login_argc
++] = "-h";
533 login_argv
[login_argc
++] = fakehost
;
534 } else if (options
.flags
& F_NOHOSTNAME
)
535 login_argv
[login_argc
++] = "-H";
539 login_argv
[login_argc
++] = "-f";
541 login_argv
[login_argc
++] = "--";
542 login_argv
[login_argc
++] = username
;
546 login_argv
[login_argc
] = NULL
; /* last login argv */
548 if (options
.chroot
&& chroot(options
.chroot
) < 0)
549 log_err(_("%s: can't change root directory %s: %m"),
550 options
.tty
, options
.chroot
);
551 if (options
.chdir
&& chdir(options
.chdir
) < 0)
552 log_err(_("%s: can't change working directory %s: %m"),
553 options
.tty
, options
.chdir
);
554 if (options
.nice
&& nice(options
.nice
) < 0)
555 log_warn(_("%s: can't change process priority: %m"),
558 free(options
.osrelease
);
560 if (close_stream(dbf
) != 0)
561 log_err("write failed: %s", DEBUG_OUTPUT
);
564 /* Let the login program take care of password validation. */
565 execv(options
.login
, login_argv
);
566 log_err(_("%s: can't exec %s: %m"), options
.tty
, login_argv
[0]);
570 * Returns : @str if \u not found
571 * : @username if @str equal to "\u"
572 * : newly allocated string if \u mixed with something other
574 static char *replace_u(char *str
, char *username
)
576 char *entry
= NULL
, *p
= str
;
577 size_t usz
= username
? strlen(username
) : 0;
581 char *tp
, *old
= entry
;
583 if (memcmp(p
, "\\u", 2) != 0) {
585 continue; /* no \u */
589 if (p
== str
&& sz
== 2) {
590 /* 'str' contains only '\u' */
595 tp
= entry
= malloc(sz
+ usz
);
597 log_err(_("failed to allocate memory: %m"));
600 /* copy chars before \u */
601 memcpy(tp
, str
, p
- str
);
606 memcpy(tp
, username
, usz
);
610 /* copy chars after \u + \0 */
611 memcpy(tp
, p
+ 2, sz
- (p
- str
) - 1);
620 return entry
? entry
: str
;
623 static void login_options_to_argv(char *argv
[], int *argc
,
624 char *str
, char *username
)
629 while (str
&& isspace(*str
))
633 while (p
&& *p
&& i
< LOGIN_ARGV_MAX
) {
636 while (isspace(*++p
))
639 argv
[i
++] = replace_u(str
, username
);
645 if (str
&& *str
&& i
< LOGIN_ARGV_MAX
)
646 argv
[i
++] = replace_u(str
, username
);
650 static void output_version(void)
652 static const char *features
[] = {
665 #ifdef ISSUEDIR_SUPPORT
671 #ifdef USE_PLYMOUTH_SUPPORT
687 printf( _("%s from %s"), program_invocation_short_name
, PACKAGE_STRING
);
689 for (i
= 0; features
[i
]; i
++) {
692 printf("%s", features
[i
]);
694 fputs(")\n", stdout
);
697 #define is_speed(str) (strlen((str)) == strspn((str), "0123456789,"))
699 /* Parse command-line arguments. */
700 static void parse_args(int argc
, char **argv
, struct options
*op
)
705 VERSION_OPTION
= CHAR_MAX
+ 1,
716 const struct option longopts
[] = {
717 { "8bits", no_argument
, NULL
, '8' },
718 { "autologin", required_argument
, NULL
, 'a' },
719 { "noreset", no_argument
, NULL
, 'c' },
720 { "chdir", required_argument
, NULL
, 'C' },
721 { "delay", required_argument
, NULL
, 'd' },
722 { "remote", no_argument
, NULL
, 'E' },
723 { "issue-file", required_argument
, NULL
, 'f' },
724 { "show-issue", no_argument
, NULL
, ISSUE_SHOW_OPTION
},
725 { "flow-control", no_argument
, NULL
, 'h' },
726 { "host", required_argument
, NULL
, 'H' },
727 { "noissue", no_argument
, NULL
, 'i' },
728 { "init-string", required_argument
, NULL
, 'I' },
729 { "noclear", no_argument
, NULL
, 'J' },
730 { "login-program", required_argument
, NULL
, 'l' },
731 { "local-line", optional_argument
, NULL
, 'L' },
732 { "extract-baud", no_argument
, NULL
, 'm' },
733 { "list-speeds", no_argument
, NULL
, LIST_SPEEDS_OPTION
},
734 { "skip-login", no_argument
, NULL
, 'n' },
735 { "nonewline", no_argument
, NULL
, 'N' },
736 { "login-options", required_argument
, NULL
, 'o' },
737 { "login-pause", no_argument
, NULL
, 'p' },
738 { "nice", required_argument
, NULL
, 'P' },
739 { "chroot", required_argument
, NULL
, 'r' },
740 { "hangup", no_argument
, NULL
, 'R' },
741 { "keep-baud", no_argument
, NULL
, 's' },
742 { "timeout", required_argument
, NULL
, 't' },
743 { "detect-case", no_argument
, NULL
, 'U' },
744 { "wait-cr", no_argument
, NULL
, 'w' },
745 { "nohints", no_argument
, NULL
, NOHINTS_OPTION
},
746 { "nohostname", no_argument
, NULL
, NOHOSTNAME_OPTION
},
747 { "long-hostname", no_argument
, NULL
, LONGHOSTNAME_OPTION
},
748 { "reload", no_argument
, NULL
, RELOAD_OPTION
},
749 { "version", no_argument
, NULL
, VERSION_OPTION
},
750 { "help", no_argument
, NULL
, HELP_OPTION
},
751 { "erase-chars", required_argument
, NULL
, ERASE_CHARS_OPTION
},
752 { "kill-chars", required_argument
, NULL
, KILL_CHARS_OPTION
},
756 while ((c
= getopt_long(argc
, argv
,
757 "8a:cC:d:Ef:hH:iI:Jl:L::mnNo:pP:r:Rst:Uw", longopts
,
761 op
->flags
|= F_EIGHTBITS
;
764 op
->autolog
= optarg
;
767 op
->flags
|= F_KEEPCFLAGS
;
773 op
->delay
= strtou32_or_err(optarg
, _("invalid delay argument"));
776 op
->flags
|= F_REMOTE
;
782 op
->flags
|= F_RTSCTS
;
788 op
->flags
&= ~F_ISSUE
;
791 init_special_char(optarg
, op
);
792 op
->flags
|= F_INITSTRING
;
795 op
->flags
|= F_NOCLEAR
;
801 /* -L and -L=always have the same meaning */
802 op
->clocal
= CLOCAL_MODE_ALWAYS
;
804 if (strcmp(optarg
, "=always") == 0)
805 op
->clocal
= CLOCAL_MODE_ALWAYS
;
806 else if (strcmp(optarg
, "=never") == 0)
807 op
->clocal
= CLOCAL_MODE_NEVER
;
808 else if (strcmp(optarg
, "=auto") == 0)
809 op
->clocal
= CLOCAL_MODE_AUTO
;
811 log_err(_("invalid argument of --local-line"));
815 op
->flags
|= F_PARSE
;
818 op
->flags
|= F_NOPROMPT
;
827 op
->flags
|= F_LOGINPAUSE
;
830 op
->nice
= strtos32_or_err(optarg
, _("invalid nice argument"));
836 op
->flags
|= F_HANGUP
;
839 op
->flags
|= F_KEEPSPEED
;
842 op
->timeout
= strtou32_or_err(optarg
, _("invalid timeout argument"));
848 op
->flags
|= F_WAITCRLF
;
851 op
->flags
|= F_NOHINTS
;
853 case NOHOSTNAME_OPTION
:
854 op
->flags
|= F_NOHOSTNAME
;
856 case LONGHOSTNAME_OPTION
:
857 op
->flags
|= F_LONGHNAME
;
859 case ERASE_CHARS_OPTION
:
860 op
->erasechars
= optarg
;
862 case KILL_CHARS_OPTION
:
863 op
->killchars
= optarg
;
868 case LIST_SPEEDS_OPTION
:
871 case ISSUE_SHOW_OPTION
:
881 errtryhelp(EXIT_FAILURE
);
885 debug("after getopt loop\n");
887 if (argc
< optind
+ 1) {
888 log_warn(_("not enough arguments"));
889 errx(EXIT_FAILURE
, _("not enough arguments"));
892 /* Accept "tty", "baudrate tty", and "tty baudrate". */
893 if (is_speed(argv
[optind
])) {
894 /* Assume BSD style speed. */
895 parse_speeds(op
, argv
[optind
++]);
896 if (argc
< optind
+ 1) {
897 log_warn(_("not enough arguments"));
898 errx(EXIT_FAILURE
, _("not enough arguments"));
900 op
->tty
= argv
[optind
++];
902 op
->tty
= argv
[optind
++];
904 char *v
= argv
[optind
];
912 /* On virtual console remember the line which is used for */
913 if (strncmp(op
->tty
, "tty", 3) == 0 &&
914 strspn(op
->tty
+ 3, "0123456789") == strlen(op
->tty
+3))
915 op
->vcline
= op
->tty
+3;
917 if (argc
> optind
&& argv
[optind
])
918 op
->term
= argv
[optind
];
920 debug("exiting parseargs\n");
923 /* Parse alternate baud rates. */
924 static void parse_speeds(struct options
*op
, char *arg
)
927 char *str
= strdup(arg
);
930 log_err(_("failed to allocate memory: %m"));
932 debug("entered parse_speeds:\n");
933 for (cp
= strtok(str
, ","); cp
!= NULL
; cp
= strtok((char *)0, ",")) {
934 if ((op
->speeds
[op
->numspeed
++] = bcode(cp
)) <= 0)
935 log_err(_("bad speed: %s"), cp
);
936 if (op
->numspeed
>= MAX_SPEED
)
937 log_err(_("too many alternate speeds"));
939 debug("exiting parsespeeds\n");
945 /* Update our utmp entry. */
946 static void update_utmp(struct options
*op
)
950 pid_t pid
= getpid();
951 pid_t sid
= getsid(0);
952 char *vcline
= op
->vcline
;
953 char *line
= op
->tty
;
957 * The utmp file holds miscellaneous information about things started by
958 * /sbin/init and other system-related events. Our purpose is to update
959 * the utmp entry for the current process, in particular the process type
960 * and the tty line we are listening to. Return successfully only if the
961 * utmp file can be opened for update, and if we are able to find our
962 * entry in the utmp file.
964 utmpxname(_PATH_UTMP
);
968 * Find my pid in utmp.
970 * FIXME: Earlier (when was that?) code here tested only utp->ut_type !=
971 * INIT_PROCESS, so maybe the >= here should be >.
973 * FIXME: The present code is taken from login.c, so if this is changed,
974 * maybe login has to be changed as well (is this true?).
976 while ((utp
= getutxent()))
977 if (utp
->ut_pid
== pid
978 && utp
->ut_type
>= INIT_PROCESS
979 && utp
->ut_type
<= DEAD_PROCESS
)
983 memcpy(&ut
, utp
, sizeof(ut
));
985 /* Some inits do not initialize utmp. */
986 memset(&ut
, 0, sizeof(ut
));
987 if (vcline
&& *vcline
)
988 /* Standard virtual console devices */
989 str2memcpy(ut
.ut_id
, vcline
, sizeof(ut
.ut_id
));
991 size_t len
= strlen(line
);
993 if (len
>= sizeof(ut
.ut_id
))
994 ptr
= line
+ len
- sizeof(ut
.ut_id
);
997 str2memcpy(ut
.ut_id
, ptr
, sizeof(ut
.ut_id
));
1001 str2memcpy(ut
.ut_user
, "LOGIN", sizeof(ut
.ut_user
));
1002 str2memcpy(ut
.ut_line
, line
, sizeof(ut
.ut_line
));
1004 str2memcpy(ut
.ut_host
, fakehost
, sizeof(ut
.ut_host
));
1006 ut
.ut_tv
.tv_sec
= t
;
1007 ut
.ut_type
= LOGIN_PROCESS
;
1009 ut
.ut_session
= sid
;
1014 updwtmpx(_PATH_WTMP
, &ut
);
1017 #endif /* SYSV_STYLE */
1019 /* Set up tty as stdin, stdout & stderr. */
1020 static void open_tty(char *tty
, struct termios
*tp
, struct options
*op
)
1022 const pid_t pid
= getpid();
1028 /* Set up new standard input, unless we are given an already opened port. */
1030 if (strcmp(tty
, "-") != 0) {
1031 char buf
[PATH_MAX
+1];
1032 struct group
*gr
= NULL
;
1038 /* Use tty group if available */
1039 if ((gr
= getgrnam("tty")))
1042 len
= snprintf(buf
, sizeof(buf
), "/dev/%s", tty
);
1043 if (len
< 0 || (size_t)len
>= sizeof(buf
))
1044 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1046 /* Open the tty as standard input. */
1047 if ((fd
= open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0)) < 0)
1048 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1051 * There is always a race between this reset and the call to
1052 * vhangup() that s.o. can use to get access to your tty.
1053 * Linux login(1) will change tty permissions. Use root owner and group
1054 * with permission -rw------- for the period between getty and login.
1056 if (fchown(fd
, 0, gid
) || fchmod(fd
, (gid
? 0620 : 0600))) {
1058 log_warn("%s: %m", buf
);
1060 log_err("%s: %m", buf
);
1063 /* Sanity checks... */
1064 if (fstat(fd
, &st
) < 0)
1065 log_err("%s: %m", buf
);
1066 if ((st
.st_mode
& S_IFMT
) != S_IFCHR
)
1067 log_err(_("/dev/%s: not a character device"), tty
);
1069 log_err(_("/dev/%s: not a tty"), tty
);
1071 if (((tid
= tcgetsid(fd
)) < 0) || (pid
!= tid
)) {
1072 if (ioctl(fd
, TIOCSCTTY
, 1) == -1)
1073 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1076 close(STDIN_FILENO
);
1079 if (op
->flags
& F_HANGUP
) {
1081 if (ioctl(fd
, TIOCNOTTY
))
1082 debug("TIOCNOTTY ioctl failed\n");
1085 * Let's close all file descriptors before vhangup
1086 * https://lkml.org/lkml/2012/6/5/145
1089 close(STDOUT_FILENO
);
1090 close(STDERR_FILENO
);
1095 log_err(_("/dev/%s: vhangup() failed: %m"), tty
);
1100 if (open(buf
, O_RDWR
|O_NOCTTY
|O_NONBLOCK
, 0) != 0)
1101 log_err(_("/dev/%s: cannot open as standard input: %m"), tty
);
1103 if (((tid
= tcgetsid(STDIN_FILENO
)) < 0) || (pid
!= tid
)) {
1104 if (ioctl(STDIN_FILENO
, TIOCSCTTY
, 1) == -1)
1105 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty
);
1111 * Standard input should already be connected to an open port. Make
1112 * sure it is open for read/write.
1115 if ((fcntl(STDIN_FILENO
, F_GETFL
, 0) & O_RDWR
) != O_RDWR
)
1116 log_err(_("%s: not open for read/write"), tty
);
1120 if (tcsetpgrp(STDIN_FILENO
, pid
))
1121 log_warn(_("/dev/%s: cannot set process group: %m"), tty
);
1123 /* Get rid of the present outputs. */
1125 close(STDOUT_FILENO
);
1126 close(STDERR_FILENO
);
1130 /* Set up standard output and standard error file descriptors. */
1133 /* set up stdout and stderr */
1134 if (dup(STDIN_FILENO
) != 1 || dup(STDIN_FILENO
) != 2)
1135 log_err(_("%s: dup problem: %m"), tty
);
1137 /* make stdio unbuffered for slow modem lines */
1138 setvbuf(stdout
, NULL
, _IONBF
, 0);
1141 * The following ioctl will fail if stdin is not a tty, but also when
1142 * there is noise on the modem control lines. In the latter case, the
1143 * common course of action is (1) fix your cables (2) give the modem
1144 * more time to properly reset after hanging up.
1146 * SunOS users can achieve (2) by patching the SunOS kernel variable
1147 * "zsadtrlow" to a larger value; 5 seconds seems to be a good value.
1148 * http://www.sunmanagers.org/archives/1993/0574.html
1150 memset(tp
, 0, sizeof(struct termios
));
1151 if (tcgetattr(STDIN_FILENO
, tp
) < 0)
1152 log_err(_("%s: failed to get terminal attributes: %m"), tty
);
1154 #if defined (__s390__) || defined (__s390x__)
1157 * Special terminal on first serial line on a S/390(x) which
1158 * is due legacy reasons a block terminal of type 3270 or
1159 * higher. Whereas the second serial line on a S/390(x) is
1160 * a real character terminal which is compatible with VT220.
1162 if (strcmp(op
->tty
, "ttyS0") == 0) /* linux/drivers/s390/char/con3215.c */
1163 op
->term
= DEFAULT_TTYS0
;
1164 else if (strncmp(op
->tty
, "3270/tty", 8) == 0) /* linux/drivers/s390/char/con3270.c */
1165 op
->term
= DEFAULT_TTY32
;
1166 else if (strcmp(op
->tty
, "ttyS1") == 0) /* linux/drivers/s390/char/sclp_vt220.c */
1167 op
->term
= DEFAULT_TTYS1
;
1171 #if defined(__FreeBSD_kernel__)
1176 * Detect if this is a virtual console or serial/modem line.
1177 * In case of a virtual console the ioctl KDGKBMODE succeeds
1178 * whereas on other lines it will fails.
1181 if (ioctl(STDIN_FILENO
, KDGKBMODE
, &op
->kbmode
) == 0)
1183 if (ioctl(STDIN_FILENO
, TIOCMGET
, &serial
) < 0 && (errno
== EINVAL
))
1186 op
->flags
|= F_VCONSOLE
;
1188 op
->term
= DEFAULT_VCTERM
;
1194 op
->term
= DEFAULT_STERM
;
1197 if (setenv("TERM", op
->term
, 1) != 0)
1198 log_err(_("failed to set the %s environment variable"), "TERM");
1201 /* Initialize termios settings. */
1202 static void termio_clear(int fd
)
1205 * Do not write a full reset (ESC c) because this destroys
1206 * the unicode mode again if the terminal was in unicode
1207 * mode. Also it clears the CONSOLE_MAGIC features which
1208 * are required for some languages/console-fonts.
1209 * Just put the cursor to the home position (ESC [ H),
1210 * erase everything below the cursor (ESC [ J), and set the
1211 * scrolling region to the full window (ESC [ r)
1213 write_all(fd
, "\033[r\033[H\033[J", 9);
1216 /* Initialize termios settings. */
1217 static void termio_init(struct options
*op
, struct termios
*tp
)
1219 speed_t ispeed
, ospeed
;
1221 #ifdef USE_PLYMOUTH_SUPPORT
1222 struct termios lock
;
1223 int i
= (plymouth_command(MAGIC_PING
) == 0) ? PLYMOUTH_TERMIOS_FLAGS_DELAY
: 0;
1225 plymouth_command(MAGIC_QUIT
);
1228 * Even with TTYReset=no it seems with systemd or plymouth
1229 * the termios flags become changed from under the first
1230 * agetty on a serial system console as the flags are locked.
1232 memset(&lock
, 0, sizeof(struct termios
));
1233 if (ioctl(STDIN_FILENO
, TIOCGLCKTRMIOS
, &lock
) < 0)
1235 if (!lock
.c_iflag
&& !lock
.c_oflag
&& !lock
.c_cflag
&& !lock
.c_lflag
)
1237 debug("termios locked\n");
1240 memset(&lock
, 0, sizeof(struct termios
));
1241 ioctl(STDIN_FILENO
, TIOCSLCKTRMIOS
, &lock
);
1244 if (op
->flags
& F_VCONSOLE
) {
1245 #if defined(IUTF8) && defined(KDGKBMODE)
1246 switch(op
->kbmode
) {
1248 setlocale(LC_CTYPE
, "C.UTF-8");
1249 op
->flags
|= F_UTF8
;
1255 setlocale(LC_CTYPE
, "POSIX");
1256 op
->flags
&= ~F_UTF8
;
1260 setlocale(LC_CTYPE
, "POSIX");
1261 op
->flags
&= ~F_UTF8
;
1263 reset_vc(op
, tp
, 0);
1265 if ((tp
->c_cflag
& (CS8
|PARODD
|PARENB
)) == CS8
)
1266 op
->flags
|= F_EIGHTBITS
;
1268 if ((op
->flags
& F_NOCLEAR
) == 0)
1269 termio_clear(STDOUT_FILENO
);
1277 if (op
->flags
& F_KEEPSPEED
|| !op
->numspeed
) {
1278 /* Save the original setting. */
1279 ispeed
= cfgetispeed(tp
);
1280 ospeed
= cfgetospeed(tp
);
1282 /* Save also the original speed to array of the speeds to make
1283 * it possible to return the the original after unexpected BREAKs.
1286 op
->speeds
[op
->numspeed
++] = ispeed
? ispeed
:
1290 ispeed
= TTYDEF_SPEED
;
1292 ospeed
= TTYDEF_SPEED
;
1294 ospeed
= ispeed
= op
->speeds
[FIRST_SPEED
];
1298 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
1299 * Special characters are set after we have read the login name; all
1300 * reads will be done in raw mode anyway. Errors will be dealt with
1304 /* The default is set c_iflag in termio_final() according to chardata.
1305 * Unfortunately, the chardata are not set according to the serial line
1306 * if --autolog is enabled. In this case we do not read from the line
1307 * at all. The best what we can do in this case is to keep c_iflag
1308 * unmodified for --autolog.
1312 tp
->c_iflag
= tp
->c_iflag
& IUTF8
;
1313 if (tp
->c_iflag
& IUTF8
)
1314 op
->flags
|= F_UTF8
;
1321 tp
->c_oflag
&= OPOST
| ONLCR
;
1323 if ((op
->flags
& F_KEEPCFLAGS
) == 0)
1324 tp
->c_cflag
= CS8
| HUPCL
| CREAD
| (tp
->c_cflag
& CLOCAL
);
1327 * Note that the speed is stored in the c_cflag termios field, so we have
1328 * set the speed always when the cflag is reset.
1330 cfsetispeed(tp
, ispeed
);
1331 cfsetospeed(tp
, ospeed
);
1333 /* The default is to follow setting from kernel, but it's possible
1334 * to explicitly remove/add CLOCAL flag by -L[=<mode>]*/
1335 switch (op
->clocal
) {
1336 case CLOCAL_MODE_ALWAYS
:
1337 tp
->c_cflag
|= CLOCAL
; /* -L or -L=always */
1339 case CLOCAL_MODE_NEVER
:
1340 tp
->c_cflag
&= ~CLOCAL
; /* -L=never */
1342 case CLOCAL_MODE_AUTO
: /* -L=auto */
1346 #ifdef HAVE_STRUCT_TERMIOS_C_LINE
1350 tp
->c_cc
[VTIME
] = 0;
1352 /* Check for terminal size and if not found set default */
1353 if (ioctl(STDIN_FILENO
, TIOCGWINSZ
, &ws
) == 0) {
1358 if (ioctl(STDIN_FILENO
, TIOCSWINSZ
, &ws
))
1359 debug("TIOCSWINSZ ioctl failed\n");
1362 /* Optionally enable hardware flow control. */
1364 if (op
->flags
& F_RTSCTS
)
1365 tp
->c_cflag
|= CRTSCTS
;
1367 /* Flush input and output queues, important for modems! */
1368 tcflush(STDIN_FILENO
, TCIOFLUSH
);
1370 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
))
1371 log_warn(_("setting terminal attributes failed: %m"));
1373 /* Go to blocking input even in local mode. */
1374 fcntl(STDIN_FILENO
, F_SETFL
,
1375 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1377 debug("term_io 2\n");
1380 /* Reset virtual console on stdin to its defaults */
1381 static void reset_vc(const struct options
*op
, struct termios
*tp
, int canon
)
1385 fl
|= (op
->flags
& F_KEEPCFLAGS
) == 0 ? 0 : UL_TTY_KEEPCFLAGS
;
1386 fl
|= (op
->flags
& F_UTF8
) == 0 ? 0 : UL_TTY_UTF8
;
1388 reset_virtual_console(tp
, fl
);
1390 #ifdef AGETTY_RELOAD
1392 * Discard all the flags that makes the line go canonical with echoing.
1393 * We need to know when the user starts typing.
1399 if (tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
))
1400 log_warn(_("setting terminal attributes failed: %m"));
1402 /* Go to blocking input even in local mode. */
1403 fcntl(STDIN_FILENO
, F_SETFL
,
1404 fcntl(STDIN_FILENO
, F_GETFL
, 0) & ~O_NONBLOCK
);
1407 /* Extract baud rate from modem status message. */
1408 static void auto_baud(struct termios
*tp
)
1418 * This works only if the modem produces its status code AFTER raising
1419 * the DCD line, and if the computer is fast enough to set the proper
1420 * baud rate before the message has gone by. We expect a message of the
1423 * <junk><number><junk>
1425 * The number is interpreted as the baud rate of the incoming call. If the
1426 * modem does not tell us the baud rate within one second, we will keep
1427 * using the current baud rate. It is advisable to enable BREAK
1428 * processing (comma-separated list of baud rates) if the processing of
1429 * modem status messages is enabled.
1433 * Use 7-bit characters, don't block if input queue is empty. Errors will
1434 * be dealt with later on.
1436 iflag
= tp
->c_iflag
;
1437 /* Enable 8th-bit stripping. */
1438 tp
->c_iflag
|= ISTRIP
;
1439 vmin
= tp
->c_cc
[VMIN
];
1440 /* Do not block when queue is empty. */
1442 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1445 * Wait for a while, then read everything the modem has said so far and
1446 * try to extract the speed of the dial-in call.
1449 if ((nread
= read(STDIN_FILENO
, buf
, sizeof(buf
) - 1)) > 0) {
1451 for (bp
= buf
; bp
< buf
+ nread
; bp
++)
1452 if (c_isascii(*bp
) && isdigit(*bp
)) {
1453 if ((speed
= bcode(bp
))) {
1454 cfsetispeed(tp
, speed
);
1455 cfsetospeed(tp
, speed
);
1461 /* Restore terminal settings. Errors will be dealt with later on. */
1462 tp
->c_iflag
= iflag
;
1463 tp
->c_cc
[VMIN
] = vmin
;
1464 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
1467 static char *xgethostname(void)
1470 size_t sz
= get_hostname_max() + 1;
1472 name
= malloc(sizeof(char) * sz
);
1474 log_err(_("failed to allocate memory: %m"));
1476 if (gethostname(name
, sz
) != 0) {
1480 name
[sz
- 1] = '\0';
1484 static char *xgetdomainname(void)
1486 #ifdef HAVE_GETDOMAINNAME
1488 const size_t sz
= get_hostname_max() + 1;
1490 name
= malloc(sizeof(char) * sz
);
1492 log_err(_("failed to allocate memory: %m"));
1494 if (getdomainname(name
, sz
) != 0) {
1498 name
[sz
- 1] = '\0';
1506 static char *read_os_release(struct options
*op
, const char *varname
)
1510 size_t varsz
= strlen(varname
);
1511 char *p
, *buf
= NULL
, *ret
= NULL
;
1513 /* read the file only once */
1514 if (!op
->osrelease
) {
1515 fd
= open(_PATH_OS_RELEASE_ETC
, O_RDONLY
);
1517 fd
= open(_PATH_OS_RELEASE_USR
, O_RDONLY
);
1519 log_warn(_("cannot open os-release file"));
1524 if (fstat(fd
, &st
) < 0 || st
.st_size
> 4 * 1024 * 1024)
1527 op
->osrelease
= malloc(st
.st_size
+ 1);
1529 log_err(_("failed to allocate memory: %m"));
1530 if (read_all(fd
, op
->osrelease
, st
.st_size
) != (ssize_t
) st
.st_size
) {
1531 free(op
->osrelease
);
1532 op
->osrelease
= NULL
;
1535 op
->osrelease
[st
.st_size
] = 0;
1537 buf
= strdup(op
->osrelease
);
1539 log_err(_("failed to allocate memory: %m"));
1545 p
+= strspn(p
, "\n\r");
1546 p
+= strspn(p
, " \t\n\r");
1549 if (strspn(p
, "#;\n") != 0) {
1550 p
+= strcspn(p
, "\n\r");
1553 if (strncmp(p
, varname
, varsz
) != 0) {
1554 p
+= strcspn(p
, "\n\r");
1558 p
+= strspn(p
, " \t\n\r");
1563 p
+= strspn(p
, " \t\n\r=\"");
1564 eol
= p
+ strcspn(p
, "\n\r");
1568 if (*eon
== '\t' || *eon
== ' ') {
1581 log_err(_("failed to allocate memory: %m"));
1591 #ifdef AGETTY_RELOAD
1592 static void open_netlink(void)
1594 struct sockaddr_nl addr
= { 0, };
1597 if (netlink_fd
!= AGETTY_RELOAD_FDNONE
)
1600 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
1602 addr
.nl_family
= AF_NETLINK
;
1603 addr
.nl_pid
= getpid();
1604 addr
.nl_groups
= netlink_groups
;
1605 if (bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) < 0)
1612 static int process_netlink_msg(int *triggered
)
1615 struct sockaddr_nl snl
;
1619 struct iovec iov
= {
1621 .iov_len
= sizeof(buf
)
1623 struct msghdr msg
= {
1625 .msg_namelen
= sizeof(snl
),
1628 .msg_control
= NULL
,
1629 .msg_controllen
= 0,
1633 rc
= recvmsg(netlink_fd
, &msg
, MSG_DONTWAIT
);
1635 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1638 /* Failure, just stop listening for changes */
1640 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1644 for (h
= (struct nlmsghdr
*)buf
; NLMSG_OK(h
, (unsigned int)rc
); h
= NLMSG_NEXT(h
, rc
)) {
1645 if (h
->nlmsg_type
== NLMSG_DONE
||
1646 h
->nlmsg_type
== NLMSG_ERROR
) {
1648 netlink_fd
= AGETTY_RELOAD_FDNONE
;
1659 static int process_netlink(void)
1662 while (process_netlink_msg(&triggered
));
1666 static int wait_for_term_input(int fd
)
1668 char buffer
[sizeof(struct inotify_event
) + NAME_MAX
+ 1];
1671 if (inotify_fd
== AGETTY_RELOAD_FDNONE
) {
1672 /* make sure the reload trigger file exists */
1673 int reload_fd
= open(AGETTY_RELOAD_FILENAME
,
1674 O_CREAT
|O_CLOEXEC
|O_RDONLY
,
1677 /* initialize reload trigger inotify stuff */
1678 if (reload_fd
>= 0) {
1679 inotify_fd
= inotify_init1(IN_NONBLOCK
| IN_CLOEXEC
);
1681 inotify_add_watch(inotify_fd
, AGETTY_RELOAD_FILENAME
,
1682 IN_ATTRIB
| IN_MODIFY
);
1686 log_warn(_("failed to create reload file: %s: %m"),
1687 AGETTY_RELOAD_FILENAME
);
1696 if (inotify_fd
>= 0) {
1697 FD_SET(inotify_fd
, &rfds
);
1698 nfds
= max(nfds
, inotify_fd
);
1700 if (netlink_fd
>= 0) {
1701 FD_SET(netlink_fd
, &rfds
);
1702 nfds
= max(nfds
, netlink_fd
);
1705 /* If waiting fails, just fall through, presumably reading input will fail */
1706 if (select(nfds
+ 1, &rfds
, NULL
, NULL
, NULL
) < 0)
1709 if (FD_ISSET(fd
, &rfds
)) {
1714 if (netlink_fd
>= 0 && FD_ISSET(netlink_fd
, &rfds
)) {
1715 if (!process_netlink())
1718 /* Just drain the inotify buffer */
1719 } else if (inotify_fd
>= 0 && FD_ISSET(inotify_fd
, &rfds
)) {
1720 while (read(inotify_fd
, buffer
, sizeof (buffer
)) > 0);
1726 #endif /* AGETTY_RELOAD */
1728 #ifdef ISSUEDIR_SUPPORT
1729 static int issuedir_filter(const struct dirent
*d
)
1733 #ifdef _DIRENT_HAVE_D_TYPE
1734 if (d
->d_type
!= DT_UNKNOWN
&& d
->d_type
!= DT_REG
&&
1735 d
->d_type
!= DT_LNK
)
1738 if (*d
->d_name
== '.')
1741 namesz
= strlen(d
->d_name
);
1742 if (!namesz
|| namesz
< ISSUEDIR_EXTSIZ
+ 1 ||
1743 strcmp(d
->d_name
+ (namesz
- ISSUEDIR_EXTSIZ
), ISSUEDIR_EXT
) != 0)
1751 static int issuefile_read_stream(struct issue
*ie
, FILE *f
, struct options
*op
, struct termios
*tp
);
1753 /* returns: 0 on success, 1 cannot open, <0 on error
1755 static int issuedir_read(struct issue
*ie
, const char *dirname
,
1756 struct options
*op
, struct termios
*tp
)
1759 struct dirent
**namelist
= NULL
;
1761 dd
= open(dirname
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
1765 nfiles
= scandirat(dd
, ".", &namelist
, issuedir_filter
, versionsort
);
1769 ie
->do_tcsetattr
= 1;
1771 for (i
= 0; i
< nfiles
; i
++) {
1772 struct dirent
*d
= namelist
[i
];
1775 f
= fopen_at(dd
, d
->d_name
, O_RDONLY
|O_CLOEXEC
, "r" UL_CLOEXECSTR
);
1777 issuefile_read_stream(ie
, f
, op
, tp
);
1782 for (i
= 0; i
< nfiles
; i
++)
1790 #else /* !ISSUEDIR_SUPPORT */
1791 static int issuedir_read(struct issue
*ie
__attribute__((__unused__
)),
1792 const char *dirname
__attribute__((__unused__
)),
1793 struct options
*op
__attribute__((__unused__
)),
1794 struct termios
*tp
__attribute__((__unused__
)))
1798 #endif /* ISSUEDIR_SUPPORT */
1800 #ifndef ISSUE_SUPPORT
1801 static void print_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1803 struct termios
*tp
__attribute__((__unused__
)))
1805 if ((op
->flags
& F_NONL
) == 0) {
1806 /* Issue not in use, start with a new line. */
1807 write_all(STDOUT_FILENO
, "\r\n", 2);
1811 static void eval_issue_file(struct issue
*ie
__attribute__((__unused__
)),
1812 struct options
*op
__attribute__((__unused__
)),
1813 struct termios
*tp
__attribute__((__unused__
)))
1817 static void show_issue(struct options
*op
__attribute__((__unused__
)))
1821 #else /* ISSUE_SUPPORT */
1823 static int issuefile_read_stream(
1824 struct issue
*ie
, FILE *f
,
1825 struct options
*op
, struct termios
*tp
)
1830 if (fstat(fileno(f
), &st
) || !S_ISREG(st
.st_mode
))
1837 ie
->output
= open_memstream(&ie
->mem
, &ie
->mem_sz
);
1840 while ((c
= getc(f
)) != EOF
) {
1842 output_special_char(ie
, getc(f
), op
, tp
, f
);
1844 putc(c
, ie
->output
);
1850 static int issuefile_read(
1851 struct issue
*ie
, const char *filename
,
1852 struct options
*op
, struct termios
*tp
)
1854 FILE *f
= fopen(filename
, "r" UL_CLOEXECSTR
);
1858 rc
= issuefile_read_stream(ie
, f
, op
, tp
);
1865 #ifdef AGETTY_RELOAD
1866 static int issue_is_changed(struct issue
*ie
)
1868 if (ie
->mem_old
&& ie
->mem
1869 && strcmp(ie
->mem_old
, ie
->mem
) == 0) {
1871 ie
->mem_old
= ie
->mem
;
1880 static void print_issue_file(struct issue
*ie
,
1884 int oflag
= tp
->c_oflag
; /* Save current setting. */
1886 if ((op
->flags
& F_NONL
) == 0) {
1887 /* Issue not in use, start with a new line. */
1888 write_all(STDOUT_FILENO
, "\r\n", 2);
1891 if (ie
->do_tcsetattr
) {
1892 if ((op
->flags
& F_VCONSOLE
) == 0) {
1893 /* Map new line in output to carriage return & new line. */
1894 tp
->c_oflag
|= (ONLCR
| OPOST
);
1895 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1900 write_all(STDOUT_FILENO
, ie
->mem
, ie
->mem_sz
);
1902 if (ie
->do_tcrestore
) {
1903 /* Restore settings. */
1904 tp
->c_oflag
= oflag
;
1905 /* Wait till output is gone. */
1906 tcsetattr(STDIN_FILENO
, TCSADRAIN
, tp
);
1909 #ifdef AGETTY_RELOAD
1911 ie
->mem_old
= ie
->mem
;
1921 static void eval_issue_file(struct issue
*ie
,
1927 #ifdef AGETTY_RELOAD
1930 if (!(op
->flags
& F_ISSUE
))
1934 * The custom issue file or directory specified by: agetty -f <path>.
1935 * Note that nothing is printed if the file/dir does not exist.
1940 if (stat(op
->issue
, &st
) < 0)
1942 if (S_ISDIR(st
.st_mode
))
1943 issuedir_read(ie
, op
->issue
, op
, tp
);
1945 issuefile_read(ie
, op
->issue
, op
, tp
);
1950 /* The default /etc/issue and optional /etc/issue.d directory as
1951 * extension to the file. The /etc/issue.d directory is ignored if
1952 * there is no /etc/issue file. The file may be empty or symlink.
1954 if (access(_PATH_ISSUE
, F_OK
|R_OK
) == 0) {
1955 issuefile_read(ie
, _PATH_ISSUE
, op
, tp
);
1956 issuedir_read(ie
, _PATH_ISSUEDIR
, op
, tp
);
1960 /* Fallback @runstatedir (usually /run) -- the file is not required to
1963 if (issuefile_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
) == 0)
1965 if (issuedir_read(ie
, _PATH_RUNSTATEDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
) == 0)
1970 /* Fallback @sysconfstaticdir (usually /usr/lib) -- the file is not
1971 * required to read the dir
1973 issuefile_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_FILENAME
, op
, tp
);
1974 issuedir_read(ie
, _PATH_SYSCONFSTATICDIR
"/" _PATH_ISSUE_DIRNAME
, op
, tp
);
1978 #ifdef AGETTY_RELOAD
1979 if (netlink_groups
!= 0)
1988 /* This is --show-issue backend, executed by normal user on the current
1991 static void show_issue(struct options
*op
)
1993 struct issue ie
= { .output
= NULL
};
1996 memset(&tp
, 0, sizeof(struct termios
));
1997 if (tcgetattr(STDIN_FILENO
, &tp
) < 0)
1998 err(EXIT_FAILURE
, _("failed to get terminal attributes: %m"));
2000 eval_issue_file(&ie
, op
, &tp
);
2003 write_all(STDOUT_FILENO
, ie
.mem
, ie
.mem_sz
);
2009 #endif /* ISSUE_SUPPORT */
2011 /* Show login prompt, optionally preceded by /etc/issue contents. */
2012 static void do_prompt(struct issue
*ie
, struct options
*op
, struct termios
*tp
)
2014 #ifdef AGETTY_RELOAD
2017 print_issue_file(ie
, op
, tp
);
2019 if (op
->flags
& F_LOGINPAUSE
) {
2020 puts(_("[press ENTER to login]"));
2021 #ifdef AGETTY_RELOAD
2023 if (!wait_for_term_input(STDIN_FILENO
)) {
2024 eval_issue_file(ie
, op
, tp
);
2025 if (issue_is_changed(ie
)) {
2026 if (op
->flags
& F_VCONSOLE
)
2027 termio_clear(STDOUT_FILENO
);
2035 if (!(op
->flags
& F_NOHINTS
) && !op
->autolog
&&
2036 (op
->flags
& F_VCONSOLE
)) {
2039 if (ioctl(STDIN_FILENO
, KDGKBLED
, &kb
) == 0) {
2040 char hint
[256] = { '\0' };
2043 if (access(_PATH_NUMLOCK_ON
, F_OK
) == 0)
2046 if (nl
&& (kb
& 0x02) == 0)
2047 append(hint
, sizeof(hint
), NULL
, _("Num Lock off"));
2049 else if (nl
== 0 && (kb
& 2) && (kb
& 0x20) == 0)
2050 append(hint
, sizeof(hint
), NULL
, _("Num Lock on"));
2052 if ((kb
& 0x04) && (kb
& 0x40) == 0)
2053 append(hint
, sizeof(hint
), ", ", _("Caps Lock on"));
2055 if ((kb
& 0x01) && (kb
& 0x10) == 0)
2056 append(hint
, sizeof(hint
), ", ", _("Scroll Lock on"));
2059 printf(_("Hint: %s\n\n"), hint
);
2062 #endif /* KDGKBLED */
2063 if ((op
->flags
& F_NOHOSTNAME
) == 0) {
2064 char *hn
= xgethostname();
2067 char *dot
= strchr(hn
, '.');
2069 struct addrinfo
*res
= NULL
;
2071 if ((op
->flags
& F_LONGHNAME
) == 0) {
2075 } else if (dot
== NULL
) {
2076 struct addrinfo hints
;
2078 memset(&hints
, 0, sizeof(hints
));
2079 hints
.ai_flags
= AI_CANONNAME
;
2081 if (!getaddrinfo(hn
, NULL
, &hints
, &res
)
2082 && res
&& res
->ai_canonname
)
2083 cn
= res
->ai_canonname
;
2086 write_all(STDOUT_FILENO
, cn
, strlen(cn
));
2087 write_all(STDOUT_FILENO
, " ", 1);
2095 /* Always show login prompt. */
2096 write_all(STDOUT_FILENO
, LOGIN
, sizeof(LOGIN
) - 1);
2100 /* Select next baud rate. */
2101 static void next_speed(struct options
*op
, struct termios
*tp
)
2103 static int baud_index
= -1;
2105 if (baud_index
== -1)
2107 * If the F_KEEPSPEED flags is set then the FIRST_SPEED is not
2108 * tested yet (see termio_init()).
2111 (op
->flags
& F_KEEPSPEED
) ? FIRST_SPEED
: 1 % op
->numspeed
;
2113 baud_index
= (baud_index
+ 1) % op
->numspeed
;
2115 cfsetispeed(tp
, op
->speeds
[baud_index
]);
2116 cfsetospeed(tp
, op
->speeds
[baud_index
]);
2117 tcsetattr(STDIN_FILENO
, TCSANOW
, tp
);
2120 /* Get user name, establish parity, speed, erase, kill & eol. */
2121 static char *get_logname(struct issue
*ie
, struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2123 static char logname
[BUFSIZ
];
2125 char c
; /* input character, full eight bits */
2126 char ascval
; /* low 7 bits of input character */
2128 static char *erase
[] = { /* backspace-space-backspace */
2129 "\010\040\010", /* space parity */
2130 "\010\040\010", /* odd parity */
2131 "\210\240\210", /* even parity */
2132 "\210\240\210", /* no parity */
2135 /* Initialize kill, erase, parity etc. (also after switching speeds). */
2139 * Flush pending input (especially important after parsing or switching
2142 if ((op
->flags
& F_VCONSOLE
) == 0)
2144 tcflush(STDIN_FILENO
, TCIFLUSH
);
2146 eightbit
= (op
->flags
& (F_EIGHTBITS
|F_UTF8
));
2150 eval_issue_file(ie
, op
, tp
);
2151 while (*logname
== '\0') {
2152 /* Write issue file and prompt */
2153 do_prompt(ie
, op
, tp
);
2156 #ifdef AGETTY_RELOAD
2157 if (!wait_for_term_input(STDIN_FILENO
)) {
2158 /* refresh prompt -- discard input data, clear terminal
2159 * and call do_prompt() again
2161 if ((op
->flags
& F_VCONSOLE
) == 0)
2163 eval_issue_file(ie
, op
, tp
);
2164 if (!issue_is_changed(ie
))
2166 tcflush(STDIN_FILENO
, TCIFLUSH
);
2167 if (op
->flags
& F_VCONSOLE
)
2168 termio_clear(STDOUT_FILENO
);
2176 /* Read name, watch for break and end-of-line. */
2177 while (cp
->eol
== '\0') {
2182 debug("read from FD\n");
2183 readres
= read(STDIN_FILENO
, &c
, 1);
2185 debug("read failed\n");
2187 /* The terminal could be open with O_NONBLOCK when
2188 * -L (force CLOCAL) is specified... */
2189 if (errno
== EINTR
|| errno
== EAGAIN
) {
2199 exit_slowly(EXIT_SUCCESS
);
2201 log_err(_("%s: read: %m"), op
->tty
);
2208 /* Do parity bit handling. */
2211 else if (c
!= (ascval
= (c
& 0177))) {
2212 uint32_t bits
; /* # of "1" bits per character */
2213 uint32_t mask
; /* mask with 1 bit up */
2214 for (bits
= 1, mask
= 1; mask
& 0177; mask
<<= 1) {
2218 cp
->parity
|= ((bits
& 1) ? 1 : 2);
2221 if (op
->killchars
&& strchr(op
->killchars
, ascval
))
2223 else if (op
->erasechars
&& strchr(op
->erasechars
, ascval
))
2228 /* Do erase, kill and end-of-line processing. */
2232 if (op
->numspeed
> 1 && !(op
->flags
& F_VCONSOLE
))
2235 exit_slowly(EXIT_SUCCESS
);
2239 *bp
= 0; /* terminate logname */
2240 cp
->eol
= ascval
; /* set end-of-line char */
2244 cp
->erase
= ascval
; /* set erase character */
2246 if ((tp
->c_lflag
& ECHO
) == 0)
2247 write_all(1, erase
[cp
->parity
], 3);
2252 cp
->kill
= ascval
; /* set kill character */
2253 while (bp
> logname
) {
2254 if ((tp
->c_lflag
& ECHO
) == 0)
2255 write_all(1, erase
[cp
->parity
], 3);
2262 if ((size_t)(bp
- logname
) >= sizeof(logname
) - 1)
2263 log_err(_("%s: input overrun"), op
->tty
);
2264 if ((tp
->c_lflag
& ECHO
) == 0)
2265 write_all(1, &c
, 1); /* echo the character */
2266 *bp
++ = ascval
; /* and store it */
2269 /* Everything was erased. */
2270 if (bp
== logname
&& cp
->eol
== '\0')
2275 #ifdef HAVE_WIDECHAR
2276 if ((op
->flags
& (F_EIGHTBITS
|F_UTF8
)) == (F_EIGHTBITS
|F_UTF8
)) {
2277 /* Check out UTF-8 multibyte characters */
2281 len
= mbstowcs((wchar_t *)0, logname
, 0);
2283 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2285 wcs
= malloc((len
+ 1) * sizeof(wchar_t));
2287 log_err(_("failed to allocate memory: %m"));
2289 len
= mbstowcs(wcs
, logname
, len
+ 1);
2291 log_err(_("%s: invalid character conversion for login name"), op
->tty
);
2295 const wint_t wc
= *wcp
++;
2297 log_err(_("%s: invalid character 0x%x in login name"), op
->tty
, wc
);
2302 if ((op
->flags
& F_LCUC
) && (cp
->capslock
= caps_lock(logname
))) {
2304 /* Handle names with upper case and no lower case. */
2305 for (bp
= logname
; *bp
; bp
++)
2307 *bp
= tolower(*bp
); /* map name to lower case */
2313 /* Set the final tty mode bits. */
2314 static void termio_final(struct options
*op
, struct termios
*tp
, struct chardata
*cp
)
2316 /* General terminal-independent stuff. */
2318 /* 2-way flow control */
2319 tp
->c_iflag
|= IXON
| IXOFF
;
2320 tp
->c_lflag
|= ICANON
| ISIG
| ECHO
| ECHOE
| ECHOK
| ECHOKE
;
2321 /* no longer| ECHOCTL | ECHOPRT */
2322 tp
->c_oflag
|= OPOST
;
2323 /* tp->c_cflag = 0; */
2324 tp
->c_cc
[VINTR
] = DEF_INTR
;
2325 tp
->c_cc
[VQUIT
] = DEF_QUIT
;
2326 tp
->c_cc
[VEOF
] = DEF_EOF
;
2327 tp
->c_cc
[VEOL
] = DEF_EOL
;
2329 tp
->c_cc
[VSWTC
] = DEF_SWITCH
;
2330 #elif defined(VSWTCH)
2331 tp
->c_cc
[VSWTCH
] = DEF_SWITCH
;
2332 #endif /* __linux__ */
2334 /* Account for special characters seen in input. */
2335 if (cp
->eol
== CR
) {
2336 tp
->c_iflag
|= ICRNL
;
2337 tp
->c_oflag
|= ONLCR
;
2339 tp
->c_cc
[VERASE
] = cp
->erase
;
2340 tp
->c_cc
[VKILL
] = cp
->kill
;
2342 /* Account for the presence or absence of parity bits in input. */
2343 switch (cp
->parity
) {
2345 /* space (always 0) parity */
2349 tp
->c_cflag
|= PARODD
;
2353 tp
->c_cflag
|= PARENB
;
2354 tp
->c_iflag
|= INPCK
| ISTRIP
;
2358 tp
->c_cflag
&= ~CSIZE
;
2362 /* Account for upper case without lower case. */
2365 tp
->c_iflag
|= IUCLC
;
2368 tp
->c_lflag
|= XCASE
;
2371 tp
->c_oflag
|= OLCUC
;
2374 /* Optionally enable hardware flow control. */
2376 if (op
->flags
& F_RTSCTS
)
2377 tp
->c_cflag
|= CRTSCTS
;
2380 /* Finally, make the new settings effective. */
2381 if (tcsetattr(STDIN_FILENO
, TCSANOW
, tp
) < 0)
2382 log_err(_("%s: failed to set terminal attributes: %m"), op
->tty
);
2386 * String contains upper case without lower case.
2387 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=52940
2388 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=156242
2390 static int caps_lock(char *s
)
2394 for (capslock
= 0; *s
; s
++) {
2396 return EXIT_SUCCESS
;
2398 capslock
= isupper(*s
);
2403 /* Convert speed string to speed code; return 0 on failure. */
2404 static speed_t
bcode(char *s
)
2406 const struct Speedtab
*sp
;
2407 long speed
= atol(s
);
2409 for (sp
= speedtab
; sp
->speed
; sp
++)
2410 if (sp
->speed
== speed
)
2415 static void __attribute__((__noreturn__
)) usage(void)
2419 fputs(USAGE_HEADER
, out
);
2420 fprintf(out
, _(" %1$s [options] <line> [<baud_rate>,...] [<termtype>]\n"
2421 " %1$s [options] <baud_rate>,... <line> [<termtype>]\n"), program_invocation_short_name
);
2423 fputs(USAGE_SEPARATOR
, out
);
2424 fputs(_("Open a terminal and set its mode.\n"), out
);
2426 fputs(USAGE_OPTIONS
, out
);
2427 fputs(_(" -8, --8bits assume 8-bit tty\n"), out
);
2428 fputs(_(" -a, --autologin <user> login the specified user automatically\n"), out
);
2429 fputs(_(" -c, --noreset do not reset control mode\n"), out
);
2430 fputs(_(" -E, --remote use -r <hostname> for login(1)\n"), out
);
2431 fputs(_(" -f, --issue-file <file> display issue file\n"), out
);
2432 fputs(_(" --show-issue display issue file and exit\n"), out
);
2433 fputs(_(" -h, --flow-control enable hardware flow control\n"), out
);
2434 fputs(_(" -H, --host <hostname> specify login host\n"), out
);
2435 fputs(_(" -i, --noissue do not display issue file\n"), out
);
2436 fputs(_(" -I, --init-string <string> set init string\n"), out
);
2437 fputs(_(" -J --noclear do not clear the screen before prompt\n"), out
);
2438 fputs(_(" -l, --login-program <file> specify login program\n"), out
);
2439 fputs(_(" -L, --local-line[=<mode>] control the local line flag\n"), out
);
2440 fputs(_(" -m, --extract-baud extract baud rate during connect\n"), out
);
2441 fputs(_(" -n, --skip-login do not prompt for login\n"), out
);
2442 fputs(_(" -N --nonewline do not print a newline before issue\n"), out
);
2443 fputs(_(" -o, --login-options <opts> options that are passed to login\n"), out
);
2444 fputs(_(" -p, --login-pause wait for any key before the login\n"), out
);
2445 fputs(_(" -r, --chroot <dir> change root to the directory\n"), out
);
2446 fputs(_(" -R, --hangup do virtually hangup on the tty\n"), out
);
2447 fputs(_(" -s, --keep-baud try to keep baud rate after break\n"), out
);
2448 fputs(_(" -t, --timeout <number> login process timeout\n"), out
);
2449 fputs(_(" -U, --detect-case detect uppercase terminal\n"), out
);
2450 fputs(_(" -w, --wait-cr wait carriage-return\n"), out
);
2451 fputs(_(" --nohints do not print hints\n"), out
);
2452 fputs(_(" --nohostname no hostname at all will be shown\n"), out
);
2453 fputs(_(" --long-hostname show full qualified hostname\n"), out
);
2454 fputs(_(" --erase-chars <string> additional backspace chars\n"), out
);
2455 fputs(_(" --kill-chars <string> additional kill chars\n"), out
);
2456 fputs(_(" --chdir <directory> chdir before the login\n"), out
);
2457 fputs(_(" --delay <number> sleep seconds before prompt\n"), out
);
2458 fputs(_(" --nice <number> run login with this priority\n"), out
);
2459 fputs(_(" --reload reload prompts on running agetty instances\n"), out
);
2460 fputs(_(" --list-speeds display supported baud rates\n"), out
);
2461 printf( " --help %s\n", USAGE_OPTSTR_HELP
);
2462 printf( " --version %s\n", USAGE_OPTSTR_VERSION
);
2463 printf(USAGE_MAN_TAIL("agetty(8)"));
2468 static void list_speeds(void)
2470 const struct Speedtab
*sp
;
2472 for (sp
= speedtab
; sp
->speed
; sp
++)
2473 printf("%10ld\n", sp
->speed
);
2477 * Helper function reports errors to console or syslog.
2478 * Will be used by log_err() and log_warn() therefore
2479 * it takes a format as well as va_list.
2481 static void dolog(int priority
2483 __attribute__((__unused__
))
2485 , const char *fmt
, va_list ap
)
2489 * If the diagnostic is reported via syslog(3), the process name is
2490 * automatically prepended to the message. If we write directly to
2491 * /dev/console, we must prepend the process name ourselves.
2493 openlog(program_invocation_short_name
, LOG_PID
, LOG_AUTHPRIV
);
2494 vsyslog(priority
, fmt
, ap
);
2498 * Write the diagnostic directly to /dev/console if we do not use
2499 * the syslog(3) facility.
2502 char new_fmt
[BUFSIZ
];
2505 snprintf(new_fmt
, sizeof(new_fmt
), "%s: %s\r\n",
2506 program_invocation_short_name
, fmt
);
2507 /* Terminate with CR-LF since the console mode is unknown. */
2508 vsnprintf(buf
, sizeof(buf
), new_fmt
, ap
);
2510 if ((fd
= open("/dev/console", 1)) >= 0) {
2511 write_all(fd
, buf
, strlen(buf
));
2514 #endif /* USE_SYSLOG */
2517 static void exit_slowly(int code
)
2519 /* Be kind to init(8). */
2524 static void log_err(const char *fmt
, ...)
2529 dolog(LOG_ERR
, fmt
, ap
);
2532 exit_slowly(EXIT_FAILURE
);
2535 static void log_warn(const char *fmt
, ...)
2540 dolog(LOG_WARNING
, fmt
, ap
);
2544 static void print_addr(struct issue
*ie
, sa_family_t family
, void *addr
)
2546 char buff
[INET6_ADDRSTRLEN
+ 1];
2548 inet_ntop(family
, addr
, buff
, sizeof(buff
));
2549 fprintf(ie
->output
, "%s", buff
);
2553 * Prints IP for the specified interface (@iface), if the interface is not
2554 * specified then prints the "best" one (UP, RUNNING, non-LOOPBACK). If not
2555 * found the "best" interface then prints at least host IP.
2557 static void output_iface_ip(struct issue
*ie
,
2558 struct ifaddrs
*addrs
,
2563 struct addrinfo hints
, *info
= NULL
;
2570 for (p
= addrs
; p
; p
= p
->ifa_next
) {
2574 p
->ifa_addr
->sa_family
!= family
)
2578 /* Filter out by interface name */
2579 if (strcmp(p
->ifa_name
, iface
) != 0)
2582 /* Select the "best" interface */
2583 if ((p
->ifa_flags
& IFF_LOOPBACK
) ||
2584 !(p
->ifa_flags
& IFF_UP
) ||
2585 !(p
->ifa_flags
& IFF_RUNNING
))
2590 switch (p
->ifa_addr
->sa_family
) {
2592 addr
= &((struct sockaddr_in
*) p
->ifa_addr
)->sin_addr
;
2595 addr
= &((struct sockaddr_in6
*) p
->ifa_addr
)->sin6_addr
;
2600 print_addr(ie
, family
, addr
);
2608 /* Hmm.. not found the best interface, print host IP at least */
2609 memset(&hints
, 0, sizeof(hints
));
2610 hints
.ai_family
= family
;
2611 if (family
== AF_INET6
)
2612 hints
.ai_flags
= AI_V4MAPPED
;
2614 host
= xgethostname();
2615 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2616 switch (info
->ai_family
) {
2618 addr
= &((struct sockaddr_in
*) info
->ai_addr
)->sin_addr
;
2621 addr
= &((struct sockaddr_in6
*) info
->ai_addr
)->sin6_addr
;
2625 print_addr(ie
, family
, addr
);
2633 * parses \x{argument}, if not argument specified then returns NULL, the @fd
2634 * has to point to one char after the sequence (it means '{').
2636 static char *get_escape_argument(FILE *fd
, char *buf
, size_t bufsz
)
2641 if (c
== EOF
|| (unsigned char) c
!= '{') {
2650 if ((unsigned char) c
!= '}' && i
< bufsz
- 1)
2651 buf
[i
++] = (unsigned char) c
;
2653 } while ((unsigned char) c
!= '}');
2659 static void output_special_char(struct issue
*ie
,
2670 char escname
[UL_COLORNAME_MAXSZ
];
2672 if (get_escape_argument(fp
, escname
, sizeof(escname
))) {
2673 const char *esc
= color_sequence_from_colorname(escname
);
2675 fputs(esc
, ie
->output
);
2677 fputs("\033", ie
->output
);
2682 fprintf(ie
->output
, "%s", uts
.sysname
);
2686 fprintf(ie
->output
, "%s", uts
.nodename
);
2690 fprintf(ie
->output
, "%s", uts
.release
);
2694 fprintf(ie
->output
, "%s", uts
.version
);
2698 fprintf(ie
->output
, "%s", uts
.machine
);
2702 char *dom
= xgetdomainname();
2704 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2711 char *host
= xgethostname();
2712 struct addrinfo hints
, *info
= NULL
;
2714 memset(&hints
, 0, sizeof(hints
));
2715 hints
.ai_flags
= AI_CANONNAME
;
2717 if (host
&& getaddrinfo(host
, NULL
, &hints
, &info
) == 0 && info
) {
2720 if (info
->ai_canonname
&&
2721 (canon
= strchr(info
->ai_canonname
, '.')))
2724 fputs(dom
? dom
: "unknown_domain", ie
->output
);
2737 localtime_r(&now
, &tm
);
2739 if (c
== 'd') /* ISO 8601 */
2740 fprintf(ie
->output
, "%s %s %d %d",
2741 nl_langinfo(ABDAY_1
+ tm
.tm_wday
),
2742 nl_langinfo(ABMON_1
+ tm
.tm_mon
),
2744 tm
.tm_year
< 70 ? tm
.tm_year
+ 2000 :
2747 fprintf(ie
->output
, "%02d:%02d:%02d",
2748 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
2752 fprintf (ie
->output
, "%s", op
->tty
);
2756 const speed_t speed
= cfgetispeed(tp
);
2759 for (i
= 0; speedtab
[i
].speed
; i
++) {
2760 if (speedtab
[i
].code
== speed
) {
2761 fprintf(ie
->output
, "%ld", speedtab
[i
].speed
);
2769 char *var
= NULL
, varname
[64];
2772 if (get_escape_argument(fp
, varname
, sizeof(varname
))) {
2773 var
= read_os_release(op
, varname
);
2775 if (strcmp(varname
, "ANSI_COLOR") == 0)
2776 fprintf(ie
->output
, "\033[%sm", var
);
2778 fputs(var
, ie
->output
);
2781 } else if ((var
= read_os_release(op
, "PRETTY_NAME"))) {
2782 fputs(var
, ie
->output
);
2784 /* \S and PRETTY_NAME not found */
2787 fputs(uts
.sysname
, ie
->output
);
2800 while ((ut
= getutxent()))
2801 if (ut
->ut_type
== USER_PROCESS
)
2805 fprintf(ie
->output
, P_("%d user", "%d users", users
), users
);
2807 fprintf (ie
->output
, "%d ", users
);
2810 #if defined(RTMGRP_IPV4_IFADDR) && defined(RTMGRP_IPV6_IFADDR)
2814 sa_family_t family
= c
== '4' ? AF_INET
: AF_INET6
;
2815 struct ifaddrs
*addrs
= NULL
;
2818 if (getifaddrs(&addrs
))
2821 if (get_escape_argument(fp
, iface
, sizeof(iface
)))
2822 output_iface_ip(ie
, addrs
, iface
, family
);
2824 output_iface_ip(ie
, addrs
, NULL
, family
);
2829 netlink_groups
|= RTMGRP_IPV4_IFADDR
;
2831 netlink_groups
|= RTMGRP_IPV6_IFADDR
;
2836 putc(c
, ie
->output
);
2841 static void init_special_char(char* arg
, struct options
*op
)
2846 op
->initstring
= malloc(strlen(arg
) + 1);
2847 if (!op
->initstring
)
2848 log_err(_("failed to allocate memory: %m"));
2851 * Copy optarg into op->initstring decoding \ddd octal
2857 /* The \\ is converted to \ */
2864 /* Handle \000 - \177. */
2866 for (i
= 1; i
<= 3; i
++) {
2867 if (*p
>= '0' && *p
<= '7') {
2884 * Appends @str to @dest and if @dest is not empty then use @sep as a
2885 * separator. The maximal final length of the @dest is @len.
2887 * Returns the final @dest length or -1 in case of error.
2889 static ssize_t
append(char *dest
, size_t len
, const char *sep
, const char *src
)
2891 size_t dsz
= 0, ssz
= 0, sz
;
2894 if (!dest
|| !len
|| !src
)
2903 if (dsz
+ ssz
+ sz
+ 1 > len
)
2908 memcpy(p
, sep
, ssz
);
2914 return dsz
+ ssz
+ sz
;
2918 * Do not allow the user to pass an option as a user name
2919 * To be more safe: Use `--' to make sure the rest is
2920 * interpreted as non-options by the program, if it supports it.
2922 static void check_username(const char* nm
)
2927 if (strlen(nm
) > 42)
2936 log_err(_("checkname failed: %m"));
2939 static void reload_agettys(void)
2941 #ifdef AGETTY_RELOAD
2942 int fd
= open(AGETTY_RELOAD_FILENAME
, O_CREAT
|O_CLOEXEC
|O_WRONLY
,
2945 err(EXIT_FAILURE
, _("cannot open %s"), AGETTY_RELOAD_FILENAME
);
2947 if (futimens(fd
, NULL
) < 0 || close(fd
) < 0)
2948 err(EXIT_FAILURE
, _("cannot touch file %s"),
2949 AGETTY_RELOAD_FILENAME
);
2952 errx(EXIT_FAILURE
, _("--reload is unsupported on your system"));