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