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