File: rungetty.c

package info (click to toggle)
rungetty 1.2-16
  • links: PTS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 280 kB
  • ctags: 265
  • sloc: ansic: 3,057; makefile: 30
file content (611 lines) | stat: -rw-r--r-- 14,182 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*******************************************************************************
 *  rungetty.c
 *  This is rungetty, a small console getty that allows for execution of
 *  arbitrary programs.
 *
 *  Copyright (C) 1999 Jakob 'sparky' Kaivo
 *  jake@nodomainname.net
 *  
 *  Based on code from mingetty by Florian La Roche. See the
 *  file mingetty.comments for original text.
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version
 *  2 of the License, or (at your option) any later version.
 *
 ******************************************************************************/

#define DEBUG_THIS 0

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <grp.h>
#include <pwd.h>
#include <string.h>
#include <time.h>
#include <utmp.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <sys/utsname.h>

#ifndef _PATH_LOGIN
#define _PATH_LOGIN "/bin/login"
#endif

#ifdef linux
#include <sys/param.h>
#define USE_SYSLOG
#endif

 /* If USE_SYSLOG is undefined all diagnostics go directly to /dev/console. */
#ifdef  USE_SYSLOG
#include <syslog.h>
#endif

#define ISSUE "/etc/issue"	/* displayed before the login prompt */
#define LOGIN " login: "	/* login prompt */
#define PROMPT_RETURN "Press return to activate "	/* when --prompt specified */

/* name of this program (argv[0]) */
static char *progname;

/* path of working directory for program */
static char *progpath = NULL;

/* 'nice' level of the program */
static int priority = 0;

/* on which tty line are we sitting? (e.g. tty1) */
static char *tty;

/* and what program do we run? */
static char *program_run;

/* some information about this host */
static struct utsname uts;

/* the hostname */
static char hn[MAXHOSTNAMELEN + 1];

/* process ID of this program */
static pid_t pid;

/* current time */
static time_t cur_time;

/* do not send a reset string to the terminal ? */
static int noclear = 0;
/* Print the whole string of gethostname() instead of just until the next "." */ static int longhostname = 0;

/* The user to run as */
static struct passwd *user;

/* The group */
static struct group *u_group;

/* set to wait for return before doing anything */
static int prompt_return = 0;

/* time to wait, seconds */
static int delay = 0;

/* AUTO_LAST points to a timestamp file used to limit autologins to
   immediately after system boot. */
#define AUTO_LAST "/var/log/autologin"
/* AUTO_TTY is the tty on which autologins will be accepted.  If set
   to an empty string, autologins will be accepted on any tty. */
#define AUTO_TTY ""
/* If supplied, attempt an automatic login with this username. */
static char *autologin_name = NULL;

/* Prompt for use with --prompt */
static char *prompt;

/*
 * output error messages
 */
static void
error (const char *fmt,...)
{
  va_list va_alist;
  char buf[256], *bp;

#ifdef USE_SYSLOG
  buf[0] = '\0';
  bp = buf;
#else /* !USE_SYSLOG */
  int fd;

  strcpy (buf, progname);
  strcat (buf, ": ");
  bp = buf + strlen (buf);
#endif /* USE_SYSLOG */

  va_start (va_alist, fmt);
  vsprintf (bp, fmt, va_alist);
  va_end (va_alist);

#ifdef	USE_SYSLOG
  openlog (progname, LOG_PID, LOG_AUTH);
  syslog (LOG_ERR, buf);
  closelog ();
#else /* !USE_SYSLOG */
  strcat (bp, "\r\n");
  if ((fd = open ("/dev/console", 1)) >= 0)
    {
      write (fd, buf, strlen (buf));
      close (fd);
    }
#endif /* USE_SYSLOG */
  exit (1);
}

/*
 * update_utmp - update our utmp entry
 *
 * The utmp file holds miscellaneous information about things started by
 * /sbin/init and other system-related events. Our purpose is to update
 * the utmp entry for the current process, in particular the process
 * type and the tty line we are listening to. Return successfully only
 * if the utmp file can be opened for update, and if we are able to find
 * our entry in the utmp file.
 */
