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