2 * Pseudo-tty backend for pterm.
4 * Unlike the other backends, data for this one is not neatly
5 * encapsulated into a data structure, because it wouldn't make
6 * sense to do so - the utmp stuff has to be done before a backend
7 * is initialised, and starting a second pterm from the same
8 * process would therefore be infeasible because privileges would
9 * already have been dropped. Hence, I haven't bothered to keep the
10 * data dynamically allocated: instead, the backend handle is just
11 * a null pointer and ignored everywhere.
15 #define _XOPEN_SOURCE_EXTENDED
29 #include <sys/types.h>
32 #include <sys/ioctl.h>
45 #define UTMP_FILE "/var/run/utmp"
48 #define WTMP_FILE "/var/log/wtmp"
52 #define LASTLOG_FILE _PATH_LASTLOG
54 #define LASTLOG_FILE "/var/log/lastlog"
59 * Set up a default for vaguely sane systems. The idea is that if
60 * OMIT_UTMP is not defined, then at least one of the symbols which
61 * enable particular forms of utmp processing should be, if only so
62 * that a link error can warn you that you should have defined
63 * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
64 * the only such symbol.
67 #if !defined HAVE_PUTUTLINE
68 #define HAVE_PUTUTLINE
72 static Config pty_cfg;
73 static int pty_master_fd;
74 static void *pty_frontend;
75 static char pty_name[FILENAME_MAX];
76 static int pty_signal_pipe[2];
77 static int pty_child_pid;
78 static int pty_term_width, pty_term_height;
79 static int pty_child_dead, pty_finished;
80 static int pty_exit_code;
82 int use_pty_argv = TRUE;
84 static void pty_close(void);
87 static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
88 static int pty_stamped_utmp = 0;
89 static struct utmp utmp_entry;
91 static void setup_utmp(char *ttyname, char *location)
94 struct lastlog lastlog_entry;
101 pw = getpwuid(getuid());
102 memset(&utmp_entry, 0, sizeof(utmp_entry));
103 utmp_entry.ut_type = USER_PROCESS;
104 utmp_entry.ut_pid = getpid();
105 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
106 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
107 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
108 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
109 /* Apparently there are some architectures where (struct utmp).ut_time
110 * is not essentially time_t (e.g. Linux amd64). Hence the temporary. */
112 utmp_entry.ut_time = uttime; /* may truncate */
114 #if defined HAVE_PUTUTLINE
117 pututline(&utmp_entry);
121 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
122 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
127 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
128 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
129 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
130 time(&lastlog_entry.ll_time);
131 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
132 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
133 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
138 pty_stamped_utmp = 1;
142 static void cleanup_utmp(void)
147 if (!pty_stamped_utmp)
150 utmp_entry.ut_type = DEAD_PROCESS;
151 memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
153 utmp_entry.ut_time = uttime;
155 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
156 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
160 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
161 utmp_entry.ut_time = 0;
163 #if defined HAVE_PUTUTLINE
166 pututline(&utmp_entry);
170 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
174 static void sigchld_handler(int signum)
176 write(pty_signal_pipe[1], "x", 1);
180 static void fatal_sig_handler(int signum)
182 putty_signal(signum, SIG_DFL);
189 static void pty_open_master(void)
192 const char chars1[] = "pqrstuvwxyz";
193 const char chars2[] = "0123456789abcdef";
195 char master_name[20];
198 for (p1 = chars1; *p1; p1++)
199 for (p2 = chars2; *p2; p2++) {
200 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
201 pty_master_fd = open(master_name, O_RDWR);
202 if (pty_master_fd >= 0) {
203 if (geteuid() == 0 ||
204 access(master_name, R_OK | W_OK) == 0)
206 close(pty_master_fd);
210 /* If we get here, we couldn't get a tty at all. */
211 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
215 strcpy(pty_name, master_name);
216 pty_name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
218 /* We need to chown/chmod the /dev/ttyXX device. */
219 gp = getgrnam("tty");
220 chown(pty_name, getuid(), gp ? gp->gr_gid : -1);
221 chmod(pty_name, 0600);
223 pty_master_fd = open("/dev/ptmx", O_RDWR);
225 if (pty_master_fd < 0) {
226 perror("/dev/ptmx: open");
230 if (grantpt(pty_master_fd) < 0) {
235 if (unlockpt(pty_master_fd) < 0) {
240 pty_name[FILENAME_MAX-1] = '\0';
241 strncpy(pty_name, ptsname(pty_master_fd), FILENAME_MAX-1);
246 * Pre-initialisation. This is here to get around the fact that GTK
247 * doesn't like being run in setuid/setgid programs (probably
248 * sensibly). So before we initialise GTK - and therefore before we
249 * even process the command line - we check to see if we're running
250 * set[ug]id. If so, we open our pty master _now_, chown it as
251 * necessary, and drop privileges. We can always close it again
252 * later. If we're potentially going to be doing utmp as well, we
253 * also fork off a utmp helper process and communicate with it by
254 * means of a pipe; the utmp helper will keep privileges in order
255 * to clean up utmp when we exit (i.e. when its end of our pipe
258 void pty_pre_init(void)
265 /* set the child signal handler straight away; it needs to be set
266 * before we ever fork. */
267 putty_signal(SIGCHLD, sigchld_handler);
270 if (geteuid() != getuid() || getegid() != getgid()) {
276 * Fork off the utmp helper.
278 if (pipe(pipefd) < 0) {
279 perror("pterm: pipe");
284 perror("pterm: fork");
286 } else if (pid == 0) {
287 char display[128], buffer[128];
292 * Now sit here until we receive a display name from the
293 * other end of the pipe, and then stamp utmp. Unstamp utmp
294 * again, and exit, when the pipe closes.
300 ret = read(pipefd[0], buffer, lenof(buffer));
304 } else if (!pty_stamped_utmp) {
305 if (dlen < lenof(display))
306 memcpy(display+dlen, buffer,
307 min(ret, lenof(display)-dlen));
308 if (buffer[ret-1] == '\0') {
310 * Now we have a display name. NUL-terminate
311 * it, and stamp utmp.
313 display[lenof(display)-1] = '\0';
315 * Trap as many fatal signals as we can in the
316 * hope of having the best possible chance to
317 * clean up utmp before termination. We are
318 * unfortunately unprotected against SIGKILL,
321 putty_signal(SIGHUP, fatal_sig_handler);
322 putty_signal(SIGINT, fatal_sig_handler);
323 putty_signal(SIGQUIT, fatal_sig_handler);
324 putty_signal(SIGILL, fatal_sig_handler);
325 putty_signal(SIGABRT, fatal_sig_handler);
326 putty_signal(SIGFPE, fatal_sig_handler);
327 putty_signal(SIGPIPE, fatal_sig_handler);
328 putty_signal(SIGALRM, fatal_sig_handler);
329 putty_signal(SIGTERM, fatal_sig_handler);
330 putty_signal(SIGSEGV, fatal_sig_handler);
331 putty_signal(SIGUSR1, fatal_sig_handler);
332 putty_signal(SIGUSR2, fatal_sig_handler);
334 putty_signal(SIGBUS, fatal_sig_handler);
337 putty_signal(SIGPOLL, fatal_sig_handler);
340 putty_signal(SIGPROF, fatal_sig_handler);
343 putty_signal(SIGSYS, fatal_sig_handler);
346 putty_signal(SIGTRAP, fatal_sig_handler);
349 putty_signal(SIGVTALRM, fatal_sig_handler);
352 putty_signal(SIGXCPU, fatal_sig_handler);
355 putty_signal(SIGXFSZ, fatal_sig_handler);
358 putty_signal(SIGIO, fatal_sig_handler);
360 setup_utmp(pty_name, display);
366 pty_utmp_helper_pid = pid;
367 pty_utmp_helper_pipe = pipefd[1];
373 #ifndef HAVE_NO_SETRESUID
374 int gid = getgid(), uid = getuid();
375 int setresgid(gid_t, gid_t, gid_t);
376 int setresuid(uid_t, uid_t, uid_t);
377 setresgid(gid, gid, gid);
378 setresuid(uid, uid, uid);
386 int pty_select_result(int fd, int event)
390 int finished = FALSE;
392 if (fd == pty_master_fd && event == 1) {
394 ret = read(pty_master_fd, buf, sizeof(buf));
397 * Clean termination condition is that either ret == 0, or ret
398 * < 0 and errno == EIO. Not sure why the latter, but it seems
401 if (ret == 0 || (ret < 0 && errno == EIO)) {
403 * We assume a clean exit if the pty has closed but the
404 * actual child process hasn't. The only way I can
405 * imagine this happening is if it detaches itself from
406 * the pty and goes daemonic - in which case the
407 * expected usage model would precisely _not_ be for
408 * the pterm window to hang around!
413 } else if (ret < 0) {
414 perror("read pty master");
416 } else if (ret > 0) {
417 from_backend(pty_frontend, 0, buf, ret);
419 } else if (fd == pty_signal_pipe[0]) {
424 read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
427 pid = waitpid(-1, &status, WNOHANG);
428 if (pid == pty_child_pid &&
429 (WIFEXITED(status) || WIFSIGNALED(status))) {
431 * The primary child process died. We could keep
432 * the terminal open for remaining subprocesses to
433 * output to, but conventional wisdom seems to feel
434 * that that's the Wrong Thing for an xterm-alike,
435 * so we bail out now (though we don't necessarily
436 * _close_ the window, depending on the state of
437 * Close On Exit). This would be easy enough to
438 * change or make configurable if necessary.
440 pty_exit_code = status;
441 pty_child_dead = TRUE;
447 if (finished && !pty_finished) {
448 uxsel_del(pty_master_fd);
455 * This is a slight layering-violation sort of hack: only
456 * if we're not closing on exit (COE is set to Never, or to
457 * Only On Clean and it wasn't a clean exit) do we output a
458 * `terminated' message.
460 if (pty_cfg.close_on_exit == FORCE_OFF ||
461 (pty_cfg.close_on_exit == AUTO && pty_exit_code != 0)) {
463 if (WIFEXITED(pty_exit_code))
464 sprintf(message, "\r\n[pterm: process terminated with exit"
465 " code %d]\r\n", WEXITSTATUS(pty_exit_code));
466 else if (WIFSIGNALED(pty_exit_code))
467 #ifdef HAVE_NO_STRSIGNAL
468 sprintf(message, "\r\n[pterm: process terminated on signal"
469 " %d]\r\n", WTERMSIG(pty_exit_code));
471 sprintf(message, "\r\n[pterm: process terminated on signal"
472 " %d (%.400s)]\r\n", WTERMSIG(pty_exit_code),
473 strsignal(WTERMSIG(pty_exit_code)));
475 from_backend(pty_frontend, 0, message, strlen(message));
478 notify_remote_exit(pty_frontend);
483 static void pty_uxsel_setup(void)
485 uxsel_set(pty_master_fd, 1, pty_select_result);
486 uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
490 * Called to set up the pty.
492 * Returns an error message, or NULL on success.
494 * Also places the canonical host name into `realhost'. It must be
495 * freed by the caller.
497 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
498 char *host, int port, char **realhost, int nodelay,
505 pty_frontend = frontend;
506 *backend_handle = NULL; /* we can't sensibly use this, sadly */
508 pty_cfg = *cfg; /* structure copy */
509 pty_term_width = cfg->width;
510 pty_term_height = cfg->height;
512 if (pty_master_fd < 0)
516 * Set the backspace character to be whichever of ^H and ^? is
517 * specified by bksp_is_delete.
520 struct termios attrs;
521 tcgetattr(pty_master_fd, &attrs);
522 attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
523 tcsetattr(pty_master_fd, TCSANOW, &attrs);
528 * Stamp utmp (that is, tell the utmp helper process to do so),
531 if (!cfg->stamp_utmp) {
532 close(pty_utmp_helper_pipe); /* just let the child process die */
533 pty_utmp_helper_pipe = -1;
535 char *location = get_x_display(pty_frontend);
536 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
538 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
540 perror("pterm: writing to utmp helper process");
541 close(pty_utmp_helper_pipe); /* arrgh, just give up */
542 pty_utmp_helper_pipe = -1;
550 windowid = get_windowid(pty_frontend);
553 * Fork and execute the command.
567 slavefd = open(pty_name, O_RDWR);
569 perror("slave pty: open");
573 close(pty_master_fd);
574 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
579 ioctl(slavefd, TIOCSCTTY, 1);
581 tcsetpgrp(slavefd, pgrp);
583 close(open(pty_name, O_WRONLY, 0));
585 /* Close everything _else_, for tidiness. */
586 for (i = 3; i < 1024; i++)
589 char term_env_var[10 + sizeof(cfg->termtype)];
590 sprintf(term_env_var, "TERM=%s", cfg->termtype);
591 putenv(term_env_var);
594 char windowid_env_var[40];
595 sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
596 putenv(windowid_env_var);
599 char *e = cfg->environmt;
600 char *var, *varend, *val, *varval;
603 while (*e && *e != '\t') e++;
610 varval = dupprintf("%.*s=%s", varend-var, var, val);
613 * We must not free varval, since putenv links it
614 * into the environment _in place_. Weird, but
615 * there we go. Memory usage will be rationalised
616 * as soon as we exec anyway.
622 * SIGINT and SIGQUIT may have been set to ignored by our
623 * parent, particularly by things like sh -c 'pterm &' and
624 * some window managers. SIGCHLD, meanwhile, has been
625 * tinkered with by the watchdog process. Reverse all this
626 * for our child process.
628 putty_signal(SIGINT, SIG_DFL);
629 putty_signal(SIGQUIT, SIG_DFL);
633 sigaddset(&set, SIGCHLD);
634 sigprocmask(SIG_UNBLOCK, &set, NULL);
637 execvp(pty_argv[0], pty_argv);
639 char *shell = getenv("SHELL");
641 if (cfg->login_shell) {
642 char *p = strrchr(shell, '/');
643 shellname = snewn(2+strlen(shell), char);
645 sprintf(shellname, "-%s", p);
648 execl(getenv("SHELL"), shellname, NULL);
652 * If we're here, exec has gone badly foom.
658 pty_child_dead = FALSE;
659 pty_finished = FALSE;
662 if (pipe(pty_signal_pipe) < 0) {
671 static void pty_reconfig(void *handle, Config *cfg)
674 * We don't have much need to reconfigure this backend, but
675 * unfortunately we do need to pick up the setting of Close On
676 * Exit so we know whether to give a `terminated' message.
678 pty_cfg = *cfg; /* structure copy */
682 * Stub routine (never called in pterm).
684 static void pty_free(void *handle)
689 * Called to send data down the pty.
691 static int pty_send(void *handle, char *buf, int len)
693 if (pty_master_fd < 0)
694 return 0; /* ignore all writes if fd closed */
697 int ret = write(pty_master_fd, buf, len);
699 perror("write pty master");
708 static void pty_close(void)
710 if (pty_master_fd >= 0) {
711 close(pty_master_fd);
715 if (pty_utmp_helper_pipe >= 0) {
716 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
717 pty_utmp_helper_pipe = -1;
723 * Called to query the current socket sendability status.
725 static int pty_sendbuffer(void *handle)
731 * Called to set the size of the window
733 static void pty_size(void *handle, int width, int height)
737 pty_term_width = width;
738 pty_term_height = height;
740 size.ws_row = (unsigned short)pty_term_height;
741 size.ws_col = (unsigned short)pty_term_width;
742 size.ws_xpixel = (unsigned short) pty_term_width *
743 font_dimension(pty_frontend, 0);
744 size.ws_ypixel = (unsigned short) pty_term_height *
745 font_dimension(pty_frontend, 1);
746 ioctl(pty_master_fd, TIOCSWINSZ, (void *)&size);
751 * Send special codes.
753 static void pty_special(void *handle, Telnet_Special code)
760 * Return a list of the special codes that make sense in this
763 static const struct telnet_special *pty_get_specials(void *handle)
766 * Hmm. When I get round to having this actually usable, it
767 * might be quite nice to have the ability to deliver a few
768 * well chosen signals to the child process - SIGINT, SIGTERM,
774 static Socket pty_socket(void *handle)
776 return NULL; /* shouldn't ever be needed */
779 static int pty_sendok(void *handle)
784 static void pty_unthrottle(void *handle, int backlog)
789 static int pty_ldisc(void *handle, int option)
791 return 0; /* neither editing nor echoing */
794 static void pty_provide_ldisc(void *handle, void *ldisc)
796 /* This is a stub. */
799 static void pty_provide_logctx(void *handle, void *logctx)
801 /* This is a stub. */
804 static int pty_exitcode(void *handle)
807 return -1; /* not dead yet */
809 return pty_exit_code;
812 Backend pty_backend = {