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