Oops; remembering to call term_provide_resize_fn in the Unix front
[u/mdw/putty] / unix / pty.c
CommitLineData
28d00fe4 1/*
2 * Pseudo-tty backend for pterm.
3 *
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.
12 */
13
054d8535 14#define _XOPEN_SOURCE
88e6b9ca 15#define _XOPEN_SOURCE_EXTENDED
054d8535 16#include <features.h>
17
1709795f 18#include <stdio.h>
19#include <stdlib.h>
054d8535 20#include <string.h>
21#include <unistd.h>
a0e16eb1 22#include <signal.h>
054d8535 23#include <fcntl.h>
88e6b9ca 24#include <termios.h>
be4f86de 25#include <grp.h>
755a6d84 26#include <utmp.h>
27#include <pwd.h>
28#include <time.h>
a0e16eb1 29#include <sys/types.h>
30#include <sys/wait.h>
88e6b9ca 31#include <sys/ioctl.h>
1709795f 32
33#include "putty.h"
34
35#ifndef FALSE
36#define FALSE 0
37#endif
38#ifndef TRUE
39#define TRUE 1
40#endif
41
755a6d84 42#ifndef UTMP_FILE
43#define UTMP_FILE "/var/run/utmp"
44#endif
45#ifndef WTMP_FILE
46#define WTMP_FILE "/var/log/wtmp"
47#endif
48#ifndef LASTLOG_FILE
49#ifdef _PATH_LASTLOG
50#define LASTLOG_FILE _PATH_LASTLOG
51#else
52#define LASTLOG_FILE "/var/log/lastlog"
53#endif
54#endif
55
f51dc031 56/*
57 * Set up a default for vaguely sane systems. The idea is that if
58 * OMIT_UTMP is not defined, then at least one of the symbols which
59 * enable particular forms of utmp processing should be, if only so
60 * that a link error can warn you that you should have defined
61 * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
62 * the only such symbol.
63 */
64#ifndef OMIT_UTMP
65#if !defined HAVE_PUTUTLINE
66#define HAVE_PUTUTLINE
67#endif
68#endif
69
054d8535 70int pty_master_fd;
95c47834 71static char pty_name[FILENAME_MAX];
f51dc031 72static int pty_stamped_utmp = 0;
a0e16eb1 73static int pty_child_pid;
95c47834 74static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
f278d6f8 75static int pty_term_width, pty_term_height;
a0e16eb1 76static sig_atomic_t pty_child_dead;
90cfd8f4 77static int pty_exit_code;
755a6d84 78#ifndef OMIT_UTMP
79static struct utmp utmp_entry;
80#endif
6169c758 81char **pty_argv;
054d8535 82
95c47834 83static void setup_utmp(char *ttyname, char *location)
755a6d84 84{
85#ifndef OMIT_UTMP
86#ifdef HAVE_LASTLOG
87 struct lastlog lastlog_entry;
88 FILE *lastlog;
89#endif
90 struct passwd *pw;
755a6d84 91 FILE *wtmp;
92
93 pw = getpwuid(getuid());
94 memset(&utmp_entry, 0, sizeof(utmp_entry));
95 utmp_entry.ut_type = USER_PROCESS;
96 utmp_entry.ut_pid = getpid();
97 strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
98 strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
99 strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
100 strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
101 time(&utmp_entry.ut_time);
102
103#if defined HAVE_PUTUTLINE
104 utmpname(UTMP_FILE);
105 setutent();
106 pututline(&utmp_entry);
107 endutent();
108#endif
109
110 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
111 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
112 fclose(wtmp);
113 }
114
115#ifdef HAVE_LASTLOG
116 memset(&lastlog_entry, 0, sizeof(lastlog_entry));
117 strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
118 strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
119 time(&lastlog_entry.ll_time);
120 if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
121 fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
122 fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
123 fclose(lastlog);
124 }
125#endif
126
f51dc031 127 pty_stamped_utmp = 1;
128
755a6d84 129#endif
130}
131
132static void cleanup_utmp(void)
133{
134#ifndef OMIT_UTMP
135 FILE *wtmp;
136
95c47834 137 if (!pty_stamped_utmp)
f51dc031 138 return;
139
755a6d84 140 utmp_entry.ut_type = DEAD_PROCESS;
141 memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
142 time(&utmp_entry.ut_time);
143
144 if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
145 fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
146 fclose(wtmp);
147 }
148
149 memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
150 utmp_entry.ut_time = 0;
151
152#if defined HAVE_PUTUTLINE
153 utmpname(UTMP_FILE);
154 setutent();
155 pututline(&utmp_entry);
156 endutent();
157#endif
158
f51dc031 159 pty_stamped_utmp = 0; /* ensure we never double-cleanup */
755a6d84 160#endif
161}
162
a0e16eb1 163static void sigchld_handler(int signum)
164{
165 pid_t pid;
166 int status;
167 pid = waitpid(-1, &status, WNOHANG);
90cfd8f4 168 if (pid == pty_child_pid && (WIFEXITED(status) || WIFSIGNALED(status))) {
169 pty_exit_code = status;
170 pty_child_dead = TRUE;
171 }
a0e16eb1 172}
173
755a6d84 174static void fatal_sig_handler(int signum)
175{
176 signal(signum, SIG_DFL);
177 cleanup_utmp();
178 setuid(getuid());
179 raise(signum);
180}
181
95c47834 182static void pty_open_master(void)
1709795f 183{
be4f86de 184#ifdef BSD_PTYS
95c47834 185 const char chars1[] = "pqrstuvwxyz";
186 const char chars2[] = "0123456789abcdef";
187 const char *p1, *p2;
188 char master_name[20];
189 struct group *gp;
190
191 for (p1 = chars1; *p1; p1++)
192 for (p2 = chars2; *p2; p2++) {
193 sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
194 pty_master_fd = open(master_name, O_RDWR);
195 if (pty_master_fd >= 0) {
196 if (geteuid() == 0 ||
197 access(master_name, R_OK | W_OK) == 0)
198 goto got_one;
199 close(pty_master_fd);
be4f86de 200 }
95c47834 201 }
be4f86de 202
95c47834 203 /* If we get here, we couldn't get a tty at all. */
204 fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
205 exit(1);
be4f86de 206
95c47834 207 got_one:
208 strcpy(pty_name, master_name);
209 pty_name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
210
211 /* We need to chown/chmod the /dev/ttyXX device. */
212 gp = getgrnam("tty");
213 chown(pty_name, getuid(), gp ? gp->gr_gid : -1);
214 chmod(pty_name, 0600);
be4f86de 215#else
054d8535 216 pty_master_fd = open("/dev/ptmx", O_RDWR);
217
218 if (pty_master_fd < 0) {
219 perror("/dev/ptmx: open");
220 exit(1);
221 }
222
223 if (grantpt(pty_master_fd) < 0) {
224 perror("grantpt");
225 exit(1);
226 }
227
228 if (unlockpt(pty_master_fd) < 0) {
229 perror("unlockpt");
230 exit(1);
231 }
232
95c47834 233 pty_name[FILENAME_MAX-1] = '\0';
234 strncpy(pty_name, ptsname(pty_master_fd), FILENAME_MAX-1);
be4f86de 235#endif
95c47834 236}
054d8535 237
95c47834 238/*
239 * Pre-initialisation. This is here to get around the fact that GTK
240 * doesn't like being run in setuid/setgid programs (probably
241 * sensibly). So before we initialise GTK - and therefore before we
242 * even process the command line - we check to see if we're running
243 * set[ug]id. If so, we open our pty master _now_, chown it as
244 * necessary, and drop privileges. We can always close it again
245 * later. If we're potentially going to be doing utmp as well, we
246 * also fork off a utmp helper process and communicate with it by
247 * means of a pipe; the utmp helper will keep privileges in order
248 * to clean up utmp when we exit (i.e. when its end of our pipe
249 * closes).
250 */
251void pty_pre_init(void)
252{
253 pid_t pid;
254 int pipefd[2];
255
256 pty_master_fd = -1;
257
258 if (geteuid() != getuid() || getegid() != getgid()) {
259 pty_open_master();
39baeaa4 260 }
261
95c47834 262#ifndef OMIT_UTMP
39baeaa4 263 /*
95c47834 264 * Fork off the utmp helper.
755a6d84 265 */
95c47834 266 if (pipe(pipefd) < 0) {
267 perror("pterm: pipe");
268 exit(1);
269 }
270 pid = fork();
271 if (pid < 0) {
272 perror("pterm: fork");
273 exit(1);
274 } else if (pid == 0) {
275 char display[128], buffer[128];
276 int dlen, ret;
277
278 close(pipefd[1]);
279 /*
280 * Now sit here until we receive a display name from the
281 * other end of the pipe, and then stamp utmp. Unstamp utmp
282 * again, and exit, when the pipe closes.
283 */
284
285 dlen = 0;
286 while (1) {
287
288 ret = read(pipefd[0], buffer, lenof(buffer));
289 if (ret <= 0) {
290 cleanup_utmp();
291 exit(0);
292 } else if (!pty_stamped_utmp) {
293 if (dlen < lenof(display))
294 memcpy(display+dlen, buffer,
295 min(ret, lenof(display)-dlen));
296 if (buffer[ret-1] == '\0') {
297 /*
298 * Now we have a display name. NUL-terminate
299 * it, and stamp utmp.
300 */
301 display[lenof(display)-1] = '\0';
302 /*
303 * Trap as many fatal signals as we can in the
304 * hope of having the best possible chance to
305 * clean up utmp before termination. We are
306 * unfortunately unprotected against SIGKILL,
307 * but that's life.
308 */
309 signal(SIGHUP, fatal_sig_handler);
310 signal(SIGINT, fatal_sig_handler);
311 signal(SIGQUIT, fatal_sig_handler);
312 signal(SIGILL, fatal_sig_handler);
313 signal(SIGABRT, fatal_sig_handler);
314 signal(SIGFPE, fatal_sig_handler);
315 signal(SIGPIPE, fatal_sig_handler);
316 signal(SIGALRM, fatal_sig_handler);
317 signal(SIGTERM, fatal_sig_handler);
318 signal(SIGSEGV, fatal_sig_handler);
319 signal(SIGUSR1, fatal_sig_handler);
320 signal(SIGUSR2, fatal_sig_handler);
755a6d84 321#ifdef SIGBUS
95c47834 322 signal(SIGBUS, fatal_sig_handler);
755a6d84 323#endif
324#ifdef SIGPOLL
95c47834 325 signal(SIGPOLL, fatal_sig_handler);
755a6d84 326#endif
327#ifdef SIGPROF
95c47834 328 signal(SIGPROF, fatal_sig_handler);
755a6d84 329#endif
330#ifdef SIGSYS
95c47834 331 signal(SIGSYS, fatal_sig_handler);
755a6d84 332#endif
333#ifdef SIGTRAP
95c47834 334 signal(SIGTRAP, fatal_sig_handler);
755a6d84 335#endif
336#ifdef SIGVTALRM
95c47834 337 signal(SIGVTALRM, fatal_sig_handler);
755a6d84 338#endif
339#ifdef SIGXCPU
95c47834 340 signal(SIGXCPU, fatal_sig_handler);
755a6d84 341#endif
342#ifdef SIGXFSZ
95c47834 343 signal(SIGXFSZ, fatal_sig_handler);
755a6d84 344#endif
345#ifdef SIGIO
95c47834 346 signal(SIGIO, fatal_sig_handler);
347#endif
348 /* Also clean up utmp on normal exit. */
349 atexit(cleanup_utmp);
350 setup_utmp(pty_name, display);
351 }
352 }
353 }
354 } else {
355 close(pipefd[0]);
356 pty_utmp_helper_pid = pid;
357 pty_utmp_helper_pipe = pipefd[1];
2747574c 358 signal(SIGCHLD, sigchld_handler);
95c47834 359 }
755a6d84 360#endif
95c47834 361
362 /* Drop privs. */
363 {
364 int gid = getgid(), uid = getuid();
365#ifndef HAVE_NO_SETRESUID
366 int setresgid(gid_t, gid_t, gid_t);
367 int setresuid(uid_t, uid_t, uid_t);
368 setresgid(gid, gid, gid);
369 setresuid(uid, uid, uid);
370#else
371 setgid(getgid());
372 setuid(getuid());
373#endif
374 }
375}
376
377/*
378 * Called to set up the pty.
379 *
380 * Returns an error message, or NULL on success.
381 *
382 * Also places the canonical host name into `realhost'. It must be
383 * freed by the caller.
384 */
28d00fe4 385static char *pty_init(void *frontend, void **backend_handle,
887035a5 386 char *host, int port, char **realhost, int nodelay)
95c47834 387{
388 int slavefd;
389 pid_t pid, pgrp;
390
28d00fe4 391 *backend_handle = NULL; /* we can't sensibly use this, sadly */
392
f278d6f8 393 pty_term_width = cfg.width;
394 pty_term_height = cfg.height;
395
95c47834 396 if (pty_master_fd < 0)
397 pty_open_master();
398
399 /*
400 * Set the backspace character to be whichever of ^H and ^? is
401 * specified by bksp_is_delete.
402 */
403 {
404 struct termios attrs;
405 tcgetattr(pty_master_fd, &attrs);
406 attrs.c_cc[VERASE] = cfg.bksp_is_delete ? '\177' : '\010';
407 tcsetattr(pty_master_fd, TCSANOW, &attrs);
408 }
409
410 /*
411 * Stamp utmp (that is, tell the utmp helper process to do so),
412 * or not.
413 */
414 if (!cfg.stamp_utmp)
415 close(pty_utmp_helper_pipe); /* just let the child process die */
416 else {
417 char *location = get_x_display();
418 int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
419 while (pos < len) {
420 int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
421 if (ret < 0) {
422 perror("pterm: writing to utmp helper process");
423 close(pty_utmp_helper_pipe); /* arrgh, just give up */
424 break;
425 }
426 pos += ret;
427 }
428 }
755a6d84 429
430 /*
054d8535 431 * Fork and execute the command.
432 */
433 pid = fork();
434 if (pid < 0) {
435 perror("fork");
88e6b9ca 436 exit(1);
054d8535 437 }
438
439 if (pid == 0) {
440 int i;
441 /*
442 * We are the child.
443 */
d37c2d81 444
95c47834 445 slavefd = open(pty_name, O_RDWR);
d37c2d81 446 if (slavefd < 0) {
447 perror("slave pty: open");
448 exit(1);
449 }
450
054d8535 451 close(pty_master_fd);
054d8535 452 fcntl(slavefd, F_SETFD, 0); /* don't close on exec */
453 dup2(slavefd, 0);
454 dup2(slavefd, 1);
455 dup2(slavefd, 2);
456 setsid();
d37c2d81 457 ioctl(slavefd, TIOCSCTTY, 1);
458 pgrp = getpid();
459 tcsetpgrp(slavefd, pgrp);
460 setpgrp();
95c47834 461 close(open(pty_name, O_WRONLY, 0));
054d8535 462 setpgrp();
054d8535 463 /* Close everything _else_, for tidiness. */
464 for (i = 3; i < 1024; i++)
465 close(i);
fe9548aa 466 {
467 char term_env_var[10 + sizeof(cfg.termtype)];
468 sprintf(term_env_var, "TERM=%s", cfg.termtype);
469 putenv(term_env_var);
470 }
8bf5c419 471 /*
472 * SIGINT and SIGQUIT may have been set to ignored by our
473 * parent, particularly by things like sh -c 'pterm &' and
474 * some window managers. Reverse this for our child process.
475 */
476 signal(SIGINT, SIG_DFL);
477 signal(SIGQUIT, SIG_DFL);
6169c758 478 if (pty_argv)
479 execvp(pty_argv[0], pty_argv);
c8ee61b9 480 else {
481 char *shell = getenv("SHELL");
482 char *shellname;
483 if (cfg.login_shell) {
484 char *p = strrchr(shell, '/');
485 shellname = smalloc(2+strlen(shell));
486 p = p ? p+1 : shell;
487 sprintf(shellname, "-%s", p);
488 } else
489 shellname = shell;
490 execl(getenv("SHELL"), shellname, NULL);
491 }
492
054d8535 493 /*
494 * If we're here, exec has gone badly foom.
495 */
496 perror("exec");
497 exit(127);
498 } else {
499 close(slavefd);
a0e16eb1 500 pty_child_pid = pid;
501 pty_child_dead = FALSE;
502 signal(SIGCHLD, sigchld_handler);
054d8535 503 }
504
1709795f 505 return NULL;
506}
507
508/*
509 * Called to send data down the pty.
510 */
28d00fe4 511static int pty_send(void *handle, char *buf, int len)
1709795f 512{
90cfd8f4 513 if (pty_master_fd < 0)
514 return 0; /* ignore all writes if fd closed */
515
054d8535 516 while (len > 0) {
517 int ret = write(pty_master_fd, buf, len);
518 if (ret < 0) {
519 perror("write pty master");
520 exit(1);
521 }
522 buf += ret;
523 len -= ret;
524 }
1709795f 525 return 0;
526}
527
90cfd8f4 528void pty_close(void)
529{
530 if (pty_master_fd >= 0) {
531 close(pty_master_fd);
532 pty_master_fd = -1;
533 }
534 close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
535}
536
1709795f 537/*
538 * Called to query the current socket sendability status.
539 */
28d00fe4 540static int pty_sendbuffer(void *handle)
1709795f 541{
542 return 0;
543}
544
545/*
546 * Called to set the size of the window
547 */
28d00fe4 548static void pty_size(void *handle, int width, int height)
1709795f 549{
88e6b9ca 550 struct winsize size;
551
f278d6f8 552 pty_term_width = width;
553 pty_term_height = height;
554
555 size.ws_row = (unsigned short)pty_term_height;
556 size.ws_col = (unsigned short)pty_term_width;
557 size.ws_xpixel = (unsigned short) pty_term_width * font_dimension(0);
558 size.ws_ypixel = (unsigned short) pty_term_height * font_dimension(1);
88e6b9ca 559 ioctl(pty_master_fd, TIOCSWINSZ, (void *)&size);
1709795f 560 return;
561}
562
563/*
564 * Send special codes.
565 */
28d00fe4 566static void pty_special(void *handle, Telnet_Special code)
1709795f 567{
568 /* Do nothing! */
569 return;
570}
571
28d00fe4 572static Socket pty_socket(void *handle)
1709795f 573{
574 return NULL; /* shouldn't ever be needed */
575}
576
28d00fe4 577static int pty_sendok(void *handle)
1709795f 578{
579 return 1;
580}
581
28d00fe4 582static void pty_unthrottle(void *handle, int backlog)
1709795f 583{
584 /* do nothing */
585}
586
28d00fe4 587static int pty_ldisc(void *handle, int option)
1709795f 588{
589 return 0; /* neither editing nor echoing */
590}
591
28d00fe4 592static int pty_exitcode(void *handle)
1709795f 593{
90cfd8f4 594 if (!pty_child_dead)
595 return -1; /* not dead yet */
596 else
597 return pty_exit_code;
1709795f 598}
599
600Backend pty_backend = {
601 pty_init,
602 pty_send,
603 pty_sendbuffer,
604 pty_size,
605 pty_special,
606 pty_socket,
607 pty_exitcode,
608 pty_sendok,
609 pty_ldisc,
610 pty_unthrottle,
611 1
612};