2 * Pseudo-tty backend for pterm.
18 #include <sys/types.h>
21 #include <sys/ioctl.h>
35 #define UTMP_FILE "/var/run/utmp"
38 #define WTMP_FILE "/var/log/wtmp"
42 #define LASTLOG_FILE _PATH_LASTLOG
44 #define LASTLOG_FILE "/var/log/lastlog"
49 * Set up a default for vaguely sane systems. The idea is that if
50 * OMIT_UTMP is not defined, then at least one of the symbols which
51 * enable particular forms of utmp processing should be, if only so
52 * that a link error can warn you that you should have defined
53 * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
54 * the only such symbol.
57 #if !defined HAVE_PUTUTLINE
58 #define HAVE_PUTUTLINE
62 typedef struct pty_tag *Pty;
65 * The pty_signal_pipe, along with the SIGCHLD handler, must be
66 * process-global rather than session-specific.
68 static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
72 int master_fd, slave_fd;
74 char name[FILENAME_MAX];
76 int term_width, term_height;
77 int child_dead, finished;
82 * We store our pty backends in a tree sorted by master fd, so that
83 * when we get an uxsel notification we know which backend instance
84 * is the owner of the pty that caused it.
86 static int pty_compare_by_fd(void *av, void *bv)
91 if (a->master_fd < b->master_fd)
93 else if (a->master_fd > b->master_fd)
98 static int pty_find_by_fd(void *av, void *bv)
103 if (a < b->master_fd)
105 else if (a > b->master_fd)
110 static tree234 *ptys_by_fd = NULL;
113 * We also have a tree sorted by child pid, so that when we wait()
114 * in response to the signal we know which backend instance is the
115 * owner of the process that caused the signal.
117 static int pty_compare_by_pid(void *av, void *bv)
122 if (a->child_pid < b->child_pid)
124 else if (a->child_pid > b->child_pid)
129 static int pty_find_by_pid(void *av, void *bv)
134 if (a < b->child_pid)
136 else if (a > b->child_pid)
141 static tree234 *ptys_by_pid = NULL;
144 * If we are using pty_pre_init(), it will need to have already
145 * allocated a pty structure, which we must then return from
146 * pty_init() rather than allocating a new one. Here we store that
147 * structure between allocation and use.
149 * Note that although most of this module is entirely capable of
150 * handling multiple ptys in a single process, pty_pre_init() is
151 * fundamentally _dependent_ on there being at most one pty per
152 * process, so the normal static-data constraints don't apply.
154 * Likewise, since utmp is only used via pty_pre_init, it too must
155 * be single-instance, so we can declare utmp-related variables
158 static Pty single_pty = NULL;
161 static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
162 static int pty_stamped_utmp;
163 static struct utmp utmp_entry;
167 * pty_argv is a grievous hack to allow a proper argv to be passed
168 * through from the Unix command line. Again, it doesn't really
169 * make sense outside a one-pty-per-process setup.
173 static void pty_close(Pty pty);
176 static void setup_utmp(char *ttyname, char *location)
179 struct lastlog lastlog_entry;
186 pw = getpwuid(getuid());
187 memset(&utmp_entry, 0, sizeof(utmp_entry));
188 utmp_entry.ut_type = USER_PROCESS;
189 utmp_entry.ut_pid = getpid();
190 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
191 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
192 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
193 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
194 /* Apparently there are some architectures where (struct utmp).ut_time
195 * is not essentially time_t (e.g. Linux amd64). Hence the temporary. */
197 utmp_entry.ut_time = uttime; /* may truncate */
199 #if defined HAVE_PUTUTLINE
202 pututline(&utmp_entry);
206 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
207 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
212 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
213 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
214 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
215 time(&lastlog_entry.ll_time);
216 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
217 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
218 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
223 pty_stamped_utmp = 1;
227 static void cleanup_utmp(void)
232 if (!pty_stamped_utmp)
235 utmp_entry.ut_type = DEAD_PROCESS;
236 memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
238 utmp_entry.ut_time = uttime;
240 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
241 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
245 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
246 utmp_entry.ut_time = 0;
248 #if defined HAVE_PUTUTLINE
251 pututline(&utmp_entry);
255 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
259 static void sigchld_handler(int signum)
261 write(pty_signal_pipe[1], "x", 1);
265 static void fatal_sig_handler(int signum)
267 putty_signal(signum, SIG_DFL);
274 static int pty_open_slave(Pty pty)
276 if (pty->slave_fd < 0)
277 pty->slave_fd = open(pty->name, O_RDWR);
279 return pty->slave_fd;
282 static void pty_open_master(Pty pty)
285 const char chars1[] = "pqrstuvwxyz";
286 const char chars2[] = "0123456789abcdef";
288 char master_name[20];
291 for (p1 = chars1; *p1; p1++)
292 for (p2 = chars2; *p2; p2++) {
293 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
294 pty->master_fd = open(master_name, O_RDWR);
295 if (pty->master_fd >= 0) {
296 if (geteuid() == 0 ||
297 access(master_name, R_OK | W_OK) == 0) {
299 * We must also check at this point that we are
300 * able to open the slave side of the pty. We
301 * wouldn't want to allocate the wrong master,
302 * get all the way down to forking, and _then_
303 * find we're unable to open the slave.
305 strcpy(pty->name, master_name);
306 pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
308 if (pty_open_slave(pty) >= 0 &&
309 access(pty->name, R_OK | W_OK) == 0)
311 if (pty->slave_fd > 0)
312 close(pty->slave_fd);
315 close(pty->master_fd);
319 /* If we get here, we couldn't get a tty at all. */
320 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
325 /* We need to chown/chmod the /dev/ttyXX device. */
326 gp = getgrnam("tty");
327 chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
328 chmod(pty->name, 0600);
330 pty->master_fd = open("/dev/ptmx", O_RDWR);
332 if (pty->master_fd < 0) {
333 perror("/dev/ptmx: open");
337 if (grantpt(pty->master_fd) < 0) {
342 if (unlockpt(pty->master_fd) < 0) {
347 pty->name[FILENAME_MAX-1] = '\0';
348 strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
352 ptys_by_fd = newtree234(pty_compare_by_fd);
353 add234(ptys_by_fd, pty);
357 * Pre-initialisation. This is here to get around the fact that GTK
358 * doesn't like being run in setuid/setgid programs (probably
359 * sensibly). So before we initialise GTK - and therefore before we
360 * even process the command line - we check to see if we're running
361 * set[ug]id. If so, we open our pty master _now_, chown it as
362 * necessary, and drop privileges. We can always close it again
363 * later. If we're potentially going to be doing utmp as well, we
364 * also fork off a utmp helper process and communicate with it by
365 * means of a pipe; the utmp helper will keep privileges in order
366 * to clean up utmp when we exit (i.e. when its end of our pipe
369 void pty_pre_init(void)
378 pty = single_pty = snew(struct pty_tag);
380 /* set the child signal handler straight away; it needs to be set
381 * before we ever fork. */
382 putty_signal(SIGCHLD, sigchld_handler);
383 pty->master_fd = pty->slave_fd = -1;
385 pty_stamped_utmp = FALSE;
388 if (geteuid() != getuid() || getegid() != getgid()) {
389 pty_open_master(pty);
394 * Fork off the utmp helper.
396 if (pipe(pipefd) < 0) {
397 perror("pterm: pipe");
402 perror("pterm: fork");
404 } else if (pid == 0) {
405 char display[128], buffer[128];
410 * Now sit here until we receive a display name from the
411 * other end of the pipe, and then stamp utmp. Unstamp utmp
412 * again, and exit, when the pipe closes.
418 ret = read(pipefd[0], buffer, lenof(buffer));
422 } else if (!pty_stamped_utmp) {
423 if (dlen < lenof(display))
424 memcpy(display+dlen, buffer,
425 min(ret, lenof(display)-dlen));
426 if (buffer[ret-1] == '\0') {
428 * Now we have a display name. NUL-terminate
429 * it, and stamp utmp.
431 display[lenof(display)-1] = '\0';
433 * Trap as many fatal signals as we can in the
434 * hope of having the best possible chance to
435 * clean up utmp before termination. We are
436 * unfortunately unprotected against SIGKILL,
439 putty_signal(SIGHUP, fatal_sig_handler);
440 putty_signal(SIGINT, fatal_sig_handler);
441 putty_signal(SIGQUIT, fatal_sig_handler);
442 putty_signal(SIGILL, fatal_sig_handler);
443 putty_signal(SIGABRT, fatal_sig_handler);
444 putty_signal(SIGFPE, fatal_sig_handler);
445 putty_signal(SIGPIPE, fatal_sig_handler);
446 putty_signal(SIGALRM, fatal_sig_handler);
447 putty_signal(SIGTERM, fatal_sig_handler);
448 putty_signal(SIGSEGV, fatal_sig_handler);
449 putty_signal(SIGUSR1, fatal_sig_handler);
450 putty_signal(SIGUSR2, fatal_sig_handler);
452 putty_signal(SIGBUS, fatal_sig_handler);
455 putty_signal(SIGPOLL, fatal_sig_handler);
458 putty_signal(SIGPROF, fatal_sig_handler);
461 putty_signal(SIGSYS, fatal_sig_handler);
464 putty_signal(SIGTRAP, fatal_sig_handler);
467 putty_signal(SIGVTALRM, fatal_sig_handler);
470 putty_signal(SIGXCPU, fatal_sig_handler);
473 putty_signal(SIGXFSZ, fatal_sig_handler);
476 putty_signal(SIGIO, fatal_sig_handler);
478 setup_utmp(pty->name, display);
484 pty_utmp_helper_pid = pid;
485 pty_utmp_helper_pipe = pipefd[1];
491 #ifndef HAVE_NO_SETRESUID
492 int gid = getgid(), uid = getuid();
493 int setresgid(gid_t, gid_t, gid_t);
494 int setresuid(uid_t, uid_t, uid_t);
495 setresgid(gid, gid, gid);
496 setresuid(uid, uid, uid);
504 int pty_real_select_result(Pty pty, int event, int status)
508 int finished = FALSE;
512 * We've been called because our child process did
513 * something. `status' tells us what.
515 if ((WIFEXITED(status) || WIFSIGNALED(status))) {
517 * The primary child process died. We could keep
518 * the terminal open for remaining subprocesses to
519 * output to, but conventional wisdom seems to feel
520 * that that's the Wrong Thing for an xterm-alike,
521 * so we bail out now (though we don't necessarily
522 * _close_ the window, depending on the state of
523 * Close On Exit). This would be easy enough to
524 * change or make configurable if necessary.
526 pty->exit_code = status;
527 pty->child_dead = TRUE;
528 del234(ptys_by_pid, pty);
534 ret = read(pty->master_fd, buf, sizeof(buf));
537 * Clean termination condition is that either ret == 0, or ret
538 * < 0 and errno == EIO. Not sure why the latter, but it seems
541 if (ret == 0 || (ret < 0 && errno == EIO)) {
543 * We assume a clean exit if the pty has closed but the
544 * actual child process hasn't. The only way I can
545 * imagine this happening is if it detaches itself from
546 * the pty and goes daemonic - in which case the
547 * expected usage model would precisely _not_ be for
548 * the pterm window to hang around!
551 if (!pty->child_dead)
553 } else if (ret < 0) {
554 perror("read pty master");
556 } else if (ret > 0) {
557 from_backend(pty->frontend, 0, buf, ret);
562 if (finished && !pty->finished) {
563 uxsel_del(pty->master_fd);
567 pty->finished = TRUE;
570 * This is a slight layering-violation sort of hack: only
571 * if we're not closing on exit (COE is set to Never, or to
572 * Only On Clean and it wasn't a clean exit) do we output a
573 * `terminated' message.
575 if (pty->cfg.close_on_exit == FORCE_OFF ||
576 (pty->cfg.close_on_exit == AUTO && pty->exit_code != 0)) {
578 if (WIFEXITED(pty->exit_code))
579 sprintf(message, "\r\n[pterm: process terminated with exit"
580 " code %d]\r\n", WEXITSTATUS(pty->exit_code));
581 else if (WIFSIGNALED(pty->exit_code))
582 #ifdef HAVE_NO_STRSIGNAL
583 sprintf(message, "\r\n[pterm: process terminated on signal"
584 " %d]\r\n", WTERMSIG(pty->exit_code));
586 sprintf(message, "\r\n[pterm: process terminated on signal"
587 " %d (%.400s)]\r\n", WTERMSIG(pty->exit_code),
588 strsignal(WTERMSIG(pty->exit_code)));
590 from_backend(pty->frontend, 0, message, strlen(message));
593 notify_remote_exit(pty->frontend);
599 int pty_select_result(int fd, int event)
604 if (fd == pty_signal_pipe[0]) {
610 read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
613 pid = waitpid(-1, &status, WNOHANG);
616 pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
619 ret = ret && pty_real_select_result(pty, -1, status);
622 pty = find234(ptys_by_fd, &fd, pty_find_by_fd);
625 ret = ret && pty_real_select_result(pty, event, 0);
631 static void pty_uxsel_setup(Pty pty)
633 uxsel_set(pty->master_fd, 1, pty_select_result);
636 * In principle this only needs calling once for all pty
637 * backend instances, but it's simplest just to call it every
638 * time; uxsel won't mind.
640 uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
644 * Called to set up the pty.
646 * Returns an error message, or NULL on success.
648 * Also places the canonical host name into `realhost'. It must be
649 * freed by the caller.
651 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
652 char *host, int port, char **realhost, int nodelay,
657 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
665 pty = snew(struct pty_tag);
666 pty->master_fd = pty->slave_fd = -1;
668 pty_stamped_utmp = FALSE;
672 pty->frontend = frontend;
673 *backend_handle = NULL; /* we can't sensibly use this, sadly */
675 pty->cfg = *cfg; /* structure copy */
676 pty->term_width = cfg->width;
677 pty->term_height = cfg->height;
679 if (pty->master_fd < 0)
680 pty_open_master(pty);
683 * Set the backspace character to be whichever of ^H and ^? is
684 * specified by bksp_is_delete.
687 struct termios attrs;
688 tcgetattr(pty->master_fd, &attrs);
689 attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
690 tcsetattr(pty->master_fd, TCSANOW, &attrs);
695 * Stamp utmp (that is, tell the utmp helper process to do so),
698 if (!cfg->stamp_utmp) {
699 close(pty_utmp_helper_pipe); /* just let the child process die */
700 pty_utmp_helper_pipe = -1;
702 char *location = get_x_display(pty->frontend);
703 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
705 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
707 perror("pterm: writing to utmp helper process");
708 close(pty_utmp_helper_pipe); /* arrgh, just give up */
709 pty_utmp_helper_pipe = -1;
717 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
718 windowid = get_windowid(pty->frontend);
722 * Fork and execute the command.
736 slavefd = pty_open_slave(pty);
738 perror("slave pty: open");
742 close(pty->master_fd);
743 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
748 ioctl(slavefd, TIOCSCTTY, 1);
750 tcsetpgrp(slavefd, pgrp);
752 close(open(pty->name, O_WRONLY, 0));
754 /* Close everything _else_, for tidiness. */
755 for (i = 3; i < 1024; i++)
758 char term_env_var[10 + sizeof(cfg->termtype)];
759 sprintf(term_env_var, "TERM=%s", cfg->termtype);
760 putenv(term_env_var);
762 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
764 char windowid_env_var[40];
765 sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
766 putenv(windowid_env_var);
770 char *e = cfg->environmt;
771 char *var, *varend, *val, *varval;
774 while (*e && *e != '\t') e++;
781 varval = dupprintf("%.*s=%s", varend-var, var, val);
784 * We must not free varval, since putenv links it
785 * into the environment _in place_. Weird, but
786 * there we go. Memory usage will be rationalised
787 * as soon as we exec anyway.
793 * SIGINT and SIGQUIT may have been set to ignored by our
794 * parent, particularly by things like sh -c 'pterm &' and
795 * some window managers. SIGCHLD, meanwhile, was blocked
796 * during pt_main() startup. Reverse all this for our child
799 putty_signal(SIGINT, SIG_DFL);
800 putty_signal(SIGQUIT, SIG_DFL);
801 block_signal(SIGCHLD, 0);
803 execvp(pty_argv[0], pty_argv);
805 char *shell = getenv("SHELL");
807 if (cfg->login_shell) {
808 char *p = strrchr(shell, '/');
809 shellname = snewn(2+strlen(shell), char);
811 sprintf(shellname, "-%s", p);
814 execl(getenv("SHELL"), shellname, (void *)NULL);
818 * If we're here, exec has gone badly foom.
823 pty->child_pid = pid;
824 pty->child_dead = FALSE;
825 pty->finished = FALSE;
826 if (pty->slave_fd > 0)
827 close(pty->slave_fd);
829 ptys_by_pid = newtree234(pty_compare_by_pid);
830 add234(ptys_by_pid, pty);
833 if (pty_signal_pipe[0] < 0 && pipe(pty_signal_pipe) < 0) {
837 pty_uxsel_setup(pty);
839 *backend_handle = pty;
844 static void pty_reconfig(void *handle, Config *cfg)
846 Pty pty = (Pty)handle;
848 * We don't have much need to reconfigure this backend, but
849 * unfortunately we do need to pick up the setting of Close On
850 * Exit so we know whether to give a `terminated' message.
852 pty->cfg = *cfg; /* structure copy */
856 * Stub routine (never called in pterm).
858 static void pty_free(void *handle)
860 Pty pty = (Pty)handle;
862 /* Either of these may fail `not found'. That's fine with us. */
863 del234(ptys_by_pid, pty);
864 del234(ptys_by_fd, pty);
870 * Called to send data down the pty.
872 static int pty_send(void *handle, char *buf, int len)
874 Pty pty = (Pty)handle;
876 if (pty->master_fd < 0)
877 return 0; /* ignore all writes if fd closed */
880 int ret = write(pty->master_fd, buf, len);
882 perror("write pty master");
891 static void pty_close(Pty pty)
893 if (pty->master_fd >= 0) {
894 close(pty->master_fd);
898 if (pty_utmp_helper_pipe >= 0) {
899 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
900 pty_utmp_helper_pipe = -1;
906 * Called to query the current socket sendability status.
908 static int pty_sendbuffer(void *handle)
910 /* Pty pty = (Pty)handle; */
915 * Called to set the size of the window
917 static void pty_size(void *handle, int width, int height)
919 Pty pty = (Pty)handle;
922 pty->term_width = width;
923 pty->term_height = height;
925 size.ws_row = (unsigned short)pty->term_height;
926 size.ws_col = (unsigned short)pty->term_width;
927 size.ws_xpixel = (unsigned short) pty->term_width *
928 font_dimension(pty->frontend, 0);
929 size.ws_ypixel = (unsigned short) pty->term_height *
930 font_dimension(pty->frontend, 1);
931 ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
936 * Send special codes.
938 static void pty_special(void *handle, Telnet_Special code)
940 /* Pty pty = (Pty)handle; */
946 * Return a list of the special codes that make sense in this
949 static const struct telnet_special *pty_get_specials(void *handle)
951 /* Pty pty = (Pty)handle; */
953 * Hmm. When I get round to having this actually usable, it
954 * might be quite nice to have the ability to deliver a few
955 * well chosen signals to the child process - SIGINT, SIGTERM,
961 static Socket pty_socket(void *handle)
963 /* Pty pty = (Pty)handle; */
964 return NULL; /* shouldn't ever be needed */
967 static int pty_sendok(void *handle)
969 /* Pty pty = (Pty)handle; */
973 static void pty_unthrottle(void *handle, int backlog)
975 /* Pty pty = (Pty)handle; */
979 static int pty_ldisc(void *handle, int option)
981 /* Pty pty = (Pty)handle; */
982 return 0; /* neither editing nor echoing */
985 static void pty_provide_ldisc(void *handle, void *ldisc)
987 /* Pty pty = (Pty)handle; */
988 /* This is a stub. */
991 static void pty_provide_logctx(void *handle, void *logctx)
993 /* Pty pty = (Pty)handle; */
994 /* This is a stub. */
997 static int pty_exitcode(void *handle)
999 Pty pty = (Pty)handle;
1001 return -1; /* not dead yet */
1003 return pty->exit_code;
1006 static int pty_cfg_info(void *handle)
1008 /* Pty pty = (Pty)handle; */
1012 Backend pty_backend = {