2 * Pseudo-tty backend for pterm.
18 #include <sys/types.h>
21 #include <sys/ioctl.h>
38 /* updwtmpx() needs the name of the wtmp file. Try to find it. */
41 #define WTMPX_FILE _PATH_WTMPX
43 #define WTMPX_FILE "/var/log/wtmpx"
49 #define LASTLOG_FILE _PATH_LASTLOG
51 #define LASTLOG_FILE "/var/log/lastlog"
56 * Set up a default for vaguely sane systems. The idea is that if
57 * OMIT_UTMP is not defined, then at least one of the symbols which
58 * enable particular forms of utmp processing should be, if only so
59 * that a link error can warn you that you should have defined
60 * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
61 * the only such symbol.
64 #if !defined HAVE_PUTUTLINE
65 #define HAVE_PUTUTLINE
69 typedef struct pty_tag *Pty;
72 * The pty_signal_pipe, along with the SIGCHLD handler, must be
73 * process-global rather than session-specific.
75 static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
79 int master_fd, slave_fd;
81 char name[FILENAME_MAX];
83 int term_width, term_height;
84 int child_dead, finished;
89 * We store our pty backends in a tree sorted by master fd, so that
90 * when we get an uxsel notification we know which backend instance
91 * is the owner of the pty that caused it.
93 static int pty_compare_by_fd(void *av, void *bv)
98 if (a->master_fd < b->master_fd)
100 else if (a->master_fd > b->master_fd)
105 static int pty_find_by_fd(void *av, void *bv)
110 if (a < b->master_fd)
112 else if (a > b->master_fd)
117 static tree234 *ptys_by_fd = NULL;
120 * We also have a tree sorted by child pid, so that when we wait()
121 * in response to the signal we know which backend instance is the
122 * owner of the process that caused the signal.
124 static int pty_compare_by_pid(void *av, void *bv)
129 if (a->child_pid < b->child_pid)
131 else if (a->child_pid > b->child_pid)
136 static int pty_find_by_pid(void *av, void *bv)
141 if (a < b->child_pid)
143 else if (a > b->child_pid)
148 static tree234 *ptys_by_pid = NULL;
151 * If we are using pty_pre_init(), it will need to have already
152 * allocated a pty structure, which we must then return from
153 * pty_init() rather than allocating a new one. Here we store that
154 * structure between allocation and use.
156 * Note that although most of this module is entirely capable of
157 * handling multiple ptys in a single process, pty_pre_init() is
158 * fundamentally _dependent_ on there being at most one pty per
159 * process, so the normal static-data constraints don't apply.
161 * Likewise, since utmp is only used via pty_pre_init, it too must
162 * be single-instance, so we can declare utmp-related variables
165 static Pty single_pty = NULL;
168 static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
169 static int pty_stamped_utmp;
170 static struct utmpx utmp_entry;
174 * pty_argv is a grievous hack to allow a proper argv to be passed
175 * through from the Unix command line. Again, it doesn't really
176 * make sense outside a one-pty-per-process setup.
180 static void pty_close(Pty pty);
183 static void setup_utmp(char *ttyname, char *location)
186 struct lastlog lastlog_entry;
192 pw = getpwuid(getuid());
193 memset(&utmp_entry, 0, sizeof(utmp_entry));
194 utmp_entry.ut_type = USER_PROCESS;
195 utmp_entry.ut_pid = getpid();
196 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
197 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
198 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
199 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
201 * Apparently there are some architectures where (struct
202 * utmpx).ut_tv is not essentially struct timeval (e.g. Linux
203 * amd64). Hence the temporary.
205 gettimeofday(&tv, NULL);
206 utmp_entry.ut_tv.tv_sec = tv.tv_sec;
207 utmp_entry.ut_tv.tv_usec = tv.tv_usec;
210 pututxline(&utmp_entry);
213 updwtmpx(WTMPX_FILE, &utmp_entry);
216 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
217 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
218 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
219 time(&lastlog_entry.ll_time);
220 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
221 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
222 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
227 pty_stamped_utmp = 1;
231 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));
240 gettimeofday(&tv, NULL);
241 utmp_entry.ut_tv.tv_sec = tv.tv_sec;
242 utmp_entry.ut_tv.tv_usec = tv.tv_usec;
244 updwtmpx(WTMPX_FILE, &utmp_entry);
246 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
247 utmp_entry.ut_tv.tv_sec = 0;
248 utmp_entry.ut_tv.tv_usec = 0;
251 pututxline(&utmp_entry);
254 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
258 static void sigchld_handler(int signum)
260 write(pty_signal_pipe[1], "x", 1);
264 static void fatal_sig_handler(int signum)
266 putty_signal(signum, SIG_DFL);
273 static int pty_open_slave(Pty pty)
275 if (pty->slave_fd < 0)
276 pty->slave_fd = open(pty->name, O_RDWR);
278 return pty->slave_fd;
281 static void pty_open_master(Pty pty)
284 const char chars1[] = "pqrstuvwxyz";
285 const char chars2[] = "0123456789abcdef";
287 char master_name[20];
290 for (p1 = chars1; *p1; p1++)
291 for (p2 = chars2; *p2; p2++) {
292 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
293 pty->master_fd = open(master_name, O_RDWR);
294 if (pty->master_fd >= 0) {
295 if (geteuid() == 0 ||
296 access(master_name, R_OK | W_OK) == 0) {
298 * We must also check at this point that we are
299 * able to open the slave side of the pty. We
300 * wouldn't want to allocate the wrong master,
301 * get all the way down to forking, and _then_
302 * find we're unable to open the slave.
304 strcpy(pty->name, master_name);
305 pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
307 if (pty_open_slave(pty) >= 0 &&
308 access(pty->name, R_OK | W_OK) == 0)
310 if (pty->slave_fd > 0)
311 close(pty->slave_fd);
314 close(pty->master_fd);
318 /* If we get here, we couldn't get a tty at all. */
319 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
324 /* We need to chown/chmod the /dev/ttyXX device. */
325 gp = getgrnam("tty");
326 chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
327 chmod(pty->name, 0600);
329 pty->master_fd = open("/dev/ptmx", O_RDWR);
331 if (pty->master_fd < 0) {
332 perror("/dev/ptmx: open");
336 if (grantpt(pty->master_fd) < 0) {
341 if (unlockpt(pty->master_fd) < 0) {
346 pty->name[FILENAME_MAX-1] = '\0';
347 strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
351 ptys_by_fd = newtree234(pty_compare_by_fd);
352 add234(ptys_by_fd, pty);
356 * Pre-initialisation. This is here to get around the fact that GTK
357 * doesn't like being run in setuid/setgid programs (probably
358 * sensibly). So before we initialise GTK - and therefore before we
359 * even process the command line - we check to see if we're running
360 * set[ug]id. If so, we open our pty master _now_, chown it as
361 * necessary, and drop privileges. We can always close it again
362 * later. If we're potentially going to be doing utmp as well, we
363 * also fork off a utmp helper process and communicate with it by
364 * means of a pipe; the utmp helper will keep privileges in order
365 * to clean up utmp when we exit (i.e. when its end of our pipe
368 void pty_pre_init(void)
377 pty = single_pty = snew(struct pty_tag);
379 /* set the child signal handler straight away; it needs to be set
380 * before we ever fork. */
381 putty_signal(SIGCHLD, sigchld_handler);
382 pty->master_fd = pty->slave_fd = -1;
384 pty_stamped_utmp = FALSE;
387 if (geteuid() != getuid() || getegid() != getgid()) {
388 pty_open_master(pty);
393 * Fork off the utmp helper.
395 if (pipe(pipefd) < 0) {
396 perror("pterm: pipe");
401 perror("pterm: fork");
403 } else if (pid == 0) {
404 char display[128], buffer[128];
409 * Now sit here until we receive a display name from the
410 * other end of the pipe, and then stamp utmp. Unstamp utmp
411 * again, and exit, when the pipe closes.
417 ret = read(pipefd[0], buffer, lenof(buffer));
421 } else if (!pty_stamped_utmp) {
422 if (dlen < lenof(display))
423 memcpy(display+dlen, buffer,
424 min(ret, lenof(display)-dlen));
425 if (buffer[ret-1] == '\0') {
427 * Now we have a display name. NUL-terminate
428 * it, and stamp utmp.
430 display[lenof(display)-1] = '\0';
432 * Trap as many fatal signals as we can in the
433 * hope of having the best possible chance to
434 * clean up utmp before termination. We are
435 * unfortunately unprotected against SIGKILL,
438 putty_signal(SIGHUP, fatal_sig_handler);
439 putty_signal(SIGINT, fatal_sig_handler);
440 putty_signal(SIGQUIT, fatal_sig_handler);
441 putty_signal(SIGILL, fatal_sig_handler);
442 putty_signal(SIGABRT, fatal_sig_handler);
443 putty_signal(SIGFPE, fatal_sig_handler);
444 putty_signal(SIGPIPE, fatal_sig_handler);
445 putty_signal(SIGALRM, fatal_sig_handler);
446 putty_signal(SIGTERM, fatal_sig_handler);
447 putty_signal(SIGSEGV, fatal_sig_handler);
448 putty_signal(SIGUSR1, fatal_sig_handler);
449 putty_signal(SIGUSR2, fatal_sig_handler);
451 putty_signal(SIGBUS, fatal_sig_handler);
454 putty_signal(SIGPOLL, fatal_sig_handler);
457 putty_signal(SIGPROF, fatal_sig_handler);
460 putty_signal(SIGSYS, fatal_sig_handler);
463 putty_signal(SIGTRAP, fatal_sig_handler);
466 putty_signal(SIGVTALRM, fatal_sig_handler);
469 putty_signal(SIGXCPU, fatal_sig_handler);
472 putty_signal(SIGXFSZ, fatal_sig_handler);
475 putty_signal(SIGIO, fatal_sig_handler);
477 setup_utmp(pty->name, display);
483 pty_utmp_helper_pid = pid;
484 pty_utmp_helper_pipe = pipefd[1];
490 #ifndef HAVE_NO_SETRESUID
491 int gid = getgid(), uid = getuid();
492 int setresgid(gid_t, gid_t, gid_t);
493 int setresuid(uid_t, uid_t, uid_t);
494 setresgid(gid, gid, gid);
495 setresuid(uid, uid, uid);
503 int pty_real_select_result(Pty pty, int event, int status)
507 int finished = FALSE;
511 * We've been called because our child process did
512 * something. `status' tells us what.
514 if ((WIFEXITED(status) || WIFSIGNALED(status))) {
516 * The primary child process died. We could keep
517 * the terminal open for remaining subprocesses to
518 * output to, but conventional wisdom seems to feel
519 * that that's the Wrong Thing for an xterm-alike,
520 * so we bail out now (though we don't necessarily
521 * _close_ the window, depending on the state of
522 * Close On Exit). This would be easy enough to
523 * change or make configurable if necessary.
525 pty->exit_code = status;
526 pty->child_dead = TRUE;
527 del234(ptys_by_pid, pty);
533 ret = read(pty->master_fd, buf, sizeof(buf));
536 * Clean termination condition is that either ret == 0, or ret
537 * < 0 and errno == EIO. Not sure why the latter, but it seems
540 if (ret == 0 || (ret < 0 && errno == EIO)) {
542 * We assume a clean exit if the pty has closed but the
543 * actual child process hasn't. The only way I can
544 * imagine this happening is if it detaches itself from
545 * the pty and goes daemonic - in which case the
546 * expected usage model would precisely _not_ be for
547 * the pterm window to hang around!
550 if (!pty->child_dead)
552 } else if (ret < 0) {
553 perror("read pty master");
555 } else if (ret > 0) {
556 from_backend(pty->frontend, 0, buf, ret);
561 if (finished && !pty->finished) {
562 uxsel_del(pty->master_fd);
566 pty->finished = TRUE;
569 * This is a slight layering-violation sort of hack: only
570 * if we're not closing on exit (COE is set to Never, or to
571 * Only On Clean and it wasn't a clean exit) do we output a
572 * `terminated' message.
574 if (pty->cfg.close_on_exit == FORCE_OFF ||
575 (pty->cfg.close_on_exit == AUTO && pty->exit_code != 0)) {
577 if (WIFEXITED(pty->exit_code))
578 sprintf(message, "\r\n[pterm: process terminated with exit"
579 " code %d]\r\n", WEXITSTATUS(pty->exit_code));
580 else if (WIFSIGNALED(pty->exit_code))
581 #ifdef HAVE_NO_STRSIGNAL
582 sprintf(message, "\r\n[pterm: process terminated on signal"
583 " %d]\r\n", WTERMSIG(pty->exit_code));
585 sprintf(message, "\r\n[pterm: process terminated on signal"
586 " %d (%.400s)]\r\n", WTERMSIG(pty->exit_code),
587 strsignal(WTERMSIG(pty->exit_code)));
589 from_backend(pty->frontend, 0, message, strlen(message));
592 notify_remote_exit(pty->frontend);
598 int pty_select_result(int fd, int event)
603 if (fd == pty_signal_pipe[0]) {
609 read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
612 pid = waitpid(-1, &status, WNOHANG);
615 pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
618 ret = ret && pty_real_select_result(pty, -1, status);
621 pty = find234(ptys_by_fd, &fd, pty_find_by_fd);
624 ret = ret && pty_real_select_result(pty, event, 0);
630 static void pty_uxsel_setup(Pty pty)
632 uxsel_set(pty->master_fd, 1, pty_select_result);
635 * In principle this only needs calling once for all pty
636 * backend instances, but it's simplest just to call it every
637 * time; uxsel won't mind.
639 uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
643 * Called to set up the pty.
645 * Returns an error message, or NULL on success.
647 * Also places the canonical host name into `realhost'. It must be
648 * freed by the caller.
650 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
651 char *host, int port, char **realhost, int nodelay,
656 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
664 pty = snew(struct pty_tag);
665 pty->master_fd = pty->slave_fd = -1;
667 pty_stamped_utmp = FALSE;
671 pty->frontend = frontend;
672 *backend_handle = NULL; /* we can't sensibly use this, sadly */
674 pty->cfg = *cfg; /* structure copy */
675 pty->term_width = cfg->width;
676 pty->term_height = cfg->height;
678 if (pty->master_fd < 0)
679 pty_open_master(pty);
682 * Set the backspace character to be whichever of ^H and ^? is
683 * specified by bksp_is_delete.
686 struct termios attrs;
687 tcgetattr(pty->master_fd, &attrs);
688 attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
689 tcsetattr(pty->master_fd, TCSANOW, &attrs);
694 * Stamp utmp (that is, tell the utmp helper process to do so),
697 if (!cfg->stamp_utmp) {
698 close(pty_utmp_helper_pipe); /* just let the child process die */
699 pty_utmp_helper_pipe = -1;
701 char *location = get_x_display(pty->frontend);
702 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
704 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
706 perror("pterm: writing to utmp helper process");
707 close(pty_utmp_helper_pipe); /* arrgh, just give up */
708 pty_utmp_helper_pipe = -1;
716 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
717 windowid = get_windowid(pty->frontend);
721 * Fork and execute the command.
735 slavefd = pty_open_slave(pty);
737 perror("slave pty: open");
741 close(pty->master_fd);
742 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
747 ioctl(slavefd, TIOCSCTTY, 1);
749 tcsetpgrp(slavefd, pgrp);
751 close(open(pty->name, O_WRONLY, 0));
753 /* Close everything _else_, for tidiness. */
754 for (i = 3; i < 1024; i++)
757 char term_env_var[10 + sizeof(cfg->termtype)];
758 sprintf(term_env_var, "TERM=%s", cfg->termtype);
759 putenv(term_env_var);
761 #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
763 char windowid_env_var[40];
764 sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
765 putenv(windowid_env_var);
769 char *e = cfg->environmt;
770 char *var, *varend, *val, *varval;
773 while (*e && *e != '\t') e++;
780 varval = dupprintf("%.*s=%s", varend-var, var, val);
783 * We must not free varval, since putenv links it
784 * into the environment _in place_. Weird, but
785 * there we go. Memory usage will be rationalised
786 * as soon as we exec anyway.
792 * SIGINT and SIGQUIT may have been set to ignored by our
793 * parent, particularly by things like sh -c 'pterm &' and
794 * some window managers. SIGCHLD, meanwhile, was blocked
795 * during pt_main() startup. Reverse all this for our child
798 putty_signal(SIGINT, SIG_DFL);
799 putty_signal(SIGQUIT, SIG_DFL);
800 block_signal(SIGCHLD, 0);
802 execvp(pty_argv[0], pty_argv);
804 char *shell = getenv("SHELL");
806 if (cfg->login_shell) {
807 char *p = strrchr(shell, '/');
808 shellname = snewn(2+strlen(shell), char);
810 sprintf(shellname, "-%s", p);
813 execl(getenv("SHELL"), shellname, (void *)NULL);
817 * If we're here, exec has gone badly foom.
822 pty->child_pid = pid;
823 pty->child_dead = FALSE;
824 pty->finished = FALSE;
825 if (pty->slave_fd > 0)
826 close(pty->slave_fd);
828 ptys_by_pid = newtree234(pty_compare_by_pid);
829 add234(ptys_by_pid, pty);
832 if (pty_signal_pipe[0] < 0 && pipe(pty_signal_pipe) < 0) {
836 pty_uxsel_setup(pty);
838 *backend_handle = pty;
843 static void pty_reconfig(void *handle, Config *cfg)
845 Pty pty = (Pty)handle;
847 * We don't have much need to reconfigure this backend, but
848 * unfortunately we do need to pick up the setting of Close On
849 * Exit so we know whether to give a `terminated' message.
851 pty->cfg = *cfg; /* structure copy */
855 * Stub routine (never called in pterm).
857 static void pty_free(void *handle)
859 Pty pty = (Pty)handle;
861 /* Either of these may fail `not found'. That's fine with us. */
862 del234(ptys_by_pid, pty);
863 del234(ptys_by_fd, pty);
869 * Called to send data down the pty.
871 static int pty_send(void *handle, char *buf, int len)
873 Pty pty = (Pty)handle;
875 if (pty->master_fd < 0)
876 return 0; /* ignore all writes if fd closed */
879 int ret = write(pty->master_fd, buf, len);
881 perror("write pty master");
890 static void pty_close(Pty pty)
892 if (pty->master_fd >= 0) {
893 close(pty->master_fd);
897 if (pty_utmp_helper_pipe >= 0) {
898 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
899 pty_utmp_helper_pipe = -1;
905 * Called to query the current socket sendability status.
907 static int pty_sendbuffer(void *handle)
909 /* Pty pty = (Pty)handle; */
914 * Called to set the size of the window
916 static void pty_size(void *handle, int width, int height)
918 Pty pty = (Pty)handle;
921 pty->term_width = width;
922 pty->term_height = height;
924 size.ws_row = (unsigned short)pty->term_height;
925 size.ws_col = (unsigned short)pty->term_width;
926 size.ws_xpixel = (unsigned short) pty->term_width *
927 font_dimension(pty->frontend, 0);
928 size.ws_ypixel = (unsigned short) pty->term_height *
929 font_dimension(pty->frontend, 1);
930 ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
935 * Send special codes.
937 static void pty_special(void *handle, Telnet_Special code)
939 /* Pty pty = (Pty)handle; */
945 * Return a list of the special codes that make sense in this
948 static const struct telnet_special *pty_get_specials(void *handle)
950 /* Pty pty = (Pty)handle; */
952 * Hmm. When I get round to having this actually usable, it
953 * might be quite nice to have the ability to deliver a few
954 * well chosen signals to the child process - SIGINT, SIGTERM,
960 static Socket pty_socket(void *handle)
962 /* Pty pty = (Pty)handle; */
963 return NULL; /* shouldn't ever be needed */
966 static int pty_sendok(void *handle)
968 /* Pty pty = (Pty)handle; */
972 static void pty_unthrottle(void *handle, int backlog)
974 /* Pty pty = (Pty)handle; */
978 static int pty_ldisc(void *handle, int option)
980 /* Pty pty = (Pty)handle; */
981 return 0; /* neither editing nor echoing */
984 static void pty_provide_ldisc(void *handle, void *ldisc)
986 /* Pty pty = (Pty)handle; */
987 /* This is a stub. */
990 static void pty_provide_logctx(void *handle, void *logctx)
992 /* Pty pty = (Pty)handle; */
993 /* This is a stub. */
996 static int pty_exitcode(void *handle)
998 Pty pty = (Pty)handle;
1000 return -1; /* not dead yet */
1002 return pty->exit_code;
1005 static int pty_cfg_info(void *handle)
1007 /* Pty pty = (Pty)handle; */
1011 Backend pty_backend = {