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