static void
update_utmp (void)
{
  struct utmp ut;
  int ut_fd;
  struct utmp *utp;
  void locktimeout (int);

  utmpname (_PATH_UTMP);
  setutent ();
  while ((utp = getutent ()))
    if (utp->ut_type == INIT_PROCESS && utp->ut_pid == pid)
      break;

  if (utp)
    {
      memcpy (&ut, utp, sizeof (ut));
    }
  else
    {
      /* some inits don't initialize utmp... */
      /* XXX we should print out a warning message */
      memset (&ut, 0, sizeof (ut));
      strncpy (ut.ut_id, tty + 3, sizeof (ut.ut_id));
    }
  endutent ();

  strncpy (ut.ut_user, "LOGIN", sizeof (ut.ut_user));
  strncpy (ut.ut_line, tty, sizeof (ut.ut_line));
  ut.ut_time = cur_time;
  ut.ut_type = LOGIN_PROCESS;
  ut.ut_pid = pid;

  pututline (&ut);
  endutent ();

  if ((ut_fd = open (_PATH_WTMP, O_APPEND | O_WRONLY)) >= 0)
    {
      (void) signal (SIGALRM, locktimeout);
      (void) alarm (3);
      flock (ut_fd, LOCK_EX);
      (void) alarm (0);
      write (ut_fd, &ut, sizeof (ut));
      flock (ut_fd, LOCK_UN);
      close (ut_fd);
    }
}

static void
output_special_char (unsigned char c)
{
  switch (c)
    {
    case 's':
      printf ("%s", uts.sysname);
      break;
    case 'n':
      printf ("%s", uts.nodename);
      break;
    case 'r':
      printf ("%s", uts.release);
      break;
    case 'v':
      printf ("%s", uts.version);
      break;
    case 'm':
      printf ("%s", uts.machine);
      break;
    case 'o':
#ifdef __USE_GNU
      printf ("%s", uts.domainname);
#else
      printf ("%s", uts.__domainname);
#endif
      break;
    case 'd':
    case 't':
      {
	char buff[20];
	struct tm *tm = localtime (&cur_time);

	strftime (buff, sizeof (buff), c == 'd' ? "%a %b %d %Y" : "%X", tm);
	fputs (buff, stdout);
	break;
      }
    case 'l':
      printf ("%s", tty);
      break;
    case 'u':
    case 'U':
      {
	int users = 0;
	struct utmp *ut;

	setutent ();
	while ((ut = getutent ()))
	  if (ut->ut_type == USER_PROCESS)
	    users++;
	endutent ();
	printf ("%d", users);
	if (c == 'U')
	  printf (" user%s", users == 1 ? "" : "s");
	break;
      }
    default:
      putchar (c);
    }
}

/* do_prompt - show login prompt, optionally preceded by /etc/issue contents */
static void
do_prompt (void)
{
  FILE *fd;
  signed int c;

  write (1, "\n", 1);		/* start a new line */
  if ((fd = fopen (ISSUE, "r")))
    {
      while ((c = getc (fd)) != EOF)
	{
	  if (c == '\\')
	    output_special_char (getc (fd));
	  else
	    putchar (c);
	}
      fflush (stdout);
      fclose (fd);
    }
  write (1, hn, strlen (hn));
  write (1, LOGIN, sizeof (LOGIN) - 1);
}

/* get_logname - get user name, establish speed, erase, kill, eol */
static char *
get_logname (void)
{
  static char logname[40];
  char *bp;
  unsigned char c;

  ioctl (0, TCFLSH, 0);		/* flush pending input */

  for (*logname = 0; *logname == 0;)
    {
      do_prompt ();
      for (bp = logname;;)
	{
	  if (read (0, &c, 1) < 1)
	    {
	      if (errno == EINTR || errno == EIO || errno == ENOENT)
		exit (0);
	      error ("%s: read: %s", tty, sys_errlist[errno]);
	    }
	  if (c == '\n' || c == '\r')
	    {
	      *bp = 0;
	      break;
	    }
	  else if (!isprint (c))
	    error ("%s: invalid character %c in login name", tty, c);
	  else if (bp - logname >= sizeof (logname) - 1)
	    error ("%s: too long login name", tty);
	  else
	    *bp++ = c;
	}
    }
  return logname;
}

