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