2 * Pseudo-tty backend for pterm.
5 #define _XOPEN_SOURCE 600
6 #define _XOPEN_SOURCE_EXTENDED
20 #include <sys/types.h>
23 #include <sys/ioctl.h>
37 #define UTMP_FILE "/var/run/utmp"
40 #define WTMP_FILE "/var/log/wtmp"
44 #define LASTLOG_FILE _PATH_LASTLOG
46 #define LASTLOG_FILE "/var/log/lastlog"
51 * Set up a default for vaguely sane systems. The idea is that if
52 * OMIT_UTMP is not defined, then at least one of the symbols which
53 * enable particular forms of utmp processing should be, if only so
54 * that a link error can warn you that you should have defined
55 * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
56 * the only such symbol.
59 #if !defined HAVE_PUTUTLINE
60 #define HAVE_PUTUTLINE
64 typedef struct pty_tag *Pty;
67 * The pty_signal_pipe, along with the SIGCHLD handler, must be
68 * process-global rather than session-specific.
70 static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
74 int master_fd, slave_fd;
76 char name[FILENAME_MAX];
78 int term_width, term_height;
79 int child_dead, finished;
84 * We store our pty backends in a tree sorted by master fd, so that
85 * when we get an uxsel notification we know which backend instance
86 * is the owner of the pty that caused it.
88 static int pty_compare_by_fd(void *av, void *bv)
93 if (a->master_fd < b->master_fd)
95 else if (a->master_fd > b->master_fd)
100 static int pty_find_by_fd(void *av, void *bv)
105 if (a < b->master_fd)
107 else if (a > b->master_fd)
112 static tree234 *ptys_by_fd = NULL;
115 * We also have a tree sorted by child pid, so that when we wait()
116 * in response to the signal we know which backend instance is the
117 * owner of the process that caused the signal.
119 static int pty_compare_by_pid(void *av, void *bv)
124 if (a->child_pid < b->child_pid)
126 else if (a->child_pid > b->child_pid)
131 static int pty_find_by_pid(void *av, void *bv)
136 if (a < b->child_pid)
138 else if (a > b->child_pid)
143 static tree234 *ptys_by_pid = NULL;
146 * If we are using pty_pre_init(), it will need to have already
147 * allocated a pty structure, which we must then return from
148 * pty_init() rather than allocating a new one. Here we store that
149 * structure between allocation and use.
151 * Note that although most of this module is entirely capable of
152 * handling multiple ptys in a single process, pty_pre_init() is
153 * fundamentally _dependent_ on there being at most one pty per
154 * process, so the normal static-data constraints don't apply.
156 * Likewise, since utmp is only used via pty_pre_init, it too must
157 * be single-instance, so we can declare utmp-related variables
160 static Pty single_pty = NULL;
163 static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
164 static int pty_stamped_utmp;
165 static struct utmp utmp_entry;
169 * pty_argv is a grievous hack to allow a proper argv to be passed
170 * through from the Unix command line. Again, it doesn't really
171 * make sense outside a one-pty-per-process setup.
175 static void pty_close(Pty pty);
178 static void setup_utmp(char *ttyname, char *location)
181 struct lastlog lastlog_entry;
188 pw = getpwuid(getuid());
189 memset(&utmp_entry, 0, sizeof(utmp_entry));
190 utmp_entry.ut_type = USER_PROCESS;
191 utmp_entry.ut_pid = getpid();
192 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
193 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
194 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
195 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
196 /* Apparently there are some architectures where (struct utmp).ut_time
197 * is not essentially time_t (e.g. Linux amd64). Hence the temporary. */
199 utmp_entry.ut_time = uttime; /* may truncate */
201 #if defined HAVE_PUTUTLINE
204 pututline(&utmp_entry);
208 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
209 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
214 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
215 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
216 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
217 time(&lastlog_entry.ll_time);
218 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
219 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
220 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
225 pty_stamped_utmp = 1;
229 static void cleanup_utmp(void)
234 if (!pty_stamped_utmp)
237 utmp_entry.ut_type = DEAD_PROCESS;
238 memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
240 utmp_entry.ut_time = uttime;
242 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
243 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
247 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
248 utmp_entry.ut_time = 0;
250 #if defined HAVE_PUTUTLINE
253 pututline(&utmp_entry);
257 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
261 static void sigchld_handler(int signum)
263 write(pty_signal_pipe[1], "x", 1);
267 static void fatal_sig_handler(int signum)
269 putty_signal(signum, SIG_DFL);
276 static int pty_open_slave(Pty pty)
278 if (pty->slave_fd < 0)
279 pty->slave_fd = open(pty->name, O_RDWR);
281 return pty->slave_fd;
284 static void pty_open_master(Pty pty)
287 const char chars1[] = "pqrstuvwxyz";
288 const char chars2[] = "0123456789abcdef";
290 char master_name[20];
293 for (p1 = chars1; *p1; p1++)
294 for (p2 = chars2; *p2; p2++) {
295 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
296 pty->master_fd = open(master_name, O_RDWR);
297 if (pty->master_fd >= 0) {
298 if (geteuid() == 0 ||
299 access(master_name, R_OK | W_OK) == 0) {
301 * We must also check at this point that we are
302 * able to open the slave side of the pty. We
303 * wouldn't want to allocate the wrong master,
304 * get all the way down to forking, and _then_
305 * find we're unable to open the slave.
307 strcpy(pty->name, master_name);
308 pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
310 if (pty_open_slave(pty) >= 0 &&
311 access(pty->name, R_OK | W_OK) == 0)
313 if (pty->slave_fd > 0)
314 close(pty->slave_fd);
317 close(pty->master_fd);
321 /* If we get here, we couldn't get a tty at all. */
322 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
327 /* We need to chown/chmod the /dev/ttyXX device. */
328 gp = getgrnam("tty");
329 chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
330 chmod(pty->name, 0600);
332 pty->master_fd = open("/dev/ptmx", O_RDWR);
334 if (pty->master_fd < 0) {
335 perror("/dev/ptmx: open");
339 if (grantpt(pty->master_fd) < 0) {
344 if (unlockpt(pty->master_fd) < 0) {
349 pty->name[FILENAME_MAX-1] = '\0';
350 strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
354 ptys_by_fd = newtree234(pty_compare_by_fd);
355 add234(ptys_by_fd, pty);
359 * Pre-initialisation. This is here to get around the fact that GTK
360 * doesn't like being run in setuid/setgid programs (probably
361 * sensibly). So before we initialise GTK - and therefore before we
362 * even process the command line - we check to see if we're running
363 * set[ug]id. If so, we open our pty master _now_, chown it as
364 * necessary, and drop privileges. We can always close it again
365 * later. If we're potentially going to be doing utmp as well, we
366 * also fork off a utmp helper process and communicate with it by
367 * means of a pipe; the utmp helper will keep privileges in order
368 * to clean up utmp when we exit (i.e. when its end of our pipe
371 void pty_pre_init(void)
380 pty = single_pty = snew(struct pty_tag);
382 /* set the child signal handler straight away; it needs to be set
383 * before we ever fork. */
384 putty_signal(SIGCHLD, sigchld_handler);
385 pty->master_fd = pty->slave_fd = -1;
387 pty_stamped_utmp = FALSE;
390 if (geteuid() != getuid() || getegid() != getgid()) {
391 pty_open_master(pty);
396 * Fork off the utmp helper.
398 if (pipe(pipefd) < 0) {
399 perror("pterm: pipe");
404 perror("pterm: fork");
406 } else if (pid == 0) {
407 char display[128], buffer[128];
412 * Now sit here until we receive a display name from the
413 * other end of the pipe, and then stamp utmp. Unstamp utmp
414 * again, and exit, when the pipe closes.
420 ret = read(pipefd[0], buffer, lenof(buffer));
424 } else if (!pty_stamped_utmp) {
425 if (dlen < lenof(display))
426 memcpy(display+dlen, buffer,
427 min(ret, lenof(display)-dlen));
428 if (buffer[ret-1] == '\0') {
430 * Now we have a display name. NUL-terminate
431 * it, and stamp utmp.
433 display[lenof(display)-1] = '\0';
435 * Trap as many fatal signals as we can in the
436 * hope of having the best possible chance to
437 * clean up utmp before termination. We are
438 * unfortunately unprotected against SIGKILL,
441 putty_signal(SIGHUP, fatal_sig_handler);
442 putty_signal(SIGINT, fatal_sig_handler);
443 putty_signal(SIGQUIT, fatal_sig_handler);
444 putty_signal(SIGILL, fatal_sig_handler);
445 putty_signal(SIGABRT, fatal_sig_handler);
446 putty_signal(SIGFPE, fatal_sig_handler);
447 putty_signal(SIGPIPE, fatal_sig_handler);
448 putty_signal(SIGALRM, fatal_sig_handler);
449 putty_signal(SIGTERM, fatal_sig_handler);
450 putty_signal(SIGSEGV, fatal_sig_handler);
451 putty_signal(SIGUSR1, fatal_sig_handler);
452 putty_signal(SIGUSR2, fatal_sig_handler);
454 putty_signal(SIGBUS, fatal_sig_handler);
457 putty_signal(SIGPOLL, fatal_sig_handler);
460 putty_signal(SIGPROF, fatal_sig_handler);
463 putty_signal(SIGSYS, fatal_sig_handler);
466 putty_signal(SIGTRAP, fatal_sig_handler);
469 putty_signal(SIGVTALRM, fatal_sig_handler);
472 putty_signal(SIGXCPU, fatal_sig_handler);
475 putty_signal(SIGXFSZ, fatal_sig_handler);
478 putty_signal(SIGIO, fatal_sig_handler);
480 setup_utmp(pty->name, display);
486 pty_utmp_helper_pid = pid;
487 pty_utmp_helper_pipe = pipefd[1];
493 #ifndef HAVE_NO_SETRESUID
494 int gid = getgid(), uid = getuid();
495 int setresgid(gid_t, gid_t, gid_t);
496 int setresuid(uid_t, uid_t, uid_t);
497 setresgid(gid, gid, gid);
498 setresuid(uid, uid, uid);
506 int pty_real_select_result(Pty pty, int event, int status)
510 int finished = FALSE;
514 * We've been called because our child process did
515 * something. `status' tells us what.
517 if ((WIFEXITED(status) || WIFSIGNALED(status))) {
519 * The primary child process died. We could keep
520 * the terminal open for remaining subprocesses to
521 * output to, but conventional wisdom seems to feel
522 * that that's the Wrong Thing for an xterm-alike,
523 * so we bail out now (though we don't necessarily
524 * _close_ the window, depending on the state of
525 * Close On Exit). This would be easy enough to
526 * change or make configurable if necessary.
528 pty->exit_code = status;
529 pty->child_dead = TRUE;
530 del234(ptys_by_pid, pty);
536 ret = read(pty->master_fd, buf, sizeof(buf));
539 * Clean termination condition is that either ret == 0, or ret
540 * < 0 and errno == EIO. Not sure why the latter, but it seems
543 if (ret == 0 || (ret < 0 && errno == EIO)) {
545 * We assume a clean exit if the pty has closed but the
546 * actual child process hasn't. The only way I can
547 * imagine this happening is if it detaches itself from
548 * the pty and goes daemonic - in which case the
549 * expected usage model would precisely _not_ be for
550 * the pterm window to hang around!
553 if (!pty->child_dead)
555 } else if (ret < 0) {
556 perror("read pty master");
558 } else if (ret > 0) {
559 from_backend(pty->frontend, 0, buf, ret);
564 if (finished && !pty->finished) {
565 uxsel_del(pty->master_fd);
569 pty->finished = TRUE;
572 * This is a slight layering-violation sort of hack: only
573 * if we're not closing on exit (COE is set to Never, or to
574 * Only On Clean and it wasn't a clean exit) do we output a
575 * `terminated' message.
577 if (pty->cfg.close_on_exit == FORCE_OFF ||
578 (pty->cfg.close_on_exit == AUTO && pty->exit_code != 0)) {
580 if (WIFEXITED(pty->exit_code))
581 sprintf(message, "\r\n[pterm: process terminated with exit"
582 " code %d]\r\n", WEXITSTATUS(pty->exit_code));
583 else if (WIFSIGNALED(pty->exit_code))
584 #ifdef HAVE_NO_STRSIGNAL
585 sprintf(message, "\r\n[pterm: process terminated on signal"
586 " %d]\r\n", WTERMSIG(pty->exit_code));
588 sprintf(message, "\r\n[pterm: process terminated on signal"
589 " %d (%.400s)]\r\n", WTERMSIG(pty->exit_code),
590 strsignal(WTERMSIG(pty->exit_code)));
592 from_backend(pty->frontend, 0, message, strlen(message));
595 notify_remote_exit(pty->frontend);
601 int pty_select_result(int fd, int event)
606 if (fd == pty_signal_pipe[0]) {
612 read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
615 pid = waitpid(-1, &status, WNOHANG);
618 pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
621 ret = ret && pty_real_select_result(pty, -1, status);
624 pty = find234(ptys_by_fd, &fd, pty_find_by_fd);
627 ret = ret && pty_real_select_result(pty, event, 0);
633 static void pty_uxsel_setup(Pty pty)
635 uxsel_set(pty->master_fd, 1, pty_select_result);
638 * In principle this only needs calling once for all pty
639 * backend instances, but it's simplest just to call it every
640 * time; uxsel won't mind.
642 uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
646 * Called to set up the pty.
648 * Returns an error message, or NULL on success.
650 * Also places the canonical host name into `realhost'. It must be
651 * freed by the caller.
653 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
654 char *host, int port, char **realhost, int nodelay,
659 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
667 pty = snew(struct pty_tag);
668 pty->master_fd = pty->slave_fd = -1;
670 pty_stamped_utmp = FALSE;
674 pty->frontend = frontend;
675 *backend_handle = NULL; /* we can't sensibly use this, sadly */
677 pty->cfg = *cfg; /* structure copy */
678 pty->term_width = cfg->width;
679 pty->term_height = cfg->height;
681 if (pty->master_fd < 0)
682 pty_open_master(pty);
685 * Set the backspace character to be whichever of ^H and ^? is
686 * specified by bksp_is_delete.
689 struct termios attrs;
690 tcgetattr(pty->master_fd, &attrs);
691 attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
692 tcsetattr(pty->master_fd, TCSANOW, &attrs);
697 * Stamp utmp (that is, tell the utmp helper process to do so),
700 if (!cfg->stamp_utmp) {
701 close(pty_utmp_helper_pipe); /* just let the child process die */
702 pty_utmp_helper_pipe = -1;
704 char *location = get_x_display(pty->frontend);
705 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
707 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
709 perror("pterm: writing to utmp helper process");
710 close(pty_utmp_helper_pipe); /* arrgh, just give up */
711 pty_utmp_helper_pipe = -1;
719 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
720 windowid = get_windowid(pty->frontend);
724 * Fork and execute the command.
738 slavefd = pty_open_slave(pty);
740 perror("slave pty: open");
744 close(pty->master_fd);
745 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
750 ioctl(slavefd, TIOCSCTTY, 1);
752 tcsetpgrp(slavefd, pgrp);
754 close(open(pty->name, O_WRONLY, 0));
756 /* Close everything _else_, for tidiness. */
757 for (i = 3; i < 1024; i++)
760 char term_env_var[10 + sizeof(cfg->termtype)];
761 sprintf(term_env_var, "TERM=%s", cfg->termtype);
762 putenv(term_env_var);
764 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
766 char windowid_env_var[40];
767 sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
768 putenv(windowid_env_var);
772 char *e = cfg->environmt;
773 char *var, *varend, *val, *varval;
776 while (*e && *e != '\t') e++;
783 varval = dupprintf("%.*s=%s", varend-var, var, val);
786 * We must not free varval, since putenv links it
787 * into the environment _in place_. Weird, but
788 * there we go. Memory usage will be rationalised
789 * as soon as we exec anyway.
795 * SIGINT and SIGQUIT may have been set to ignored by our
796 * parent, particularly by things like sh -c 'pterm &' and
797 * some window managers. SIGCHLD, meanwhile, was blocked
798 * during pt_main() startup. Reverse all this for our child
801 putty_signal(SIGINT, SIG_DFL);
802 putty_signal(SIGQUIT, SIG_DFL);
803 block_signal(SIGCHLD, 0);
805 execvp(pty_argv[0], pty_argv);
807 char *shell = getenv("SHELL");
809 if (cfg->login_shell) {
810 char *p = strrchr(shell, '/');
811 shellname = snewn(2+strlen(shell), char);
813 sprintf(shellname, "-%s", p);
816 execl(getenv("SHELL"), shellname, NULL);
820 * If we're here, exec has gone badly foom.
825 pty->child_pid = pid;
826 pty->child_dead = FALSE;
827 pty->finished = FALSE;
828 if (pty->slave_fd > 0)
829 close(pty->slave_fd);
831 ptys_by_pid = newtree234(pty_compare_by_pid);
832 add234(ptys_by_pid, pty);
835 if (pty_signal_pipe[0] < 0 && pipe(pty_signal_pipe) < 0) {
839 pty_uxsel_setup(pty);
841 *backend_handle = pty;
846 static void pty_reconfig(void *handle, Config *cfg)
848 Pty pty = (Pty)handle;
850 * We don't have much need to reconfigure this backend, but
851 * unfortunately we do need to pick up the setting of Close On
852 * Exit so we know whether to give a `terminated' message.
854 pty->cfg = *cfg; /* structure copy */
858 * Stub routine (never called in pterm).
860 static void pty_free(void *handle)
862 Pty pty = (Pty)handle;
864 /* Either of these may fail `not found'. That's fine with us. */
865 del234(ptys_by_pid, pty);
866 del234(ptys_by_fd, pty);
872 * Called to send data down the pty.
874 static int pty_send(void *handle, char *buf, int len)
876 Pty pty = (Pty)handle;
878 if (pty->master_fd < 0)
879 return 0; /* ignore all writes if fd closed */
882 int ret = write(pty->master_fd, buf, len);
884 perror("write pty master");
893 static void pty_close(Pty pty)
895 if (pty->master_fd >= 0) {
896 close(pty->master_fd);
900 if (pty_utmp_helper_pipe >= 0) {
901 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
902 pty_utmp_helper_pipe = -1;
908 * Called to query the current socket sendability status.
910 static int pty_sendbuffer(void *handle)
912 /* Pty pty = (Pty)handle; */
917 * Called to set the size of the window
919 static void pty_size(void *handle, int width, int height)
921 Pty pty = (Pty)handle;
924 pty->term_width = width;
925 pty->term_height = height;
927 size.ws_row = (unsigned short)pty->term_height;
928 size.ws_col = (unsigned short)pty->term_width;
929 size.ws_xpixel = (unsigned short) pty->term_width *
930 font_dimension(pty->frontend, 0);
931 size.ws_ypixel = (unsigned short) pty->term_height *
932 font_dimension(pty->frontend, 1);
933 ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
938 * Send special codes.
940 static void pty_special(void *handle, Telnet_Special code)
942 /* Pty pty = (Pty)handle; */
948 * Return a list of the special codes that make sense in this
951 static const struct telnet_special *pty_get_specials(void *handle)
953 /* Pty pty = (Pty)handle; */
955 * Hmm. When I get round to having this actually usable, it
956 * might be quite nice to have the ability to deliver a few
957 * well chosen signals to the child process - SIGINT, SIGTERM,
963 static Socket pty_socket(void *handle)
965 /* Pty pty = (Pty)handle; */
966 return NULL; /* shouldn't ever be needed */
969 static int pty_sendok(void *handle)
971 /* Pty pty = (Pty)handle; */
975 static void pty_unthrottle(void *handle, int backlog)
977 /* Pty pty = (Pty)handle; */
981 static int pty_ldisc(void *handle, int option)
983 /* Pty pty = (Pty)handle; */
984 return 0; /* neither editing nor echoing */
987 static void pty_provide_ldisc(void *handle, void *ldisc)
989 /* Pty pty = (Pty)handle; */
990 /* This is a stub. */
993 static void pty_provide_logctx(void *handle, void *logctx)
995 /* Pty pty = (Pty)handle; */
996 /* This is a stub. */
999 static int pty_exitcode(void *handle)
1001 Pty pty = (Pty)handle;
1003 return -1; /* not dead yet */
1005 return pty->exit_code;
1008 static int pty_cfg_info(void *handle)
1010 /* Pty pty = (Pty)handle; */
1014 Backend pty_backend = {