]> git.ipfire.org Git - thirdparty/util-linux.git/blame - term-utils/agetty.c
findmnt: avoid unused parameter warning
[thirdparty/util-linux.git] / term-utils / agetty.c
CommitLineData
b75c8134 1/*
53d55042
SK
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.
b75c8134
KZ
6 *
7 * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
1683f6bf
DWF
8 * Adopt the mingetty features for a better support
9 * of virtual consoles by Werner Fink <werner@suse.de>
b75c8134 10 *
53d55042 11 * This program is freely distributable.
b75c8134 12 */
6dbe3af9
KZ
13#include <stdio.h>
14#include <unistd.h>
15#include <stdlib.h>
2b6fc908 16#include <string.h>
1961482a 17#include <termios.h>
6dbe3af9
KZ
18#include <signal.h>
19#include <errno.h>
3aa6b68f 20#include <sys/ioctl.h>
6dbe3af9
KZ
21#include <sys/types.h>
22#include <sys/stat.h>
23#include <fcntl.h>
22853e4a 24#include <stdarg.h>
6dbe3af9
KZ
25#include <ctype.h>
26#include <utmp.h>
27#include <getopt.h>
22853e4a 28#include <time.h>
6dbe3af9 29#include <sys/file.h>
e61e66bd 30#include <sys/socket.h>
729def03 31#include <langinfo.h>
3aa6b68f 32#include <grp.h>
2b945eda
KZ
33#include <arpa/inet.h>
34#include <netdb.h>
35#include <ifaddrs.h>
df73ad46 36
8abcf290 37#include "strutils.h"
e12c9866 38#include "all-io.h"
7eda085c 39#include "nls.h"
e6590f06 40#include "pathnames.h"
e5b17b31 41#include "c.h"
1683f6bf 42#include "widechar.h"
879a7ab4 43#include "ttyutils.h"
6dbe3af9 44
fd6b7a7f 45#ifdef __linux__
0da025da 46# include <sys/kd.h>
53d55042
SK
47# include <sys/param.h>
48# define USE_SYSLOG
729def03
WF
49# ifndef DEFAULT_VCTERM
50# define DEFAULT_VCTERM "linux"
51# endif
52# ifndef DEFAULT_STERM
53# define DEFAULT_STERM "vt102"
54# endif
4585ec0b
ST
55#elif defined(__GNU__)
56# define USE_SYSLOG
57# ifndef DEFAULT_VCTERM
58# define DEFAULT_VCTERM "hurd"
59# endif
60# ifndef DEFAULT_STERM
61# define DEFAULT_STERM "vt102"
62# endif
729def03
WF
63#else
64# ifndef DEFAULT_VCTERM
65# define DEFAULT_VCTERM "vt100"
66# endif
67# ifndef DEFAULT_STERM
68# define DEFAULT_STERM "vt100"
69# endif
6dbe3af9
KZ
70#endif
71
53d55042 72/* If USE_SYSLOG is undefined all diagnostics go to /dev/console. */
6dbe3af9 73#ifdef USE_SYSLOG
53d55042 74# include <syslog.h>
6dbe3af9
KZ
75#endif
76
b75c8134
KZ
77/*
78 * Some heuristics to find out what environment we are in: if it is not
53d55042
SK
79 * System V, assume it is SunOS 4. The LOGIN_PROCESS is defined in System V
80 * utmp.h, which will select System V style getty.
b75c8134 81 */
53d55042
SK
82#ifdef LOGIN_PROCESS
83# define SYSV_STYLE
6dbe3af9
KZ
84#endif
85
b75c8134
KZ
86/*
87 * Things you may want to modify.
88 *
89 * If ISSUE is not defined, agetty will never display the contents of the
90 * /etc/issue file. You will not want to spit out large "issue" files at the
91 * wrong baud rate. Relevant for System V only.
92 *
93 * You may disagree with the default line-editing etc. characters defined
94 * below. Note, however, that DEL cannot be used for interrupt generation
95 * and for line editing at the same time.
96 */
6dbe3af9 97
53d55042 98/* Displayed before the login prompt. */
6dbe3af9 99#ifdef SYSV_STYLE
96cc7b0b 100# define ISSUE _PATH_ISSUE
53d55042 101# include <sys/utsname.h>
6dbe3af9
KZ
102#endif
103
53d55042 104/* Login prompt. */
e85281a8 105#define LOGIN "login: "
9aeb66dc 106#define LOGIN_ARGV_MAX 16 /* Numbers of args for login */
6dbe3af9 107
b75c8134
KZ
108/*
109 * When multiple baud rates are specified on the command line, the first one
110 * we will try is the first one specified.
111 */
6dbe3af9
KZ
112#define FIRST_SPEED 0
113
114/* Storage for command-line options. */
53d55042 115#define MAX_SPEED 10 /* max. nr. of baud rates */
6dbe3af9
KZ
116
117struct options {
bde20e1b
WF
118 int flags; /* toggle switches, see below */
119 int timeout; /* time-out period */
eb8e1f9f 120 char *autolog; /* login the user automatically */
e85281a8
DWF
121 char *chdir; /* Chdir before the login */
122 char *chroot; /* Chroot before the login */
bde20e1b 123 char *login; /* login program */
eb8e1f9f 124 char *logopt; /* options for login program */
bde20e1b 125 char *tty; /* name of tty */
729def03
WF
126 char *vcline; /* line of virtual console */
127 char *term; /* terminal type */
bde20e1b
WF
128 char *initstring; /* modem init string */
129 char *issue; /* alternative issue file */
cb872ac9
KZ
130 char *erasechars; /* string with erase chars */
131 char *killchars; /* string with kill chars */
e85281a8
DWF
132 int delay; /* Sleep seconds before prompt */
133 int nice; /* Run login with this priority */
bde20e1b 134 int numspeed; /* number of baud rates to try */
ef264c83 135 int clocal; /* CLOCAL_MODE_* */
bde20e1b 136 speed_t speeds[MAX_SPEED]; /* baud rates to be tried */
6dbe3af9
KZ
137};
138
ef264c83
KZ
139enum {
140 CLOCAL_MODE_AUTO = 0,
141 CLOCAL_MODE_ALWAYS,
142 CLOCAL_MODE_NEVER
143};
144
53d55042
SK
145#define F_PARSE (1<<0) /* process modem status messages */
146#define F_ISSUE (1<<1) /* display /etc/issue */
147#define F_RTSCTS (1<<2) /* enable RTS/CTS flow control */
ef264c83 148
53d55042
SK
149#define F_INITSTRING (1<<4) /* initstring is set */
150#define F_WAITCRLF (1<<5) /* wait for CR or LF */
151#define F_CUSTISSUE (1<<6) /* give alternative issue file */
152#define F_NOPROMPT (1<<7) /* do not ask for login name! */
153#define F_LCUC (1<<8) /* support for *LCUC stty modes */
154#define F_KEEPSPEED (1<<9) /* follow baud rate from kernel */
155#define F_KEEPCFLAGS (1<<10) /* reuse c_cflags setup from kernel */
bde20e1b 156#define F_EIGHTBITS (1<<11) /* Assume 8bit-clean tty */
3aa6b68f
WF
157#define F_VCONSOLE (1<<12) /* This is a virtual console */
158#define F_HANGUP (1<<13) /* Do call vhangup(2) */
0da025da 159#define F_UTF8 (1<<14) /* We can do UTF8 */
eb8e1f9f 160#define F_LOGINPAUSE (1<<15) /* Wait for any key before dropping login prompt */
e85281a8
DWF
161#define F_NOCLEAR (1<<16) /* Do not clear the screen before prompting */
162#define F_NONL (1<<17) /* No newline before issue */
163#define F_NOHOSTNAME (1<<18) /* Do not show the hostname */
164#define F_LONGHNAME (1<<19) /* Show Full qualified hostname */
36601b23 165#define F_NOHINTS (1<<20) /* Don't print hints */
01095ae3 166#define F_REMOTE (1<<21) /* Add '-h fakehost' to login(1) command line */
0da025da
WF
167
168#define serial_tty_option(opt, flag) \
169 (((opt)->flags & (F_VCONSOLE|(flag))) == (flag))
6dbe3af9 170
fd6b7a7f 171struct Speedtab {
53d55042 172 long speed;
bde20e1b 173 speed_t code;
fd6b7a7f
KZ
174};
175
1a204cd2 176static const struct Speedtab speedtab[] = {
53d55042
SK
177 {50, B50},
178 {75, B75},
179 {110, B110},
180 {134, B134},
181 {150, B150},
182 {200, B200},
183 {300, B300},
184 {600, B600},
185 {1200, B1200},
186 {1800, B1800},
187 {2400, B2400},
188 {4800, B4800},
189 {9600, B9600},
fd6b7a7f 190#ifdef B19200
53d55042 191 {19200, B19200},
fd6b7a7f
KZ
192#endif
193#ifdef B38400
53d55042 194 {38400, B38400},
fd6b7a7f
KZ
195#endif
196#ifdef EXTA
53d55042 197 {19200, EXTA},
fd6b7a7f
KZ
198#endif
199#ifdef EXTB
53d55042 200 {38400, EXTB},
fd6b7a7f
KZ
201#endif
202#ifdef B57600
53d55042 203 {57600, B57600},
fd6b7a7f
KZ
204#endif
205#ifdef B115200
53d55042 206 {115200, B115200},
fd6b7a7f
KZ
207#endif
208#ifdef B230400
53d55042 209 {230400, B230400},
fd6b7a7f 210#endif
53d55042 211 {0, 0},
6dbe3af9
KZ
212};
213
729def03 214static void init_special_char(char* arg, struct options *op);
53d55042
SK
215static void parse_args(int argc, char **argv, struct options *op);
216static void parse_speeds(struct options *op, char *arg);
729def03
WF
217static void update_utmp(struct options *op);
218static void open_tty(char *tty, struct termios *tp, struct options *op);
53d55042 219static void termio_init(struct options *op, struct termios *tp);
0da025da 220static void reset_vc (const struct options *op, struct termios *tp);
53d55042 221static void auto_baud(struct termios *tp);
2b945eda
KZ
222static void output_special_char (unsigned char c, struct options *op,
223 struct termios *tp, FILE *fp);
53d55042
SK
224static void do_prompt(struct options *op, struct termios *tp);
225static void next_speed(struct options *op, struct termios *tp);
226static char *get_logname(struct options *op,
227 struct termios *tp, struct chardata *cp);
228static void termio_final(struct options *op,
229 struct termios *tp, struct chardata *cp);
230static int caps_lock(char *s);
bde20e1b
WF
231static speed_t bcode(char *s);
232static void usage(FILE * out) __attribute__((__noreturn__));
763d7a87
KZ
233static void log_err(const char *, ...) __attribute__((__noreturn__))
234 __attribute__((__format__(printf, 1, 2)));
235static void log_warn (const char *, ...)
236 __attribute__((__format__(printf, 1, 2)));
a694957a 237static ssize_t append(char *dest, size_t len, const char *sep, const char *src);
9aeb66dc
KZ
238static void check_username (const char* nm);
239static void login_options_to_argv(char *argv[], int *argc, char *str, char *username);
6dbe3af9 240
eb63b9b8 241/* Fake hostname for ut_host specified on command line. */
bde20e1b 242static char *fakehost;
eb63b9b8 243
6dbe3af9 244#ifdef DEBUGGING
1aba8336
SK
245#ifndef
246# define DEBUG_OUTPUT "/dev/ttyp0"
247#endif
783b08fc 248#define debug(s) do { fprintf(dbf,s); fflush(dbf); } while (0)
6dbe3af9
KZ
249FILE *dbf;
250#else
efcf26f4
KZ
251#define debug(s) do { ; } while (0)
252#endif
6dbe3af9 253
53d55042 254int main(int argc, char **argv)
6dbe3af9 255{
9aeb66dc 256 char *username = NULL; /* login name, given to /bin/login */
eb8e1f9f
WF
257 struct chardata chardata; /* will be set by get_logname() */
258 struct termios termios; /* terminal mode bits */
1a204cd2 259 struct options options = {
eb8e1f9f
WF
260 .flags = F_ISSUE, /* show /etc/issue (SYSV_STYLE) */
261 .login = _PATH_LOGIN, /* default login program */
eb8e1f9f 262 .tty = "tty1", /* default tty line */
5676f365 263 .issue = ISSUE /* default issue file */
70bedfa1 264 };
9aeb66dc
KZ
265 char *login_argv[LOGIN_ARGV_MAX + 1];
266 int login_argc = 0;
3aa6b68f
WF
267 struct sigaction sa, sa_hup, sa_quit, sa_int;
268 sigset_t set;
70bedfa1
KZ
269
270 setlocale(LC_ALL, "");
271 bindtextdomain(PACKAGE, LOCALEDIR);
272 textdomain(PACKAGE);
b75c8134 273
3aa6b68f
WF
274 /* In case vhangup(2) has to called */
275 sa.sa_handler = SIG_IGN;
276 sa.sa_flags = SA_RESTART;
277 sigemptyset (&sa.sa_mask);
278 sigaction(SIGHUP, &sa, &sa_hup);
279 sigaction(SIGQUIT, &sa, &sa_quit);
280 sigaction(SIGINT, &sa, &sa_int);
281
6dbe3af9 282#ifdef DEBUGGING
1aba8336 283 dbf = fopen(DEBUG_OUTPUT, "w");
53d55042
SK
284 for (int i = 1; i < argc; i++)
285 debug(argv[i]);
286#endif /* DEBUGGING */
6dbe3af9 287
70bedfa1 288 /* Parse command-line arguments. */
70bedfa1 289 parse_args(argc, argv, &options);
6dbe3af9 290
9aeb66dc
KZ
291 login_argv[login_argc++] = options.login; /* set login program name */
292
70bedfa1 293 /* Update the utmp file. */
6dbe3af9 294#ifdef SYSV_STYLE
729def03 295 update_utmp(&options);
6dbe3af9 296#endif
e85281a8
DWF
297 if (options.delay)
298 sleep(options.delay);
299
70bedfa1 300 debug("calling open_tty\n");
53d55042 301
70bedfa1 302 /* Open the tty as standard { input, output, error }. */
729def03 303 open_tty(options.tty, &termios, &options);
70bedfa1 304
3aa6b68f
WF
305 /* Unmask SIGHUP if inherited */
306 sigemptyset(&set);
307 sigaddset(&set, SIGHUP);
308 sigprocmask(SIG_UNBLOCK, &set, NULL);
309 sigaction(SIGHUP, &sa_hup, NULL);
310
70bedfa1
KZ
311 tcsetpgrp(STDIN_FILENO, getpid());
312 /* Initialize the termios settings (raw mode, eight-bit, blocking i/o). */
313 debug("calling termio_init\n");
53d55042 314 termio_init(&options, &termios);
70bedfa1 315
53d55042 316 /* Write the modem init string and DO NOT flush the buffers. */
eb8e1f9f
WF
317 if (serial_tty_option(&options, F_INITSTRING) &&
318 options.initstring && *options.initstring != '\0') {
70bedfa1 319 debug("writing init string\n");
729def03 320 write_all(STDOUT_FILENO, options.initstring,
3aa6b68f 321 strlen(options.initstring));
70bedfa1
KZ
322 }
323
714cff30
KZ
324 if (options.flags & F_VCONSOLE || options.clocal != CLOCAL_MODE_ALWAYS)
325 /* Go to blocking mode unless -L is specified, this change
326 * affects stdout, stdin and stderr as all the file descriptors
327 * are created by dup(). */
70bedfa1 328 fcntl(STDOUT_FILENO, F_SETFL,
53d55042 329 fcntl(STDOUT_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
70bedfa1
KZ
330
331 /* Optionally detect the baud rate from the modem status message. */
332 debug("before autobaud\n");
0da025da 333 if (serial_tty_option(&options, F_PARSE))
70bedfa1
KZ
334 auto_baud(&termios);
335
336 /* Set the optional timer. */
337 if (options.timeout)
763d7a87 338 alarm((unsigned) options.timeout);
70bedfa1 339
53d55042 340 /* Optionally wait for CR or LF before writing /etc/issue */
0da025da 341 if (serial_tty_option(&options, F_WAITCRLF)) {
70bedfa1
KZ
342 char ch;
343
344 debug("waiting for cr-lf\n");
53d55042
SK
345 while (read(STDIN_FILENO, &ch, 1) == 1) {
346 /* Strip "parity bit". */
347 ch &= 0x7f;
fd6b7a7f 348#ifdef DEBUGGING
70bedfa1 349 fprintf(dbf, "read %c\n", ch);
fd6b7a7f 350#endif
53d55042
SK
351 if (ch == '\n' || ch == '\r')
352 break;
70bedfa1 353 }
726f69e2 354 }
726f69e2 355
f5664477 356 INIT_CHARDATA(&chardata);
933956cb
KZ
357
358 if (options.autolog) {
359 debug("doing auto login\n");
360 username = options.autolog;
361 }
362
1683f6bf 363 if ((options.flags & F_NOPROMPT) == 0) {
eb8e1f9f 364 if (options.autolog) {
933956cb 365 /* Autologin prompt */
eb8e1f9f 366 do_prompt(&options, &termios);
8c219bf4 367 printf(_("%s%s (automatic login)\n"), LOGIN, options.autolog);
eb8e1f9f
WF
368 } else {
369 /* Read the login name. */
370 debug("reading login name\n");
9aeb66dc 371 while ((username =
f8bd089b 372 get_logname(&options, &termios, &chardata)) == NULL)
eb8e1f9f
WF
373 if ((options.flags & F_VCONSOLE) == 0)
374 next_speed(&options, &termios);
375 }
70bedfa1 376 }
6dbe3af9 377
70bedfa1 378 /* Disable timer. */
70bedfa1 379 if (options.timeout)
53d55042 380 alarm(0);
6dbe3af9 381
0da025da
WF
382 if ((options.flags & F_VCONSOLE) == 0) {
383 /* Finalize the termios settings. */
384 termio_final(&options, &termios, &chardata);
6dbe3af9 385
0da025da
WF
386 /* Now the newline character should be properly written. */
387 write_all(STDOUT_FILENO, "\r\n", 2);
388 }
6dbe3af9 389
763d7a87
KZ
390 sigaction(SIGQUIT, &sa_quit, NULL);
391 sigaction(SIGINT, &sa_int, NULL);
3aa6b68f 392
9aeb66dc
KZ
393 if (username)
394 check_username(username);
395
396 if (options.logopt) {
397 /*
398 * The --login-options completely overwrites the default
399 * way how agetty composes login(1) command line.
400 */
401 login_options_to_argv(login_argv, &login_argc,
402 options.logopt, username);
01095ae3
KZ
403 } else {
404 if (fakehost && (options.flags & F_REMOTE)) {
405 login_argv[login_argc++] = "-h";
406 login_argv[login_argc++] = fakehost;
407 }
408 if (username) {
409 if (options.autolog)
410 login_argv[login_argc++] = "-f";
411 else
412 login_argv[login_argc++] = "--";
413 login_argv[login_argc++] = username;
414 }
9aeb66dc 415 }
eb8e1f9f 416
9aeb66dc 417 login_argv[login_argc] = NULL; /* last login argv */
eb8e1f9f 418
e85281a8
DWF
419 if (options.chroot) {
420 if (chroot(options.chroot) < 0)
421 log_err(_("%s: can't change root directory %s: %m"),
422 options.tty, options.chroot);
423 }
424 if (options.chdir) {
425 if (chdir(options.chdir) < 0)
426 log_err(_("%s: can't change working directory %s: %m"),
427 options.tty, options.chdir);
428 }
429 if (options.nice) {
430 if (nice(options.nice) < 0)
431 log_warn(_("%s: can't change process priority: %m"),
432 options.tty);
433 }
434
1aba8336
SK
435#ifdef DEBUGGING
436 fprintf(dbf, "read %c\n", ch);
437 if (close_stream(dbf) != 0)
438 log_err("write failed: %s", DEBUG_OUTPUT);
439#endif
440
70bedfa1 441 /* Let the login program take care of password validation. */
9aeb66dc
KZ
442 execv(options.login, login_argv);
443 log_err(_("%s: can't exec %s: %m"), options.tty, login_argv[0]);
444}
445
446/*
447 * Returns : @str if \u not found
448 * : @username if @str equal to "\u"
449 * : newly allocated string if \u mixed with something other
450 */
451static char *replace_u(char *str, char *username)
452{
453 char *entry = NULL, *p = str;
454 size_t usz = username ? strlen(username) : 0;
455
456 while (*p) {
457 size_t sz;
458 char *tp, *old = entry;
459
460 if (memcmp(p, "\\u", 2)) {
461 p++;
462 continue; /* no \u */
463 }
464 sz = strlen(str);
465
466 if (p == str && sz == 2)
467 /* 'str' contains only '\u' */
468 return username;
469
470 tp = entry = malloc(sz + usz);
471 if (!tp)
472 log_err(_("failed to allocate memory: %m"));
473
474 if (p != str) {
475 /* copy chars befor \u */
476 memcpy(tp, str, p - str);
477 tp += p - str;
478 }
479 if (usz) {
480 /* copy username */
481 memcpy(tp, username, usz);
482 tp += usz;
483 }
484 if (*(p + 2))
485 /* copy chars after \u + \0 */
486 memcpy(tp, p + 2, sz - (p - str) - 1);
487 else
488 *tp = '\0';
489
490 p = tp;
491 str = entry;
492 free(old);
493 }
494
495 return entry ? entry : str;
496}
497
498static void login_options_to_argv(char *argv[], int *argc,
499 char *str, char *username)
500{
501 char *p;
502 int i = *argc;
503
504 while (str && isspace(*str))
505 str++;
506 p = str;
507
508 while (p && *p && i < LOGIN_ARGV_MAX) {
509 if (isspace(*p)) {
510 *p = '\0';
511 while (isspace(*++p))
512 ;
513 if (*p) {
514 argv[i++] = replace_u(str, username);
515 str = p;
516 }
517 } else
518 p++;
519 }
520 if (str && *str && i < LOGIN_ARGV_MAX)
521 argv[i++] = replace_u(str, username);
522 *argc = i;
6dbe3af9
KZ
523}
524
53d55042 525/* Parse command-line arguments. */
bde20e1b 526static void parse_args(int argc, char **argv, struct options *op)
6dbe3af9 527{
53d55042 528 int c;
70bedfa1
KZ
529
530 enum {
531 VERSION_OPTION = CHAR_MAX + 1,
36601b23 532 NOHINTS_OPTION,
e85281a8
DWF
533 NOHOSTNAME_OPTION,
534 LONGHOSTNAME_OPTION,
cb872ac9
KZ
535 HELP_OPTION,
536 ERASE_CHARS_OPTION,
537 KILL_CHARS_OPTION,
70bedfa1 538 };
3aa6b68f 539 const struct option longopts[] = {
70bedfa1 540 { "8bits", no_argument, 0, '8' },
eb8e1f9f 541 { "autologin", required_argument, 0, 'a' },
70bedfa1 542 { "noreset", no_argument, 0, 'c' },
e85281a8
DWF
543 { "chdir", required_argument, 0, 'C' },
544 { "delay", required_argument, 0, 'd' },
01095ae3 545 { "remote", no_argument, 0, 'E' },
70bedfa1
KZ
546 { "issue-file", required_argument, 0, 'f' },
547 { "flow-control", no_argument, 0, 'h' },
548 { "host", required_argument, 0, 'H' },
549 { "noissue", no_argument, 0, 'i' },
550 { "init-string", required_argument, 0, 'I' },
e85281a8 551 { "noclear", no_argument, 0, 'J' },
70bedfa1 552 { "login-program", required_argument, 0, 'l' },
ef264c83 553 { "local-line", optional_argument, 0, 'L' },
70bedfa1
KZ
554 { "extract-baud", no_argument, 0, 'm' },
555 { "skip-login", no_argument, 0, 'n' },
e85281a8 556 { "nonewline", no_argument, 0, 'N' },
eb8e1f9f 557 { "login-options", required_argument, 0, 'o' },
3fc62fd3 558 { "login-pause", no_argument, 0, 'p' },
e85281a8
DWF
559 { "nice", required_argument, 0, 'P' },
560 { "chroot", required_argument, 0, 'r' },
3aa6b68f 561 { "hangup", no_argument, 0, 'R' },
70bedfa1
KZ
562 { "keep-baud", no_argument, 0, 's' },
563 { "timeout", required_argument, 0, 't' },
564 { "detect-case", no_argument, 0, 'U' },
565 { "wait-cr", no_argument, 0, 'w' },
36601b23 566 { "nohints", no_argument, 0, NOHINTS_OPTION },
3fc62fd3 567 { "nohostname", no_argument, 0, NOHOSTNAME_OPTION },
e85281a8 568 { "long-hostname", no_argument, 0, LONGHOSTNAME_OPTION },
70bedfa1
KZ
569 { "version", no_argument, 0, VERSION_OPTION },
570 { "help", no_argument, 0, HELP_OPTION },
cb872ac9
KZ
571 { "erase-chars", required_argument, 0, ERASE_CHARS_OPTION },
572 { "kill-chars", required_argument, 0, KILL_CHARS_OPTION },
70bedfa1
KZ
573 { NULL, 0, 0, 0 }
574 };
575
763d7a87 576 while ((c = getopt_long(argc, argv,
01095ae3 577 "8a:cC:d:Ef:hH:iI:Jl:LmnNo:pP:r:Rst:Uw", longopts,
53d55042 578 NULL)) != -1) {
70bedfa1
KZ
579 switch (c) {
580 case '8':
bde20e1b 581 op->flags |= F_EIGHTBITS;
70bedfa1 582 break;
eb8e1f9f
WF
583 case 'a':
584 op->autolog = optarg;
585 break;
70bedfa1
KZ
586 case 'c':
587 op->flags |= F_KEEPCFLAGS;
588 break;
e85281a8
DWF
589 case 'C':
590 op->chdir = optarg;
591 break;
592 case 'd':
593 op->delay = atoi(optarg);
594 break;
01095ae3
KZ
595 case 'E':
596 op->flags |= F_REMOTE;
597 break;
53d55042 598 case 'f':
70bedfa1
KZ
599 op->flags |= F_CUSTISSUE;
600 op->issue = optarg;
601 break;
53d55042 602 case 'h':
70bedfa1
KZ
603 op->flags |= F_RTSCTS;
604 break;
53d55042 605 case 'H':
70bedfa1
KZ
606 fakehost = optarg;
607 break;
53d55042 608 case 'i':
70bedfa1
KZ
609 op->flags &= ~F_ISSUE;
610 break;
611 case 'I':
729def03
WF
612 init_special_char(optarg, op);
613 op->flags |= F_INITSTRING;
614 break;
e85281a8
DWF
615 case 'J':
616 op->flags |= F_NOCLEAR;
617 break;
70bedfa1 618 case 'l':
53d55042 619 op->login = optarg;
70bedfa1 620 break;
53d55042 621 case 'L':
ef264c83
KZ
622 /* -L and -L=always have the same meaning */
623 op->clocal = CLOCAL_MODE_ALWAYS;
624 if (optarg) {
625 if (strcmp(optarg, "=always") == 0)
626 op->clocal = CLOCAL_MODE_ALWAYS;
627 else if (strcmp(optarg, "=never") == 0)
628 op->clocal = CLOCAL_MODE_NEVER;
629 else if (strcmp(optarg, "=auto") == 0)
630 op->clocal = CLOCAL_MODE_AUTO;
631 else
632 log_err(_("unssuported --local-line mode argument"));
633 }
70bedfa1 634 break;
53d55042 635 case 'm':
70bedfa1
KZ
636 op->flags |= F_PARSE;
637 break;
638 case 'n':
639 op->flags |= F_NOPROMPT;
640 break;
eb8e1f9f
WF
641 case 'o':
642 op->logopt = optarg;
643 break;
644 case 'p':
645 op->flags |= F_LOGINPAUSE;
646 break;
e85281a8
DWF
647 case 'P':
648 op->nice = atoi(optarg);
649 break;
650 case 'r':
651 op->chroot = optarg;
652 break;
3aa6b68f
WF
653 case 'R':
654 op->flags |= F_HANGUP;
655 break;
70bedfa1 656 case 's':
53d55042 657 op->flags |= F_KEEPSPEED;
70bedfa1 658 break;
53d55042 659 case 't':
70bedfa1 660 if ((op->timeout = atoi(optarg)) <= 0)
bde20e1b 661 log_err(_("bad timeout value: %s"), optarg);
70bedfa1
KZ
662 break;
663 case 'U':
664 op->flags |= F_LCUC;
665 break;
666 case 'w':
667 op->flags |= F_WAITCRLF;
668 break;
36601b23
KZ
669 case NOHINTS_OPTION:
670 op->flags |= F_NOHINTS;
671 break;
e85281a8
DWF
672 case NOHOSTNAME_OPTION:
673 op->flags |= F_NOHOSTNAME;
674 break;
675 case LONGHOSTNAME_OPTION:
676 op->flags |= F_LONGHNAME;
677 break;
cb872ac9
KZ
678 case ERASE_CHARS_OPTION:
679 op->erasechars = optarg;
680 break;
681 case KILL_CHARS_OPTION:
682 op->killchars = optarg;
683 break;
70bedfa1
KZ
684 case VERSION_OPTION:
685 printf(_("%s from %s\n"), program_invocation_short_name,
53d55042 686 PACKAGE_STRING);
70bedfa1
KZ
687 exit(EXIT_SUCCESS);
688 case HELP_OPTION:
689 usage(stdout);
690 default:
691 usage(stderr);
726f69e2 692 }
6dbe3af9 693 }
70bedfa1
KZ
694
695 debug("after getopt loop\n");
696
729def03 697 if (argc < optind + 1) {
bde20e1b 698 log_warn(_("not enough arguments"));
70bedfa1
KZ
699 usage(stderr);
700 }
701
729def03 702 /* Accept "tty", "baudrate tty", and "tty baudrate". */
53d55042
SK
703 if ('0' <= argv[optind][0] && argv[optind][0] <= '9') {
704 /* Assume BSD style speed. */
705 parse_speeds(op, argv[optind++]);
729def03
WF
706 if (argc < optind + 1) {
707 warn(_("not enough arguments"));
708 usage(stderr);
709 }
710 op->tty = argv[optind++];
70bedfa1 711 } else {
53d55042 712 op->tty = argv[optind++];
729def03
WF
713 if (argc > optind) {
714 char *v = argv[optind++];
715 if ('0' <= *v && *v <= '9')
716 parse_speeds(op, v);
717 else
718 op->speeds[op->numspeed++] = bcode("9600");
719 }
70bedfa1
KZ
720 }
721
729def03
WF
722 /* On virtual console remember the line which is used for */
723 if (strncmp(op->tty, "tty", 3) == 0 &&
724 strspn(op->tty + 3, "0123456789") == strlen(op->tty+3))
725 op->vcline = op->tty+3;
726
70bedfa1 727 if (argc > optind && argv[optind])
729def03 728 op->term = argv[optind];
6dbe3af9 729
66ee8158 730#ifdef DO_DEVFS_FIDDLING
70bedfa1 731 /*
53d55042 732 * Some devfs junk, following Goswin Brederlow:
70bedfa1
KZ
733 * turn ttyS<n> into tts/<n>
734 * turn tty<n> into vc/<n>
53d55042 735 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=72241
70bedfa1
KZ
736 */
737 if (op->tty && strlen(op->tty) < 90) {
738 char dev_name[100];
739 struct stat st;
740
741 if (strncmp(op->tty, "ttyS", 4) == 0) {
742 strcpy(dev_name, "/dev/");
743 strcat(dev_name, op->tty);
744 if (stat(dev_name, &st) < 0) {
745 strcpy(dev_name, "/dev/tts/");
746 strcat(dev_name, op->tty + 4);
ca8e91a4
KZ
747 if (stat(dev_name, &st) == 0) {
748 op->tty = strdup(dev_name + 5);
749 if (!op->tty)
750 log_err(_("failed to allocate memory: %m"));
751 }
70bedfa1
KZ
752 }
753 } else if (strncmp(op->tty, "tty", 3) == 0) {
754 strcpy(dev_name, "/dev/");
755 strncat(dev_name, op->tty, 90);
756 if (stat(dev_name, &st) < 0) {
757 strcpy(dev_name, "/dev/vc/");
758 strcat(dev_name, op->tty + 3);
ca8e91a4
KZ
759 if (stat(dev_name, &st) == 0) {
760 op->tty = strdup(dev_name + 5);
761 if (!op->tty)
762 log_err(_("failed to allocate memory: %m"));
763 }
70bedfa1
KZ
764 }
765 }
766 }
53d55042 767#endif /* DO_DEVFS_FIDDLING */
66ee8158 768
70bedfa1 769 debug("exiting parseargs\n");
6dbe3af9
KZ
770}
771
53d55042 772/* Parse alternate baud rates. */
bde20e1b 773static void parse_speeds(struct options *op, char *arg)
6dbe3af9 774{
53d55042 775 char *cp;
6dbe3af9 776
f021834e 777 debug("entered parse_speeds\n");
f8bd089b 778 for (cp = strtok(arg, ","); cp != NULL; cp = strtok((char *)0, ",")) {
70bedfa1 779 if ((op->speeds[op->numspeed++] = bcode(cp)) <= 0)
bde20e1b 780 log_err(_("bad speed: %s"), cp);
70bedfa1 781 if (op->numspeed >= MAX_SPEED)
bde20e1b 782 log_err(_("too many alternate speeds"));
70bedfa1
KZ
783 }
784 debug("exiting parsespeeds\n");
6dbe3af9
KZ
785}
786
787#ifdef SYSV_STYLE
788
53d55042 789/* Update our utmp entry. */
729def03 790static void update_utmp(struct options *op)
6dbe3af9 791{
53d55042
SK
792 struct utmp ut;
793 time_t t;
729def03
WF
794 pid_t pid = getpid();
795 pid_t sid = getsid(0);
796 char *vcline = op->vcline;
797 char *line = op->tty;
53d55042 798 struct utmp *utp;
70bedfa1
KZ
799
800 /*
801 * The utmp file holds miscellaneous information about things started by
802 * /sbin/init and other system-related events. Our purpose is to update
803 * the utmp entry for the current process, in particular the process type
804 * and the tty line we are listening to. Return successfully only if the
805 * utmp file can be opened for update, and if we are able to find our
806 * entry in the utmp file.
807 */
70bedfa1
KZ
808 utmpname(_PATH_UTMP);
809 setutent();
810
53d55042 811 /*
729def03 812 * Find my pid in utmp.
53d55042
SK
813 *
814 * FIXME: Earlier (when was that?) code here tested only utp->ut_type !=
815 * INIT_PROCESS, so maybe the >= here should be >.
816 *
817 * FIXME: The present code is taken from login.c, so if this is changed,
818 * maybe login has to be changed as well (is this true?).
819 */
70bedfa1 820 while ((utp = getutent()))
729def03 821 if (utp->ut_pid == pid
70bedfa1
KZ
822 && utp->ut_type >= INIT_PROCESS
823 && utp->ut_type <= DEAD_PROCESS)
824 break;
825
826 if (utp) {
827 memcpy(&ut, utp, sizeof(ut));
828 } else {
53d55042 829 /* Some inits do not initialize utmp. */
70bedfa1 830 memset(&ut, 0, sizeof(ut));
729def03
WF
831 if (vcline && *vcline)
832 /* Standard virtual console devices */
763d7a87 833 strncpy(ut.ut_id, vcline, sizeof(ut.ut_id));
729def03
WF
834 else {
835 size_t len = strlen(line);
836 char * ptr;
763d7a87
KZ
837 if (len >= sizeof(ut.ut_id))
838 ptr = line + len - sizeof(ut.ut_id);
729def03
WF
839 else
840 ptr = line;
763d7a87 841 strncpy(ut.ut_id, ptr, sizeof(ut.ut_id));
729def03 842 }
70bedfa1
KZ
843 }
844
845 strncpy(ut.ut_user, "LOGIN", sizeof(ut.ut_user));
846 strncpy(ut.ut_line, line, sizeof(ut.ut_line));
847 if (fakehost)
848 strncpy(ut.ut_host, fakehost, sizeof(ut.ut_host));
849 time(&t);
850 ut.ut_time = t;
851 ut.ut_type = LOGIN_PROCESS;
729def03
WF
852 ut.ut_pid = pid;
853 ut.ut_session = sid;
70bedfa1
KZ
854
855 pututline(&ut);
856 endutent();
857
858 {
48d7b13a 859#ifdef HAVE_UPDWTMP
70bedfa1 860 updwtmp(_PATH_WTMP, &ut);
5c36a0eb 861#else
70bedfa1
KZ
862 int ut_fd;
863 int lf;
864
53d55042 865 if ((lf = open(_PATH_WTMPLOCK, O_CREAT | O_WRONLY, 0660)) >= 0) {
70bedfa1 866 flock(lf, LOCK_EX);
53d55042
SK
867 if ((ut_fd =
868 open(_PATH_WTMP, O_APPEND | O_WRONLY)) >= 0) {
729def03 869 write_all(ut_fd, &ut, sizeof(ut));
70bedfa1
KZ
870 close(ut_fd);
871 }
872 flock(lf, LOCK_UN);
873 close(lf);
874 }
53d55042 875#endif /* HAVE_UPDWTMP */
70bedfa1 876 }
6dbe3af9
KZ
877}
878
53d55042 879#endif /* SYSV_STYLE */
6dbe3af9 880
53d55042 881/* Set up tty as stdin, stdout & stderr. */
729def03 882static void open_tty(char *tty, struct termios *tp, struct options *op)
6dbe3af9 883{
3aa6b68f 884 const pid_t pid = getpid();
783b08fc 885 int serial, closed = 0;
6dbe3af9 886
3aa6b68f
WF
887 /* Set up new standard input, unless we are given an already opened port. */
888
889 if (strcmp(tty, "-") != 0) {
890 char buf[PATH_MAX+1];
891 struct group *gr = NULL;
70bedfa1 892 struct stat st;
3aa6b68f
WF
893 int fd, len;
894 pid_t tid;
895 gid_t gid = 0;
896
897 /* Use tty group if available */
898 if ((gr = getgrnam("tty")))
899 gid = gr->gr_gid;
900
763d7a87
KZ
901 if (((len = snprintf(buf, sizeof(buf), "/dev/%s", tty)) >=
902 (int)sizeof(buf)) || (len < 0))
3aa6b68f
WF
903 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
904
905 /*
906 * There is always a race between this reset and the call to
907 * vhangup() that s.o. can use to get access to your tty.
908 * Linux login(1) will change tty permissions. Use root owner and group
909 * with permission -rw------- for the period between getty and login.
910 */
91984e93 911 if (chown(buf, 0, gid) || chmod(buf, (gid ? 0620 : 0600))) {
3aa6b68f
WF
912 if (errno == EROFS)
913 log_warn("%s: %m", buf);
914 else
915 log_err("%s: %m", buf);
916 }
6dbe3af9 917
3aa6b68f
WF
918 /* Open the tty as standard input. */
919 if ((fd = open(buf, O_RDWR|O_NOCTTY|O_NONBLOCK, 0)) < 0)
920 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
921
922 /* Sanity checks... */
763d7a87 923 if (!isatty(fd))
3aa6b68f
WF
924 log_err(_("/dev/%s: not a character device"), tty);
925 if (fstat(fd, &st) < 0)
763d7a87 926 log_err("%s: %m", buf);
70bedfa1 927 if ((st.st_mode & S_IFMT) != S_IFCHR)
bde20e1b 928 log_err(_("/dev/%s: not a character device"), tty);
6dbe3af9 929
3aa6b68f 930 if (((tid = tcgetsid(fd)) < 0) || (pid != tid)) {
763d7a87 931 if (ioctl(fd, TIOCSCTTY, 1) == -1)
8c219bf4 932 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty);
3aa6b68f
WF
933 }
934
783b08fc
KZ
935 close(STDIN_FILENO);
936 errno = 0;
937
3aa6b68f 938 if (op->flags & F_HANGUP) {
783b08fc
KZ
939
940 if (ioctl(fd, TIOCNOTTY))
941 debug("TIOCNOTTY ioctl failed\n");
942
3aa6b68f 943 /*
783b08fc
KZ
944 * Let's close all file decriptors before vhangup
945 * https://lkml.org/lkml/2012/6/5/145
3aa6b68f 946 */
783b08fc
KZ
947 close(fd);
948 close(STDOUT_FILENO);
949 close(STDERR_FILENO);
950 errno = 0;
951 closed = 1;
952
3aa6b68f 953 if (vhangup())
8c219bf4 954 log_err(_("/dev/%s: vhangup() failed: %m"), tty);
783b08fc
KZ
955 } else
956 close(fd);
6dbe3af9 957
70bedfa1 958 debug("open(2)\n");
3aa6b68f
WF
959 if (open(buf, O_RDWR|O_NOCTTY|O_NONBLOCK, 0) != 0)
960 log_err(_("/dev/%s: cannot open as standard input: %m"), tty);
783b08fc 961
3aa6b68f 962 if (((tid = tcgetsid(STDIN_FILENO)) < 0) || (pid != tid)) {
763d7a87 963 if (ioctl(STDIN_FILENO, TIOCSCTTY, 1) == -1)
8c219bf4 964 log_warn(_("/dev/%s: cannot get controlling tty: %m"), tty);
3aa6b68f
WF
965 }
966
70bedfa1 967 } else {
3aa6b68f 968
70bedfa1
KZ
969 /*
970 * Standard input should already be connected to an open port. Make
971 * sure it is open for read/write.
972 */
3aa6b68f 973
70bedfa1 974 if ((fcntl(STDIN_FILENO, F_GETFL, 0) & O_RDWR) != O_RDWR)
bde20e1b 975 log_err(_("%s: not open for read/write"), tty);
3aa6b68f 976
70bedfa1
KZ
977 }
978
3aa6b68f 979 if (tcsetpgrp(STDIN_FILENO, pid))
8c219bf4 980 log_warn(_("/dev/%s: cannot set process group: %m"), tty);
3aa6b68f
WF
981
982 /* Get rid of the present outputs. */
783b08fc
KZ
983 if (!closed) {
984 close(STDOUT_FILENO);
985 close(STDERR_FILENO);
986 errno = 0;
987 }
3aa6b68f 988
70bedfa1
KZ
989 /* Set up standard output and standard error file descriptors. */
990 debug("duping\n");
53d55042 991
70bedfa1
KZ
992 /* set up stdout and stderr */
993 if (dup(STDIN_FILENO) != 1 || dup(STDIN_FILENO) != 2)
bde20e1b 994 log_err(_("%s: dup problem: %m"), tty);
6dbe3af9 995
3aa6b68f
WF
996 /* make stdio unbuffered for slow modem lines */
997 setvbuf(stdout, NULL, _IONBF, 0);
998
6dbe3af9 999 /*
70bedfa1
KZ
1000 * The following ioctl will fail if stdin is not a tty, but also when
1001 * there is noise on the modem control lines. In the latter case, the
53d55042
SK
1002 * common course of action is (1) fix your cables (2) give the modem
1003 * more time to properly reset after hanging up.
1004 *
1005 * SunOS users can achieve (2) by patching the SunOS kernel variable
1006 * "zsadtrlow" to a larger value; 5 seconds seems to be a good value.
1007 * http://www.sunmanagers.org/archives/1993/0574.html
6dbe3af9 1008 */
bde20e1b 1009 memset(tp, 0, sizeof(struct termios));
70bedfa1 1010 if (tcgetattr(STDIN_FILENO, tp) < 0)
8c219bf4 1011 log_err(_("%s: failed to get terminal attributes: %m"), tty);
70bedfa1
KZ
1012
1013 /*
3aa6b68f
WF
1014 * Detect if this is a virtual console or serial/modem line.
1015 * In case of a virtual console the ioctl TIOCMGET fails and
1016 * the error number will be set to EINVAL.
70bedfa1 1017 */
89aed1c9 1018 if (ioctl(STDIN_FILENO, TIOCMGET, &serial) < 0 && (errno == EINVAL)) {
3aa6b68f
WF
1019 op->flags |= F_VCONSOLE;
1020 if (!op->term)
1021 op->term = DEFAULT_VCTERM;
1022 } else if (!op->term)
1023 op->term = DEFAULT_STERM;
729def03
WF
1024
1025 setenv("TERM", op->term, 1);
6dbe3af9
KZ
1026}
1027
53d55042 1028/* Initialize termios settings. */
bde20e1b 1029static void termio_init(struct options *op, struct termios *tp)
6dbe3af9 1030{
70bedfa1 1031 speed_t ispeed, ospeed;
1683f6bf 1032 struct winsize ws;
70bedfa1 1033
0da025da
WF
1034 if (op->flags & F_VCONSOLE) {
1035#if defined(IUTF8) && defined(KDGKBMODE)
1036 int mode;
1037
1038 /* Detect mode of current keyboard setup, e.g. for UTF-8 */
1039 if (ioctl(STDIN_FILENO, KDGKBMODE, &mode) < 0)
1040 mode = K_RAW;
1041 switch(mode) {
1042 case K_UNICODE:
b0198a11 1043 setlocale(LC_CTYPE, "C.UTF-8");
0da025da
WF
1044 op->flags |= F_UTF8;
1045 break;
1046 case K_RAW:
1047 case K_MEDIUMRAW:
1048 case K_XLATE:
1049 default:
1050 setlocale(LC_CTYPE, "POSIX");
1051 op->flags &= ~F_UTF8;
1052 break;
1053 }
1054#else
1055 setlocale(LC_CTYPE, "POSIX");
1056 op->flags &= ~F_UTF8;
1057#endif
1058 reset_vc(op, tp);
1059
1060 if ((tp->c_cflag & (CS8|PARODD|PARENB)) == CS8)
1061 op->flags |= F_EIGHTBITS;
1062
e85281a8
DWF
1063 if ((op->flags & F_NOCLEAR) == 0) {
1064 /*
1065 * Do not write a full reset (ESC c) because this destroys
1066 * the unicode mode again if the terminal was in unicode
1067 * mode. Also it clears the CONSOLE_MAGIC features which
1068 * are required for some languages/console-fonts.
1069 * Just put the cursor to the home position (ESC [ H),
1070 * erase everything below the cursor (ESC [ J), and set the
1071 * scrolling region to the full window (ESC [ r)
1072 */
1073 write_all(STDOUT_FILENO, "\033[r\033[H\033[J", 9);
1074 }
0da025da
WF
1075 return;
1076 }
1077
70bedfa1 1078 if (op->flags & F_KEEPSPEED) {
53d55042
SK
1079 /* Save the original setting. */
1080 ispeed = cfgetispeed(tp);
70bedfa1 1081 ospeed = cfgetospeed(tp);
1683f6bf
DWF
1082
1083 if (!ispeed) ispeed = TTYDEF_SPEED;
1084 if (!ospeed) ospeed = TTYDEF_SPEED;
1085
53d55042 1086 } else {
70bedfa1 1087 ospeed = ispeed = op->speeds[FIRST_SPEED];
53d55042 1088 }
70bedfa1
KZ
1089
1090 /*
1091 * Initial termios settings: 8-bit characters, raw-mode, blocking i/o.
1092 * Special characters are set after we have read the login name; all
1093 * reads will be done in raw mode anyway. Errors will be dealt with
53d55042 1094 * later on.
70bedfa1 1095 */
53d55042
SK
1096
1097 /* Flush input and output queues, important for modems! */
1098 tcflush(STDIN_FILENO, TCIOFLUSH);
70bedfa1 1099
8408647d
WF
1100#ifdef IUTF8
1101 tp->c_iflag = tp->c_iflag & IUTF8;
7478fce0
ST
1102 if (tp->c_iflag & IUTF8)
1103 op->flags |= F_UTF8;
8408647d
WF
1104#else
1105 tp->c_iflag = 0;
1106#endif
9c62a232
DJ
1107 tp->c_lflag = 0;
1108 tp->c_oflag &= OPOST | ONLCR;
70bedfa1 1109
1683f6bf 1110 if ((op->flags & F_KEEPCFLAGS) == 0)
70bedfa1
KZ
1111 tp->c_cflag = CS8 | HUPCL | CREAD | (tp->c_cflag & CLOCAL);
1112
53d55042
SK
1113 /*
1114 * Note that the speed is stored in the c_cflag termios field, so we have
70bedfa1
KZ
1115 * set the speed always when the cflag se reseted.
1116 */
1117 cfsetispeed(tp, ispeed);
1118 cfsetospeed(tp, ospeed);
1119
ef264c83
KZ
1120 /* The default is to follow setting from kernel, but it's possible
1121 * to explicitly remove/add CLOCAL flag by -L[=<mode>]*/
1122 switch (op->clocal) {
1123 case CLOCAL_MODE_ALWAYS:
1124 tp->c_cflag |= CLOCAL; /* -L or -L=always */
1125 break;
1126 case CLOCAL_MODE_NEVER:
1127 tp->c_cflag &= ~CLOCAL; /* -L=never */
1128 break;
1129 case CLOCAL_MODE_AUTO: /* -L=auto */
1130 break;
1131 }
1132
30e8b186 1133#ifdef HAVE_STRUCT_TERMIOS_C_LINE
70bedfa1 1134 tp->c_line = 0;
1961482a 1135#endif
70bedfa1
KZ
1136 tp->c_cc[VMIN] = 1;
1137 tp->c_cc[VTIME] = 0;
7eda085c 1138
1683f6bf
DWF
1139 /* Check for terminal size and if not found set default */
1140 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0) {
1141 int set = 0;
1142 if (ws.ws_row == 0) {
1143 ws.ws_row = 24;
1144 set++;
1145 }
1146 if (ws.ws_col == 0) {
1147 ws.ws_col = 80;
1148 set++;
1149 }
efcf26f4
KZ
1150 if (ioctl(STDIN_FILENO, TIOCSWINSZ, &ws))
1151 debug("TIOCSWINSZ ioctl failed\n");
1683f6bf
DWF
1152 }
1153
53d55042 1154 /* Optionally enable hardware flow control. */
7eda085c 1155#ifdef CRTSCTS
70bedfa1
KZ
1156 if (op->flags & F_RTSCTS)
1157 tp->c_cflag |= CRTSCTS;
7eda085c
KZ
1158#endif
1159
53d55042 1160 tcsetattr(STDIN_FILENO, TCSANOW, tp);
fd6b7a7f 1161
53d55042
SK
1162 /* Go to blocking input even in local mode. */
1163 fcntl(STDIN_FILENO, F_SETFL,
1164 fcntl(STDIN_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
fd6b7a7f 1165
70bedfa1 1166 debug("term_io 2\n");
6dbe3af9
KZ
1167}
1168
0da025da
WF
1169/* Reset virtual console on stdin to its defaults */
1170static void reset_vc(const struct options *op, struct termios *tp)
1171{
879a7ab4
KZ
1172 int fl = 0;
1173
1174 fl |= (op->flags & F_KEEPCFLAGS) == 0 ? 0 : UL_TTY_KEEPCFLAGS;
1175 fl |= (op->flags & F_UTF8) == 0 ? 0 : UL_TTY_UTF8;
1176
1177 reset_virtual_console(tp, fl);
0da025da 1178
0da025da 1179 if (tcsetattr(STDIN_FILENO, TCSADRAIN, tp))
8c219bf4 1180 log_warn(_("setting terminal attributes failed: %m"));
0da025da
WF
1181}
1182
53d55042 1183/* Extract baud rate from modem status message. */
bde20e1b 1184static void auto_baud(struct termios *tp)
6dbe3af9 1185{
bde20e1b 1186 speed_t speed;
53d55042 1187 int vmin;
70bedfa1 1188 unsigned iflag;
53d55042
SK
1189 char buf[BUFSIZ];
1190 char *bp;
1191 int nread;
70bedfa1
KZ
1192
1193 /*
1194 * This works only if the modem produces its status code AFTER raising
1195 * the DCD line, and if the computer is fast enough to set the proper
1196 * baud rate before the message has gone by. We expect a message of the
1197 * following format:
1198 *
1199 * <junk><number><junk>
1200 *
1201 * The number is interpreted as the baud rate of the incoming call. If the
1202 * modem does not tell us the baud rate within one second, we will keep
1203 * using the current baud rate. It is advisable to enable BREAK
1204 * processing (comma-separated list of baud rates) if the processing of
1205 * modem status messages is enabled.
1206 */
1207
1208 /*
1209 * Use 7-bit characters, don't block if input queue is empty. Errors will
53d55042 1210 * be dealt with later on.
70bedfa1 1211 */
70bedfa1 1212 iflag = tp->c_iflag;
53d55042
SK
1213 /* Enable 8th-bit stripping. */
1214 tp->c_iflag |= ISTRIP;
70bedfa1 1215 vmin = tp->c_cc[VMIN];
53d55042
SK
1216 /* Do not block when queue is empty. */
1217 tp->c_cc[VMIN] = 0;
70bedfa1
KZ
1218 tcsetattr(STDIN_FILENO, TCSANOW, tp);
1219
1220 /*
1221 * Wait for a while, then read everything the modem has said so far and
1222 * try to extract the speed of the dial-in call.
1223 */
53d55042 1224 sleep(1);
70bedfa1
KZ
1225 if ((nread = read(STDIN_FILENO, buf, sizeof(buf) - 1)) > 0) {
1226 buf[nread] = '\0';
53d55042 1227 for (bp = buf; bp < buf + nread; bp++)
70bedfa1
KZ
1228 if (isascii(*bp) && isdigit(*bp)) {
1229 if ((speed = bcode(bp))) {
1230 cfsetispeed(tp, speed);
1231 cfsetospeed(tp, speed);
1232 }
1233 break;
1234 }
6dbe3af9 1235 }
6dbe3af9 1236
53d55042 1237 /* Restore terminal settings. Errors will be dealt with later on. */
70bedfa1
KZ
1238 tp->c_iflag = iflag;
1239 tp->c_cc[VMIN] = vmin;
53d55042 1240 tcsetattr(STDIN_FILENO, TCSANOW, tp);
6dbe3af9
KZ
1241}
1242
2448f336
KZ
1243static char *xgethostname(void)
1244{
1245 char *name;
1246 size_t sz = get_hostname_max() + 1;
1247
1248 name = malloc(sizeof(char) * sz);
1249 if (!name)
1250 log_err(_("failed to allocate memory: %m"));
1251
8362545b
KZ
1252 if (gethostname(name, sz) != 0) {
1253 free(name);
2448f336 1254 return NULL;
8362545b 1255 }
2448f336
KZ
1256 name[sz - 1] = '\0';
1257 return name;
1258}
1259
1260static char *xgetdomainname(void)
1261{
1262#ifdef HAVE_GETDOMAINNAME
1263 char *name;
1264 size_t sz = get_hostname_max() + 1;
1265
1266 name = malloc(sizeof(char) * sz);
1267 if (!name)
1268 log_err(_("failed to allocate memory: %m"));
1269
8362545b
KZ
1270 if (getdomainname(name, sz) != 0) {
1271 free(name);
2448f336 1272 return NULL;
8362545b 1273 }
2448f336
KZ
1274 name[sz - 1] = '\0';
1275 return name;
1276#endif
1277 return NULL;
1278}
1279
53d55042 1280/* Show login prompt, optionally preceded by /etc/issue contents. */
bde20e1b 1281static void do_prompt(struct options *op, struct termios *tp)
6dbe3af9
KZ
1282{
1283#ifdef ISSUE
53d55042 1284 FILE *fd;
53d55042 1285#endif /* ISSUE */
6dbe3af9 1286
e85281a8
DWF
1287 if ((op->flags & F_NONL) == 0) {
1288 /* Issue not in use, start with a new line. */
1289 write_all(STDOUT_FILENO, "\r\n", 2);
1290 }
3aa6b68f 1291
53d55042 1292#ifdef ISSUE
70bedfa1 1293 if ((op->flags & F_ISSUE) && (fd = fopen(op->issue, "r"))) {
1683f6bf 1294 int c, oflag = tp->c_oflag; /* Save current setting. */
3aa6b68f 1295
1683f6bf
DWF
1296 if ((op->flags & F_VCONSOLE) == 0) {
1297 /* Map new line in output to carriage return & new line. */
1298 tp->c_oflag |= (ONLCR | OPOST);
1299 tcsetattr(STDIN_FILENO, TCSADRAIN, tp);
1300 }
70bedfa1
KZ
1301
1302 while ((c = getc(fd)) != EOF) {
729def03 1303 if (c == '\\')
2b945eda 1304 output_special_char(getc(fd), op, tp, fd);
729def03 1305 else
763d7a87 1306 putchar(c);
70bedfa1
KZ
1307 }
1308 fflush(stdout);
6dbe3af9 1309
1683f6bf
DWF
1310 if ((op->flags & F_VCONSOLE) == 0) {
1311 /* Restore settings. */
1312 tp->c_oflag = oflag;
1313 /* Wait till output is gone. */
1314 tcsetattr(STDIN_FILENO, TCSADRAIN, tp);
1315 }
53d55042 1316 fclose(fd);
6dbe3af9 1317 }
eb8e1f9f
WF
1318#endif /* ISSUE */
1319 if (op->flags & F_LOGINPAUSE) {
8c219bf4 1320 puts(_("[press ENTER to login]"));
eb8e1f9f
WF
1321 getc(stdin);
1322 }
1323#ifdef KDGKBLED
36601b23
KZ
1324 if (!(op->flags & F_NOHINTS) && !op->autolog &&
1325 (op->flags & F_VCONSOLE)) {
a694957a
KZ
1326 int kb = 0;
1327
eb8e1f9f 1328 if (ioctl(STDIN_FILENO, KDGKBLED, &kb) == 0) {
a694957a
KZ
1329 char hint[256] = { '\0' };
1330 int nl = 0;
a694957a 1331
01c5b787 1332 if (access(_PATH_NUMLOCK_ON, F_OK) == 0)
a694957a
KZ
1333 nl = 1;
1334
1335 if (nl && (kb & 0x02) == 0)
1336 append(hint, sizeof(hint), NULL, _("Num Lock off"));
1337
1338 else if (nl == 0 && (kb & 2) && (kb & 0x20) == 0)
1339 append(hint, sizeof(hint), NULL, _("Num Lock on"));
1340
1341 if ((kb & 0x04) && (kb & 0x40) == 0)
1342 append(hint, sizeof(hint), ", ", _("Caps Lock on"));
1343
1344 if ((kb & 0x01) && (kb & 0x10) == 0)
1345 append(hint, sizeof(hint), ", ", _("Scroll Lock on"));
1346
1347 if (*hint)
1348 printf(_("Hint: %s\n\n"), hint);
eb8e1f9f
WF
1349 }
1350 }
1351#endif /* KDGKBLED */
e85281a8 1352 if ((op->flags & F_NOHOSTNAME) == 0) {
2448f336
KZ
1353 char *hn = xgethostname();
1354
1355 if (hn) {
e85281a8 1356 char *dot = strchr(hn, '.');
74b3df85
SK
1357 char *cn = hn;
1358 struct addrinfo *res = NULL;
e85281a8 1359
e85281a8
DWF
1360 if ((op->flags & F_LONGHNAME) == 0) {
1361 if (dot)
1362 *dot = '\0';
74b3df85
SK
1363
1364 } else if (dot == NULL) {
1365 struct addrinfo hints;
1366
1367 memset(&hints, 0, sizeof(hints));
1368 hints.ai_flags = AI_CANONNAME;
1369
1370 if (!getaddrinfo(hn, NULL, &hints, &res)
1371 && res && res->ai_canonname)
1372 cn = res->ai_canonname;
1373 }
1374
1375 write_all(STDOUT_FILENO, cn, strlen(cn));
e85281a8 1376 write_all(STDOUT_FILENO, " ", 1);
74b3df85
SK
1377
1378 if (res)
1379 freeaddrinfo(res);
2448f336 1380 free(hn);
e85281a8 1381 }
70bedfa1 1382 }
933956cb 1383 if (!op->autolog) {
eb8e1f9f
WF
1384 /* Always show login prompt. */
1385 write_all(STDOUT_FILENO, LOGIN, sizeof(LOGIN) - 1);
1386 }
6dbe3af9
KZ
1387}
1388
53d55042 1389/* Select next baud rate. */
bde20e1b 1390static void next_speed(struct options *op, struct termios *tp)
6dbe3af9 1391{
70bedfa1
KZ
1392 static int baud_index = -1;
1393
1394 if (baud_index == -1)
1395 /*
53d55042 1396 * If the F_KEEPSPEED flags is set then the FIRST_SPEED is not
70bedfa1
KZ
1397 * tested yet (see termio_init()).
1398 */
53d55042
SK
1399 baud_index =
1400 (op->flags & F_KEEPSPEED) ? FIRST_SPEED : 1 % op->numspeed;
70bedfa1
KZ
1401 else
1402 baud_index = (baud_index + 1) % op->numspeed;
1403
1404 cfsetispeed(tp, op->speeds[baud_index]);
1405 cfsetospeed(tp, op->speeds[baud_index]);
53d55042 1406 tcsetattr(STDIN_FILENO, TCSANOW, tp);
6dbe3af9
KZ
1407}
1408
53d55042 1409/* Get user name, establish parity, speed, erase, kill & eol. */
bde20e1b 1410static char *get_logname(struct options *op, struct termios *tp, struct chardata *cp)
6dbe3af9 1411{
70bedfa1 1412 static char logname[BUFSIZ];
53d55042
SK
1413 char *bp;
1414 char c; /* input character, full eight bits */
1415 char ascval; /* low 7 bits of input character */
1683f6bf 1416 int eightbit;
53d55042
SK
1417 static char *erase[] = { /* backspace-space-backspace */
1418 "\010\040\010", /* space parity */
1419 "\010\040\010", /* odd parity */
1420 "\210\240\210", /* even parity */
1421 "\210\240\210", /* no parity */
70bedfa1
KZ
1422 };
1423
1424 /* Initialize kill, erase, parity etc. (also after switching speeds). */
f5664477 1425 INIT_CHARDATA(cp);
70bedfa1 1426
53d55042
SK
1427 /*
1428 * Flush pending input (especially important after parsing or switching
1429 * the baud rate).
1430 */
1683f6bf
DWF
1431 if ((op->flags & F_VCONSOLE) == 0)
1432 sleep(1);
53d55042 1433 tcflush(STDIN_FILENO, TCIFLUSH);
70bedfa1 1434
1683f6bf
DWF
1435 eightbit = (op->flags & F_EIGHTBITS);
1436 bp = logname;
1437 *bp = '\0';
1438
1439 while (*logname == '\0') {
1440
1441 /* Write issue file and prompt */
70bedfa1
KZ
1442 do_prompt(op, tp);
1443
1683f6bf
DWF
1444 cp->eol = '\0';
1445
1446 /* Read name, watch for break and end-of-line. */
1447 while (cp->eol == '\0') {
1448
cb872ac9
KZ
1449 char key;
1450
763d7a87 1451 if (read(STDIN_FILENO, &c, 1) < 1) {
1683f6bf 1452
714cff30
KZ
1453 /* The terminal could be open with O_NONBLOCK when
1454 * -L (force CLOCAL) is specified... */
1683f6bf 1455 if (errno == EINTR || errno == EAGAIN) {
714cff30 1456 usleep(250000);
1683f6bf
DWF
1457 continue;
1458 }
1459 switch (errno) {
1460 case 0:
1461 case EIO:
1462 case ESRCH:
1463 case EINVAL:
1464 case ENOENT:
1465 break;
1466 default:
1467 log_err(_("%s: read: %m"), op->tty);
1468 }
70bedfa1 1469 }
1683f6bf 1470
70bedfa1 1471 /* Do parity bit handling. */
1683f6bf 1472 if (eightbit)
70bedfa1 1473 ascval = c;
1683f6bf
DWF
1474 else if (c != (ascval = (c & 0177))) {
1475 uint32_t bits; /* # of "1" bits per character */
1476 uint32_t mask; /* mask with 1 bit up */
1477 for (bits = 1, mask = 1; mask & 0177; mask <<= 1) {
70bedfa1 1478 if (mask & ascval)
53d55042 1479 bits++;
1683f6bf 1480 }
70bedfa1
KZ
1481 cp->parity |= ((bits & 1) ? 1 : 2);
1482 }
1683f6bf 1483
cb872ac9
KZ
1484 if (op->killchars && strchr(op->killchars, ascval))
1485 key = CTL('U');
1486 else if (op->erasechars && strchr(op->erasechars, ascval))
1487 key = DEL;
1488 else
1489 key = ascval;
1490
70bedfa1 1491 /* Do erase, kill and end-of-line processing. */
cb872ac9 1492 switch (key) {
1683f6bf
DWF
1493 case 0:
1494 *bp = 0;
1495 if (op->numspeed > 1)
4a9b7543 1496 return NULL;
1683f6bf 1497 break;
70bedfa1
KZ
1498 case CR:
1499 case NL:
1683f6bf
DWF
1500 *bp = 0; /* terminate logname */
1501 cp->eol = ascval; /* set end-of-line char */
70bedfa1
KZ
1502 break;
1503 case BS:
1504 case DEL:
1683f6bf 1505 cp->erase = ascval; /* set erase character */
70bedfa1 1506 if (bp > logname) {
b9261127 1507 if ((tp->c_lflag & ECHO) == 0)
1683f6bf 1508 write_all(1, erase[cp->parity], 3);
70bedfa1
KZ
1509 bp--;
1510 }
1511 break;
1512 case CTL('U'):
1683f6bf 1513 cp->kill = ascval; /* set kill character */
70bedfa1 1514 while (bp > logname) {
b9261127 1515 if ((tp->c_lflag & ECHO) == 0)
1683f6bf 1516 write_all(1, erase[cp->parity], 3);
70bedfa1
KZ
1517 bp--;
1518 }
1519 break;
1520 case CTL('D'):
1521 exit(EXIT_SUCCESS);
1522 default:
1683f6bf
DWF
1523 if (!isascii(ascval) || !isprint(ascval))
1524 break;
1525 if ((size_t)(bp - logname) >= sizeof(logname) - 1)
bde20e1b 1526 log_err(_("%s: input overrun"), op->tty);
b9261127 1527 if ((tp->c_lflag & ECHO) == 0)
1683f6bf
DWF
1528 write_all(1, &c, 1); /* echo the character */
1529 *bp++ = ascval; /* and store it */
70bedfa1
KZ
1530 break;
1531 }
6dbe3af9 1532 }
6dbe3af9 1533 }
1683f6bf
DWF
1534#ifdef HAVE_WIDECHAR
1535 if ((op->flags & (F_EIGHTBITS|F_UTF8)) == (F_EIGHTBITS|F_UTF8)) {
1536 /* Check out UTF-8 multibyte characters */
1537 ssize_t len;
1538 wchar_t *wcs, *wcp;
1539
1540 len = mbstowcs((wchar_t *)0, logname, 0);
1541 if (len < 0)
8c219bf4 1542 log_err(_("%s: invalid character conversion for login name"), op->tty);
1683f6bf 1543
ca8e91a4
KZ
1544 wcs = (wchar_t *) malloc((len + 1) * sizeof(wchar_t));
1545 if (!wcs)
1546 log_err(_("failed to allocate memory: %m"));
1683f6bf
DWF
1547
1548 len = mbstowcs(wcs, logname, len + 1);
1549 if (len < 0)
8c219bf4 1550 log_err(_("%s: invalid character conversion for login name"), op->tty);
1683f6bf
DWF
1551
1552 wcp = wcs;
1553 while (*wcp) {
1554 const wint_t wc = *wcp++;
1555 if (!iswprint(wc))
8c219bf4 1556 log_err(_("%s: invalid character 0x%x in login name"), op->tty, wc);
1683f6bf
DWF
1557 }
1558 free(wcs);
1559 } else
1560#endif
1561 if ((op->flags & F_LCUC) && (cp->capslock = caps_lock(logname))) {
1562
1563 /* Handle names with upper case and no lower case. */
70bedfa1
KZ
1564 for (bp = logname; *bp; bp++)
1565 if (isupper(*bp))
1683f6bf
DWF
1566 *bp = tolower(*bp); /* map name to lower case */
1567 }
1568
70bedfa1 1569 return logname;
6dbe3af9
KZ
1570}
1571
53d55042 1572/* Set the final tty mode bits. */
bde20e1b 1573static void termio_final(struct options *op, struct termios *tp, struct chardata *cp)
6dbe3af9 1574{
70bedfa1 1575 /* General terminal-independent stuff. */
53d55042
SK
1576
1577 /* 2-way flow control */
1578 tp->c_iflag |= IXON | IXOFF;
1579 tp->c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE;
1580 /* no longer| ECHOCTL | ECHOPRT */
70bedfa1
KZ
1581 tp->c_oflag |= OPOST;
1582 /* tp->c_cflag = 0; */
53d55042
SK
1583 tp->c_cc[VINTR] = DEF_INTR;
1584 tp->c_cc[VQUIT] = DEF_QUIT;
1585 tp->c_cc[VEOF] = DEF_EOF;
70bedfa1 1586 tp->c_cc[VEOL] = DEF_EOL;
fd6b7a7f 1587#ifdef __linux__
53d55042 1588 tp->c_cc[VSWTC] = DEF_SWITCH;
1961482a 1589#elif defined(VSWTCH)
53d55042
SK
1590 tp->c_cc[VSWTCH] = DEF_SWITCH;
1591#endif /* __linux__ */
6dbe3af9 1592
70bedfa1
KZ
1593 /* Account for special characters seen in input. */
1594 if (cp->eol == CR) {
53d55042
SK
1595 tp->c_iflag |= ICRNL;
1596 tp->c_oflag |= ONLCR;
70bedfa1 1597 }
53d55042
SK
1598 tp->c_cc[VERASE] = cp->erase;
1599 tp->c_cc[VKILL] = cp->kill;
70bedfa1
KZ
1600
1601 /* Account for the presence or absence of parity bits in input. */
1602 switch (cp->parity) {
53d55042
SK
1603 case 0:
1604 /* space (always 0) parity */
1605 break;
1606 case 1:
1607 /* odd parity */
1608 tp->c_cflag |= PARODD;
1609 /* do not break */
1610 case 2:
1611 /* even parity */
1612 tp->c_cflag |= PARENB;
1613 tp->c_iflag |= INPCK | ISTRIP;
1614 /* do not break */
1615 case (1 | 2):
1616 /* no parity bit */
1617 tp->c_cflag &= ~CSIZE;
1618 tp->c_cflag |= CS7;
1619 break;
70bedfa1
KZ
1620 }
1621 /* Account for upper case without lower case. */
1622 if (cp->capslock) {
ee519041 1623#ifdef IUCLC
70bedfa1 1624 tp->c_iflag |= IUCLC;
ee519041 1625#endif
b75c8134 1626#ifdef XCASE
70bedfa1 1627 tp->c_lflag |= XCASE;
1961482a 1628#endif
ee519041 1629#ifdef OLCUC
70bedfa1 1630 tp->c_oflag |= OLCUC;
ee519041 1631#endif
70bedfa1 1632 }
53d55042 1633 /* Optionally enable hardware flow control. */
6dbe3af9 1634#ifdef CRTSCTS
70bedfa1
KZ
1635 if (op->flags & F_RTSCTS)
1636 tp->c_cflag |= CRTSCTS;
6dbe3af9
KZ
1637#endif
1638
53d55042 1639 /* Finally, make the new settings effective. */
70bedfa1 1640 if (tcsetattr(STDIN_FILENO, TCSANOW, tp) < 0)
8c219bf4 1641 log_err(_("%s: failed to set terminal attributes: %m"), op->tty);
6dbe3af9
KZ
1642}
1643
53d55042
SK
1644/*
1645 * String contains upper case without lower case.
1646 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=52940
1647 * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=156242
1648 */
bde20e1b 1649static int caps_lock(char *s)
6dbe3af9 1650{
53d55042 1651 int capslock;
70bedfa1
KZ
1652
1653 for (capslock = 0; *s; s++) {
1654 if (islower(*s))
1655 return EXIT_SUCCESS;
1656 if (capslock == 0)
1657 capslock = isupper(*s);
1658 }
1659 return capslock;
6dbe3af9
KZ
1660}
1661
53d55042 1662/* Convert speed string to speed code; return 0 on failure. */
bde20e1b 1663static speed_t bcode(char *s)
6dbe3af9 1664{
1a204cd2 1665 const struct Speedtab *sp;
53d55042 1666 long speed = atol(s);
6dbe3af9 1667
70bedfa1
KZ
1668 for (sp = speedtab; sp->speed; sp++)
1669 if (sp->speed == speed)
1670 return sp->code;
1671 return 0;
6dbe3af9
KZ
1672}
1673
7d368556 1674static void __attribute__ ((__noreturn__)) usage(FILE *out)
6dbe3af9 1675{
7d368556 1676 fputs(USAGE_HEADER, out);
4cfda3dc 1677 fprintf(out, _(" %1$s [options] line [baud_rate,...] [termtype]\n"
7d368556
SK
1678 " %1$s [options] baud_rate,... line [termtype]\n"), program_invocation_short_name);
1679 fputs(USAGE_OPTIONS, out);
1680 fputs(_(" -8, --8bits assume 8-bit tty\n"), out);
1681 fputs(_(" -a, --autologin <user> login the specified user automatically\n"), out);
1682 fputs(_(" -c, --noreset do not reset control mode\n"), out);
1505a0b2 1683 fputs(_(" -E, --remote use -r <hostname> for login(1)\n"), out);
7d368556
SK
1684 fputs(_(" -f, --issue-file <file> display issue file\n"), out);
1685 fputs(_(" -h, --flow-control enable hardware flow control\n"), out);
1686 fputs(_(" -H, --host <hostname> specify login host\n"), out);
1687 fputs(_(" -i, --noissue do not display issue file\n"), out);
1688 fputs(_(" -I, --init-string <string> set init string\n"), out);
1689 fputs(_(" -l, --login-program <file> specify login program\n"), out);
ef264c83 1690 fputs(_(" -L, --local-line[=<mode>] cotrol local line flag\n"), out);
7d368556
SK
1691 fputs(_(" -m, --extract-baud extract baud rate during connect\n"), out);
1692 fputs(_(" -n, --skip-login do not prompt for login\n"), out);
1693 fputs(_(" -o, --login-options <opts> options that are passed to login\n"), out);
1694 fputs(_(" -p, --loginpause wait for any key before the login\n"), out);
4b856ee4 1695 fputs(_(" -r, --chroot <dir> change root to the directory\n"), out);
7d368556
SK
1696 fputs(_(" -R, --hangup do virtually hangup on the tty\n"), out);
1697 fputs(_(" -s, --keep-baud try to keep baud rate after break\n"), out);
1698 fputs(_(" -t, --timeout <number> login process timeout\n"), out);
1699 fputs(_(" -U, --detect-case detect uppercase terminal\n"), out);
1700 fputs(_(" -w, --wait-cr wait carriage-return\n"), out);
1701 fputs(_(" --noclear do not clear the screen before prompt\n"), out);
1702 fputs(_(" --nohints do not print hints\n"), out);
1703 fputs(_(" --nonewline do not print a newline before issue\n"), out);
1704 fputs(_(" --no-hostname no hostname at all will be shown\n"), out);
1705 fputs(_(" --long-hostname show full qualified hostname\n"), out);
1706 fputs(_(" --erase-chars <string> additional backspace chars\n"), out);
1707 fputs(_(" --kill-chars <string> additional kill chars\n"), out);
86ad1432
SK
1708 fputs(_(" --help display this help and exit\n"), out);
1709 fputs(_(" --version output version information and exit\n"), out);
7d368556 1710 fprintf(out, USAGE_MAN_TAIL("agetty(8)"));
70bedfa1
KZ
1711
1712 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
6dbe3af9
KZ
1713}
1714
bde20e1b
WF
1715/*
1716 * Helper function reports errors to console or syslog.
1717 * Will be used by log_err() and log_warn() therefore
1718 * it takes a format as well as va_list.
1719 */
6dbe3af9
KZ
1720#define str2cpy(b,s1,s2) strcat(strcpy(b,s1),s2)
1721
bde20e1b 1722static void dolog(int priority, const char *fmt, va_list ap)
53d55042 1723{
6dbe3af9 1724#ifndef USE_SYSLOG
53d55042 1725 int fd;
6dbe3af9 1726#endif
53d55042
SK
1727 char buf[BUFSIZ];
1728 char *bp;
6dbe3af9 1729
70bedfa1
KZ
1730 /*
1731 * If the diagnostic is reported via syslog(3), the process name is
1732 * automatically prepended to the message. If we write directly to
1733 * /dev/console, we must prepend the process name ourselves.
1734 */
6dbe3af9 1735#ifdef USE_SYSLOG
70bedfa1
KZ
1736 buf[0] = '\0';
1737 bp = buf;
6dbe3af9 1738#else
53d55042 1739 str2cpy(buf, program_invocation_short_name, ": ");
70bedfa1 1740 bp = buf + strlen(buf);
53d55042 1741#endif /* USE_SYSLOG */
763d7a87 1742 vsnprintf(bp, sizeof(buf)-strlen(buf), fmt, ap);
6dbe3af9 1743
70bedfa1
KZ
1744 /*
1745 * Write the diagnostic directly to /dev/console if we do not use the
1746 * syslog(3) facility.
1747 */
6dbe3af9 1748#ifdef USE_SYSLOG
53d55042 1749 openlog(program_invocation_short_name, LOG_PID, LOG_AUTHPRIV);
bde20e1b 1750 syslog(priority, "%s", buf);
70bedfa1 1751 closelog();
6dbe3af9 1752#else
70bedfa1 1753 /* Terminate with CR-LF since the console mode is unknown. */
53d55042 1754 strcat(bp, "\r\n");
70bedfa1 1755 if ((fd = open("/dev/console", 1)) >= 0) {
729def03 1756 write_all(fd, buf, strlen(buf));
53d55042 1757 close(fd);
70bedfa1 1758 }
53d55042 1759#endif /* USE_SYSLOG */
bde20e1b
WF
1760}
1761
1762static void log_err(const char *fmt, ...)
1763{
1764 va_list ap;
1765
1766 va_start(ap, fmt);
1767 dolog(LOG_ERR, fmt, ap);
1768 va_end(ap);
1769
53d55042
SK
1770 /* Be kind to init(8). */
1771 sleep(10);
70bedfa1 1772 exit(EXIT_FAILURE);
6dbe3af9 1773}
bde20e1b
WF
1774
1775static void log_warn(const char *fmt, ...)
1776{
1777 va_list ap;
1778
1779 va_start(ap, fmt);
1780 dolog(LOG_WARNING, fmt, ap);
1781 va_end(ap);
1782}
729def03 1783
2b945eda
KZ
1784static void output_iface_ip(struct ifaddrs *addrs, const char *iface, sa_family_t family)
1785{
1786 if (!iface)
1787 return;
1788
1789 if (addrs->ifa_name
1790 && strcmp(addrs->ifa_name, iface) == 0
1791 && addrs->ifa_addr
1792 && addrs->ifa_addr->sa_family == family) {
1793
1794 void *addr = NULL;
1795 char buff[INET6_ADDRSTRLEN + 1];
1796
1797 switch (addrs->ifa_addr->sa_family) {
1798 case AF_INET:
1799 addr = &((struct sockaddr_in *) addrs->ifa_addr)->sin_addr;
1800 break;
1801 case AF_INET6:
1802 addr = &((struct sockaddr_in6 *) addrs->ifa_addr)->sin6_addr;
1803 break;
1804 }
1805 if (addr) {
1806 inet_ntop(addrs->ifa_addr->sa_family, addr, buff, sizeof(buff));
1807 printf("%s", buff);
1808 }
1809
1810 } else if (addrs->ifa_next)
1811 output_iface_ip(addrs->ifa_next, iface, family);
1812}
1813
1814static void output_ip(sa_family_t family)
1815{
2448f336 1816 char *host;
2b945eda
KZ
1817 struct addrinfo hints, *info = NULL;
1818
1819 memset(&hints, 0, sizeof(hints));
1820 hints.ai_family = family;
1821 if (family == AF_INET6)
1822 hints.ai_flags = AI_V4MAPPED;
1823
2448f336
KZ
1824 host = xgethostname();
1825 if (host && getaddrinfo(host, NULL, &hints, &info) == 0 && info) {
2b945eda
KZ
1826
1827 void *addr = NULL;
2b945eda
KZ
1828
1829 switch (info->ai_family) {
1830 case AF_INET:
1831 addr = &((struct sockaddr_in *) info->ai_addr)->sin_addr;
1832 break;
1833 case AF_INET6:
1834 addr = &((struct sockaddr_in6 *) info->ai_addr)->sin6_addr;
1835 break;
1836 }
915c1d99
KZ
1837 if (addr) {
1838 char buff[INET6_ADDRSTRLEN + 1];
1839
1840 inet_ntop(info->ai_family, (void *) addr, buff, sizeof(buff));
1841 printf("%s", buff);
1842 }
2b945eda
KZ
1843
1844 freeaddrinfo(info);
1845 }
2448f336 1846 free(host);
2b945eda
KZ
1847}
1848
1849/*
1850 * parses \x{argument}, if not argument specified then returns NULL, the @fd
1851 * has to point to one char after the sequence (it means '{').
1852 */
1853static char *get_escape_argument(FILE *fd, char *buf, size_t bufsz)
1854{
1855 size_t i = 0;
1856 int c = fgetc(fd);
1857
1858 if (c == EOF || (unsigned char) c != '{') {
1859 ungetc(c, fd);
1860 return NULL;
1861 }
1862
1863 do {
1864 c = fgetc(fd);
1865 if (c == EOF)
1866 return NULL;
1867 if ((unsigned char) c != '}' && i < bufsz - 1)
1868 buf[i++] = (unsigned char) c;
1869
1870 } while ((unsigned char) c != '}');
1871
1872 buf[i] = '\0';
1873 return buf;
1874}
1875
729def03 1876static void output_special_char(unsigned char c, struct options *op,
2b945eda 1877 struct termios *tp, FILE *fp)
729def03
WF
1878{
1879 struct utsname uts;
763d7a87
KZ
1880
1881 uname(&uts);
3aa6b68f 1882
729def03
WF
1883 switch (c) {
1884 case 's':
763d7a87 1885 printf("%s", uts.sysname);
729def03
WF
1886 break;
1887 case 'n':
763d7a87 1888 printf("%s", uts.nodename);
729def03
WF
1889 break;
1890 case 'r':
763d7a87 1891 printf("%s", uts.release);
729def03
WF
1892 break;
1893 case 'v':
763d7a87 1894 printf("%s", uts.version);
729def03
WF
1895 break;
1896 case 'm':
763d7a87 1897 printf("%s", uts.machine);
729def03
WF
1898 break;
1899 case 'o':
1900 {
2448f336
KZ
1901 char *dom = xgetdomainname();
1902
1903 fputs(dom ? dom : "unknown_domain", stdout);
1904 free(dom);
729def03
WF
1905 break;
1906 }
1907 case 'O':
1908 {
2448f336
KZ
1909 char *dom = NULL;
1910 char *host = xgethostname();
729def03
WF
1911 struct addrinfo hints, *info = NULL;
1912
1913 memset(&hints, 0, sizeof(hints));
1914 hints.ai_flags = AI_CANONNAME;
1915
2448f336 1916 if (host && getaddrinfo(host, NULL, &hints, &info) == 0 && info) {
729def03 1917 char *canon;
2448f336 1918
729def03
WF
1919 if (info->ai_canonname &&
1920 (canon = strchr(info->ai_canonname, '.')))
1921 dom = canon + 1;
729def03 1922 }
2448f336
KZ
1923 fputs(dom ? dom : "unknown_domain", stdout);
1924 if (info)
1925 freeaddrinfo(info);
1926 free(host);
729def03
WF
1927 break;
1928 }
1929 case 'd':
1930 case 't':
1931 {
1932 time_t now;
1933 struct tm *tm;
1934
763d7a87 1935 time(&now);
729def03
WF
1936 tm = localtime(&now);
1937
d9201203
KZ
1938 if (!tm)
1939 break;
1940
729def03 1941 if (c == 'd') /* ISO 8601 */
763d7a87 1942 printf("%s %s %d %d",
729def03
WF
1943 nl_langinfo(ABDAY_1 + tm->tm_wday),
1944 nl_langinfo(ABMON_1 + tm->tm_mon),
1945 tm->tm_mday,
1946 tm->tm_year < 70 ? tm->tm_year + 2000 :
1947 tm->tm_year + 1900);
1948 else
763d7a87 1949 printf("%02d:%02d:%02d",
729def03
WF
1950 tm->tm_hour, tm->tm_min, tm->tm_sec);
1951 break;
1952 }
1953 case 'l':
763d7a87 1954 printf ("%s", op->tty);
729def03
WF
1955 break;
1956 case 'b':
1957 {
1958 const speed_t speed = cfgetispeed(tp);
1959 int i;
1960
1961 for (i = 0; speedtab[i].speed; i++) {
1962 if (speedtab[i].code == speed) {
1963 printf("%ld", speedtab[i].speed);
1964 break;
1965 }
1966 }
1967 break;
1968 }
1969 case 'u':
1970 case 'U':
1971 {
1972 int users = 0;
1973 struct utmp *ut;
1974 setutent();
1975 while ((ut = getutent()))
1976 if (ut->ut_type == USER_PROCESS)
1977 users++;
1978 endutent();
729def03 1979 if (c == 'U')
9e531400
BS
1980 printf(P_("%d user", "%d users", users), users);
1981 else
1982 printf ("%d ", users);
729def03
WF
1983 break;
1984 }
2b945eda
KZ
1985 case '4':
1986 case '6':
1987 {
1988 sa_family_t family = c == '4' ? AF_INET : AF_INET6;
1989 char iface[128];
1990
1991 if (get_escape_argument(fp, iface, sizeof(iface))) { /* interface IP */
1992 struct ifaddrs *addrs;
1993 int status = getifaddrs(&addrs);
1994 if (status != 0)
1995 break;
1996 output_iface_ip(addrs, iface, family);
1997 freeifaddrs(addrs);
1998 } else /* host IP */
1999 output_ip(family);
2000 break;
2001 }
729def03 2002 default:
763d7a87 2003 putchar(c);
729def03
WF
2004 break;
2005 }
2006}
2007
2008static void init_special_char(char* arg, struct options *op)
2009{
2010 char ch, *p, *q;
2011 int i;
2012
ca8e91a4
KZ
2013 op->initstring = malloc(strlen(arg) + 1);
2014 if (!op->initstring)
2015 log_err(_("failed to allocate memory: %m"));
729def03
WF
2016
2017 /*
2018 * Copy optarg into op->initstring decoding \ddd octal
2019 * codes into chars.
2020 */
2021 q = op->initstring;
2022 p = arg;
2023 while (*p) {
2024 /* The \\ is converted to \ */
2025 if (*p == '\\') {
2026 p++;
2027 if (*p == '\\') {
2028 ch = '\\';
2029 p++;
2030 } else {
2031 /* Handle \000 - \177. */
2032 ch = 0;
2033 for (i = 1; i <= 3; i++) {
2034 if (*p >= '0' && *p <= '7') {
2035 ch <<= 3;
2036 ch += *p - '0';
2037 p++;
2038 } else {
2039 break;
2040 }
2041 }
2042 }
2043 *q++ = ch;
2044 } else
2045 *q++ = *p++;
2046 }
2047 *q = '\0';
2048}
eb8e1f9f 2049
a694957a
KZ
2050/*
2051 * Appends @str to @dest and if @dest is not empty then use use @sep as a
2052 * separator. The maximal final length of the @dest is @len.
2053 *
2054 * Returns the final @dest length or -1 in case of error.
2055 */
2056static ssize_t append(char *dest, size_t len, const char *sep, const char *src)
2057{
2058 size_t dsz = 0, ssz = 0, sz;
2059 char *p;
2060
2061 if (!dest || !len || !src)
2062 return -1;
2063
2064 if (*dest)
2065 dsz = strlen(dest);
2066 if (dsz && sep)
2067 ssz = strlen(sep);
2068 sz = strlen(src);
2069
2070 if (dsz + ssz + sz + 1 > len)
2071 return -1;
2072
2073 p = dest + dsz;
2074 if (ssz) {
2075 memcpy(p, sep, ssz);
2076 p += ssz;
2077 }
2078 memcpy(p, src, sz);
2079 *(p + sz) = '\0';
2080
2081 return dsz + ssz + sz;
2082}
9aeb66dc 2083
eb8e1f9f
WF
2084/*
2085 * Do not allow the user to pass an option as a user name
2086 * To be more safe: Use `--' to make sure the rest is
2087 * interpreted as non-options by the program, if it supports it.
2088 */
9aeb66dc 2089static void check_username(const char* nm)
eb8e1f9f
WF
2090{
2091 const char *p = nm;
2092 if (!nm)
2093 goto err;
763d7a87 2094 if (strlen(nm) > 42)
eb8e1f9f 2095 goto err;
763d7a87 2096 while (isspace(*p))
eb8e1f9f
WF
2097 p++;
2098 if (*p == '-')
2099 goto err;
2100 return;
2101err:
2102 errno = EPERM;
8c219bf4 2103 log_err(_("checkname failed: %m"));
eb8e1f9f
WF
2104}
2105