]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/pty.c
027e13910510c6587256b8bcf7c92e3eabe6031c
[PuTTY.git] / 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 sig_atomic_t pty_child_dead;
63 #ifndef OMIT_UTMP
64 static struct utmp utmp_entry;
65 #endif
66 char **pty_argv;
67
68 int pty_child_is_dead(void)
69 {
70     return pty_child_dead;
71 }
72
73 static void pty_size(void);
74
75 static void setup_utmp(char *ttyname, char *location)
76 {
77 #ifndef OMIT_UTMP
78 #ifdef HAVE_LASTLOG
79     struct lastlog lastlog_entry;
80     FILE *lastlog;
81 #endif
82     struct passwd *pw;
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
119     pty_stamped_utmp = 1;
120
121 #endif
122 }
123
124 static void cleanup_utmp(void)
125 {
126 #ifndef OMIT_UTMP
127     FILE *wtmp;
128
129     if (!pty_stamped_utmp)
130         return;
131
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
151     pty_stamped_utmp = 0;              /* ensure we never double-cleanup */
152 #endif
153 }
154
155 static 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
164 static void fatal_sig_handler(int signum)
165 {
166     signal(signum, SIG_DFL);
167     cleanup_utmp();
168     setuid(getuid());
169     raise(signum);
170 }
171
172 static void pty_open_master(void)
173 {
174 #ifdef BSD_PTYS
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);
190             }
191         }
192
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);
196
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);
205 #else
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
223     pty_name[FILENAME_MAX-1] = '\0';
224     strncpy(pty_name, ptsname(pty_master_fd), FILENAME_MAX-1);
225 #endif
226 }
227
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  */
241 void 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();
250     }
251
252 #ifndef OMIT_UTMP
253     /*
254      * Fork off the utmp helper.
255      */
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);
311 #ifdef SIGBUS
312                     signal(SIGBUS, fatal_sig_handler);
313 #endif
314 #ifdef SIGPOLL
315                     signal(SIGPOLL, fatal_sig_handler);
316 #endif
317 #ifdef SIGPROF
318                     signal(SIGPROF, fatal_sig_handler);
319 #endif
320 #ifdef SIGSYS
321                     signal(SIGSYS, fatal_sig_handler);
322 #endif
323 #ifdef SIGTRAP
324                     signal(SIGTRAP, fatal_sig_handler);
325 #endif
326 #ifdef SIGVTALRM
327                     signal(SIGVTALRM, fatal_sig_handler);
328 #endif
329 #ifdef SIGXCPU
330                     signal(SIGXCPU, fatal_sig_handler);
331 #endif
332 #ifdef SIGXFSZ
333                     signal(SIGXFSZ, fatal_sig_handler);
334 #endif
335 #ifdef SIGIO
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     }
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(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     }
412
413     /*
414      * Fork and execute the command.
415      */
416     pid = fork();
417     if (pid < 0) {
418         perror("fork");
419         exit(1);
420     }
421
422     if (pid == 0) {
423         int i;
424         /*
425          * We are the child.
426          */
427
428         slavefd = open(pty_name, O_RDWR);
429         if (slavefd < 0) {
430             perror("slave pty: open");
431             exit(1);
432         }
433
434         close(pty_master_fd);
435         close(0);
436         close(1);
437         close(2);
438         fcntl(slavefd, F_SETFD, 0);    /* don't close on exec */
439         dup2(slavefd, 0);
440         dup2(slavefd, 1);
441         dup2(slavefd, 2);
442         setsid();
443         ioctl(slavefd, TIOCSCTTY, 1);
444         pgrp = getpid();
445         tcsetpgrp(slavefd, pgrp);
446         setpgrp();
447         close(open(pty_name, O_WRONLY, 0));
448         setpgrp();
449         /* Close everything _else_, for tidiness. */
450         for (i = 3; i < 1024; i++)
451             close(i);
452         {
453             char term_env_var[10 + sizeof(cfg.termtype)];
454             sprintf(term_env_var, "TERM=%s", cfg.termtype);
455             putenv(term_env_var);
456         }
457         if (pty_argv)
458             execvp(pty_argv[0], pty_argv);
459         else {
460             char *shell = getenv("SHELL");
461             char *shellname;
462             if (cfg.login_shell) {
463                 char *p = strrchr(shell, '/');
464                 shellname = smalloc(2+strlen(shell));
465                 p = p ? p+1 : shell;
466                 sprintf(shellname, "-%s", p);
467             } else
468                 shellname = shell;
469             execl(getenv("SHELL"), shellname, NULL);
470         }
471
472         /*
473          * If we're here, exec has gone badly foom.
474          */
475         perror("exec");
476         exit(127);
477     } else {
478         close(slavefd);
479         pty_child_pid = pid;
480         pty_child_dead = FALSE;
481         signal(SIGCHLD, sigchld_handler);
482     }
483
484     return NULL;
485 }
486
487 /*
488  * Called to send data down the pty.
489  */
490 static int pty_send(char *buf, int len)
491 {
492     while (len > 0) {
493         int ret = write(pty_master_fd, buf, len);
494         if (ret < 0) {
495             perror("write pty master");
496             exit(1);
497         }
498         buf += ret;
499         len -= ret;
500     }
501     return 0;
502 }
503
504 /*
505  * Called to query the current socket sendability status.
506  */
507 static int pty_sendbuffer(void)
508 {
509     return 0;
510 }
511
512 /*
513  * Called to set the size of the window
514  */
515 static void pty_size(void)
516 {
517     struct winsize size;
518
519     size.ws_row = (unsigned short)rows;
520     size.ws_col = (unsigned short)cols;
521     size.ws_xpixel = (unsigned short) cols * font_dimension(0);
522     size.ws_ypixel = (unsigned short) rows * font_dimension(1);
523     ioctl(pty_master_fd, TIOCSWINSZ, (void *)&size);
524     return;
525 }
526
527 /*
528  * Send special codes.
529  */
530 static void pty_special(Telnet_Special code)
531 {
532     /* Do nothing! */
533     return;
534 }
535
536 static Socket pty_socket(void)
537 {
538     return NULL;                       /* shouldn't ever be needed */
539 }
540
541 static int pty_sendok(void)
542 {
543     return 1;
544 }
545
546 static void pty_unthrottle(int backlog)
547 {
548     /* do nothing */
549 }
550
551 static int pty_ldisc(int option)
552 {
553     return 0;                          /* neither editing nor echoing */
554 }
555
556 static int pty_exitcode(void)
557 {
558     /* Shouldn't ever be required */
559     return 0;
560 }
561
562 Backend pty_backend = {
563     pty_init,
564     pty_send,
565     pty_sendbuffer,
566     pty_size,
567     pty_special,
568     pty_socket,
569     pty_exitcode,
570     pty_sendok,
571     pty_ldisc,
572     pty_unthrottle,
573     1
574 };