static struct option const long_options[] =
{
  {"noclear", no_argument, &noclear, 1},
  {"long-hostname", no_argument, &longhostname, 1},
  {"autologin", required_argument, NULL, 'a'},
  {"prompt", optional_argument, NULL, 'p'},
  {"path", required_argument, NULL, 'w'},
  {"nice", required_argument, &priority, 'n'},
  {0, 0, 0, 0}
};

void
locktimeout (int dummy)
{
#ifdef USE_SYSLOG
  openlog (progname, LOG_PID, LOG_AUTH);
  syslog (LOG_ALERT, "Lock failed on wtmp");
  closelog ();
#else
  int fd;
  char buf[] = "Lock failed on wtmp\n";

  if ((fd = open ("/dev/console", 1)) >= 0)
    {
      write (fd, buf, strlen (buf));
      close (fd);
    }
#endif
}

/*
 * autologin_ok -- returns 1 if it's okay to auto-login when:
 *   this login is from /dev/tty1; and
 *   there was a login name passed with the --autologin option; and
 *   the autologin_name contains only "nice" characters; and
 *   this is the first autologin attempt since the last boot; 
 * return 0 otherwise.
 */
static int
autologin_ok (void)
{
  char c, *cp;
  int stat_err, fd;
  struct sysinfo info;
  struct stat sbuf;

  /* Autologins are restricted to AUTO_TTY if non-empty. */
  if (AUTO_TTY[0] && strcmp (tty, AUTO_TTY))
    return 0;

  /* An all-alphanumeric autologin name must be supplied. */
  if (autologin_name == NULL || autologin_name[0] == '\0')
    return 0;
  for (cp = autologin_name; (c = *cp); cp++)
    if (!isalnum (c) && c != '_')
      return 0;

  /* Get the uptime in info.uptime, and the last autologin time
     in sbuf.st_mtime. */
  sysinfo (&info);
  stat_err = stat (AUTO_LAST, &sbuf);

  /* If a stat error other than "no such file" occurs, I don't
     know what went wrong, so I'll proceed with caution by
     denying the autologin request. */
  if (stat_err && errno != ENOENT)
    return 0;

  /* If there's been an autologin granted since the last boot,
     deny this and any subsequent attempts.  Note that this test
     is skipped if the AUTO_LAST file doesn't exist. */
  if (!stat_err && time (NULL) - info.uptime < sbuf.st_mtime)
    return 0;

  /* Create the AUTO_LAST file.  The mtime of this file provides
     a persistent record of the last time that an autologin
     request was granted.  Deny the autologin request if either
     the file open or file close fails. */
  if ((fd = open (AUTO_LAST, O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0)
    return 0;
  if (close (fd) != 0)
    return 0;

  /* All tests are okay, so grant the autologin request. */
  return 1;
}

void
mingetty_login (char *logname, char *tty)
{
  if (autologin_ok ())
    {
      execl (_PATH_LOGIN, _PATH_LOGIN, "-f", autologin_name, NULL);
    }
  else
    {
      while ((logname = get_logname ()) == 0);
      execl (_PATH_LOGIN, _PATH_LOGIN, "--", logname, NULL);
    }
  error ("%s: can't exec " _PATH_LOGIN ": %s", tty, sys_errlist[errno]);
  exit (0);
}

/* open_tty - set up tty as standard { input, output, error } */
static void
open_tty (void)
{
  struct sigaction sa;
  char buf[20];
  int fd;

  /* Set up new standard input. */
  strcpy (buf, "/dev/");
  strcat (buf, tty);
  if (chown (buf, 0, 0) || chmod (buf, 0600))
    error ("%s: %s", buf, sys_errlist[errno]);

  sa.sa_handler = SIG_IGN;
  sa.sa_flags = 0;
  sigemptyset (&sa.sa_mask);
  sigaction (SIGHUP, &sa, NULL);

  /* vhangup() will replace all open file descriptors that point to our
     controlling tty by a dummy that will deny further reading/writing
     to our device. It will also reset the tty to sane defaults, so we
     don't have to modify the tty device for sane settings.
     We also get a SIGHUP/SIGCONT.
   */
  if ((fd = open (buf, O_RDWR, 0)) < 0
      || ioctl (fd, TIOCSCTTY, (void *) 1) == -1)
    error ("%s: cannot open tty: %s", buf, sys_errlist[errno]);
  if (!isatty (fd))
    error ("%s: not a tty", buf);

  vhangup ();
  /* Get rid of the present stdout/stderr. */
  close (2);
  close (1);
  close (0);
  close (fd);
  /* ioctl (0, TIOCNOTTY, (char *)1); */

  if (open (buf, O_RDWR, 0) != 0)
    error ("%s: cannot open as standard input: %s", buf,
	   sys_errlist[errno]);

  /* Set up standard output and standard error file descriptors. */
  if (dup (0) != 1 || dup (0) != 2)
    error ("%s: dup problem: %s", buf, sys_errlist[errno]);

  /* Write a reset string to the terminal. This is very linux-specific
     and should be checked for other systems. */
  if (!noclear)
    write (0, "\033[H\033[J", 6);

  sa.sa_handler = SIG_DFL;
  sa.sa_flags = 0;
  sigemptyset (&sa.sa_mask);
  sigaction (SIGHUP, &sa, NULL);

  if (prompt_return)
    {
      write (1, prompt, strlen (prompt));
      if (program_run)
	{
	  write (1, "`", 1);
	  write (1, program_run, strlen (program_run));
	  write (1, "'", 1);
	}
      write (1, "\n", 1);
      read (0, buf, 1);
    }

#if	DEBUG_THIS
  printf ("session=%d, pid=%d, pgid=%d\n", getsid (0), getpid (), getpgid (0));
#endif
}

static void
usage (void)
{
  error ("usage: '%s tty program'", progname);
}


/*
 * main program
 */
int
main (int argc, char **argv)
{

  char *logname, *s;
  int c;

  progname = argv[0];
  uname (&uts);
  gethostname (hn, MAXHOSTNAMELEN);
  pid = getpid ();
  time (&cur_time);
  while ((c = getopt_long (argc, argv, "d:n:u:w:g:", long_options, (int *) 0)) != EOF)
    {
      switch (c)
	{
	case 0:
	  break;
	case 'a':
	  autologin_name = optarg;
	  break;
	case 'd':
	  delay = atoi (optarg);
	  break;
	case 'g':
	  u_group = getgrnam (optarg);
	  break;
	case 'n':
	  priority = atoi (optarg);
	  break;
	case 'p':
	  if (optarg)
	    prompt = optarg;
	  else
	    prompt = PROMPT_RETURN;
	  prompt_return = 1;
	  break;
	case 'u':
	  user = getpwnam (optarg);
	  break;
	case 'w':
	  progpath = optarg;
	  break;
	default:
	  usage ();
	}
    }
  if (!longhostname && (s = strchr (hn, '.')))
    *s = '\0';
  if (!user)
    user = getpwnam ("nobody");
  if (!u_group)
    u_group = getgrnam ("nogroup");
  tty = argv[optind];
  if (!tty)
    usage ();
  program_run = argv[optind + 1];
  update_utmp ();

  if (delay)
    sleep (delay);

  open_tty ();

#ifdef linux
  putenv ("TERM=linux");
#else
  putenv ("TERM=vt100");
#endif
/* disabled -- get path from init  putenv ("PATH=/bin:/usr/bin:/usr/ucb:/usr/local/bin"); */

  /* flush input and output queues, important for modems */
  ioctl (0, TCFLSH, 2);

  if (!program_run)
    mingetty_login (logname, tty);

  setgid (u_group->gr_gid);
  initgroups (user->pw_name, user->pw_gid);
  setuid (user->pw_uid);

  if (progpath)
    chdir (progpath);

  nice (priority);

  execvp (program_run, &argv[optind + 1]);
  error ("%s: can't exec %s : %s", tty, program_run, sys_errlist[errno]);
  exit (0);
}