+static void setup_utmp(char *ttyname)
+{
+#ifndef OMIT_UTMP
+#ifdef HAVE_LASTLOG
+ struct lastlog lastlog_entry;
+ FILE *lastlog;
+#endif
+ struct passwd *pw;
+ char *location;
+ FILE *wtmp;
+
+ if (!cfg.stamp_utmp)
+ return;
+
+ pw = getpwuid(getuid());
+ location = get_x_display();
+ memset(&utmp_entry, 0, sizeof(utmp_entry));
+ utmp_entry.ut_type = USER_PROCESS;
+ utmp_entry.ut_pid = getpid();
+ strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
+ strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
+ strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
+ strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
+ time(&utmp_entry.ut_time);
+
+#if defined HAVE_PUTUTLINE
+ utmpname(UTMP_FILE);
+ setutent();
+ pututline(&utmp_entry);
+ endutent();
+#endif
+
+ if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
+ fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
+ fclose(wtmp);
+ }
+
+#ifdef HAVE_LASTLOG
+ memset(&lastlog_entry, 0, sizeof(lastlog_entry));
+ strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
+ strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
+ time(&lastlog_entry.ll_time);
+ if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
+ fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
+ fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
+ fclose(lastlog);
+ }
+#endif
+
+ pty_stamped_utmp = 1;
+
+#endif
+}
+
+static void cleanup_utmp(void)
+{
+#ifndef OMIT_UTMP
+ FILE *wtmp;
+
+ if (!cfg.stamp_utmp || !pty_stamped_utmp)
+ return;
+
+ utmp_entry.ut_type = DEAD_PROCESS;
+ memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
+ time(&utmp_entry.ut_time);
+
+ if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
+ fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
+ fclose(wtmp);
+ }
+
+ memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
+ utmp_entry.ut_time = 0;
+
+#if defined HAVE_PUTUTLINE
+ utmpname(UTMP_FILE);
+ setutent();
+ pututline(&utmp_entry);
+ endutent();
+#endif
+
+ pty_stamped_utmp = 0; /* ensure we never double-cleanup */
+#endif
+}
+
+static void sigchld_handler(int signum)
+{
+ pid_t pid;
+ int status;
+ pid = waitpid(-1, &status, WNOHANG);
+ if (pid == pty_child_pid && (WIFEXITED(status) || WIFSIGNALED(status)))
+ pty_child_dead = TRUE;
+}
+
+static void fatal_sig_handler(int signum)
+{
+ signal(signum, SIG_DFL);
+ cleanup_utmp();
+ setuid(getuid());
+ raise(signum);
+}
+