]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/agetty.c
agetty: fix \S usage
[thirdparty/util-linux.git] / term-utils / agetty.c
1 /*
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.
6 *
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>
10 *
11 * This program is freely distributable.
12 */
13
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <termios.h>
19 #include <signal.h>
20 #include <errno.h>
21 #include <sys/ioctl.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <fcntl.h>
26 #include <stdarg.h>
27 #include <ctype.h>
28 #include <utmp.h>
29 #include <getopt.h>
30 #include <time.h>
31 #include <sys/file.h>
32 #include <sys/socket.h>
33 #include <langinfo.h>
34 #include <grp.h>
35 #include <arpa/inet.h>
36 #include <netdb.h>
37 #include <ifaddrs.h>
38 #include <net/if.h>
39
40 #include "strutils.h"
41 #include "all-io.h"
42 #include "nls.h"
43 #include "pathnames.h"
44 #include "c.h"
45 #include "widechar.h"
46 #include "ttyutils.h"
47 #include "color-names.h"
48
49 #ifdef USE_PLYMOUTH_SUPPORT
50 # include "plymouth-ctrl.h"
51 #endif
52
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
56
57 #if defined(__FreeBSD_kernel__)
58 #include <pty.h>
59 #endif
60
61 #ifdef __linux__
62 # include <sys/kd.h>
63 # define USE_SYSLOG
64 # ifndef DEFAULT_VCTERM
65 # define DEFAULT_VCTERM "linux"
66 # endif
67 # if defined (__s390__) || defined (__s390x__)
68 # define DEFAULT_TTYS0 "dumb"
69 # define DEFAULT_TTY32 "ibm327x"
70 # define DEFAULT_TTYS1 "vt220"
71 # endif
72 # ifndef DEFAULT_STERM
73 # define DEFAULT_STERM "vt102"
74 # endif
75 #elif defined(__GNU__)
76 # define USE_SYSLOG
77 # ifndef DEFAULT_VCTERM
78 # define DEFAULT_VCTERM "hurd"
79 # endif
80 # ifndef DEFAULT_STERM
81 # define DEFAULT_STERM "vt102"
82 # endif
83 #else
84 # ifndef DEFAULT_VCTERM
85 # define DEFAULT_VCTERM "vt100"
86 # endif
87 # ifndef DEFAULT_STERM
88 # define DEFAULT_STERM "vt100"
89 # endif
90 #endif
91
92 #ifdef __FreeBSD_kernel__
93 #define USE_SYSLOG
94 #endif
95
96 /* If USE_SYSLOG is undefined all diagnostics go to /dev/console. */
97 #ifdef USE_SYSLOG
98 # include <syslog.h>
99 #endif
100
101 /*
102 * Some heuristics to find out what environment we are in: if it is not
103 * System V, assume it is SunOS 4. The LOGIN_PROCESS is defined in System V
104 * utmp.h, which will select System V style getty.
105 */
106 #ifdef LOGIN_PROCESS
107 # define SYSV_STYLE
108 #endif
109
110 /*
111 * Things you may want to modify.
112 *
113 * If ISSUE is not defined, agetty will never display the contents of the
114 * /etc/issue file. You will not want to spit out large "issue" files at the
115 * wrong baud rate. Relevant for System V only.
116 *
117 * You may disagree with the default line-editing etc. characters defined
118 * below. Note, however, that DEL cannot be used for interrupt generation
119 * and for line editing at the same time.
120 */
121
122 /* Displayed before the login prompt. */
123 #ifdef SYSV_STYLE
124 # define ISSUE _PATH_ISSUE
125 # include <sys/utsname.h>
126 #endif
127
128 /* Login prompt. */
129 #define LOGIN "login: "
130 #define LOGIN_ARGV_MAX 16 /* Numbers of args for login */
131
132 /*
133 * agetty --reload
134 */
135 #ifdef AGETTY_RELOAD
136 # include <sys/inotify.h>
137 # include <linux/netlink.h>
138 # include <linux/rtnetlink.h>
139 # define AGETTY_RELOAD_FILENAME "/run/agetty.reload" /* trigger file */
140 # define AGETTY_RELOAD_FDNONE -2 /* uninitialized fd */
141 static int inotify_fd = AGETTY_RELOAD_FDNONE;
142 static int netlink_fd = AGETTY_RELOAD_FDNONE;
143 #endif
144
145 /*
146 * When multiple baud rates are specified on the command line, the first one
147 * we will try is the first one specified.
148 */
149 #define FIRST_SPEED 0
150
151 /* Storage for command-line options. */
152 #define MAX_SPEED 10 /* max. nr. of baud rates */
153
154 struct options {
155 int flags; /* toggle switches, see below */
156 unsigned int timeout; /* time-out period */
157 char *autolog; /* login the user automatically */
158 char *chdir; /* Chdir before the login */
159 char *chroot; /* Chroot before the login */
160 char *login; /* login program */
161 char *logopt; /* options for login program */
162 char *tty; /* name of tty */
163 char *vcline; /* line of virtual console */
164 char *term; /* terminal type */
165 char *initstring; /* modem init string */
166 char *issue; /* alternative issue file */
167 char *erasechars; /* string with erase chars */
168 char *killchars; /* string with kill chars */
169 char *osrelease; /* /etc/os-release data */
170 unsigned int delay; /* Sleep seconds before prompt */
171 int nice; /* Run login with this priority */
172 int numspeed; /* number of baud rates to try */
173 int clocal; /* CLOCAL_MODE_* */
174 int kbmode; /* Keyboard mode if virtual console */
175 speed_t speeds[MAX_SPEED]; /* baud rates to be tried */
176 };
177
178 enum {
179 CLOCAL_MODE_AUTO = 0,
180 CLOCAL_MODE_ALWAYS,
181 CLOCAL_MODE_NEVER
182 };
183
184 #define F_PARSE (1<<0) /* process modem status messages */
185 #define F_ISSUE (1<<1) /* display /etc/issue */
186 #define F_RTSCTS (1<<2) /* enable RTS/CTS flow control */
187
188 #define F_INITSTRING (1<<4) /* initstring is set */
189 #define F_WAITCRLF (1<<5) /* wait for CR or LF */
190 #define F_CUSTISSUE (1<<6) /* give alternative issue file */
191 #define F_NOPROMPT (1<<7) /* do not ask for login name! */
192 #define F_LCUC (1<<8) /* support for *LCUC stty modes */
193 #define F_KEEPSPEED (1<<9) /* follow baud rate from kernel */
194 #define F_KEEPCFLAGS (1<<10) /* reuse c_cflags setup from kernel */
195 #define F_EIGHTBITS (1<<11) /* Assume 8bit-clean tty */
196 #define F_VCONSOLE (1<<12) /* This is a virtual console */
197 #define F_HANGUP (1<<13) /* Do call vhangup(2) */
198 #define F_UTF8 (1<<14) /* We can do UTF8 */
199 #define F_LOGINPAUSE (1<<15) /* Wait for any key before dropping login prompt */
200 #define F_NOCLEAR (1<<16) /* Do not clear the screen before prompting */
201 #define F_NONL (1<<17) /* No newline before issue */
202 #define F_NOHOSTNAME (1<<18) /* Do not show the hostname */
203 #define F_LONGHNAME (1<<19) /* Show Full qualified hostname */
204 #define F_NOHINTS (1<<20) /* Don't print hints */
205 #define F_REMOTE (1<<21) /* Add '-h fakehost' to login(1) command line */
206
207 #define serial_tty_option(opt, flag) \
208 (((opt)->flags & (F_VCONSOLE|(flag))) == (flag))
209
210 struct Speedtab {
211 long speed;
212 speed_t code;
213 };
214
215 static const struct Speedtab speedtab[] = {
216 {50, B50},
217 {75, B75},
218 {110, B110},
219 {134, B134},
220 {150, B150},
221 {200, B200},
222 {300, B300},
223 {600, B600},
224 {1200, B1200},
225 {1800, B1800},
226 {2400, B2400},
227 {4800, B4800},
228 {9600, B9600},
229 #ifdef B19200
230 {19200, B19200},
231 #elif defined(EXTA)
232 {19200, EXTA},
233 #endif
234 #ifdef B38400
235 {38400, B38400},
236 #elif defined(EXTB)
237 {38400, EXTB},
238 #endif
239 #ifdef B57600
240 {57600, B57600},
241 #endif
242 #ifdef B115200
243 {115200, B115200},
244 #endif
245 #ifdef B230400
246 {230400, B230400},
247 #endif
248 #ifdef B460800
249 {460800, B460800},
250 #endif
251 #ifdef B500000
252 {500000, B500000},
253 #endif
254 #ifdef B576000
255 {576000, B576000},
256 #endif
257 #ifdef B921600
258 {921600, B921600},
259 #endif
260 #ifdef B1000000
261 {1000000, B1000000},
262 #endif
263 #ifdef B1152000
264 {1152000, B1152000},
265 #endif
266 #ifdef B1500000
267 {1500000, B1500000},
268 #endif
269 #ifdef B2000000
270 {2000000, B2000000},
271 #endif
272 #ifdef B2500000
273 {2500000, B2500000},
274 #endif
275 #ifdef B3000000
276 {3000000, B3000000},
277 #endif
278 #ifdef B3500000
279 {3500000, B3500000},
280 #endif
281 #ifdef B4000000
282 {4000000, B4000000},
283 #endif
284 {0, 0},
285 };
286
287 static void init_special_char(char* arg, struct options *op);
288 static void parse_args(int argc, char **argv, struct options *op);
289 static void parse_speeds(struct options *op, char *arg);
290 static void update_utmp(struct options *op);
291 static void open_tty(char *tty, struct termios *tp, struct options *op);
292 static void termio_init(struct options *op, struct termios *tp);
293 static void reset_vc (const struct options *op, struct termios *tp);
294 static void auto_baud(struct termios *tp);
295 static void output_special_char (unsigned char c, struct options *op,
296 struct termios *tp, FILE *fp);
297 static void do_prompt(struct options *op, struct termios *tp);
298 static void next_speed(struct options *op, struct termios *tp);
299 static char *get_logname(struct options *op,
300 struct termios *tp, struct chardata *cp);
301 static void termio_final(struct options *op,
302 struct termios *tp, struct chardata *cp);
303 static int caps_lock(char *s);
304 static speed_t bcode(char *s);
305 static void usage(FILE * out) __attribute__((__noreturn__));
306 static void log_err(const char *, ...) __attribute__((__noreturn__))
307 __attribute__((__format__(printf, 1, 2)));
308 static void log_warn (const char *, ...)
309 __attribute__((__format__(printf, 1, 2)));
310 static ssize_t append(char *dest, size_t len, const char *sep, const char *src);
311 static void check_username (const char* nm);
312 static void login_options_to_argv(char *argv[], int *argc, char *str, char *username);
313 static void reload_agettys(void);
314
315 /* Fake hostname for ut_host specified on command line. */
316 static char *fakehost;
317
318 #ifdef DEBUGGING
319 # include "closestream.h"
320 # ifndef DEBUG_OUTPUT
321 # define DEBUG_OUTPUT "/dev/tty10"
322 # endif
323 # define debug(s) do { fprintf(dbf,s); fflush(dbf); } while (0)
324 FILE *dbf;
325 #else
326 # define debug(s) do { ; } while (0)
327 #endif
328
329 int main(int argc, char **argv)
330 {
331 char *username = NULL; /* login name, given to /bin/login */
332 struct chardata chardata; /* will be set by get_logname() */
333 struct termios termios; /* terminal mode bits */
334 struct options options = {
335 .flags = F_ISSUE, /* show /etc/issue (SYSV_STYLE) */
336 .login = _PATH_LOGIN, /* default login program */
337 .tty = "tty1", /* default tty line */
338 .issue = ISSUE /* default issue file */
339 };
340 char *login_argv[LOGIN_ARGV_MAX + 1];
341 int login_argc = 0;
342 struct sigaction sa, sa_hup, sa_quit, sa_int;
343 sigset_t set;
344
345 setlocale(LC_ALL, "");
346 bindtextdomain(PACKAGE, LOCALEDIR);
347 textdomain(PACKAGE);
348
349 /* In case vhangup(2) has to called */
350 sa.sa_handler = SIG_IGN;
351 sa.sa_flags = SA_RESTART;
352 sigemptyset (&sa.sa_mask);
353 sigaction(SIGHUP, &sa, &sa_hup);
354 sigaction(SIGQUIT, &sa, &sa_quit);
355 sigaction(SIGINT, &sa, &sa_int);
356
357 #ifdef DEBUGGING
358 dbf = fopen(DEBUG_OUTPUT, "w");
359 for (int i = 1; i < argc; i++) {
360 if (i > 1)
361 debug(" ");
362 debug(argv[i]);
363 }
364 debug("\n");
365 #endif /* DEBUGGING */
366
367 /* Parse command-line arguments. */
368 parse_args(argc, argv, &options);
369
370 login_argv[login_argc++] = options.login; /* set login program name */
371
372 /* Update the utmp file. */
373 #ifdef SYSV_STYLE
374 update_utmp(&options);
375 #endif
376 if (options.delay)
377 sleep(options.delay);
378
379 debug("calling open_tty\n");
380
381 /* Open the tty as standard { input, output, error }. */
382 open_tty(options.tty, &termios, &options);
383
384 /* Unmask SIGHUP if inherited */
385 sigemptyset(&set);
386 sigaddset(&set, SIGHUP);
387 sigprocmask(SIG_UNBLOCK, &set, NULL);
388 sigaction(SIGHUP, &sa_hup, NULL);
389
390 tcsetpgrp(STDIN_FILENO, getpid());
391
392 /* Default is to follow the current line speed and then default to 9600 */
393 if ((options.flags & F_VCONSOLE) == 0 && options.numspeed == 0) {
394 options.speeds[options.numspeed++] = bcode("9600");
395 options.flags |= F_KEEPSPEED;
396 }
397
398 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
399 debug("calling termio_init\n");
400 termio_init(&options, &termios);
401
402 /* Write the modem init string and DO NOT flush the buffers. */
403 if (serial_tty_option(&options, F_INITSTRING) &&
404 options.initstring && *options.initstring != '\0') {
405 debug("writing init string\n");
406 write_all(STDOUT_FILENO, options.initstring,
407 strlen(options.initstring));
408 }
409
410 if (options.flags & F_VCONSOLE || options.clocal != CLOCAL_MODE_ALWAYS)
411 /* Go to blocking mode unless -L is specified, this change
412 * affects stdout, stdin and stderr as all the file descriptors
413 * are created by dup(). */
414 fcntl(STDOUT_FILENO, F_SETFL,
415 fcntl(STDOUT_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
416
417 /* Optionally detect the baud rate from the modem status message. */
418 debug("before autobaud\n");
419 if (serial_tty_option(&options, F_PARSE))
420 auto_baud(&termios);
421
422 /* Set the optional timer. */
423 if (options.timeout)
424 alarm(options.timeout);
425
426 /* Optionally wait for CR or LF before writing /etc/issue */
427 if (serial_tty_option(&options, F_WAITCRLF)) {
428 char ch;
429
430 debug("waiting for cr-lf\n");
431 while (read(STDIN_FILENO, &ch, 1) == 1) {
432 /* Strip "parity bit". */
433 ch &= 0x7f;
434 #ifdef DEBUGGING
435 fprintf(dbf, "read %c\n", ch);
436 #endif
437 if (ch == '\n' || ch == '\r')
438 break;
439 }
440 }
441
442 INIT_CHARDATA(&chardata);
443
444 if (options.autolog) {
445 debug("doing auto login\n");
446 username = options.autolog;
447 }
448
449 if ((options.flags & F_NOPROMPT) == 0) {
450 if (options.autolog) {
451 /* Autologin prompt */
452 do_prompt(&options, &termios);
453 printf(_("%s%s (automatic login)\n"), LOGIN, options.autolog);
454 } else {
455 /* Read the login name. */
456 debug("reading login name\n");
457 while ((username =
458 get_logname(&options, &termios, &chardata)) == NULL)
459 if ((options.flags & F_VCONSOLE) == 0 && options.numspeed)
460 next_speed(&options, &termios);
461 }
462 }
463
464 /* Disable timer. */
465 if (options.timeout)
466 alarm(0);
467
468 if ((options.flags & F_VCONSOLE) == 0) {
469 /* Finalize the termios settings. */
470 termio_final(&options, &termios, &chardata);
471
472 /* Now the newline character should be properly written. */
473 write_all(STDOUT_FILENO, "\r\n", 2);
474 }
475
476 sigaction(SIGQUIT, &sa_quit, NULL);
477 sigaction(SIGINT, &sa_int, NULL);
478
479 if (username)
480 check_username(username);
481
482 if (options.logopt) {
483 /*
484 * The --login-options completely overwrites the default
485 * way how agetty composes login(1) command line.
486 */
487 login_options_to_argv(login_argv, &login_argc,
488 options.logopt, username);
489 } else {
490 if (fakehost && (options.flags & F_REMOTE)) {
491 login_argv[login_argc++] = "-h";
492 login_argv[login_argc++] = fakehost;
493 }
494 if (username) {
495 if (options.autolog)
496 login_argv[login_argc++] = "-f";
497 else
498 login_argv[login_argc++] = "--";
499 login_argv[login_argc++] = username;
500 }
501 }
502
503 login_argv[login_argc] = NULL; /* last login argv */
504
505 if (options.chroot) {
506 if (chroot(options.chroot) < 0)
507 log_err(_("%s: can't change root directory %s: %m"),
508 options.tty, options.chroot);
509 }
510 if (options.chdir) {
511 if (chdir(options.chdir) < 0)
512 log_err(_("%s: can't change working directory %s: %m"),
513 options.tty, options.chdir);
514 }
515 if (options.nice) {
516 if (nice(options.nice) < 0)
517 log_warn(_("%s: can't change process priority: %m"),
518 options.tty);
519 }
520 free(options.osrelease);
521 #ifdef DEBUGGING
522 if (close_stream(dbf) != 0)
523 log_err("write failed: %s", DEBUG_OUTPUT);
524 #endif
525
526 /* Let the login program take care of password validation. */
527 execv(options.login, login_argv);
528 log_err(_("%s: can't exec %s: %m"), options.tty, login_argv[0]);
529 }
530
531 /*
532 * Returns : @str if \u not found
533 * : @username if @str equal to "\u"
534 * : newly allocated string if \u mixed with something other
535 */
536 static char *replace_u(char *str, char *username)
537 {
538 char *entry = NULL, *p = str;
539 size_t usz = username ? strlen(username) : 0;
540
541 while (*p) {
542 size_t sz;
543 char *tp, *old = entry;
544
545 if (memcmp(p, "\\u", 2)) {
546 p++;
547 continue; /* no \u */
548 }
549 sz = strlen(str);
550
551 if (p == str && sz == 2) {
552 /* 'str' contains only '\u' */
553 free(old);
554 return username;
555 }
556
557 tp = entry = malloc(sz + usz);
558 if (!tp)
559 log_err(_("failed to allocate memory: %m"));
560
561 if (p != str) {
562 /* copy chars before \u */
563 memcpy(tp, str, p - str);
564 tp += p - str;
565 }
566 if (usz) {
567 /* copy username */
568 memcpy(tp, username, usz);
569 tp += usz;
570 }
571 if (*(p + 2))
572 /* copy chars after \u + \0 */
573 memcpy(tp, p + 2, sz - (p - str) - 1);
574 else
575 *tp = '\0';
576
577 p = tp;
578 str = entry;
579 free(old);
580 }
581
582 return entry ? entry : str;
583 }
584
585 static void login_options_to_argv(char *argv[], int *argc,
586 char *str, char *username)
587 {
588 char *p;
589 int i = *argc;
590
591 while (str && isspace(*str))
592 str++;
593 p = str;
594
595 while (p && *p && i < LOGIN_ARGV_MAX) {
596 if (isspace(*p)) {
597 *p = '\0';
598 while (isspace(*++p))
599 ;
600 if (*p) {
601 argv[i++] = replace_u(str, username);
602 str = p;
603 }
604 } else
605 p++;
606 }
607 if (str && *str && i < LOGIN_ARGV_MAX)
608 argv[i++] = replace_u(str, username);
609 *argc = i;
610 }
611
612 #define is_speed(str) (strlen((str)) == strspn((str), "0123456789,"))
613
614 /* Parse command-line arguments. */
615 static void parse_args(int argc, char **argv, struct options *op)
616 {
617 int c;
618
619 enum {
620 VERSION_OPTION = CHAR_MAX + 1,
621 NOHINTS_OPTION,
622 NOHOSTNAME_OPTION,
623 LONGHOSTNAME_OPTION,
624 HELP_OPTION,
625 ERASE_CHARS_OPTION,
626 KILL_CHARS_OPTION,
627 RELOAD_OPTION,
628 };
629 const struct option longopts[] = {
630 { "8bits", no_argument, 0, '8' },
631 { "autologin", required_argument, 0, 'a' },
632 { "noreset", no_argument, 0, 'c' },
633 { "chdir", required_argument, 0, 'C' },
634 { "delay", required_argument, 0, 'd' },
635 { "remote", no_argument, 0, 'E' },
636 { "issue-file", required_argument, 0, 'f' },
637 { "flow-control", no_argument, 0, 'h' },
638 { "host", required_argument, 0, 'H' },
639 { "noissue", no_argument, 0, 'i' },
640 { "init-string", required_argument, 0, 'I' },
641 { "noclear", no_argument, 0, 'J' },
642 { "login-program", required_argument, 0, 'l' },
643 { "local-line", optional_argument, 0, 'L' },
644 { "extract-baud", no_argument, 0, 'm' },
645 { "skip-login", no_argument, 0, 'n' },
646 { "nonewline", no_argument, 0, 'N' },
647 { "login-options", required_argument, 0, 'o' },
648 { "login-pause", no_argument, 0, 'p' },
649 { "nice", required_argument, 0, 'P' },
650 { "chroot", required_argument, 0, 'r' },
651 { "hangup", no_argument, 0, 'R' },
652 { "keep-baud", no_argument, 0, 's' },
653 { "timeout", required_argument, 0, 't' },
654 { "detect-case", no_argument, 0, 'U' },
655 { "wait-cr", no_argument, 0, 'w' },
656 { "nohints", no_argument, 0, NOHINTS_OPTION },
657 { "nohostname", no_argument, 0, NOHOSTNAME_OPTION },
658 { "long-hostname", no_argument, 0, LONGHOSTNAME_OPTION },
659 { "reload", no_argument, 0, RELOAD_OPTION },
660 { "version", no_argument, 0, VERSION_OPTION },
661 { "help", no_argument, 0, HELP_OPTION },
662 { "erase-chars", required_argument, 0, ERASE_CHARS_OPTION },
663 { "kill-chars", required_argument, 0, KILL_CHARS_OPTION },
664 { NULL, 0, 0, 0 }
665 };
666
667 while ((c = getopt_long(argc, argv,
668 "8a:cC:d:Ef:hH:iI:Jl:L::mnNo:pP:r:Rst:Uw", longopts,
669 NULL)) != -1) {
670 switch (c) {
671 case '8':
672 op->flags |= F_EIGHTBITS;
673 break;
674 case 'a':
675 op->autolog = optarg;
676 break;
677 case 'c':
678 op->flags |= F_KEEPCFLAGS;
679 break;
680 case 'C':
681 op->chdir = optarg;
682 break;
683 case 'd':
684 op->delay = strtou32_or_err(optarg, _("invalid delay argument"));
685 break;
686 case 'E':
687 op->flags |= F_REMOTE;
688 break;
689 case 'f':
690 op->flags |= F_CUSTISSUE;
691 op->issue = optarg;
692 break;
693 case 'h':
694 op->flags |= F_RTSCTS;
695 break;
696 case 'H':
697 fakehost = optarg;
698 break;
699 case 'i':
700 op->flags &= ~F_ISSUE;
701 break;
702 case 'I':
703 init_special_char(optarg, op);
704 op->flags |= F_INITSTRING;
705 break;
706 case 'J':
707 op->flags |= F_NOCLEAR;
708 break;
709 case 'l':
710 op->login = optarg;
711 break;
712 case 'L':
713 /* -L and -L=always have the same meaning */
714 op->clocal = CLOCAL_MODE_ALWAYS;
715 if (optarg) {
716 if (strcmp(optarg, "=always") == 0)
717 op->clocal = CLOCAL_MODE_ALWAYS;
718 else if (strcmp(optarg, "=never") == 0)
719 op->clocal = CLOCAL_MODE_NEVER;
720 else if (strcmp(optarg, "=auto") == 0)
721 op->clocal = CLOCAL_MODE_AUTO;
722 else
723 log_err(_("invalid argument of --local-line"));
724 }
725 break;
726 case 'm':
727 op->flags |= F_PARSE;
728 break;
729 case 'n':
730 op->flags |= F_NOPROMPT;
731 break;
732 case 'N':
733 op->flags |= F_NONL;
734 break;
735 case 'o':
736 op->logopt = optarg;
737 break;
738 case 'p':
739 op->flags |= F_LOGINPAUSE;
740 break;
741 case 'P':
742 op->nice = strtos32_or_err(optarg, _("invalid nice argument"));
743 break;
744 case 'r':
745 op->chroot = optarg;
746 break;
747 case 'R':
748 op->flags |= F_HANGUP;
749 break;
750 case 's':
751 op->flags |= F_KEEPSPEED;
752 break;
753 case 't':
754 op->timeout = strtou32_or_err(optarg, _("invalid timeout argument"));
755 break;
756 case 'U':
757 op->flags |= F_LCUC;
758 break;
759 case 'w':
760 op->flags |= F_WAITCRLF;
761 break;
762 case NOHINTS_OPTION:
763 op->flags |= F_NOHINTS;
764 break;
765 case NOHOSTNAME_OPTION:
766 op->flags |= F_NOHOSTNAME;
767 break;
768 case LONGHOSTNAME_OPTION:
769 op->flags |= F_LONGHNAME;
770 break;
771 case ERASE_CHARS_OPTION:
772 op->erasechars = optarg;
773 break;
774 case KILL_CHARS_OPTION:
775 op->killchars = optarg;
776 break;
777 case RELOAD_OPTION:
778 reload_agettys();
779 exit(EXIT_SUCCESS);
780 case VERSION_OPTION:
781 printf(UTIL_LINUX_VERSION);
782 exit(EXIT_SUCCESS);
783 case HELP_OPTION:
784 usage(stdout);
785 default:
786 usage(stderr);
787 }
788 }
789
790 debug("after getopt loop\n");
791
792 if (argc < optind + 1) {
793 log_warn(_("not enough arguments"));
794 usage(stderr);
795 }
796
797 /* Accept "tty", "baudrate tty", and "tty baudrate". */
798 if (is_speed(argv[optind])) {
799 /* Assume BSD style speed. */
800 parse_speeds(op, argv[optind++]);
801 if (argc < optind + 1) {
802 warn(_("not enough arguments"));
803 usage(stderr);
804 }
805 op->tty = argv[optind++];
806 } else {
807 op->tty = argv[optind++];
808 if (argc > optind) {
809 char *v = argv[optind];
810 if (is_speed(v)) {
811 parse_speeds(op, v);
812 optind++;
813 }
814 }
815 }
816
817 /* On virtual console remember the line which is used for */
818 if (strncmp(op->tty, "tty", 3) == 0 &&
819 strspn(op->tty + 3, "0123456789") == strlen(op->tty+3))
820 op->vcline = op->tty+3;
821
822 if (argc > optind && argv[optind])
823 op->term = argv[optind];
824
825 #ifdef DO_DEVFS_FIDDLING
826 /*
827 * Some devfs junk, following Goswin Brederlow:
828 * turn ttyS<n> into tts/<n>
829 * turn tty<n> into vc/<n>
830 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=72241
831 */
832 if (op->tty && strlen(op->tty) < 90) {
833 char dev_name[100];
834 struct stat st;
835
836 if (strncmp(op->tty, "ttyS", 4) == 0) {
837 strcpy(dev_name, "/dev/");
838 strcat(dev_name, op->tty);
839 if (stat(dev_name, &st) < 0) {
840 strcpy(dev_name, "/dev/tts/");
841 strcat(dev_name, op->tty + 4);
842 if (stat(dev_name, &st) == 0) {
843 op->tty = strdup(dev_name + 5);
844 if (!op->tty)
845 log_err(_("failed to allocate memory: %m"));
846 }
847 }
848 } else if (strncmp(op->tty, "tty", 3) == 0) {
849 strcpy(dev_name, "/dev/");
850 strncat(dev_name, op->tty, 90);
851 if (stat(dev_name, &st) < 0) {
852 strcpy(dev_name, "/dev/vc/");
853 strcat(dev_name, op->tty + 3);
854 if (stat(dev_name, &st) == 0) {
855 op->tty = strdup(dev_name + 5);
856 if (!op->tty)
857 log_err(_("failed to allocate memory: %m"));
858 }
859 }
860 }
861 }
862 #endif /* DO_DEVFS_FIDDLING */
863
864 debug("exiting parseargs\n");
865 }
866
867 /* Parse alternate baud rates. */
868 static void parse_speeds(struct options *op, char *arg)
869 {
870 char *cp;
871 char *str = strdup(arg);
872
873 if (!str)
874 log_err(_("failed to allocate memory: %m"));
875
876 debug("entered parse_speeds:\n");
877 for (cp = strtok(str, ","); cp != NULL; cp = strtok((char *)0, ",")) {
878 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
879 log_err(_("bad speed: %s"), cp);
880 if (op->numspeed >= MAX_SPEED)
881 log_err(_("too many alternate speeds"));
882 }
883 debug("exiting parsespeeds\n");
884 free(str);
885 }
886
887 #ifdef SYSV_STYLE
888
889 /* Update our utmp entry. */
890 static void update_utmp(struct options *op)
891 {
892 struct utmp ut;
893 time_t t;
894 pid_t pid = getpid();
895 pid_t sid = getsid(0);
896 char *vcline = op->vcline;
897 char *line = op->tty;
898 struct utmp *utp;
899
900 /*
901 * The utmp file holds miscellaneous information about things started by
902 * /sbin/init and other system-related events. Our purpose is to update
903 * the utmp entry for the current process, in particular the process type
904 * and the tty line we are listening to. Return successfully only if the
905 * utmp file can be opened for update, and if we are able to find our
906 * entry in the utmp file.
907 */
908 utmpname(_PATH_UTMP);
909 setutent();
910
911 /*
912 * Find my pid in utmp.
913 *
914 * FIXME: Earlier (when was that?) code here tested only utp->ut_type !=
915 * INIT_PROCESS, so maybe the >= here should be >.
916 *
917 * FIXME: The present code is taken from login.c, so if this is changed,
918 * maybe login has to be changed as well (is this true?).
919 */
920 while ((utp = getutent()))
921 if (utp->ut_pid == pid
922 && utp->ut_type >= INIT_PROCESS
923 && utp->ut_type <= DEAD_PROCESS)
924 break;
925
926 if (utp) {
927 memcpy(&ut, utp, sizeof(ut));
928 } else {
929 /* Some inits do not initialize utmp. */
930 memset(&ut, 0, sizeof(ut));
931 if (vcline && *vcline)
932 /* Standard virtual console devices */
933 strncpy(ut.ut_id, vcline, sizeof(ut.ut_id));
934 else {
935 size_t len = strlen(line);
936 char * ptr;
937 if (len >= sizeof(ut.ut_id))
938 ptr = line + len - sizeof(ut.ut_id);
939 else
940 ptr = line;
941 strncpy(ut.ut_id, ptr, sizeof(ut.ut_id));
942 }
943 }
944
945 strncpy(ut.ut_user, "LOGIN", sizeof(ut.ut_user));
946 strncpy(ut.ut_line, line, sizeof(ut.ut_line));
947 if (fakehost)
948 strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
949 time(&t);
950 #if defined(_HAVE_UT_TV)
951 ut.ut_tv.tv_sec = t;
952 #else
953 ut.ut_time = t;
954 #endif
955 ut.ut_type = LOGIN_PROCESS;
956 ut.ut_pid = pid;
957 ut.ut_session = sid;
958
959 pututline(&ut);
960 endutent();
961
962 {
963 #ifdef HAVE_UPDWTMP
964 updwtmp(_PATH_WTMP, &ut);
965 #else
966 int ut_fd;
967 int lf;
968
969 if ((lf = open(_PATH_WTMPLOCK, O_CREAT | O_WRONLY, 0660)) >= 0) {
970 flock(lf, LOCK_EX);
971 if ((ut_fd =
972 open(_PATH_WTMP, O_APPEND | O_WRONLY)) >= 0) {
973 write_all(ut_fd, &ut, sizeof(ut));
974 close(ut_fd);
975 }
976 flock(lf, LOCK_UN);
977 close(lf);
978 }
979 #endif /* HAVE_UPDWTMP */
980 }
981 }
982
983 #endif /* SYSV_STYLE */
984
985 /* Set up tty as stdin, stdout & stderr. */
986 static void open_tty(char *tty, struct termios *tp, struct options *op)
987 {
988 const pid_t pid = getpid();
989 int closed = 0;
990 #ifndef KDGKBMODE
991 int serial;
992 #endif
993
994 /* Set up new standard input, unless we are given an already opened port. */
995
996 if (strcmp(tty, "-") != 0) {
997 char buf[PATH_MAX+1];
998 struct group *gr = NULL;
999 struct stat st;
1000 int fd, len;
1001 pid_t tid;
1002 gid_t gid = 0;
1003
1004 /* Use tty group if available */
1005 if ((gr = getgrnam("tty")))
1006 gid = gr->gr_gid;
1007
1008 len = snprintf(buf, sizeof(buf), "/dev/%s", tty);
1009 if (len < 0 || (size_t)len >= sizeof(buf))
1010 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
1011
1012 /* Open the tty as standard input. */
1013 if ((fd = open(buf, O_RDWR|O_NOCTTY|O_NONBLOCK, 0)) < 0)
1014 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
1015
1016 /*
1017 * There is always a race between this reset and the call to
1018 * vhangup() that s.o. can use to get access to your tty.
1019 * Linux login(1) will change tty permissions. Use root owner and group
1020 * with permission -rw------- for the period between getty and login.
1021 */
1022 if (fchown(fd, 0, gid) || fchmod(fd, (gid ? 0620 : 0600))) {
1023 if (errno == EROFS)
1024 log_warn("%s: %m", buf);
1025 else
1026 log_err("%s: %m", buf);
1027 }
1028
1029 /* Sanity checks... */
1030 if (fstat(fd, &st) < 0)
1031 log_err("%s: %m", buf);
1032 if ((st.st_mode & S_IFMT) != S_IFCHR)
1033 log_err(_("/dev/%s: not a character device"), tty);
1034 if (!isatty(fd))
1035 log_err(_("/dev/%s: not a tty"), tty);
1036
1037 if (((tid = tcgetsid(fd)) < 0) || (pid != tid)) {
1038 if (ioctl(fd, TIOCSCTTY, 1) == -1)
1039 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty);
1040 }
1041
1042 close(STDIN_FILENO);
1043 errno = 0;
1044
1045 if (op->flags & F_HANGUP) {
1046
1047 if (ioctl(fd, TIOCNOTTY))
1048 debug("TIOCNOTTY ioctl failed\n");
1049
1050 /*
1051 * Let's close all file descriptors before vhangup
1052 * https://lkml.org/lkml/2012/6/5/145
1053 */
1054 close(fd);
1055 close(STDOUT_FILENO);
1056 close(STDERR_FILENO);
1057 errno = 0;
1058 closed = 1;
1059
1060 if (vhangup())
1061 log_err(_("/dev/%s: vhangup() failed: %m"), tty);
1062 } else
1063 close(fd);
1064
1065 debug("open(2)\n");
1066 if (open(buf, O_RDWR|O_NOCTTY|O_NONBLOCK, 0) != 0)
1067 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
1068
1069 if (((tid = tcgetsid(STDIN_FILENO)) < 0) || (pid != tid)) {
1070 if (ioctl(STDIN_FILENO, TIOCSCTTY, 1) == -1)
1071 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty);
1072 }
1073
1074 } else {
1075
1076 /*
1077 * Standard input should already be connected to an open port. Make
1078 * sure it is open for read/write.
1079 */
1080
1081 if ((fcntl(STDIN_FILENO, F_GETFL, 0) & O_RDWR) != O_RDWR)
1082 log_err(_("%s: not open for read/write"), tty);
1083
1084 }
1085
1086 if (tcsetpgrp(STDIN_FILENO, pid))
1087 log_warn(_("/dev/%s: cannot set process group: %m"), tty);
1088
1089 /* Get rid of the present outputs. */
1090 if (!closed) {
1091 close(STDOUT_FILENO);
1092 close(STDERR_FILENO);
1093 errno = 0;
1094 }
1095
1096 /* Set up standard output and standard error file descriptors. */
1097 debug("duping\n");
1098
1099 /* set up stdout and stderr */
1100 if (dup(STDIN_FILENO) != 1 || dup(STDIN_FILENO) != 2)
1101 log_err(_("%s: dup problem: %m"), tty);
1102
1103 /* make stdio unbuffered for slow modem lines */
1104 setvbuf(stdout, NULL, _IONBF, 0);
1105
1106 /*
1107 * The following ioctl will fail if stdin is not a tty, but also when
1108 * there is noise on the modem control lines. In the latter case, the
1109 * common course of action is (1) fix your cables (2) give the modem
1110 * more time to properly reset after hanging up.
1111 *
1112 * SunOS users can achieve (2) by patching the SunOS kernel variable
1113 * "zsadtrlow" to a larger value; 5 seconds seems to be a good value.
1114 * http://www.sunmanagers.org/archives/1993/0574.html
1115 */
1116 memset(tp, 0, sizeof(struct termios));
1117 if (tcgetattr(STDIN_FILENO, tp) < 0)
1118 log_err(_("%s: failed to get terminal attributes: %m"), tty);
1119
1120 #if defined (__s390__) || defined (__s390x__)
1121 if (!op->term) {
1122 /*
1123 * Special terminal on first serial line on a S/390(x) which
1124 * is due legacy reasons a block terminal of type 3270 or
1125 * higher. Whereas the second serial line on a S/390(x) is
1126 * a real character terminal which is compatible with VT220.
1127 */
1128 if (strcmp(op->tty, "ttyS0") == 0) /* linux/drivers/s390/char/con3215.c */
1129 op->term = DEFAULT_TTYS0;
1130 else if (strncmp(op->tty, "3270/tty", 8) == 0) /* linux/drivers/s390/char/con3270.c */
1131 op->term = DEFAULT_TTY32;
1132 else if (strcmp(op->tty, "ttyS1") == 0) /* linux/drivers/s390/char/sclp_vt220.c */
1133 op->term = DEFAULT_TTYS1;
1134 }
1135 #endif
1136
1137 #if defined(__FreeBSD_kernel__)
1138 login_tty (0);
1139 #endif
1140
1141 /*
1142 * Detect if this is a virtual console or serial/modem line.
1143 * In case of a virtual console the ioctl KDGKBMODE succeeds
1144 * whereas on other lines it will fails.
1145 */
1146 #ifdef KDGKBMODE
1147 if (ioctl(STDIN_FILENO, KDGKBMODE, &op->kbmode) == 0)
1148 #else
1149 if (ioctl(STDIN_FILENO, TIOCMGET, &serial) < 0 && (errno == EINVAL))
1150 #endif
1151 {
1152 op->flags |= F_VCONSOLE;
1153 if (!op->term)
1154 op->term = DEFAULT_VCTERM;
1155 } else {
1156 #ifdef K_RAW
1157 op->kbmode = K_RAW;
1158 #endif
1159 if (!op->term)
1160 op->term = DEFAULT_STERM;
1161 }
1162
1163 setenv("TERM", op->term, 1);
1164 }
1165
1166 /* Initialize termios settings. */
1167 static void termio_clear(int fd)
1168 {
1169 /*
1170 * Do not write a full reset (ESC c) because this destroys
1171 * the unicode mode again if the terminal was in unicode
1172 * mode. Also it clears the CONSOLE_MAGIC features which
1173 * are required for some languages/console-fonts.
1174 * Just put the cursor to the home position (ESC [ H),
1175 * erase everything below the cursor (ESC [ J), and set the
1176 * scrolling region to the full window (ESC [ r)
1177 */
1178 write_all(fd, "\033[r\033[H\033[J", 9);
1179 }
1180
1181 /* Initialize termios settings. */
1182 static void termio_init(struct options *op, struct termios *tp)
1183 {
1184 speed_t ispeed, ospeed;
1185 struct winsize ws;
1186 #ifdef USE_PLYMOUTH_SUPPORT
1187 struct termios lock;
1188 int i = (plymouth_command(MAGIC_PING) == 0) ? PLYMOUTH_TERMIOS_FLAGS_DELAY : 0;
1189 if (i)
1190 plymouth_command(MAGIC_QUIT);
1191 while (i-- > 0) {
1192 /*
1193 * Even with TTYReset=no it seems with systemd or plymouth
1194 * the termios flags become changed from under the first
1195 * agetty on a serial system console as the flags are locked.
1196 */
1197 memset(&lock, 0, sizeof(struct termios));
1198 if (ioctl(STDIN_FILENO, TIOCGLCKTRMIOS, &lock) < 0)
1199 break;
1200 if (!lock.c_iflag && !lock.c_oflag && !lock.c_cflag && !lock.c_lflag)
1201 break;
1202 debug("termios locked\n");
1203 sleep(1);
1204 }
1205 memset(&lock, 0, sizeof(struct termios));
1206 ioctl(STDIN_FILENO, TIOCSLCKTRMIOS, &lock);
1207 #endif
1208
1209 if (op->flags & F_VCONSOLE) {
1210 #if defined(IUTF8) && defined(KDGKBMODE)
1211 switch(op->kbmode) {
1212 case K_UNICODE:
1213 setlocale(LC_CTYPE, "C.UTF-8");
1214 op->flags |= F_UTF8;
1215 break;
1216 case K_RAW:
1217 case K_MEDIUMRAW:
1218 case K_XLATE:
1219 default:
1220 setlocale(LC_CTYPE, "POSIX");
1221 op->flags &= ~F_UTF8;
1222 break;
1223 }
1224 #else
1225 setlocale(LC_CTYPE, "POSIX");
1226 op->flags &= ~F_UTF8;
1227 #endif
1228 reset_vc(op, tp);
1229
1230 if ((tp->c_cflag & (CS8|PARODD|PARENB)) == CS8)
1231 op->flags |= F_EIGHTBITS;
1232
1233 if ((op->flags & F_NOCLEAR) == 0)
1234 termio_clear(STDOUT_FILENO);
1235 return;
1236 }
1237
1238 /*
1239 * Serial line
1240 */
1241
1242 if (op->flags & F_KEEPSPEED || !op->numspeed) {
1243 /* Save the original setting. */
1244 ispeed = cfgetispeed(tp);
1245 ospeed = cfgetospeed(tp);
1246
1247 if (!ispeed) ispeed = TTYDEF_SPEED;
1248 if (!ospeed) ospeed = TTYDEF_SPEED;
1249
1250 } else {
1251 ospeed = ispeed = op->speeds[FIRST_SPEED];
1252 }
1253
1254 /*
1255 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
1256 * Special characters are set after we have read the login name; all
1257 * reads will be done in raw mode anyway. Errors will be dealt with
1258 * later on.
1259 */
1260
1261 #ifdef IUTF8
1262 tp->c_iflag = tp->c_iflag & IUTF8;
1263 if (tp->c_iflag & IUTF8)
1264 op->flags |= F_UTF8;
1265 #else
1266 tp->c_iflag = 0;
1267 #endif
1268 tp->c_lflag = 0;
1269 tp->c_oflag &= OPOST | ONLCR;
1270
1271 if ((op->flags & F_KEEPCFLAGS) == 0)
1272 tp->c_cflag = CS8 | HUPCL | CREAD | (tp->c_cflag & CLOCAL);
1273
1274 /*
1275 * Note that the speed is stored in the c_cflag termios field, so we have
1276 * set the speed always when the cflag is reset.
1277 */
1278 cfsetispeed(tp, ispeed);
1279 cfsetospeed(tp, ospeed);
1280
1281 /* The default is to follow setting from kernel, but it's possible
1282 * to explicitly remove/add CLOCAL flag by -L[=<mode>]*/
1283 switch (op->clocal) {
1284 case CLOCAL_MODE_ALWAYS:
1285 tp->c_cflag |= CLOCAL; /* -L or -L=always */
1286 break;
1287 case CLOCAL_MODE_NEVER:
1288 tp->c_cflag &= ~CLOCAL; /* -L=never */
1289 break;
1290 case CLOCAL_MODE_AUTO: /* -L=auto */
1291 break;
1292 }
1293
1294 #ifdef HAVE_STRUCT_TERMIOS_C_LINE
1295 tp->c_line = 0;
1296 #endif
1297 tp->c_cc[VMIN] = 1;
1298 tp->c_cc[VTIME] = 0;
1299
1300 /* Check for terminal size and if not found set default */
1301 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0) {
1302 int set = 0;
1303 if (ws.ws_row == 0) {
1304 ws.ws_row = 24;
1305 set++;
1306 }
1307 if (ws.ws_col == 0) {
1308 ws.ws_col = 80;
1309 set++;
1310 }
1311 if (ioctl(STDIN_FILENO, TIOCSWINSZ, &ws))
1312 debug("TIOCSWINSZ ioctl failed\n");
1313 }
1314
1315 /* Optionally enable hardware flow control. */
1316 #ifdef CRTSCTS
1317 if (op->flags & F_RTSCTS)
1318 tp->c_cflag |= CRTSCTS;
1319 #endif
1320 /* Flush input and output queues, important for modems! */
1321 tcflush(STDIN_FILENO, TCIOFLUSH);
1322
1323 if (tcsetattr(STDIN_FILENO, TCSANOW, tp))
1324 log_warn(_("setting terminal attributes failed: %m"));
1325
1326 /* Go to blocking input even in local mode. */
1327 fcntl(STDIN_FILENO, F_SETFL,
1328 fcntl(STDIN_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
1329
1330 debug("term_io 2\n");
1331 }
1332
1333 /* Reset virtual console on stdin to its defaults */
1334 static void reset_vc(const struct options *op, struct termios *tp)
1335 {
1336 int fl = 0;
1337
1338 fl |= (op->flags & F_KEEPCFLAGS) == 0 ? 0 : UL_TTY_KEEPCFLAGS;
1339 fl |= (op->flags & F_UTF8) == 0 ? 0 : UL_TTY_UTF8;
1340
1341 reset_virtual_console(tp, fl);
1342
1343 if (tcsetattr(STDIN_FILENO, TCSADRAIN, tp))
1344 log_warn(_("setting terminal attributes failed: %m"));
1345
1346 /* Go to blocking input even in local mode. */
1347 fcntl(STDIN_FILENO, F_SETFL,
1348 fcntl(STDIN_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
1349 }
1350
1351 /* Extract baud rate from modem status message. */
1352 static void auto_baud(struct termios *tp)
1353 {
1354 speed_t speed;
1355 int vmin;
1356 unsigned iflag;
1357 char buf[BUFSIZ];
1358 char *bp;
1359 int nread;
1360
1361 /*
1362 * This works only if the modem produces its status code AFTER raising
1363 * the DCD line, and if the computer is fast enough to set the proper
1364 * baud rate before the message has gone by. We expect a message of the
1365 * following format:
1366 *
1367 * <junk><number><junk>
1368 *
1369 * The number is interpreted as the baud rate of the incoming call. If the
1370 * modem does not tell us the baud rate within one second, we will keep
1371 * using the current baud rate. It is advisable to enable BREAK
1372 * processing (comma-separated list of baud rates) if the processing of
1373 * modem status messages is enabled.
1374 */
1375
1376 /*
1377 * Use 7-bit characters, don't block if input queue is empty. Errors will
1378 * be dealt with later on.
1379 */
1380 iflag = tp->c_iflag;
1381 /* Enable 8th-bit stripping. */
1382 tp->c_iflag |= ISTRIP;
1383 vmin = tp->c_cc[VMIN];
1384 /* Do not block when queue is empty. */
1385 tp->c_cc[VMIN] = 0;
1386 tcsetattr(STDIN_FILENO, TCSANOW, tp);
1387
1388 /*
1389 * Wait for a while, then read everything the modem has said so far and
1390 * try to extract the speed of the dial-in call.
1391 */
1392 sleep(1);
1393 if ((nread = read(STDIN_FILENO, buf, sizeof(buf) - 1)) > 0) {
1394 buf[nread] = '\0';
1395 for (bp = buf; bp < buf + nread; bp++)
1396 if (isascii(*bp) && isdigit(*bp)) {
1397 if ((speed = bcode(bp))) {
1398 cfsetispeed(tp, speed);
1399 cfsetospeed(tp, speed);
1400 }
1401 break;
1402 }
1403 }
1404
1405 /* Restore terminal settings. Errors will be dealt with later on. */
1406 tp->c_iflag = iflag;
1407 tp->c_cc[VMIN] = vmin;
1408 tcsetattr(STDIN_FILENO, TCSANOW, tp);
1409 }
1410
1411 static char *xgethostname(void)
1412 {
1413 char *name;
1414 size_t sz = get_hostname_max() + 1;
1415
1416 name = malloc(sizeof(char) * sz);
1417 if (!name)
1418 log_err(_("failed to allocate memory: %m"));
1419
1420 if (gethostname(name, sz) != 0) {
1421 free(name);
1422 return NULL;
1423 }
1424 name[sz - 1] = '\0';
1425 return name;
1426 }
1427
1428 static char *xgetdomainname(void)
1429 {
1430 #ifdef HAVE_GETDOMAINNAME
1431 char *name;
1432 size_t sz = get_hostname_max() + 1;
1433
1434 name = malloc(sizeof(char) * sz);
1435 if (!name)
1436 log_err(_("failed to allocate memory: %m"));
1437
1438 if (getdomainname(name, sz) != 0) {
1439 free(name);
1440 return NULL;
1441 }
1442 name[sz - 1] = '\0';
1443 return name;
1444 #endif
1445 return NULL;
1446 }
1447
1448 static char *read_os_release(struct options *op, const char *varname)
1449 {
1450 int fd = -1;
1451 struct stat st;
1452 size_t varsz = strlen(varname);
1453 char *p, *buf = NULL, *ret = NULL;
1454
1455 /* read the file only once */
1456 if (!op->osrelease) {
1457 fd = open(_PATH_OS_RELEASE_ETC, O_RDONLY);
1458 if (fd == -1) {
1459 fd = open(_PATH_OS_RELEASE_USR, O_RDONLY);
1460 if (fd == -1) {
1461 log_warn(_("cannot open os-release file"));
1462 return NULL;
1463 }
1464 }
1465
1466 if (fstat(fd, &st) < 0 || st.st_size > 4 * 1024 * 1024)
1467 goto done;
1468
1469 op->osrelease = malloc(st.st_size + 1);
1470 if (!op->osrelease)
1471 log_err(_("failed to allocate memory: %m"));
1472 if (read_all(fd, op->osrelease, st.st_size) != (ssize_t) st.st_size) {
1473 free(op->osrelease);
1474 op->osrelease = NULL;
1475 goto done;
1476 }
1477 op->osrelease[st.st_size] = 0;
1478 }
1479 buf = strdup(op->osrelease);
1480 if (!buf)
1481 log_err(_("failed to allocate memory: %m"));
1482 p = buf;
1483
1484 for (;;) {
1485 char *eol, *eon;
1486
1487 p += strspn(p, "\n\r");
1488 p += strspn(p, " \t\n\r");
1489 if (!*p)
1490 break;
1491 if (strspn(p, "#;\n") != 0) {
1492 p += strcspn(p, "\n\r");
1493 continue;
1494 }
1495 if (strncmp(p, varname, varsz) != 0) {
1496 p += strcspn(p, "\n\r");
1497 continue;
1498 }
1499 p += varsz;
1500 p += strspn(p, " \t\n\r=\"");
1501 eol = p + strcspn(p, "\n\r");
1502 *eol = '\0';
1503 eon = eol-1;
1504 while (eon > p) {
1505 if (*eon == '\t' || *eon == ' ') {
1506 eon--;
1507 continue;
1508 }
1509 if (*eon == '"') {
1510 *eon = '\0';
1511 break;
1512 }
1513 break;
1514 }
1515 free(ret);
1516 ret = strdup(p);
1517 if (!ret)
1518 log_err(_("failed to allocate memory: %m"));
1519 p = eol + 1;
1520 }
1521 done:
1522 free(buf);
1523 if (fd >= 0)
1524 close(fd);
1525 return ret;
1526 }
1527
1528 #ifdef AGETTY_RELOAD
1529 static void open_netlink(void)
1530 {
1531 struct sockaddr_nl addr = { 0, };
1532 int sock;
1533
1534 if (netlink_fd != AGETTY_RELOAD_FDNONE)
1535 return;
1536
1537 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1538 if (sock >= 0) {
1539 addr.nl_family = AF_NETLINK;
1540 addr.nl_pid = getpid();
1541 addr.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
1542 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
1543 close(sock);
1544 else
1545 netlink_fd = sock;
1546 }
1547 }
1548
1549 static int process_netlink_msg(int *changed)
1550 {
1551 char buf[4096];
1552 struct sockaddr_nl snl;
1553 struct nlmsghdr *h;
1554 int rc;
1555
1556 struct iovec iov = {
1557 .iov_base = buf,
1558 .iov_len = sizeof(buf)
1559 };
1560 struct msghdr msg = {
1561 .msg_name = &snl,
1562 .msg_namelen = sizeof(snl),
1563 .msg_iov = &iov,
1564 .msg_iovlen = 1,
1565 .msg_control = NULL,
1566 .msg_controllen = 0,
1567 .msg_flags = 0
1568 };
1569
1570 rc = recvmsg(netlink_fd, &msg, MSG_DONTWAIT);
1571 if (rc < 0) {
1572 if (errno == EWOULDBLOCK || errno == EAGAIN)
1573 return 0;
1574
1575 /* Failure, just stop listening for changes */
1576 close(netlink_fd);
1577 netlink_fd = AGETTY_RELOAD_FDNONE;
1578 return 0;
1579 }
1580
1581 for (h = (struct nlmsghdr *)buf; NLMSG_OK(h, (unsigned int)rc); h = NLMSG_NEXT(h, rc)) {
1582 if (h->nlmsg_type == NLMSG_DONE ||
1583 h->nlmsg_type == NLMSG_ERROR) {
1584 close(netlink_fd);
1585 netlink_fd = AGETTY_RELOAD_FDNONE;
1586 return 0;
1587 }
1588
1589 *changed = 1;
1590 break;
1591 }
1592
1593 return 1;
1594 }
1595
1596 static int process_netlink(void)
1597 {
1598 int changed = 0;
1599 while (process_netlink_msg(&changed));
1600 return changed;
1601 }
1602
1603 static int wait_for_term_input(int fd)
1604 {
1605 char buffer[sizeof(struct inotify_event) + NAME_MAX + 1];
1606 struct termios orig, nonc;
1607 fd_set rfds;
1608 int count, i;
1609
1610 /* Our aim here is to fall through if something fails
1611 * and not be stuck waiting. On failure assume we have input */
1612
1613 if (tcgetattr(fd, &orig) != 0)
1614 return 1;
1615
1616 memcpy(&nonc, &orig, sizeof (nonc));
1617 nonc.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHOKE);
1618 nonc.c_cc[VMIN] = 1;
1619 nonc.c_cc[VTIME] = 0;
1620
1621 if (tcsetattr(fd, TCSANOW, &nonc) != 0)
1622 return 1;
1623
1624 if (inotify_fd == AGETTY_RELOAD_FDNONE) {
1625 /* make sure the reload trigger file exists */
1626 int reload_fd = open(AGETTY_RELOAD_FILENAME,
1627 O_CREAT|O_CLOEXEC|O_RDONLY,
1628 S_IRUSR|S_IWUSR);
1629
1630 /* initialize reload trigger inotify stuff */
1631 if (reload_fd >= 0) {
1632 inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
1633 if (inotify_fd > 0)
1634 inotify_add_watch(inotify_fd, AGETTY_RELOAD_FILENAME,
1635 IN_ATTRIB | IN_MODIFY);
1636
1637 close(reload_fd);
1638 } else
1639 log_warn(_("failed to create reload file: %s: %m"),
1640 AGETTY_RELOAD_FILENAME);
1641 }
1642
1643 while (1) {
1644 int nfds = fd;
1645
1646 FD_ZERO(&rfds);
1647 FD_SET(fd, &rfds);
1648
1649 if (inotify_fd >= 0) {
1650 FD_SET(inotify_fd, &rfds);
1651 nfds = max(nfds, inotify_fd);
1652 }
1653 if (netlink_fd >= 0) {
1654 FD_SET(netlink_fd, &rfds);
1655 nfds = max(nfds, netlink_fd);
1656 }
1657
1658 /* If waiting fails, just fall through, presumably reading input will fail */
1659 if (select(nfds + 1, &rfds, NULL, NULL, NULL) < 0)
1660 return 1;
1661
1662 if (FD_ISSET(fd, &rfds)) {
1663 count = read(fd, buffer, sizeof (buffer));
1664
1665 tcsetattr(fd, TCSANOW, &orig);
1666
1667 /* Reinject the bytes we read back into the buffer, usually just one byte */
1668 for (i = 0; i < count; i++)
1669 ioctl(fd, TIOCSTI, buffer + i);
1670
1671 /* Have terminal input */
1672 return 1;
1673
1674 } else if (netlink_fd >= 0 && FD_ISSET(netlink_fd, &rfds)) {
1675 if (!process_netlink())
1676 continue;
1677
1678 /* Just drain the inotify buffer */
1679 } else if (inotify_fd >= 0 && FD_ISSET(inotify_fd, &rfds)) {
1680 while (read(inotify_fd, buffer, sizeof (buffer)) > 0);
1681 }
1682
1683 tcsetattr(fd, TCSANOW, &orig);
1684
1685 /* Need to reprompt */
1686 return 0;
1687 }
1688 }
1689 #endif /* AGETTY_RELOAD */
1690 static void print_issue_file(struct options *op, struct termios *tp)
1691 {
1692 #ifdef ISSUE
1693 FILE *fd;
1694 #endif
1695 if ((op->flags & F_NONL) == 0) {
1696 /* Issue not in use, start with a new line. */
1697 write_all(STDOUT_FILENO, "\r\n", 2);
1698 }
1699
1700 #ifdef ISSUE
1701 if ((op->flags & F_ISSUE) && (fd = fopen(op->issue, "r"))) {
1702 int c, oflag = tp->c_oflag; /* Save current setting. */
1703
1704 if ((op->flags & F_VCONSOLE) == 0) {
1705 /* Map new line in output to carriage return & new line. */
1706 tp->c_oflag |= (ONLCR | OPOST);
1707 tcsetattr(STDIN_FILENO, TCSADRAIN, tp);
1708 }
1709
1710 while ((c = getc(fd)) != EOF) {
1711 if (c == '\\')
1712 output_special_char(getc(fd), op, tp, fd);
1713 else
1714 putchar(c);
1715 }
1716 fflush(stdout);
1717
1718 if ((op->flags & F_VCONSOLE) == 0) {
1719 /* Restore settings. */
1720 tp->c_oflag = oflag;
1721 /* Wait till output is gone. */
1722 tcsetattr(STDIN_FILENO, TCSADRAIN, tp);
1723 }
1724 fclose(fd);
1725 }
1726 #endif /* ISSUE */
1727 }
1728
1729 /* Show login prompt, optionally preceded by /etc/issue contents. */
1730 static void do_prompt(struct options *op, struct termios *tp)
1731 {
1732 #ifdef AGETTY_RELOAD
1733 again:
1734 #endif
1735 print_issue_file(op, tp);
1736
1737 if (op->flags & F_LOGINPAUSE) {
1738 puts(_("[press ENTER to login]"));
1739 #ifdef AGETTY_RELOAD
1740 if (!wait_for_term_input(STDIN_FILENO)) {
1741 /* reload issue */
1742 if (op->flags & F_VCONSOLE)
1743 termio_clear(STDOUT_FILENO);
1744 goto again;
1745 }
1746 #endif
1747 getc(stdin);
1748 }
1749 #ifdef KDGKBLED
1750 if (!(op->flags & F_NOHINTS) && !op->autolog &&
1751 (op->flags & F_VCONSOLE)) {
1752 int kb = 0;
1753
1754 if (ioctl(STDIN_FILENO, KDGKBLED, &kb) == 0) {
1755 char hint[256] = { '\0' };
1756 int nl = 0;
1757
1758 if (access(_PATH_NUMLOCK_ON, F_OK) == 0)
1759 nl = 1;
1760
1761 if (nl && (kb & 0x02) == 0)
1762 append(hint, sizeof(hint), NULL, _("Num Lock off"));
1763
1764 else if (nl == 0 && (kb & 2) && (kb & 0x20) == 0)
1765 append(hint, sizeof(hint), NULL, _("Num Lock on"));
1766
1767 if ((kb & 0x04) && (kb & 0x40) == 0)
1768 append(hint, sizeof(hint), ", ", _("Caps Lock on"));
1769
1770 if ((kb & 0x01) && (kb & 0x10) == 0)
1771 append(hint, sizeof(hint), ", ", _("Scroll Lock on"));
1772
1773 if (*hint)
1774 printf(_("Hint: %s\n\n"), hint);
1775 }
1776 }
1777 #endif /* KDGKBLED */
1778 if ((op->flags & F_NOHOSTNAME) == 0) {
1779 char *hn = xgethostname();
1780
1781 if (hn) {
1782 char *dot = strchr(hn, '.');
1783 char *cn = hn;
1784 struct addrinfo *res = NULL;
1785
1786 if ((op->flags & F_LONGHNAME) == 0) {
1787 if (dot)
1788 *dot = '\0';
1789
1790 } else if (dot == NULL) {
1791 struct addrinfo hints;
1792
1793 memset(&hints, 0, sizeof(hints));
1794 hints.ai_flags = AI_CANONNAME;
1795
1796 if (!getaddrinfo(hn, NULL, &hints, &res)
1797 && res && res->ai_canonname)
1798 cn = res->ai_canonname;
1799 }
1800
1801 write_all(STDOUT_FILENO, cn, strlen(cn));
1802 write_all(STDOUT_FILENO, " ", 1);
1803
1804 if (res)
1805 freeaddrinfo(res);
1806 free(hn);
1807 }
1808 }
1809 if (!op->autolog) {
1810 /* Always show login prompt. */
1811 write_all(STDOUT_FILENO, LOGIN, sizeof(LOGIN) - 1);
1812 }
1813 }
1814
1815 /* Select next baud rate. */
1816 static void next_speed(struct options *op, struct termios *tp)
1817 {
1818 static int baud_index = -1;
1819
1820 if (baud_index == -1)
1821 /*
1822 * If the F_KEEPSPEED flags is set then the FIRST_SPEED is not
1823 * tested yet (see termio_init()).
1824 */
1825 baud_index =
1826 (op->flags & F_KEEPSPEED) ? FIRST_SPEED : 1 % op->numspeed;
1827 else
1828 baud_index = (baud_index + 1) % op->numspeed;
1829
1830 cfsetispeed(tp, op->speeds[baud_index]);
1831 cfsetospeed(tp, op->speeds[baud_index]);
1832 tcsetattr(STDIN_FILENO, TCSANOW, tp);
1833 }
1834
1835 /* Get user name, establish parity, speed, erase, kill & eol. */
1836 static char *get_logname(struct options *op, struct termios *tp, struct chardata *cp)
1837 {
1838 static char logname[BUFSIZ];
1839 char *bp;
1840 char c; /* input character, full eight bits */
1841 char ascval; /* low 7 bits of input character */
1842 int eightbit;
1843 static char *erase[] = { /* backspace-space-backspace */
1844 "\010\040\010", /* space parity */
1845 "\010\040\010", /* odd parity */
1846 "\210\240\210", /* even parity */
1847 "\210\240\210", /* no parity */
1848 };
1849
1850 /* Initialize kill, erase, parity etc. (also after switching speeds). */
1851 INIT_CHARDATA(cp);
1852
1853 /*
1854 * Flush pending input (especially important after parsing or switching
1855 * the baud rate).
1856 */
1857 if ((op->flags & F_VCONSOLE) == 0)
1858 sleep(1);
1859 tcflush(STDIN_FILENO, TCIFLUSH);
1860
1861 eightbit = (op->flags & F_EIGHTBITS);
1862 bp = logname;
1863 *bp = '\0';
1864
1865 while (*logname == '\0') {
1866
1867 /* Write issue file and prompt */
1868 do_prompt(op, tp);
1869
1870 #ifdef AGETTY_RELOAD
1871 /* If asked to reprompt *before* terminal input arrives, then do so */
1872 if (!wait_for_term_input(STDIN_FILENO)) {
1873 if (op->flags & F_VCONSOLE)
1874 termio_clear(STDOUT_FILENO);
1875 continue;
1876 }
1877 #endif
1878 cp->eol = '\0';
1879
1880 /* Read name, watch for break and end-of-line. */
1881 while (cp->eol == '\0') {
1882
1883 char key;
1884
1885 if (read(STDIN_FILENO, &c, 1) < 1) {
1886
1887 /* The terminal could be open with O_NONBLOCK when
1888 * -L (force CLOCAL) is specified... */
1889 if (errno == EINTR || errno == EAGAIN) {
1890 xusleep(250000);
1891 continue;
1892 }
1893 switch (errno) {
1894 case 0:
1895 case EIO:
1896 case ESRCH:
1897 case EINVAL:
1898 case ENOENT:
1899 break;
1900 default:
1901 log_err(_("%s: read: %m"), op->tty);
1902 }
1903 }
1904
1905 /* Do parity bit handling. */
1906 if (eightbit)
1907 ascval = c;
1908 else if (c != (ascval = (c & 0177))) {
1909 uint32_t bits; /* # of "1" bits per character */
1910 uint32_t mask; /* mask with 1 bit up */
1911 for (bits = 1, mask = 1; mask & 0177; mask <<= 1) {
1912 if (mask & ascval)
1913 bits++;
1914 }
1915 cp->parity |= ((bits & 1) ? 1 : 2);
1916 }
1917
1918 if (op->killchars && strchr(op->killchars, ascval))
1919 key = CTL('U');
1920 else if (op->erasechars && strchr(op->erasechars, ascval))
1921 key = DEL;
1922 else
1923 key = ascval;
1924
1925 /* Do erase, kill and end-of-line processing. */
1926 switch (key) {
1927 case 0:
1928 *bp = 0;
1929 if (op->numspeed > 1)
1930 return NULL;
1931 break;
1932 case CR:
1933 case NL:
1934 *bp = 0; /* terminate logname */
1935 cp->eol = ascval; /* set end-of-line char */
1936 break;
1937 case BS:
1938 case DEL:
1939 cp->erase = ascval; /* set erase character */
1940 if (bp > logname) {
1941 if ((tp->c_lflag & ECHO) == 0)
1942 write_all(1, erase[cp->parity], 3);
1943 bp--;
1944 }
1945 break;
1946 case CTL('U'):
1947 cp->kill = ascval; /* set kill character */
1948 while (bp > logname) {
1949 if ((tp->c_lflag & ECHO) == 0)
1950 write_all(1, erase[cp->parity], 3);
1951 bp--;
1952 }
1953 break;
1954 case CTL('D'):
1955 exit(EXIT_SUCCESS);
1956 default:
1957 if (!isascii(ascval) || !isprint(ascval))
1958 break;
1959 if ((size_t)(bp - logname) >= sizeof(logname) - 1)
1960 log_err(_("%s: input overrun"), op->tty);
1961 if ((tp->c_lflag & ECHO) == 0)
1962 write_all(1, &c, 1); /* echo the character */
1963 *bp++ = ascval; /* and store it */
1964 break;
1965 }
1966 }
1967 }
1968 #ifdef HAVE_WIDECHAR
1969 if ((op->flags & (F_EIGHTBITS|F_UTF8)) == (F_EIGHTBITS|F_UTF8)) {
1970 /* Check out UTF-8 multibyte characters */
1971 ssize_t len;
1972 wchar_t *wcs, *wcp;
1973
1974 len = mbstowcs((wchar_t *)0, logname, 0);
1975 if (len < 0)
1976 log_err(_("%s: invalid character conversion for login name"), op->tty);
1977
1978 wcs = malloc((len + 1) * sizeof(wchar_t));
1979 if (!wcs)
1980 log_err(_("failed to allocate memory: %m"));
1981
1982 len = mbstowcs(wcs, logname, len + 1);
1983 if (len < 0)
1984 log_err(_("%s: invalid character conversion for login name"), op->tty);
1985
1986 wcp = wcs;
1987 while (*wcp) {
1988 const wint_t wc = *wcp++;
1989 if (!iswprint(wc))
1990 log_err(_("%s: invalid character 0x%x in login name"), op->tty, wc);
1991 }
1992 free(wcs);
1993 } else
1994 #endif
1995 if ((op->flags & F_LCUC) && (cp->capslock = caps_lock(logname))) {
1996
1997 /* Handle names with upper case and no lower case. */
1998 for (bp = logname; *bp; bp++)
1999 if (isupper(*bp))
2000 *bp = tolower(*bp); /* map name to lower case */
2001 }
2002
2003 return logname;
2004 }
2005
2006 /* Set the final tty mode bits. */
2007 static void termio_final(struct options *op, struct termios *tp, struct chardata *cp)
2008 {
2009 /* General terminal-independent stuff. */
2010
2011 /* 2-way flow control */
2012 tp->c_iflag |= IXON | IXOFF;
2013 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
2014 /* no longer| ECHOCTL | ECHOPRT */
2015 tp->c_oflag |= OPOST;
2016 /* tp->c_cflag = 0; */
2017 tp->c_cc[VINTR] = DEF_INTR;
2018 tp->c_cc[VQUIT] = DEF_QUIT;
2019 tp->c_cc[VEOF] = DEF_EOF;
2020 tp->c_cc[VEOL] = DEF_EOL;
2021 #ifdef __linux__
2022 tp->c_cc[VSWTC] = DEF_SWITCH;
2023 #elif defined(VSWTCH)
2024 tp->c_cc[VSWTCH] = DEF_SWITCH;
2025 #endif /* __linux__ */
2026
2027 /* Account for special characters seen in input. */
2028 if (cp->eol == CR) {
2029 tp->c_iflag |= ICRNL;
2030 tp->c_oflag |= ONLCR;
2031 }
2032 tp->c_cc[VERASE] = cp->erase;
2033 tp->c_cc[VKILL] = cp->kill;
2034
2035 /* Account for the presence or absence of parity bits in input. */
2036 switch (cp->parity) {
2037 case 0:
2038 /* space (always 0) parity */
2039 break;
2040 case 1:
2041 /* odd parity */
2042 tp->c_cflag |= PARODD;
2043 /* do not break */
2044 case 2:
2045 /* even parity */
2046 tp->c_cflag |= PARENB;
2047 tp->c_iflag |= INPCK | ISTRIP;
2048 /* do not break */
2049 case (1 | 2):
2050 /* no parity bit */
2051 tp->c_cflag &= ~CSIZE;
2052 tp->c_cflag |= CS7;
2053 break;
2054 }
2055 /* Account for upper case without lower case. */
2056 if (cp->capslock) {
2057 #ifdef IUCLC
2058 tp->c_iflag |= IUCLC;
2059 #endif
2060 #ifdef XCASE
2061 tp->c_lflag |= XCASE;
2062 #endif
2063 #ifdef OLCUC
2064 tp->c_oflag |= OLCUC;
2065 #endif
2066 }
2067 /* Optionally enable hardware flow control. */
2068 #ifdef CRTSCTS
2069 if (op->flags & F_RTSCTS)
2070 tp->c_cflag |= CRTSCTS;
2071 #endif
2072
2073 /* Finally, make the new settings effective. */
2074 if (tcsetattr(STDIN_FILENO, TCSANOW, tp) < 0)
2075 log_err(_("%s: failed to set terminal attributes: %m"), op->tty);
2076 }
2077
2078 /*
2079 * String contains upper case without lower case.
2080 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=52940
2081 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=156242
2082 */
2083 static int caps_lock(char *s)
2084 {
2085 int capslock;
2086
2087 for (capslock = 0; *s; s++) {
2088 if (islower(*s))
2089 return EXIT_SUCCESS;
2090 if (capslock == 0)
2091 capslock = isupper(*s);
2092 }
2093 return capslock;
2094 }
2095
2096 /* Convert speed string to speed code; return 0 on failure. */
2097 static speed_t bcode(char *s)
2098 {
2099 const struct Speedtab *sp;
2100 long speed = atol(s);
2101
2102 for (sp = speedtab; sp->speed; sp++)
2103 if (sp->speed == speed)
2104 return sp->code;
2105 return 0;
2106 }
2107
2108 static void __attribute__ ((__noreturn__)) usage(FILE *out)
2109 {
2110 fputs(USAGE_HEADER, out);
2111 fprintf(out, _(" %1$s [options] <line> [<baud_rate>,...] [<termtype>]\n"
2112 " %1$s [options] <baud_rate>,... <line> [<termtype>]\n"), program_invocation_short_name);
2113
2114 fputs(USAGE_SEPARATOR, out);
2115 fputs(_("Open a terminal and set its mode.\n"), out);
2116
2117 fputs(USAGE_OPTIONS, out);
2118 fputs(_(" -8, --8bits assume 8-bit tty\n"), out);
2119 fputs(_(" -a, --autologin <user> login the specified user automatically\n"), out);
2120 fputs(_(" -c, --noreset do not reset control mode\n"), out);
2121 fputs(_(" -E, --remote use -r <hostname> for login(1)\n"), out);
2122 fputs(_(" -f, --issue-file <file> display issue file\n"), out);
2123 fputs(_(" -h, --flow-control enable hardware flow control\n"), out);
2124 fputs(_(" -H, --host <hostname> specify login host\n"), out);
2125 fputs(_(" -i, --noissue do not display issue file\n"), out);
2126 fputs(_(" -I, --init-string <string> set init string\n"), out);
2127 fputs(_(" -J --noclear do not clear the screen before prompt\n"), out);
2128 fputs(_(" -l, --login-program <file> specify login program\n"), out);
2129 fputs(_(" -L, --local-line[=<mode>] control the local line flag\n"), out);
2130 fputs(_(" -m, --extract-baud extract baud rate during connect\n"), out);
2131 fputs(_(" -n, --skip-login do not prompt for login\n"), out);
2132 fputs(_(" -N --nonewline do not print a newline before issue\n"), out);
2133 fputs(_(" -o, --login-options <opts> options that are passed to login\n"), out);
2134 fputs(_(" -p, --login-pause wait for any key before the login\n"), out);
2135 fputs(_(" -r, --chroot <dir> change root to the directory\n"), out);
2136 fputs(_(" -R, --hangup do virtually hangup on the tty\n"), out);
2137 fputs(_(" -s, --keep-baud try to keep baud rate after break\n"), out);
2138 fputs(_(" -t, --timeout <number> login process timeout\n"), out);
2139 fputs(_(" -U, --detect-case detect uppercase terminal\n"), out);
2140 fputs(_(" -w, --wait-cr wait carriage-return\n"), out);
2141 fputs(_(" --nohints do not print hints\n"), out);
2142 fputs(_(" --nohostname no hostname at all will be shown\n"), out);
2143 fputs(_(" --long-hostname show full qualified hostname\n"), out);
2144 fputs(_(" --erase-chars <string> additional backspace chars\n"), out);
2145 fputs(_(" --kill-chars <string> additional kill chars\n"), out);
2146 fputs(_(" --chdir <directory> chdir before the login\n"), out);
2147 fputs(_(" --delay <number> sleep seconds before prompt\n"), out);
2148 fputs(_(" --nice <number> run login with this priority\n"), out);
2149 fputs(_(" --reload reload prompts on running agetty instances\n"), out);
2150 fputs(_(" --help display this help and exit\n"), out);
2151 fputs(_(" --version output version information and exit\n"), out);
2152 fprintf(out, USAGE_MAN_TAIL("agetty(8)"));
2153
2154 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
2155 }
2156
2157 /*
2158 * Helper function reports errors to console or syslog.
2159 * Will be used by log_err() and log_warn() therefore
2160 * it takes a format as well as va_list.
2161 */
2162 #define str2cpy(b,s1,s2) strcat(strcpy(b,s1),s2)
2163
2164 static void dolog(int priority, const char *fmt, va_list ap)
2165 {
2166 #ifndef USE_SYSLOG
2167 int fd;
2168 #endif
2169 char buf[BUFSIZ];
2170 char *bp;
2171
2172 /*
2173 * If the diagnostic is reported via syslog(3), the process name is
2174 * automatically prepended to the message. If we write directly to
2175 * /dev/console, we must prepend the process name ourselves.
2176 */
2177 #ifdef USE_SYSLOG
2178 buf[0] = '\0';
2179 bp = buf;
2180 #else
2181 str2cpy(buf, program_invocation_short_name, ": ");
2182 bp = buf + strlen(buf);
2183 #endif /* USE_SYSLOG */
2184 vsnprintf(bp, sizeof(buf)-strlen(buf), fmt, ap);
2185
2186 /*
2187 * Write the diagnostic directly to /dev/console if we do not use the
2188 * syslog(3) facility.
2189 */
2190 #ifdef USE_SYSLOG
2191 openlog(program_invocation_short_name, LOG_PID, LOG_AUTHPRIV);
2192 syslog(priority, "%s", buf);
2193 closelog();
2194 #else
2195 /* Terminate with CR-LF since the console mode is unknown. */
2196 strcat(bp, "\r\n");
2197 if ((fd = open("/dev/console", 1)) >= 0) {
2198 write_all(fd, buf, strlen(buf));
2199 close(fd);
2200 }
2201 #endif /* USE_SYSLOG */
2202 }
2203
2204 static void log_err(const char *fmt, ...)
2205 {
2206 va_list ap;
2207
2208 va_start(ap, fmt);
2209 dolog(LOG_ERR, fmt, ap);
2210 va_end(ap);
2211
2212 /* Be kind to init(8). */
2213 sleep(10);
2214 exit(EXIT_FAILURE);
2215 }
2216
2217 static void log_warn(const char *fmt, ...)
2218 {
2219 va_list ap;
2220
2221 va_start(ap, fmt);
2222 dolog(LOG_WARNING, fmt, ap);
2223 va_end(ap);
2224 }
2225
2226 static void print_addr(sa_family_t family, void *addr)
2227 {
2228 char buff[INET6_ADDRSTRLEN + 1];
2229
2230 inet_ntop(family, addr, buff, sizeof(buff));
2231 printf("%s", buff);
2232 }
2233
2234 /*
2235 * Prints IP for the specified interface (@iface), if the interface is not
2236 * specified then prints the "best" one (UP, RUNNING, non-LOOPBACK). If not
2237 * found the "best" interface then prints at least host IP.
2238 */
2239 static void output_iface_ip(struct ifaddrs *addrs,
2240 const char *iface,
2241 sa_family_t family)
2242 {
2243 struct ifaddrs *p;
2244 struct addrinfo hints, *info = NULL;
2245 char *host = NULL;
2246 void *addr = NULL;
2247
2248 if (!addrs)
2249 return;
2250
2251 for (p = addrs; p; p = p->ifa_next) {
2252
2253 if (!p->ifa_name ||
2254 !p->ifa_addr ||
2255 p->ifa_addr->sa_family != family)
2256 continue;
2257
2258 if (iface) {
2259 /* Filter out by interface name */
2260 if (strcmp(p->ifa_name, iface) != 0)
2261 continue;
2262 } else {
2263 /* Select the "best" interface */
2264 if ((p->ifa_flags & IFF_LOOPBACK) ||
2265 !(p->ifa_flags & IFF_UP) ||
2266 !(p->ifa_flags & IFF_RUNNING))
2267 continue;
2268 }
2269
2270 addr = NULL;
2271 switch (p->ifa_addr->sa_family) {
2272 case AF_INET:
2273 addr = &((struct sockaddr_in *) p->ifa_addr)->sin_addr;
2274 break;
2275 case AF_INET6:
2276 addr = &((struct sockaddr_in6 *) p->ifa_addr)->sin6_addr;
2277 break;
2278 }
2279
2280 if (addr) {
2281 print_addr(family, addr);
2282 return;
2283 }
2284 }
2285
2286 if (iface)
2287 return;
2288
2289 /* Hmm.. not found the best interface, print host IP at least */
2290 memset(&hints, 0, sizeof(hints));
2291 hints.ai_family = family;
2292 if (family == AF_INET6)
2293 hints.ai_flags = AI_V4MAPPED;
2294
2295 host = xgethostname();
2296 if (host && getaddrinfo(host, NULL, &hints, &info) == 0 && info) {
2297 switch (info->ai_family) {
2298 case AF_INET:
2299 addr = &((struct sockaddr_in *) info->ai_addr)->sin_addr;
2300 break;
2301 case AF_INET6:
2302 addr = &((struct sockaddr_in6 *) info->ai_addr)->sin6_addr;
2303 break;
2304 }
2305 if (addr)
2306 print_addr(family, addr);
2307
2308 freeaddrinfo(info);
2309 }
2310 free(host);
2311 }
2312
2313 /*
2314 * parses \x{argument}, if not argument specified then returns NULL, the @fd
2315 * has to point to one char after the sequence (it means '{').
2316 */
2317 static char *get_escape_argument(FILE *fd, char *buf, size_t bufsz)
2318 {
2319 size_t i = 0;
2320 int c = fgetc(fd);
2321
2322 if (c == EOF || (unsigned char) c != '{') {
2323 ungetc(c, fd);
2324 return NULL;
2325 }
2326
2327 do {
2328 c = fgetc(fd);
2329 if (c == EOF)
2330 return NULL;
2331 if ((unsigned char) c != '}' && i < bufsz - 1)
2332 buf[i++] = (unsigned char) c;
2333
2334 } while ((unsigned char) c != '}');
2335
2336 buf[i] = '\0';
2337 return buf;
2338 }
2339
2340 static void output_special_char(unsigned char c, struct options *op,
2341 struct termios *tp, FILE *fp)
2342 {
2343 struct utsname uts;
2344
2345 uname(&uts);
2346
2347 switch (c) {
2348 case 'e':
2349 {
2350 char escname[UL_COLORNAME_MAXSZ];
2351
2352 if (get_escape_argument(fp, escname, sizeof(escname))) {
2353 const char *esc = color_sequence_from_colorname(escname);
2354 if (esc)
2355 fputs(esc, stdout);
2356 } else
2357 fputs("\033", stdout);
2358 break;
2359 }
2360 case 's':
2361 printf("%s", uts.sysname);
2362 break;
2363 case 'n':
2364 printf("%s", uts.nodename);
2365 break;
2366 case 'r':
2367 printf("%s", uts.release);
2368 break;
2369 case 'v':
2370 printf("%s", uts.version);
2371 break;
2372 case 'm':
2373 printf("%s", uts.machine);
2374 break;
2375 case 'o':
2376 {
2377 char *dom = xgetdomainname();
2378
2379 fputs(dom ? dom : "unknown_domain", stdout);
2380 free(dom);
2381 break;
2382 }
2383 case 'O':
2384 {
2385 char *dom = NULL;
2386 char *host = xgethostname();
2387 struct addrinfo hints, *info = NULL;
2388
2389 memset(&hints, 0, sizeof(hints));
2390 hints.ai_flags = AI_CANONNAME;
2391
2392 if (host && getaddrinfo(host, NULL, &hints, &info) == 0 && info) {
2393 char *canon;
2394
2395 if (info->ai_canonname &&
2396 (canon = strchr(info->ai_canonname, '.')))
2397 dom = canon + 1;
2398 }
2399 fputs(dom ? dom : "unknown_domain", stdout);
2400 if (info)
2401 freeaddrinfo(info);
2402 free(host);
2403 break;
2404 }
2405 case 'd':
2406 case 't':
2407 {
2408 time_t now;
2409 struct tm *tm;
2410
2411 time(&now);
2412 tm = localtime(&now);
2413
2414 if (!tm)
2415 break;
2416
2417 if (c == 'd') /* ISO 8601 */
2418 printf("%s %s %d %d",
2419 nl_langinfo(ABDAY_1 + tm->tm_wday),
2420 nl_langinfo(ABMON_1 + tm->tm_mon),
2421 tm->tm_mday,
2422 tm->tm_year < 70 ? tm->tm_year + 2000 :
2423 tm->tm_year + 1900);
2424 else
2425 printf("%02d:%02d:%02d",
2426 tm->tm_hour, tm->tm_min, tm->tm_sec);
2427 break;
2428 }
2429 case 'l':
2430 printf ("%s", op->tty);
2431 break;
2432 case 'b':
2433 {
2434 const speed_t speed = cfgetispeed(tp);
2435 int i;
2436
2437 for (i = 0; speedtab[i].speed; i++) {
2438 if (speedtab[i].code == speed) {
2439 printf("%ld", speedtab[i].speed);
2440 break;
2441 }
2442 }
2443 break;
2444 }
2445 case 'S':
2446 {
2447 char *var = NULL, varname[64];
2448
2449 /* \S{varname} */
2450 if (get_escape_argument(fp, varname, sizeof(varname))) {
2451 var = read_os_release(op, varname);
2452 if (var) {
2453 if (strcmp(varname, "ANSI_COLOR") == 0)
2454 printf("\033[%sm", var);
2455 else
2456 fputs(var, stdout);
2457 }
2458 /* \S */
2459 } else if ((var = read_os_release(op, "PRETTY_NAME"))) {
2460 fputs(var, stdout);
2461
2462 /* \S and PRETTY_NAME not found */
2463 } else {
2464 fputs(uts.sysname, stdout);
2465 }
2466 break;
2467 }
2468 case 'u':
2469 case 'U':
2470 {
2471 int users = 0;
2472 struct utmp *ut;
2473 setutent();
2474 while ((ut = getutent()))
2475 if (ut->ut_type == USER_PROCESS)
2476 users++;
2477 endutent();
2478 if (c == 'U')
2479 printf(P_("%d user", "%d users", users), users);
2480 else
2481 printf ("%d ", users);
2482 break;
2483 }
2484 case '4':
2485 case '6':
2486 {
2487 sa_family_t family = c == '4' ? AF_INET : AF_INET6;
2488 struct ifaddrs *addrs = NULL;
2489 char iface[128];
2490
2491 #ifdef AGETTY_RELOAD
2492 open_netlink();
2493 #endif
2494
2495 if (getifaddrs(&addrs))
2496 break;
2497
2498 if (get_escape_argument(fp, iface, sizeof(iface)))
2499 output_iface_ip(addrs, iface, family);
2500 else
2501 output_iface_ip(addrs, NULL, family);
2502
2503 freeifaddrs(addrs);
2504 break;
2505 }
2506 default:
2507 putchar(c);
2508 break;
2509 }
2510 }
2511
2512 static void init_special_char(char* arg, struct options *op)
2513 {
2514 char ch, *p, *q;
2515 int i;
2516
2517 op->initstring = malloc(strlen(arg) + 1);
2518 if (!op->initstring)
2519 log_err(_("failed to allocate memory: %m"));
2520
2521 /*
2522 * Copy optarg into op->initstring decoding \ddd octal
2523 * codes into chars.
2524 */
2525 q = op->initstring;
2526 p = arg;
2527 while (*p) {
2528 /* The \\ is converted to \ */
2529 if (*p == '\\') {
2530 p++;
2531 if (*p == '\\') {
2532 ch = '\\';
2533 p++;
2534 } else {
2535 /* Handle \000 - \177. */
2536 ch = 0;
2537 for (i = 1; i <= 3; i++) {
2538 if (*p >= '0' && *p <= '7') {
2539 ch <<= 3;
2540 ch += *p - '0';
2541 p++;
2542 } else {
2543 break;
2544 }
2545 }
2546 }
2547 *q++ = ch;
2548 } else
2549 *q++ = *p++;
2550 }
2551 *q = '\0';
2552 }
2553
2554 /*
2555 * Appends @str to @dest and if @dest is not empty then use use @sep as a
2556 * separator. The maximal final length of the @dest is @len.
2557 *
2558 * Returns the final @dest length or -1 in case of error.
2559 */
2560 static ssize_t append(char *dest, size_t len, const char *sep, const char *src)
2561 {
2562 size_t dsz = 0, ssz = 0, sz;
2563 char *p;
2564
2565 if (!dest || !len || !src)
2566 return -1;
2567
2568 if (*dest)
2569 dsz = strlen(dest);
2570 if (dsz && sep)
2571 ssz = strlen(sep);
2572 sz = strlen(src);
2573
2574 if (dsz + ssz + sz + 1 > len)
2575 return -1;
2576
2577 p = dest + dsz;
2578 if (ssz) {
2579 memcpy(p, sep, ssz);
2580 p += ssz;
2581 }
2582 memcpy(p, src, sz);
2583 *(p + sz) = '\0';
2584
2585 return dsz + ssz + sz;
2586 }
2587
2588 /*
2589 * Do not allow the user to pass an option as a user name
2590 * To be more safe: Use `--' to make sure the rest is
2591 * interpreted as non-options by the program, if it supports it.
2592 */
2593 static void check_username(const char* nm)
2594 {
2595 const char *p = nm;
2596 if (!nm)
2597 goto err;
2598 if (strlen(nm) > 42)
2599 goto err;
2600 while (isspace(*p))
2601 p++;
2602 if (*p == '-')
2603 goto err;
2604 return;
2605 err:
2606 errno = EPERM;
2607 log_err(_("checkname failed: %m"));
2608 }
2609
2610 static void reload_agettys(void)
2611 {
2612 #ifdef AGETTY_RELOAD
2613 int fd = open(AGETTY_RELOAD_FILENAME, O_CREAT|O_CLOEXEC|O_WRONLY,
2614 S_IRUSR|S_IWUSR);
2615 if (fd < 0)
2616 err(EXIT_FAILURE, _("cannot open %s"), AGETTY_RELOAD_FILENAME);
2617
2618 if (futimens(fd, NULL) < 0 || close(fd) < 0)
2619 err(EXIT_FAILURE, _("cannot touch file %s"),
2620 AGETTY_RELOAD_FILENAME);
2621 #else
2622 /* very unusual */
2623 errx(EXIT_FAILURE, _("--reload is unsupported on your system"));
2624 #endif
2625 }