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