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.
176 static void pty_close(Pty pty);
179 static void setup_utmp(char *ttyname, char *location)
182 struct lastlog lastlog_entry;
189 pw = getpwuid(getuid());
190 memset(&utmp_entry, 0, sizeof(utmp_entry));
191 utmp_entry.ut_type = USER_PROCESS;
192 utmp_entry.ut_pid = getpid();
193 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
194 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
195 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
196 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
197 /* Apparently there are some architectures where (struct utmp).ut_time
198 * is not essentially time_t (e.g. Linux amd64). Hence the temporary. */
200 utmp_entry.ut_time = uttime; /* may truncate */
202 #if defined HAVE_PUTUTLINE
205 pututline(&utmp_entry);
209 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
210 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
215 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
216 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
217 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
218 time(&lastlog_entry.ll_time);
219 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
220 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
221 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
226 pty_stamped_utmp = 1;
230 static void cleanup_utmp(void)
235 if (!pty_stamped_utmp)
238 utmp_entry.ut_type = DEAD_PROCESS;
239 memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
241 utmp_entry.ut_time = uttime;
243 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
244 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
248 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
249 utmp_entry.ut_time = 0;
251 #if defined HAVE_PUTUTLINE
254 pututline(&utmp_entry);
258 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
262 static void sigchld_handler(int signum)
264 write(pty_signal_pipe[1], "x", 1);
268 static void fatal_sig_handler(int signum)
270 putty_signal(signum, SIG_DFL);
277 static int pty_open_slave(Pty pty)
279 if (pty->slave_fd < 0)
280 pty->slave_fd = open(pty->name, O_RDWR);
282 return pty->slave_fd;
285 static void pty_open_master(Pty pty)
288 const char chars1[] = "pqrstuvwxyz";
289 const char chars2[] = "0123456789abcdef";
291 char master_name[20];
294 for (p1 = chars1; *p1; p1++)
295 for (p2 = chars2; *p2; p2++) {
296 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
297 pty->master_fd = open(master_name, O_RDWR);
298 if (pty->master_fd >= 0) {
299 if (geteuid() == 0 ||
300 access(master_name, R_OK | W_OK) == 0) {
302 * We must also check at this point that we are
303 * able to open the slave side of the pty. We
304 * wouldn't want to allocate the wrong master,
305 * get all the way down to forking, and _then_
306 * find we're unable to open the slave.
308 strcpy(pty->name, master_name);
309 pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
311 if (pty_open_slave(pty) >= 0 &&
312 access(pty->name, R_OK | W_OK) == 0)
314 if (pty->slave_fd > 0)
315 close(pty->slave_fd);
318 close(pty->master_fd);
322 /* If we get here, we couldn't get a tty at all. */
323 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
328 /* We need to chown/chmod the /dev/ttyXX device. */
329 gp = getgrnam("tty");
330 chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
331 chmod(pty->name, 0600);
333 pty->master_fd = open("/dev/ptmx", O_RDWR);
335 if (pty->master_fd < 0) {
336 perror("/dev/ptmx: open");
340 if (grantpt(pty->master_fd) < 0) {
345 if (unlockpt(pty->master_fd) < 0) {
350 pty->name[FILENAME_MAX-1] = '\0';
351 strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
355 ptys_by_fd = newtree234(pty_compare_by_fd);
356 add234(ptys_by_fd, pty);
360 * Pre-initialisation. This is here to get around the fact that GTK
361 * doesn't like being run in setuid/setgid programs (probably
362 * sensibly). So before we initialise GTK - and therefore before we
363 * even process the command line - we check to see if we're running
364 * set[ug]id. If so, we open our pty master _now_, chown it as
365 * necessary, and drop privileges. We can always close it again
366 * later. If we're potentially going to be doing utmp as well, we
367 * also fork off a utmp helper process and communicate with it by
368 * means of a pipe; the utmp helper will keep privileges in order
369 * to clean up utmp when we exit (i.e. when its end of our pipe
372 void pty_pre_init(void)
381 pty = single_pty = snew(struct pty_tag);
383 /* set the child signal handler straight away; it needs to be set
384 * before we ever fork. */
385 putty_signal(SIGCHLD, sigchld_handler);
386 pty->master_fd = pty->slave_fd = -1;
388 pty_stamped_utmp = FALSE;
391 if (geteuid() != getuid() || getegid() != getgid()) {
392 pty_open_master(pty);
397 * Fork off the utmp helper.
399 if (pipe(pipefd) < 0) {
400 perror("pterm: pipe");
405 perror("pterm: fork");
407 } else if (pid == 0) {
408 char display[128], buffer[128];
413 * Now sit here until we receive a display name from the
414 * other end of the pipe, and then stamp utmp. Unstamp utmp
415 * again, and exit, when the pipe closes.
421 ret = read(pipefd[0], buffer, lenof(buffer));
425 } else if (!pty_stamped_utmp) {
426 if (dlen < lenof(display))
427 memcpy(display+dlen, buffer,
428 min(ret, lenof(display)-dlen));
429 if (buffer[ret-1] == '\0') {
431 * Now we have a display name. NUL-terminate
432 * it, and stamp utmp.
434 display[lenof(display)-1] = '\0';
436 * Trap as many fatal signals as we can in the
437 * hope of having the best possible chance to
438 * clean up utmp before termination. We are
439 * unfortunately unprotected against SIGKILL,
442 putty_signal(SIGHUP, fatal_sig_handler);
443 putty_signal(SIGINT, fatal_sig_handler);
444 putty_signal(SIGQUIT, fatal_sig_handler);
445 putty_signal(SIGILL, fatal_sig_handler);
446 putty_signal(SIGABRT, fatal_sig_handler);
447 putty_signal(SIGFPE, fatal_sig_handler);
448 putty_signal(SIGPIPE, fatal_sig_handler);
449 putty_signal(SIGALRM, fatal_sig_handler);
450 putty_signal(SIGTERM, fatal_sig_handler);
451 putty_signal(SIGSEGV, fatal_sig_handler);
452 putty_signal(SIGUSR1, fatal_sig_handler);
453 putty_signal(SIGUSR2, fatal_sig_handler);
455 putty_signal(SIGBUS, fatal_sig_handler);
458 putty_signal(SIGPOLL, fatal_sig_handler);
461 putty_signal(SIGPROF, fatal_sig_handler);
464 putty_signal(SIGSYS, fatal_sig_handler);
467 putty_signal(SIGTRAP, fatal_sig_handler);
470 putty_signal(SIGVTALRM, fatal_sig_handler);
473 putty_signal(SIGXCPU, fatal_sig_handler);
476 putty_signal(SIGXFSZ, fatal_sig_handler);
479 putty_signal(SIGIO, fatal_sig_handler);
481 setup_utmp(pty->name, display);
487 pty_utmp_helper_pid = pid;
488 pty_utmp_helper_pipe = pipefd[1];
494 #ifndef HAVE_NO_SETRESUID
495 int gid = getgid(), uid = getuid();
496 int setresgid(gid_t, gid_t, gid_t);
497 int setresuid(uid_t, uid_t, uid_t);
498 setresgid(gid, gid, gid);
499 setresuid(uid, uid, uid);
507 int pty_real_select_result(Pty pty, int event, int status)
511 int finished = FALSE;
515 * We've been called because our child process did
516 * something. `status' tells us what.
518 if ((WIFEXITED(status) || WIFSIGNALED(status))) {
520 * The primary child process died. We could keep
521 * the terminal open for remaining subprocesses to
522 * output to, but conventional wisdom seems to feel
523 * that that's the Wrong Thing for an xterm-alike,
524 * so we bail out now (though we don't necessarily
525 * _close_ the window, depending on the state of
526 * Close On Exit). This would be easy enough to
527 * change or make configurable if necessary.
529 pty->exit_code = status;
530 pty->child_dead = TRUE;
531 del234(ptys_by_pid, pty);
537 ret = read(pty->master_fd, buf, sizeof(buf));
540 * Clean termination condition is that either ret == 0, or ret
541 * < 0 and errno == EIO. Not sure why the latter, but it seems
544 if (ret == 0 || (ret < 0 && errno == EIO)) {
546 * We assume a clean exit if the pty has closed but the
547 * actual child process hasn't. The only way I can
548 * imagine this happening is if it detaches itself from
549 * the pty and goes daemonic - in which case the
550 * expected usage model would precisely _not_ be for
551 * the pterm window to hang around!
554 if (!pty->child_dead)
556 } else if (ret < 0) {
557 perror("read pty master");
559 } else if (ret > 0) {
560 from_backend(pty->frontend, 0, buf, ret);
565 if (finished && !pty->finished) {
566 uxsel_del(pty->master_fd);
570 pty->finished = TRUE;
573 * This is a slight layering-violation sort of hack: only
574 * if we're not closing on exit (COE is set to Never, or to
575 * Only On Clean and it wasn't a clean exit) do we output a
576 * `terminated' message.
578 if (pty->cfg.close_on_exit == FORCE_OFF ||
579 (pty->cfg.close_on_exit == AUTO && pty->exit_code != 0)) {
581 if (WIFEXITED(pty->exit_code))
582 sprintf(message, "\r\n[pterm: process terminated with exit"
583 " code %d]\r\n", WEXITSTATUS(pty->exit_code));
584 else if (WIFSIGNALED(pty->exit_code))
585 #ifdef HAVE_NO_STRSIGNAL
586 sprintf(message, "\r\n[pterm: process terminated on signal"
587 " %d]\r\n", WTERMSIG(pty->exit_code));
589 sprintf(message, "\r\n[pterm: process terminated on signal"
590 " %d (%.400s)]\r\n", WTERMSIG(pty->exit_code),
591 strsignal(WTERMSIG(pty->exit_code)));
593 from_backend(pty->frontend, 0, message, strlen(message));
596 notify_remote_exit(pty->frontend);
602 int pty_select_result(int fd, int event)
607 if (fd == pty_signal_pipe[0]) {
613 read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
616 pid = waitpid(-1, &status, WNOHANG);
619 pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
622 ret = ret && pty_real_select_result(pty, -1, status);
625 pty = find234(ptys_by_fd, &fd, pty_find_by_fd);
628 ret = ret && pty_real_select_result(pty, event, 0);
634 static void pty_uxsel_setup(Pty pty)
636 uxsel_set(pty->master_fd, 1, pty_select_result);
639 * In principle this only needs calling once for all pty
640 * backend instances, but it's simplest just to call it every
641 * time; uxsel won't mind.
643 uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
647 * Called to set up the pty.
649 * Returns an error message, or NULL on success.
651 * Also places the canonical host name into `realhost'. It must be
652 * freed by the caller.
654 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
655 char *host, int port, char **realhost, int nodelay,
660 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
668 pty = snew(struct pty_tag);
669 pty->master_fd = pty->slave_fd = -1;
671 pty_stamped_utmp = FALSE;
675 pty->frontend = frontend;
676 *backend_handle = NULL; /* we can't sensibly use this, sadly */
678 pty->cfg = *cfg; /* structure copy */
679 pty->term_width = cfg->width;
680 pty->term_height = cfg->height;
682 if (pty->master_fd < 0)
683 pty_open_master(pty);
686 * Set the backspace character to be whichever of ^H and ^? is
687 * specified by bksp_is_delete.
690 struct termios attrs;
691 tcgetattr(pty->master_fd, &attrs);
692 attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
693 tcsetattr(pty->master_fd, TCSANOW, &attrs);
698 * Stamp utmp (that is, tell the utmp helper process to do so),
701 if (!cfg->stamp_utmp) {
702 close(pty_utmp_helper_pipe); /* just let the child process die */
703 pty_utmp_helper_pipe = -1;
705 char *location = get_x_display(pty->frontend);
706 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
708 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
710 perror("pterm: writing to utmp helper process");
711 close(pty_utmp_helper_pipe); /* arrgh, just give up */
712 pty_utmp_helper_pipe = -1;
720 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
721 windowid = get_windowid(pty->frontend);
725 * Fork and execute the command.
739 slavefd = pty_open_slave(pty);
741 perror("slave pty: open");
745 close(pty->master_fd);
746 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
751 ioctl(slavefd, TIOCSCTTY, 1);
753 tcsetpgrp(slavefd, pgrp);
755 close(open(pty->name, O_WRONLY, 0));
757 /* Close everything _else_, for tidiness. */
758 for (i = 3; i < 1024; i++)
761 char term_env_var[10 + sizeof(cfg->termtype)];
762 sprintf(term_env_var, "TERM=%s", cfg->termtype);
763 putenv(term_env_var);
765 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
767 char windowid_env_var[40];
768 sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
769 putenv(windowid_env_var);
773 char *e = cfg->environmt;
774 char *var, *varend, *val, *varval;
777 while (*e && *e != '\t') e++;
784 varval = dupprintf("%.*s=%s", varend-var, var, val);
787 * We must not free varval, since putenv links it
788 * into the environment _in place_. Weird, but
789 * there we go. Memory usage will be rationalised
790 * as soon as we exec anyway.
796 * SIGINT and SIGQUIT may have been set to ignored by our
797 * parent, particularly by things like sh -c 'pterm &' and
798 * some window managers. SIGCHLD, meanwhile, was blocked
799 * during pt_main() startup. Reverse all this for our child
802 putty_signal(SIGINT, SIG_DFL);
803 putty_signal(SIGQUIT, SIG_DFL);
804 block_signal(SIGCHLD, 0);
806 execvp(pty_argv[0], pty_argv);
808 char *shell = getenv("SHELL");
810 if (cfg->login_shell) {
811 char *p = strrchr(shell, '/');
812 shellname = snewn(2+strlen(shell), char);
814 sprintf(shellname, "-%s", p);
817 execl(getenv("SHELL"), shellname, NULL);
821 * If we're here, exec has gone badly foom.
826 pty->child_pid = pid;
827 pty->child_dead = FALSE;
828 pty->finished = FALSE;
829 if (pty->slave_fd > 0)
830 close(pty->slave_fd);
832 ptys_by_pid = newtree234(pty_compare_by_pid);
833 add234(ptys_by_pid, pty);
836 if (pty_signal_pipe[0] < 0 && pipe(pty_signal_pipe) < 0) {
840 pty_uxsel_setup(pty);
842 *backend_handle = pty;
847 static void pty_reconfig(void *handle, Config *cfg)
849 Pty pty = (Pty)handle;
851 * We don't have much need to reconfigure this backend, but
852 * unfortunately we do need to pick up the setting of Close On
853 * Exit so we know whether to give a `terminated' message.
855 pty->cfg = *cfg; /* structure copy */
859 * Stub routine (never called in pterm).
861 static void pty_free(void *handle)
863 Pty pty = (Pty)handle;
865 /* Either of these may fail `not found'. That's fine with us. */
866 del234(ptys_by_pid, pty);
867 del234(ptys_by_fd, pty);
873 * Called to send data down the pty.
875 static int pty_send(void *handle, char *buf, int len)
877 Pty pty = (Pty)handle;
879 if (pty->master_fd < 0)
880 return 0; /* ignore all writes if fd closed */
883 int ret = write(pty->master_fd, buf, len);
885 perror("write pty master");
894 static void pty_close(Pty pty)
896 if (pty->master_fd >= 0) {
897 close(pty->master_fd);
901 if (pty_utmp_helper_pipe >= 0) {
902 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
903 pty_utmp_helper_pipe = -1;
909 * Called to query the current socket sendability status.
911 static int pty_sendbuffer(void *handle)
913 /* Pty pty = (Pty)handle; */
918 * Called to set the size of the window
920 static void pty_size(void *handle, int width, int height)
922 Pty pty = (Pty)handle;
925 pty->term_width = width;
926 pty->term_height = height;
928 size.ws_row = (unsigned short)pty->term_height;
929 size.ws_col = (unsigned short)pty->term_width;
930 size.ws_xpixel = (unsigned short) pty->term_width *
931 font_dimension(pty->frontend, 0);
932 size.ws_ypixel = (unsigned short) pty->term_height *
933 font_dimension(pty->frontend, 1);
934 ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
939 * Send special codes.
941 static void pty_special(void *handle, Telnet_Special code)
943 /* Pty pty = (Pty)handle; */
949 * Return a list of the special codes that make sense in this
952 static const struct telnet_special *pty_get_specials(void *handle)
954 /* Pty pty = (Pty)handle; */
956 * Hmm. When I get round to having this actually usable, it
957 * might be quite nice to have the ability to deliver a few
958 * well chosen signals to the child process - SIGINT, SIGTERM,
964 static Socket pty_socket(void *handle)
966 /* Pty pty = (Pty)handle; */
967 return NULL; /* shouldn't ever be needed */
970 static int pty_sendok(void *handle)
972 /* Pty pty = (Pty)handle; */
976 static void pty_unthrottle(void *handle, int backlog)
978 /* Pty pty = (Pty)handle; */
982 static int pty_ldisc(void *handle, int option)
984 /* Pty pty = (Pty)handle; */
985 return 0; /* neither editing nor echoing */
988 static void pty_provide_ldisc(void *handle, void *ldisc)
990 /* Pty pty = (Pty)handle; */
991 /* This is a stub. */
994 static void pty_provide_logctx(void *handle, void *logctx)
996 /* Pty pty = (Pty)handle; */
997 /* This is a stub. */
1000 static int pty_exitcode(void *handle)
1002 Pty pty = (Pty)handle;
1004 return -1; /* not dead yet */
1006 return pty->exit_code;
1009 static int pty_cfg_info(void *handle)
1011 /* Pty pty = (Pty)handle; */
1015 Backend pty_backend = {