drm/radeon: Reduce differences with Linux 3.18
[dragonfly.git] / sbin / init / init.c
blobb6e9902dc3cfa2f29e1f147ed3c7f7e9d4655cf0
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
32 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California. All rights reserved.
33 * @(#)init.c 8.1 (Berkeley) 7/15/93
34 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/mount.h>
40 #include <sys/sysctl.h>
41 #include <sys/wait.h>
42 #include <sys/stat.h>
44 #include <db.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <libutil.h>
48 #include <utmpx.h>
49 #include <paths.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <time.h>
56 #include <ttyent.h>
57 #include <unistd.h>
58 #include <sys/reboot.h>
59 #include <err.h>
61 #include <stdarg.h>
63 #ifdef SECURE
64 #include <pwd.h>
65 #endif
67 #ifdef LOGIN_CAP
68 #include <login_cap.h>
69 #endif
71 #include "pathnames.h"
74 * Sleep times; used to prevent thrashing.
76 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
77 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
78 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
79 #define WINDOW_WAIT 3 /* wait N secs after starting window */
80 #define STALL_TIMEOUT 30 /* wait N secs after warning */
81 #define DEATH_WATCH 10 /* wait N secs for procs to die */
82 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
85 * User-based resource limits.
87 #define RESOURCE_RC "daemon"
88 #define RESOURCE_WINDOW "default"
89 #define RESOURCE_GETTY "default"
91 #ifndef DEFAULT_STATE
92 #define DEFAULT_STATE runcom
93 #endif
95 typedef enum {
96 invalid_state,
97 single_user,
98 runcom,
99 read_ttys,
100 multi_user,
101 clean_ttys,
102 catatonia,
103 death
104 } state_t;
105 typedef state_t (*state_func_t)(void);
107 static state_t f_single_user(void);
108 static state_t f_runcom(void);
109 static state_t f_read_ttys(void);
110 static state_t f_multi_user(void);
111 static state_t f_clean_ttys(void);
112 static state_t f_catatonia(void);
113 static state_t f_death(void);
115 state_func_t state_funcs[] = {
116 NULL,
117 f_single_user,
118 f_runcom,
119 f_read_ttys,
120 f_multi_user,
121 f_clean_ttys,
122 f_catatonia,
123 f_death
126 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
127 #define FALSE 0
128 #define TRUE 1
130 static void transition(state_t);
131 static volatile sig_atomic_t requested_transition = DEFAULT_STATE;
133 static void setctty(const char *);
135 typedef struct init_session {
136 int se_index; /* index of entry in ttys file */
137 pid_t se_process; /* controlling process */
138 struct timeval se_started; /* used to avoid thrashing */
139 int se_flags; /* status of session */
140 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
141 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
142 int se_nspace; /* spacing count */
143 char *se_device; /* filename of port */
144 char *se_getty; /* what to run on that port */
145 char *se_getty_argv_space; /* pre-parsed argument array space */
146 char **se_getty_argv; /* pre-parsed argument array */
147 char *se_window; /* window system (started only once) */
148 char *se_window_argv_space; /* pre-parsed argument array space */
149 char **se_window_argv; /* pre-parsed argument array */
150 char *se_type; /* default terminal type */
151 struct init_session *se_prev;
152 struct init_session *se_next;
153 } session_t;
155 static void handle(sig_t, ...);
156 static void delset(sigset_t *, ...);
158 static void stall(const char *, ...) __printflike(1, 2);
159 static void warning(const char *, ...) __printflike(1, 2);
160 static void emergency(const char *, ...) __printflike(1, 2);
161 static void disaster(int);
162 static void badsys(int);
163 static int runshutdown(void);
164 static char *strk(char *);
166 #define DEATH 'd'
167 #define SINGLE_USER 's'
168 #define RUNCOM 'r'
169 #define READ_TTYS 't'
170 #define MULTI_USER 'm'
171 #define CLEAN_TTYS 'T'
172 #define CATATONIA 'c'
174 static void free_session(session_t *);
175 static session_t *new_session(session_t *, int, struct ttyent *);
176 static void adjttyent(struct ttyent *typ);
178 static char **construct_argv(char *);
179 static void start_window_system(session_t *);
180 static void collect_child(pid_t);
181 static pid_t start_getty(session_t *);
182 static void transition_handler(int);
183 static void alrm_handler(int);
184 static void setsecuritylevel(int);
185 static int getsecuritylevel(void);
186 static char *get_chroot(void);
187 static int setupargv(session_t *, struct ttyent *);
188 #ifdef LOGIN_CAP
189 static void setprocresources(const char *);
190 #endif
192 static void clear_session_logs(session_t *);
194 static int start_session_db(void);
195 static void add_session(session_t *);
196 static void del_session(session_t *);
197 static session_t *find_session(pid_t);
199 #ifdef SUPPORT_UTMPX
200 static struct timeval boot_time;
201 state_t current_state = death;
202 static void session_utmpx(const session_t *, int);
203 static void make_utmpx(const char *, const char *, int, pid_t,
204 const struct timeval *, int);
205 static char get_runlevel(const state_t);
206 static void utmpx_set_runlevel(char, char);
207 #endif
209 static int Reboot = FALSE;
210 static int howto = RB_AUTOBOOT;
212 static DB *session_db;
213 static volatile sig_atomic_t clang;
214 static session_t *sessions;
217 * The mother of all processes.
220 main(int argc, char *argv[])
222 char *init_chroot;
223 int c;
224 struct sigaction sa;
225 sigset_t mask;
226 struct stat sts;
228 #ifdef SUPPORT_UTMPX
229 (void)gettimeofday(&boot_time, NULL);
230 #endif /* SUPPORT_UTMPX */
232 /* Dispose of random users. */
233 if (getuid() != 0)
234 errx(1, "%s", strerror(EPERM));
236 /* System V users like to reexec init. */
237 if (getpid() != 1) {
238 #ifdef COMPAT_SYSV_INIT
239 /* So give them what they want */
240 if (argc > 1) {
241 if (strlen(argv[1]) == 1) {
242 char runlevel = *argv[1];
243 int sig;
245 switch (runlevel) {
246 case '0': /* halt + poweroff */
247 sig = SIGUSR2;
248 break;
249 case '1': /* single-user */
250 sig = SIGTERM;
251 break;
252 case '6': /* reboot */
253 sig = SIGINT;
254 break;
255 case 'c': /* block further logins */
256 sig = SIGTSTP;
257 break;
258 case 'q': /* rescan /etc/ttys */
259 sig = SIGHUP;
260 break;
261 default:
262 goto invalid;
264 kill(1, sig);
265 _exit(0);
266 } else
267 invalid:
268 errx(1, "invalid run-level ``%s''", argv[1]);
269 } else
270 #endif
271 errx(1, "already running");
274 * Note that this does NOT open a file...
275 * Does 'init' deserve its own facility number?
277 openlog("init", LOG_CONS, LOG_AUTH);
280 * If chroot has been requested by the boot loader,
281 * do it now. Try to be robust: If the directory
282 * doesn't exist, continue anyway.
284 init_chroot = get_chroot();
285 if (init_chroot != NULL) {
286 if (chdir(init_chroot) == -1 || chroot(".") == -1)
287 warning("can't chroot to %s: %m", init_chroot);
288 free(init_chroot);
292 * Create an initial session.
294 if (setsid() < 0)
295 warning("initial setsid() failed: %m");
298 * Establish an initial user so that programs running
299 * single user do not freak out and die (like passwd).
301 if (setlogin("root") < 0)
302 warning("setlogin() failed: %m");
304 if (stat("/dev/null", &sts) < 0) {
305 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
306 sleep(5);
310 * This code assumes that we always get arguments through flags,
311 * never through bits set in some random machine register.
313 while ((c = getopt(argc, argv, "dsf")) != -1)
314 switch (c) {
315 case 'd':
316 /* We don't support DEVFS. */
317 break;
318 case 's':
319 requested_transition = single_user;
320 break;
321 case 'f':
322 runcom_mode = FASTBOOT;
323 break;
324 default:
325 warning("unrecognized flag '-%c'", c);
326 break;
329 if (optind != argc)
330 warning("ignoring excess arguments");
333 * We catch or block signals rather than ignore them,
334 * so that they get reset on exec.
336 handle(badsys, SIGSYS, 0);
337 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
338 SIGBUS, SIGXCPU, SIGXFSZ, 0);
339 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
340 SIGUSR1, SIGUSR2, 0);
341 handle(alrm_handler, SIGALRM, 0);
342 sigfillset(&mask);
343 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
344 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
345 SIGUSR1, SIGUSR2, 0);
346 sigprocmask(SIG_SETMASK, &mask, NULL);
347 sigemptyset(&sa.sa_mask);
348 sa.sa_flags = 0;
349 sa.sa_handler = SIG_IGN;
350 sigaction(SIGTTIN, &sa, NULL);
351 sigaction(SIGTTOU, &sa, NULL);
354 * Paranoia.
356 close(0);
357 close(1);
358 close(2);
361 * Start the state machine.
363 transition(requested_transition);
366 * Should never reach here.
368 return 1;
372 * Associate a function with a signal handler.
374 static void
375 handle(sig_t handler, ...)
377 int sig;
378 struct sigaction sa;
379 sigset_t mask_everything;
380 va_list ap;
382 va_start(ap, handler);
384 sa.sa_handler = handler;
385 sigfillset(&mask_everything);
387 while ((sig = va_arg(ap, int)) != 0) {
388 sa.sa_mask = mask_everything;
389 /* XXX SA_RESTART? */
390 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
391 sigaction(sig, &sa, NULL);
393 va_end(ap);
397 * Delete a set of signals from a mask.
399 static void
400 delset(sigset_t *maskp, ...)
402 int sig;
403 va_list ap;
405 va_start(ap, maskp);
407 while ((sig = va_arg(ap, int)) != 0)
408 sigdelset(maskp, sig);
409 va_end(ap);
413 * Log a message and sleep for a while (to give someone an opportunity
414 * to read it and to save log or hardcopy output if the problem is chronic).
416 static void
417 stall(const char *message, ...)
419 va_list ap;
421 va_start(ap, message);
423 vsyslog(LOG_ALERT, message, ap);
424 va_end(ap);
425 sleep(STALL_TIMEOUT);
429 * Like stall(), but doesn't sleep.
430 * If cpp had variadic macros, the two functions could be #defines for another.
432 static void
433 warning(const char *message, ...)
435 va_list ap;
437 va_start(ap, message);
439 vsyslog(LOG_ALERT, message, ap);
440 va_end(ap);
444 * Log an emergency message.
446 static void
447 emergency(const char *message, ...)
449 va_list ap;
451 va_start(ap, message);
453 vsyslog(LOG_EMERG, message, ap);
454 va_end(ap);
458 * Catch a SIGSYS signal.
460 * These may arise if a system does not support sysctl.
461 * We tolerate up to 25 of these, then throw in the towel.
463 static void
464 badsys(int sig)
466 static int badcount = 0;
468 if (badcount++ < 25)
469 return;
470 disaster(sig);
474 * Catch an unexpected signal.
476 static void
477 disaster(int sig)
479 emergency("fatal signal: %s",
480 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
482 sleep(STALL_TIMEOUT);
483 _exit(sig); /* reboot */
487 * Get the security level of the kernel.
489 static int
490 getsecuritylevel(void)
492 #ifdef KERN_SECURELVL
493 int name[2], curlevel;
494 size_t len;
496 name[0] = CTL_KERN;
497 name[1] = KERN_SECURELVL;
498 len = sizeof curlevel;
499 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
500 emergency("cannot get kernel security level: %s",
501 strerror(errno));
502 return (-1);
504 return (curlevel);
505 #else
506 return (-1);
507 #endif
511 * Get the value of the "init_chroot" variable from the
512 * kernel environment (or NULL if not set).
515 static char *
516 get_chroot(void)
518 static const char ichname[] = "init_chroot="; /* includes '=' */
519 const int ichlen = strlen(ichname);
520 int real_oid[CTL_MAXNAME];
521 char sbuf[1024];
522 size_t oidlen, slen;
523 char *res;
524 int i;
526 oidlen = NELEM(real_oid);
527 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
528 warning("cannot find kern.environment base sysctl OID");
529 return NULL;
531 if (oidlen + 1 >= NELEM(real_oid)) {
532 warning("kern.environment OID is too large!");
533 return NULL;
535 res = NULL;
536 real_oid[oidlen] = 0;
538 for (i = 0; ; i++) {
539 real_oid[oidlen + 1] = i;
540 slen = sizeof(sbuf);
541 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
542 if (errno != ENOENT)
543 warning("sysctl kern.environment.%d: %m", i);
544 break;
548 * slen includes the terminating \0, but do a few sanity
549 * checks anyway.
551 if (slen == 0)
552 continue;
553 sbuf[slen - 1] = 0;
554 if (strncmp(sbuf, ichname, ichlen) != 0)
555 continue;
556 if (sbuf[ichlen])
557 res = strdup(sbuf + ichlen);
558 break;
560 return (res);
564 * Set the security level of the kernel.
566 static void
567 setsecuritylevel(int newlevel)
569 #ifdef KERN_SECURELVL
570 int name[2], curlevel;
572 curlevel = getsecuritylevel();
573 if (newlevel == curlevel)
574 return;
575 name[0] = CTL_KERN;
576 name[1] = KERN_SECURELVL;
577 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
578 emergency(
579 "cannot change kernel security level from %d to %d: %s",
580 curlevel, newlevel, strerror(errno));
581 return;
583 #ifdef SECURE
584 warning("kernel security level changed from %d to %d",
585 curlevel, newlevel);
586 #endif
587 #endif
591 * Change states in the finite state machine.
592 * The initial state is passed as an argument.
594 static void
595 transition(state_t s)
597 for (;;) {
598 #ifdef SUPPORT_UTMPX
599 utmpx_set_runlevel(get_runlevel(current_state),
600 get_runlevel(s));
601 current_state = s;
602 #endif
603 s = (*state_funcs[s])();
608 * Close out the accounting files for a login session.
610 static void
611 clear_session_logs(session_t *sp)
613 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
615 #ifdef SUPPORT_UTMPX
616 if (logoutx(line, 0, DEAD_PROCESS))
617 logwtmpx(line, "", "", 0, DEAD_PROCESS);
618 #endif
619 if (logout(line))
620 logwtmp(line, "", "");
624 * Start a session and allocate a controlling terminal.
625 * Only called by children of init after forking.
627 static void
628 setctty(const char *name)
630 int fd;
632 revoke(name);
633 if ((fd = open(name, O_RDWR)) == -1) {
634 stall("can't open %s: %m", name);
635 _exit(1);
637 if (login_tty(fd) == -1) {
638 stall("can't get %s for controlling terminal: %m", name);
639 _exit(1);
644 * Bring the system up single user.
646 static state_t
647 f_single_user(void)
649 pid_t pid, wpid;
650 int status;
651 sigset_t mask;
652 const char *shell = _PATH_BSHELL;
653 const char *argv[2];
654 #ifdef SECURE
655 struct ttyent *typ;
656 struct passwd *pp;
657 static const char banner[] =
658 "Enter root password, or ^D to go multi-user\n";
659 char *clear, *password;
660 #endif
661 #ifdef DEBUGSHELL
662 char altshell[128];
663 #endif
665 if (Reboot) {
666 /* Instead of going single user, let's reboot the machine */
667 sync();
668 alarm(2);
669 pause();
670 reboot(howto);
671 _exit(0);
674 if ((pid = fork()) == 0) {
676 * Start the single user session.
678 setctty(_PATH_CONSOLE);
680 #ifdef SECURE
682 * Check the root password.
683 * We don't care if the console is 'on' by default;
684 * it's the only tty that can be 'off' and 'secure'.
686 typ = getttynam("console");
687 pp = getpwnam("root");
688 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
689 pp && *pp->pw_passwd) {
690 write(2, banner, sizeof banner - 1);
691 for (;;) {
692 clear = getpass("Password:");
693 if (clear == NULL || *clear == '\0')
694 _exit(0);
695 password = crypt(clear, pp->pw_passwd);
696 bzero(clear, _PASSWORD_LEN);
697 if (password != NULL && strcmp(password, pp->pw_passwd) == 0)
698 break;
699 warning("single-user login failed\n");
702 endttyent();
703 endpwent();
704 #endif /* SECURE */
706 #ifdef DEBUGSHELL
708 char *cp = altshell;
709 int num;
711 #define SHREQUEST \
712 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
713 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
714 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
715 num != 0 && *cp != '\n' && cp < &altshell[127])
716 cp++;
717 *cp = '\0';
718 if (altshell[0] != '\0')
719 shell = altshell;
721 #endif /* DEBUGSHELL */
724 * Unblock signals.
725 * We catch all the interesting ones,
726 * and those are reset to SIG_DFL on exec.
728 sigemptyset(&mask);
729 sigprocmask(SIG_SETMASK, &mask, NULL);
732 * Fire off a shell.
733 * If the default one doesn't work, try the Bourne shell.
735 argv[0] = "-sh";
736 argv[1] = NULL;
737 execv(shell, __DECONST(char **, argv));
738 emergency("can't exec %s for single user: %m", shell);
739 execv(_PATH_BSHELL, __DECONST(char **, argv));
740 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
741 sleep(STALL_TIMEOUT);
742 _exit(1);
745 if (pid == -1) {
747 * We are seriously hosed. Do our best.
749 emergency("can't fork single-user shell, trying again");
750 while (waitpid(-1, NULL, WNOHANG) > 0)
751 continue;
752 return single_user;
755 requested_transition = 0;
756 do {
757 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
758 collect_child(wpid);
759 if (wpid == -1) {
760 if (errno == EINTR)
761 continue;
762 warning("wait for single-user shell failed: %m; restarting");
763 return single_user;
765 if (wpid == pid && WIFSTOPPED(status)) {
766 warning("init: shell stopped, restarting\n");
767 kill(pid, SIGCONT);
768 wpid = -1;
770 } while (wpid != pid && !requested_transition);
772 if (requested_transition)
773 return requested_transition;
775 if (!WIFEXITED(status)) {
776 if (WTERMSIG(status) == SIGKILL) {
778 * reboot(8) killed shell?
780 warning("single user shell terminated.");
781 sleep(STALL_TIMEOUT);
782 _exit(0);
783 } else {
784 warning("single user shell terminated, restarting");
785 return single_user;
789 runcom_mode = FASTBOOT;
790 return runcom;
794 * Run the system startup script.
796 static state_t
797 f_runcom(void)
799 pid_t pid, wpid;
800 int status;
801 const char *argv[4];
802 struct sigaction sa;
804 if ((pid = fork()) == 0) {
805 sigemptyset(&sa.sa_mask);
806 sa.sa_flags = 0;
807 sa.sa_handler = SIG_IGN;
808 sigaction(SIGTSTP, &sa, NULL);
809 sigaction(SIGHUP, &sa, NULL);
811 setctty(_PATH_CONSOLE);
813 argv[0] = "sh";
814 argv[1] = _PATH_RUNCOM;
815 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
816 argv[3] = NULL;
818 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
820 #ifdef LOGIN_CAP
821 setprocresources(RESOURCE_RC);
822 #endif
823 execv(_PATH_BSHELL, __DECONST(char **, argv));
824 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
825 _exit(1); /* force single user mode */
828 if (pid == -1) {
829 emergency("can't fork for %s on %s: %m",
830 _PATH_BSHELL, _PATH_RUNCOM);
831 while (waitpid(-1, NULL, WNOHANG) > 0)
832 continue;
833 sleep(STALL_TIMEOUT);
834 return single_user;
838 * Copied from single_user(). This is a bit paranoid.
840 requested_transition = 0;
841 do {
842 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
843 collect_child(wpid);
844 if (wpid == -1) {
845 if (requested_transition == death)
846 return death;
847 if (errno == EINTR)
848 continue;
849 warning("wait for %s on %s failed: %m; going to single user mode",
850 _PATH_BSHELL, _PATH_RUNCOM);
851 return single_user;
853 if (wpid == pid && WIFSTOPPED(status)) {
854 warning("init: %s on %s stopped, restarting\n",
855 _PATH_BSHELL, _PATH_RUNCOM);
856 kill(pid, SIGCONT);
857 wpid = -1;
859 } while (wpid != pid);
861 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
862 requested_transition == catatonia) {
863 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
864 sigset_t s;
866 sigfillset(&s);
867 for (;;)
868 sigsuspend(&s);
871 if (!WIFEXITED(status)) {
872 warning("%s on %s terminated abnormally, going to single user mode",
873 _PATH_BSHELL, _PATH_RUNCOM);
874 return single_user;
877 if (WEXITSTATUS(status))
878 return single_user;
880 runcom_mode = AUTOBOOT; /* the default */
881 #ifdef SUPPORT_UTMPX
882 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
883 #endif
884 logwtmp("~", "reboot", "");
885 return read_ttys;
889 * Open the session database.
891 * NB: We could pass in the size here; is it necessary?
893 static int
894 start_session_db(void)
896 if (session_db && (*session_db->close)(session_db))
897 emergency("session database close: %s", strerror(errno));
898 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
899 emergency("session database open: %s", strerror(errno));
900 return (1);
902 return (0);
907 * Add a new login session.
909 static void
910 add_session(session_t *sp)
912 DBT key;
913 DBT data;
915 key.data = &sp->se_process;
916 key.size = sizeof sp->se_process;
917 data.data = &sp;
918 data.size = sizeof sp;
920 if ((*session_db->put)(session_db, &key, &data, 0))
921 emergency("insert %d: %s", sp->se_process, strerror(errno));
922 #ifdef SUPPORT_UTMPX
923 session_utmpx(sp, 1);
924 #endif
928 * Delete an old login session.
930 static void
931 del_session(session_t *sp)
933 DBT key;
935 key.data = &sp->se_process;
936 key.size = sizeof sp->se_process;
938 if ((*session_db->del)(session_db, &key, 0))
939 emergency("delete %d: %s", sp->se_process, strerror(errno));
940 #ifdef SUPPORT_UTMPX
941 session_utmpx(sp, 0);
942 #endif
946 * Look up a login session by pid.
948 static session_t *
949 find_session(pid_t pid)
951 DBT key;
952 DBT data;
953 session_t *ret;
955 key.data = &pid;
956 key.size = sizeof pid;
957 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
958 return 0;
959 bcopy(data.data, (char *)&ret, sizeof(ret));
960 return ret;
964 * Construct an argument vector from a command line.
966 static char **
967 construct_argv(char *command)
969 int argc = 0;
970 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
971 * sizeof (char *));
973 if ((argv[argc++] = strk(command)) == NULL) {
974 free(argv);
975 return (NULL);
977 while ((argv[argc++] = strk(NULL)) != NULL)
978 continue;
979 return argv;
983 * Deallocate a session descriptor.
985 static void
986 free_session(session_t *sp)
988 free(sp->se_device);
989 if (sp->se_getty) {
990 free(sp->se_getty);
991 free(sp->se_getty_argv_space);
992 free(sp->se_getty_argv);
994 if (sp->se_window) {
995 free(sp->se_window);
996 free(sp->se_window_argv_space);
997 free(sp->se_window_argv);
999 if (sp->se_type)
1000 free(sp->se_type);
1001 free(sp);
1004 static
1005 void
1006 adjttyent(struct ttyent *typ)
1008 struct stat st;
1009 uint32_t rdev;
1010 char *devpath;
1011 size_t rdev_size = sizeof(rdev);
1013 if (typ->ty_name == NULL)
1014 return;
1017 * IFCONSOLE option forces tty off if not the console.
1019 if (typ->ty_status & TTY_IFCONSOLE) {
1020 asprintf(&devpath, "%s%s", _PATH_DEV, typ->ty_name);
1021 if (stat(devpath, &st) < 0 ||
1022 sysctlbyname("kern.console_rdev",
1023 &rdev, &rdev_size,
1024 NULL, 0) < 0) {
1025 /* device does not exist or no sysctl, disable */
1026 typ->ty_status &= ~TTY_ON;
1027 } else if (rdev != st.st_rdev) {
1028 typ->ty_status &= ~TTY_ON;
1030 free(devpath);
1035 * Allocate a new session descriptor.
1036 * Mark it SE_PRESENT.
1038 static session_t *
1039 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1041 session_t *sp;
1042 int fd;
1044 if (typ->ty_name == NULL || typ->ty_getty == NULL)
1045 return 0;
1047 if ((typ->ty_status & TTY_ON) == 0)
1048 return 0;
1050 sp = (session_t *) calloc(1, sizeof (session_t));
1052 asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1053 sp->se_index = session_index;
1054 sp->se_flags |= SE_PRESENT;
1057 * Attempt to open the device, if we get "device not configured"
1058 * then don't add the device to the session list.
1060 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1061 if (errno == ENXIO) {
1062 free_session(sp);
1063 return (0);
1065 } else
1066 close(fd);
1068 if (setupargv(sp, typ) == 0) {
1069 free_session(sp);
1070 return (0);
1073 sp->se_next = NULL;
1074 if (sprev == NULL) {
1075 sessions = sp;
1076 sp->se_prev = NULL;
1077 } else {
1078 sprev->se_next = sp;
1079 sp->se_prev = sprev;
1082 return sp;
1086 * Calculate getty and if useful window argv vectors.
1088 static int
1089 setupargv(session_t *sp, struct ttyent *typ)
1092 if (sp->se_getty) {
1093 free(sp->se_getty);
1094 free(sp->se_getty_argv_space);
1095 free(sp->se_getty_argv);
1097 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1098 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1099 sp->se_getty_argv_space = strdup(sp->se_getty);
1100 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1101 if (sp->se_getty_argv == NULL) {
1102 warning("can't parse getty for port %s", sp->se_device);
1103 free(sp->se_getty);
1104 free(sp->se_getty_argv_space);
1105 sp->se_getty = sp->se_getty_argv_space = NULL;
1106 return (0);
1108 if (sp->se_window) {
1109 free(sp->se_window);
1110 free(sp->se_window_argv_space);
1111 free(sp->se_window_argv);
1113 sp->se_window = sp->se_window_argv_space = NULL;
1114 sp->se_window_argv = NULL;
1115 if (typ->ty_window) {
1116 sp->se_window = strdup(typ->ty_window);
1117 sp->se_window_argv_space = strdup(sp->se_window);
1118 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1119 if (sp->se_window_argv == NULL) {
1120 warning("can't parse window for port %s",
1121 sp->se_device);
1122 free(sp->se_window_argv_space);
1123 free(sp->se_window);
1124 sp->se_window = sp->se_window_argv_space = NULL;
1125 return (0);
1128 if (sp->se_type)
1129 free(sp->se_type);
1130 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1131 return (1);
1135 * Walk the list of ttys and create sessions for each active line.
1137 static state_t
1138 f_read_ttys(void)
1140 int session_index = 0;
1141 session_t *sp, *snext;
1142 struct ttyent *typ;
1144 #ifdef SUPPORT_UTMPX
1145 if (sessions == NULL) {
1146 struct stat st;
1148 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1151 * If wtmpx is not empty, pick the down time from there
1153 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1154 struct timeval down_time;
1156 TIMESPEC_TO_TIMEVAL(&down_time,
1157 st.st_atime > st.st_mtime ?
1158 &st.st_atimespec : &st.st_mtimespec);
1159 make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1162 #endif
1164 * Destroy any previous session state.
1165 * There shouldn't be any, but just in case...
1167 for (sp = sessions; sp; sp = snext) {
1168 if (sp->se_process)
1169 clear_session_logs(sp);
1170 snext = sp->se_next;
1171 free_session(sp);
1173 sessions = NULL;
1174 if (start_session_db())
1175 return single_user;
1178 * Allocate a session entry for each active port.
1179 * Note that sp starts at 0.
1181 while ((typ = getttyent()) != NULL) {
1182 adjttyent(typ);
1183 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1184 sp = snext;
1187 endttyent();
1189 return multi_user;
1193 * Start a window system running.
1195 static void
1196 start_window_system(session_t *sp)
1198 pid_t pid;
1199 sigset_t mask;
1200 char term[64], *env[2];
1202 if ((pid = fork()) == -1) {
1203 emergency("can't fork for window system on port %s: %m",
1204 sp->se_device);
1205 /* hope that getty fails and we can try again */
1206 return;
1209 if (pid)
1210 return;
1212 sigemptyset(&mask);
1213 sigprocmask(SIG_SETMASK, &mask, NULL);
1215 if (setsid() < 0)
1216 emergency("setsid failed (window) %m");
1218 #ifdef LOGIN_CAP
1219 setprocresources(RESOURCE_WINDOW);
1220 #endif
1221 if (sp->se_type) {
1222 /* Don't use malloc after fork */
1223 strcpy(term, "TERM=");
1224 strncat(term, sp->se_type, sizeof(term) - 6);
1225 env[0] = term;
1226 env[1] = NULL;
1228 else
1229 env[0] = NULL;
1230 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1231 stall("can't exec window system '%s' for port %s: %m",
1232 sp->se_window_argv[0], sp->se_device);
1233 _exit(1);
1237 * Start a login session running.
1239 static pid_t
1240 start_getty(session_t *sp)
1242 pid_t pid;
1243 sigset_t mask;
1244 time_t current_time = time(NULL);
1245 int too_quick = 0;
1246 char term[64], *env[2];
1248 if (current_time >= sp->se_started.tv_sec &&
1249 current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1250 if (++sp->se_nspace > GETTY_NSPACE) {
1251 sp->se_nspace = 0;
1252 too_quick = 1;
1254 } else
1255 sp->se_nspace = 0;
1258 * fork(), not vfork() -- we can't afford to block.
1260 if ((pid = fork()) == -1) {
1261 emergency("can't fork for getty on port %s: %m", sp->se_device);
1262 return -1;
1265 if (pid)
1266 return pid;
1268 if (too_quick) {
1269 warning("getty repeating too quickly on port %s, sleeping %d secs",
1270 sp->se_device, GETTY_SLEEP);
1271 sleep((unsigned) GETTY_SLEEP);
1274 if (sp->se_window) {
1275 start_window_system(sp);
1276 sleep(WINDOW_WAIT);
1279 sigemptyset(&mask);
1280 sigprocmask(SIG_SETMASK, &mask, NULL);
1282 #ifdef LOGIN_CAP
1283 setprocresources(RESOURCE_GETTY);
1284 #endif
1285 if (sp->se_type) {
1286 /* Don't use malloc after fork */
1287 strcpy(term, "TERM=");
1288 strncat(term, sp->se_type, sizeof(term) - 6);
1289 env[0] = term;
1290 env[1] = NULL;
1292 else
1293 env[0] = NULL;
1294 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1295 stall("can't exec getty '%s' for port %s: %m",
1296 sp->se_getty_argv[0], sp->se_device);
1297 _exit(1);
1301 * Collect exit status for a child.
1302 * If an exiting login, start a new login running.
1304 static void
1305 collect_child(pid_t pid)
1307 session_t *sp, *sprev, *snext;
1309 if (! sessions)
1310 return;
1312 if (! (sp = find_session(pid)))
1313 return;
1315 clear_session_logs(sp);
1316 del_session(sp);
1317 sp->se_process = 0;
1319 if (sp->se_flags & SE_SHUTDOWN) {
1320 if ((sprev = sp->se_prev) != NULL)
1321 sprev->se_next = sp->se_next;
1322 else
1323 sessions = sp->se_next;
1324 if ((snext = sp->se_next) != NULL)
1325 snext->se_prev = sp->se_prev;
1326 free_session(sp);
1327 return;
1330 if ((pid = start_getty(sp)) == -1) {
1331 /* serious trouble */
1332 requested_transition = clean_ttys;
1333 return;
1336 sp->se_process = pid;
1337 gettimeofday(&sp->se_started, NULL);
1338 add_session(sp);
1342 * Catch a signal and request a state transition.
1344 static void
1345 transition_handler(int sig)
1348 switch (sig) {
1349 case SIGHUP:
1350 requested_transition = clean_ttys;
1351 break;
1352 case SIGUSR2:
1353 howto = RB_POWEROFF;
1354 /* FALLTHROUGH */
1355 case SIGUSR1:
1356 howto |= RB_HALT;
1357 /* FALLTHROUGH */
1358 case SIGINT:
1359 Reboot = TRUE;
1360 /* FALLTHROUGH */
1361 case SIGTERM:
1362 requested_transition = death;
1363 break;
1364 case SIGTSTP:
1365 requested_transition = catatonia;
1366 break;
1367 default:
1368 requested_transition = 0;
1369 break;
1374 * Take the system multiuser.
1376 static state_t
1377 f_multi_user(void)
1379 pid_t pid;
1380 session_t *sp;
1382 requested_transition = 0;
1385 * If the administrator has not set the security level to -1
1386 * to indicate that the kernel should not run multiuser in secure
1387 * mode, and the run script has not set a higher level of security
1388 * than level 1, then put the kernel into secure mode.
1390 if (getsecuritylevel() == 0)
1391 setsecuritylevel(1);
1393 for (sp = sessions; sp; sp = sp->se_next) {
1394 if (sp->se_process)
1395 continue;
1396 if ((pid = start_getty(sp)) == -1) {
1397 /* serious trouble */
1398 requested_transition = clean_ttys;
1399 break;
1401 sp->se_process = pid;
1402 gettimeofday(&sp->se_started, NULL);
1403 add_session(sp);
1406 while (!requested_transition)
1407 if ((pid = waitpid(-1, NULL, 0)) != -1)
1408 collect_child(pid);
1410 return requested_transition;
1414 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1416 static state_t
1417 f_clean_ttys(void)
1419 session_t *sp, *sprev;
1420 struct ttyent *typ;
1421 int session_index = 0;
1422 int devlen;
1423 char *old_getty, *old_window, *old_type;
1425 if (! sessions)
1426 return multi_user;
1429 * mark all sessions for death, (!SE_PRESENT)
1430 * as we find or create new ones they'll be marked as keepers,
1431 * we'll later nuke all the ones not found in /etc/ttys
1433 for (sp = sessions; sp != NULL; sp = sp->se_next)
1434 sp->se_flags &= ~SE_PRESENT;
1436 devlen = sizeof(_PATH_DEV) - 1;
1437 while ((typ = getttyent()) != NULL) {
1438 ++session_index;
1440 adjttyent(typ);
1441 for (sprev = NULL, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1442 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1443 break;
1445 if (sp) {
1446 /* we want this one to live */
1447 sp->se_flags |= SE_PRESENT;
1448 if (sp->se_index != session_index) {
1449 warning("port %s changed utmp index from %d to %d",
1450 sp->se_device, sp->se_index,
1451 session_index);
1452 sp->se_index = session_index;
1454 if ((typ->ty_status & TTY_ON) == 0 ||
1455 typ->ty_getty == 0) {
1456 sp->se_flags |= SE_SHUTDOWN;
1457 kill(sp->se_process, SIGHUP);
1458 continue;
1460 sp->se_flags &= ~SE_SHUTDOWN;
1461 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1462 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1463 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1464 if (setupargv(sp, typ) == 0) {
1465 warning("can't parse getty for port %s",
1466 sp->se_device);
1467 sp->se_flags |= SE_SHUTDOWN;
1468 kill(sp->se_process, SIGHUP);
1470 else if ( !old_getty
1471 || (!old_type && sp->se_type)
1472 || (old_type && !sp->se_type)
1473 || (!old_window && sp->se_window)
1474 || (old_window && !sp->se_window)
1475 || (strcmp(old_getty, sp->se_getty) != 0)
1476 || (old_window && strcmp(old_window, sp->se_window) != 0)
1477 || (old_type && strcmp(old_type, sp->se_type) != 0)
1479 /* Don't set SE_SHUTDOWN here */
1480 sp->se_nspace = 0;
1481 sp->se_started.tv_sec = sp->se_started.tv_usec = 0;
1482 kill(sp->se_process, SIGHUP);
1484 if (old_getty)
1485 free(old_getty);
1486 if (old_window)
1487 free(old_window);
1488 if (old_type)
1489 free(old_type);
1490 continue;
1493 new_session(sprev, session_index, typ);
1496 endttyent();
1499 * sweep through and kill all deleted sessions
1500 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1502 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1503 if ((sp->se_flags & SE_PRESENT) == 0) {
1504 sp->se_flags |= SE_SHUTDOWN;
1505 kill(sp->se_process, SIGHUP);
1509 return multi_user;
1513 * Block further logins.
1515 static state_t
1516 f_catatonia(void)
1518 session_t *sp;
1520 for (sp = sessions; sp; sp = sp->se_next)
1521 sp->se_flags |= SE_SHUTDOWN;
1523 return multi_user;
1527 * Note SIGALRM.
1529 static void
1530 alrm_handler(int sig __unused)
1532 clang = 1;
1536 * Bring the system down to single user.
1538 static state_t
1539 f_death(void)
1541 session_t *sp;
1542 int i;
1543 pid_t pid;
1544 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1546 #ifdef SUPPORT_UTMPX
1547 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1548 #endif
1549 logwtmp("~", "shutdown", "");
1551 for (sp = sessions; sp; sp = sp->se_next) {
1552 sp->se_flags |= SE_SHUTDOWN;
1553 kill(sp->se_process, SIGHUP);
1556 /* Try to run the rc.shutdown script within a period of time */
1557 runshutdown();
1559 for (i = 0; i < 2; ++i) {
1560 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1561 return single_user;
1563 clang = 0;
1564 alarm(DEATH_WATCH);
1566 if ((pid = waitpid(-1, NULL, 0)) != -1)
1567 collect_child(pid);
1568 while (clang == 0 && errno != ECHILD);
1570 if (errno == ECHILD)
1571 return single_user;
1574 warning("some processes would not die; ps axl advised");
1576 return single_user;
1580 * Run the system shutdown script.
1582 * Exit codes: XXX I should document more
1583 * -2 shutdown script terminated abnormally
1584 * -1 fatal error - can't run script
1585 * 0 good.
1586 * >0 some error (exit code)
1588 static int
1589 runshutdown(void)
1591 pid_t pid, wpid;
1592 int status;
1593 int shutdowntimeout;
1594 size_t len;
1595 const char *argv[4];
1596 struct sigaction sa;
1597 struct stat sb;
1600 * rc.shutdown is optional, so to prevent any unnecessary
1601 * complaints from the shell we simply don't run it if the
1602 * file does not exist. If the stat() here fails for other
1603 * reasons, we'll let the shell complain.
1605 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1606 return 0;
1608 if ((pid = fork()) == 0) {
1609 int fd;
1611 /* Assume that init already grab console as ctty before */
1613 sigemptyset(&sa.sa_mask);
1614 sa.sa_flags = 0;
1615 sa.sa_handler = SIG_IGN;
1616 sigaction(SIGTSTP, &sa, NULL);
1617 sigaction(SIGHUP, &sa, NULL);
1619 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1620 warning("can't open %s: %m", _PATH_CONSOLE);
1621 else {
1622 dup2(fd, 0);
1623 dup2(fd, 1);
1624 dup2(fd, 2);
1625 if (fd > 2)
1626 close(fd);
1630 * Run the shutdown script.
1632 argv[0] = "sh";
1633 argv[1] = _PATH_RUNDOWN;
1634 if (Reboot)
1635 argv[2] = "reboot";
1636 else
1637 argv[2] = "single";
1638 argv[3] = NULL;
1640 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1642 #ifdef LOGIN_CAP
1643 setprocresources(RESOURCE_RC);
1644 #endif
1645 execv(_PATH_BSHELL, __DECONST(char **, argv));
1646 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1647 _exit(1); /* force single user mode */
1650 if (pid == -1) {
1651 emergency("can't fork for %s on %s: %m",
1652 _PATH_BSHELL, _PATH_RUNDOWN);
1653 while (waitpid(-1, NULL, WNOHANG) > 0)
1654 continue;
1655 sleep(STALL_TIMEOUT);
1656 return -1;
1659 len = sizeof(shutdowntimeout);
1660 if (sysctlbyname("kern.init_shutdown_timeout",
1661 &shutdowntimeout,
1662 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1663 shutdowntimeout = DEATH_SCRIPT;
1664 alarm(shutdowntimeout);
1665 clang = 0;
1667 * Copied from single_user(). This is a bit paranoid.
1668 * Use the same ALRM handler.
1670 do {
1671 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1672 collect_child(wpid);
1673 if (clang == 1) {
1674 /* we were waiting for the sub-shell */
1675 kill(wpid, SIGTERM);
1676 warning("timeout expired for %s on %s: %m; going to single user mode",
1677 _PATH_BSHELL, _PATH_RUNDOWN);
1678 return -1;
1680 if (wpid == -1) {
1681 if (errno == EINTR)
1682 continue;
1683 warning("wait for %s on %s failed: %m; going to single user mode",
1684 _PATH_BSHELL, _PATH_RUNDOWN);
1685 return -1;
1687 if (wpid == pid && WIFSTOPPED(status)) {
1688 warning("init: %s on %s stopped, restarting\n",
1689 _PATH_BSHELL, _PATH_RUNDOWN);
1690 kill(pid, SIGCONT);
1691 wpid = -1;
1693 } while (wpid != pid && !clang);
1695 /* Turn off the alarm */
1696 alarm(0);
1698 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1699 requested_transition == catatonia) {
1701 * /etc/rc.shutdown executed /sbin/reboot;
1702 * wait for the end quietly
1704 sigset_t s;
1706 sigfillset(&s);
1707 for (;;)
1708 sigsuspend(&s);
1711 if (!WIFEXITED(status)) {
1712 warning("%s on %s terminated abnormally, going to single user mode",
1713 _PATH_BSHELL, _PATH_RUNDOWN);
1714 return -2;
1717 if ((status = WEXITSTATUS(status)) != 0)
1718 warning("%s returned status %d", _PATH_RUNDOWN, status);
1720 return status;
1723 static char *
1724 strk(char *p)
1726 static char *t;
1727 char *q;
1728 int c;
1730 if (p)
1731 t = p;
1732 if (!t)
1733 return 0;
1735 c = *t;
1736 while (c == ' ' || c == '\t' )
1737 c = *++t;
1738 if (!c) {
1739 t = NULL;
1740 return 0;
1742 q = t;
1743 if (c == '\'') {
1744 c = *++t;
1745 q = t;
1746 while (c && c != '\'')
1747 c = *++t;
1748 if (!c) /* unterminated string */
1749 q = t = NULL;
1750 else
1751 *t++ = 0;
1752 } else {
1753 while (c && c != ' ' && c != '\t' )
1754 c = *++t;
1755 *t++ = 0;
1756 if (!c)
1757 t = NULL;
1759 return q;
1762 #ifdef LOGIN_CAP
1763 static void
1764 setprocresources(const char *cname)
1766 login_cap_t *lc;
1767 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1768 setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1769 login_close(lc);
1772 #endif
1774 #ifdef SUPPORT_UTMPX
1775 static void
1776 session_utmpx(const session_t *sp, int add)
1778 const char *name = sp->se_getty ? sp->se_getty :
1779 (sp->se_window ? sp->se_window : "");
1780 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1782 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1783 sp->se_process, &sp->se_started, sp->se_index);
1786 static void
1787 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1788 const struct timeval *tv, int session)
1790 struct utmpx ut;
1791 const char *eline;
1793 (void)memset(&ut, 0, sizeof(ut));
1794 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1795 ut.ut_type = type;
1796 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1797 ut.ut_pid = pid;
1798 if (tv)
1799 ut.ut_tv = *tv;
1800 else
1801 (void)gettimeofday(&ut.ut_tv, NULL);
1802 ut.ut_session = session;
1804 eline = line + strlen(line);
1805 if ((size_t)(eline - line) >= sizeof(ut.ut_id))
1806 line = eline - sizeof(ut.ut_id);
1807 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1809 if (pututxline(&ut) == NULL)
1810 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1811 endutxent();
1814 static char
1815 get_runlevel(const state_t s)
1817 if (s == single_user)
1818 return SINGLE_USER;
1819 if (s == runcom)
1820 return RUNCOM;
1821 if (s == read_ttys)
1822 return READ_TTYS;
1823 if (s == multi_user)
1824 return MULTI_USER;
1825 if (s == clean_ttys)
1826 return CLEAN_TTYS;
1827 if (s == catatonia)
1828 return CATATONIA;
1829 return DEATH;
1832 static void
1833 utmpx_set_runlevel(char old, char new)
1835 struct utmpx ut;
1838 * Don't record any transitions until we did the first transition
1839 * to read ttys, which is when we are guaranteed to have a read-write
1840 * /var. Perhaps use a different variable for this?
1842 if (sessions == NULL)
1843 return;
1845 (void)memset(&ut, 0, sizeof(ut));
1846 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1847 ut.ut_type = RUN_LVL;
1848 (void)gettimeofday(&ut.ut_tv, NULL);
1849 ut.ut_exit.e_exit = old;
1850 ut.ut_exit.e_termination = new;
1851 if (pututxline(&ut) == NULL)
1852 warning("can't add utmpx record for `runlevel': %m");
1853 endutxent();
1855 #endif