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