]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxpty.c
8c25f932fbdb123b28c4f77f6cdd25c2d107c0f2
[PuTTY.git] / unix / uxpty.c
1 /*
2  * Pseudo-tty backend for pterm.
3  */
4
5 #define _GNU_SOURCE
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <signal.h>
12 #include <fcntl.h>
13 #include <termios.h>
14 #include <grp.h>
15 #include <utmp.h>
16 #include <pwd.h>
17 #include <time.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
21 #include <sys/ioctl.h>
22 #include <errno.h>
23
24 #include "putty.h"
25 #include "tree234.h"
26
27 #ifndef FALSE
28 #define FALSE 0
29 #endif
30 #ifndef TRUE
31 #define TRUE 1
32 #endif
33
34 #ifndef UTMP_FILE
35 #define UTMP_FILE "/var/run/utmp"
36 #endif
37 #ifndef WTMP_FILE
38 #define WTMP_FILE "/var/log/wtmp"
39 #endif
40 #ifndef LASTLOG_FILE
41 #ifdef _PATH_LASTLOG
42 #define LASTLOG_FILE _PATH_LASTLOG
43 #else
44 #define LASTLOG_FILE "/var/log/lastlog"
45 #endif
46 #endif
47
48 /*
49  * Set up a default for vaguely sane systems. The idea is that if
50  * OMIT_UTMP is not defined, then at least one of the symbols which
51  * enable particular forms of utmp processing should be, if only so
52  * that a link error can warn you that you should have defined
53  * OMIT_UTMP if you didn't want any. Currently HAVE_PUTUTLINE is
54  * the only such symbol.
55  */
56 #ifndef OMIT_UTMP
57 #if !defined HAVE_PUTUTLINE
58 #define HAVE_PUTUTLINE
59 #endif
60 #endif
61
62 typedef struct pty_tag *Pty;
63
64 /*
65  * The pty_signal_pipe, along with the SIGCHLD handler, must be
66  * process-global rather than session-specific.
67  */
68 static int pty_signal_pipe[2] = { -1, -1 };   /* obviously bogus initial val */
69
70 struct pty_tag {
71     Config cfg;
72     int master_fd, slave_fd;
73     void *frontend;
74     char name[FILENAME_MAX];
75     int child_pid;
76     int term_width, term_height;
77     int child_dead, finished;
78     int exit_code;
79 };
80
81 /*
82  * We store our pty backends in a tree sorted by master fd, so that
83  * when we get an uxsel notification we know which backend instance
84  * is the owner of the pty that caused it.
85  */
86 static int pty_compare_by_fd(void *av, void *bv)
87 {
88     Pty a = (Pty)av;
89     Pty b = (Pty)bv;
90
91     if (a->master_fd < b->master_fd)
92         return -1;
93     else if (a->master_fd > b->master_fd)
94         return +1;
95     return 0;
96 }
97
98 static int pty_find_by_fd(void *av, void *bv)
99 {
100     int a = *(int *)av;
101     Pty b = (Pty)bv;
102
103     if (a < b->master_fd)
104         return -1;
105     else if (a > b->master_fd)
106         return +1;
107     return 0;
108 }
109
110 static tree234 *ptys_by_fd = NULL;
111
112 /*
113  * We also have a tree sorted by child pid, so that when we wait()
114  * in response to the signal we know which backend instance is the
115  * owner of the process that caused the signal.
116  */
117 static int pty_compare_by_pid(void *av, void *bv)
118 {
119     Pty a = (Pty)av;
120     Pty b = (Pty)bv;
121
122     if (a->child_pid < b->child_pid)
123         return -1;
124     else if (a->child_pid > b->child_pid)
125         return +1;
126     return 0;
127 }
128
129 static int pty_find_by_pid(void *av, void *bv)
130 {
131     int a = *(int *)av;
132     Pty b = (Pty)bv;
133
134     if (a < b->child_pid)
135         return -1;
136     else if (a > b->child_pid)
137         return +1;
138     return 0;
139 }
140
141 static tree234 *ptys_by_pid = NULL;
142
143 /*
144  * If we are using pty_pre_init(), it will need to have already
145  * allocated a pty structure, which we must then return from
146  * pty_init() rather than allocating a new one. Here we store that
147  * structure between allocation and use.
148  * 
149  * Note that although most of this module is entirely capable of
150  * handling multiple ptys in a single process, pty_pre_init() is
151  * fundamentally _dependent_ on there being at most one pty per
152  * process, so the normal static-data constraints don't apply.
153  * 
154  * Likewise, since utmp is only used via pty_pre_init, it too must
155  * be single-instance, so we can declare utmp-related variables
156  * here.
157  */
158 static Pty single_pty = NULL;
159
160 #ifndef OMIT_UTMP
161 static int pty_utmp_helper_pid, pty_utmp_helper_pipe;
162 static int pty_stamped_utmp;
163 static struct utmp utmp_entry;
164 #endif
165
166 /*
167  * pty_argv is a grievous hack to allow a proper argv to be passed
168  * through from the Unix command line. Again, it doesn't really
169  * make sense outside a one-pty-per-process setup.
170  */
171 char **pty_argv;
172
173 static void pty_close(Pty pty);
174
175 #ifndef OMIT_UTMP
176 static void setup_utmp(char *ttyname, char *location)
177 {
178 #ifdef HAVE_LASTLOG
179     struct lastlog lastlog_entry;
180     FILE *lastlog;
181 #endif
182     struct passwd *pw;
183     FILE *wtmp;
184     time_t uttime;
185
186     pw = getpwuid(getuid());
187     memset(&utmp_entry, 0, sizeof(utmp_entry));
188     utmp_entry.ut_type = USER_PROCESS;
189     utmp_entry.ut_pid = getpid();
190     strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
191     strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
192     strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
193     strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
194     /* Apparently there are some architectures where (struct utmp).ut_time
195      * is not essentially time_t (e.g. Linux amd64). Hence the temporary. */
196     time(&uttime);
197     utmp_entry.ut_time = uttime; /* may truncate */
198
199 #if defined HAVE_PUTUTLINE
200     utmpname(UTMP_FILE);
201     setutent();
202     pututline(&utmp_entry);
203     endutent();
204 #endif
205
206     if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
207         fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
208         fclose(wtmp);
209     }
210
211 #ifdef HAVE_LASTLOG
212     memset(&lastlog_entry, 0, sizeof(lastlog_entry));
213     strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
214     strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
215     time(&lastlog_entry.ll_time);
216     if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
217         fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
218         fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
219         fclose(lastlog);
220     }
221 #endif
222
223     pty_stamped_utmp = 1;
224
225 }
226
227 static void cleanup_utmp(void)
228 {
229     FILE *wtmp;
230     time_t uttime;
231
232     if (!pty_stamped_utmp)
233         return;
234
235     utmp_entry.ut_type = DEAD_PROCESS;
236     memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
237     time(&uttime);
238     utmp_entry.ut_time = uttime;
239
240     if ((wtmp = fopen(WTMP_FILE, "a")) != NULL) {
241         fwrite(&utmp_entry, 1, sizeof(utmp_entry), wtmp);
242         fclose(wtmp);
243     }
244
245     memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
246     utmp_entry.ut_time = 0;
247
248 #if defined HAVE_PUTUTLINE
249     utmpname(UTMP_FILE);
250     setutent();
251     pututline(&utmp_entry);
252     endutent();
253 #endif
254
255     pty_stamped_utmp = 0;              /* ensure we never double-cleanup */
256 }
257 #endif
258
259 static void sigchld_handler(int signum)
260 {
261     write(pty_signal_pipe[1], "x", 1);
262 }
263
264 #ifndef OMIT_UTMP
265 static void fatal_sig_handler(int signum)
266 {
267     putty_signal(signum, SIG_DFL);
268     cleanup_utmp();
269     setuid(getuid());
270     raise(signum);
271 }
272 #endif
273
274 static int pty_open_slave(Pty pty)
275 {
276     if (pty->slave_fd < 0)
277         pty->slave_fd = open(pty->name, O_RDWR);
278
279     return pty->slave_fd;
280 }
281
282 static void pty_open_master(Pty pty)
283 {
284 #ifdef BSD_PTYS
285     const char chars1[] = "pqrstuvwxyz";
286     const char chars2[] = "0123456789abcdef";
287     const char *p1, *p2;
288     char master_name[20];
289     struct group *gp;
290
291     for (p1 = chars1; *p1; p1++)
292         for (p2 = chars2; *p2; p2++) {
293             sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
294             pty->master_fd = open(master_name, O_RDWR);
295             if (pty->master_fd >= 0) {
296                 if (geteuid() == 0 ||
297                     access(master_name, R_OK | W_OK) == 0) {
298                     /*
299                      * We must also check at this point that we are
300                      * able to open the slave side of the pty. We
301                      * wouldn't want to allocate the wrong master,
302                      * get all the way down to forking, and _then_
303                      * find we're unable to open the slave.
304                      */
305                     strcpy(pty->name, master_name);
306                     pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
307
308                     if (pty_open_slave(pty) >= 0 &&
309                         access(pty->name, R_OK | W_OK) == 0)
310                         goto got_one;
311                     if (pty->slave_fd > 0)
312                         close(pty->slave_fd);
313                     pty->slave_fd = -1;
314                 }
315                 close(pty->master_fd);
316             }
317         }
318
319     /* If we get here, we couldn't get a tty at all. */
320     fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
321     exit(1);
322
323     got_one:
324
325     /* We need to chown/chmod the /dev/ttyXX device. */
326     gp = getgrnam("tty");
327     chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
328     chmod(pty->name, 0600);
329 #else
330     pty->master_fd = open("/dev/ptmx", O_RDWR);
331
332     if (pty->master_fd < 0) {
333         perror("/dev/ptmx: open");
334         exit(1);
335     }
336
337     if (grantpt(pty->master_fd) < 0) {
338         perror("grantpt");
339         exit(1);
340     }
341     
342     if (unlockpt(pty->master_fd) < 0) {
343         perror("unlockpt");
344         exit(1);
345     }
346
347     pty->name[FILENAME_MAX-1] = '\0';
348     strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
349 #endif
350
351     if (!ptys_by_fd)
352         ptys_by_fd = newtree234(pty_compare_by_fd);
353     add234(ptys_by_fd, pty);
354 }
355
356 /*
357  * Pre-initialisation. This is here to get around the fact that GTK
358  * doesn't like being run in setuid/setgid programs (probably
359  * sensibly). So before we initialise GTK - and therefore before we
360  * even process the command line - we check to see if we're running
361  * set[ug]id. If so, we open our pty master _now_, chown it as
362  * necessary, and drop privileges. We can always close it again
363  * later. If we're potentially going to be doing utmp as well, we
364  * also fork off a utmp helper process and communicate with it by
365  * means of a pipe; the utmp helper will keep privileges in order
366  * to clean up utmp when we exit (i.e. when its end of our pipe
367  * closes).
368  */
369 void pty_pre_init(void)
370 {
371     Pty pty;
372
373 #ifndef OMIT_UTMP
374     pid_t pid;
375     int pipefd[2];
376 #endif
377
378     pty = single_pty = snew(struct pty_tag);
379
380     /* set the child signal handler straight away; it needs to be set
381      * before we ever fork. */
382     putty_signal(SIGCHLD, sigchld_handler);
383     pty->master_fd = pty->slave_fd = -1;
384 #ifndef OMIT_UTMP
385     pty_stamped_utmp = FALSE;
386 #endif
387
388     if (geteuid() != getuid() || getegid() != getgid()) {
389         pty_open_master(pty);
390     }
391
392 #ifndef OMIT_UTMP
393     /*
394      * Fork off the utmp helper.
395      */
396     if (pipe(pipefd) < 0) {
397         perror("pterm: pipe");
398         exit(1);
399     }
400     pid = fork();
401     if (pid < 0) {
402         perror("pterm: fork");
403         exit(1);
404     } else if (pid == 0) {
405         char display[128], buffer[128];
406         int dlen, ret;
407
408         close(pipefd[1]);
409         /*
410          * Now sit here until we receive a display name from the
411          * other end of the pipe, and then stamp utmp. Unstamp utmp
412          * again, and exit, when the pipe closes.
413          */
414
415         dlen = 0;
416         while (1) {
417             
418             ret = read(pipefd[0], buffer, lenof(buffer));
419             if (ret <= 0) {
420                 cleanup_utmp();
421                 _exit(0);
422             } else if (!pty_stamped_utmp) {
423                 if (dlen < lenof(display))
424                     memcpy(display+dlen, buffer,
425                            min(ret, lenof(display)-dlen));
426                 if (buffer[ret-1] == '\0') {
427                     /*
428                      * Now we have a display name. NUL-terminate
429                      * it, and stamp utmp.
430                      */
431                     display[lenof(display)-1] = '\0';
432                     /*
433                      * Trap as many fatal signals as we can in the
434                      * hope of having the best possible chance to
435                      * clean up utmp before termination. We are
436                      * unfortunately unprotected against SIGKILL,
437                      * but that's life.
438                      */
439                     putty_signal(SIGHUP, fatal_sig_handler);
440                     putty_signal(SIGINT, fatal_sig_handler);
441                     putty_signal(SIGQUIT, fatal_sig_handler);
442                     putty_signal(SIGILL, fatal_sig_handler);
443                     putty_signal(SIGABRT, fatal_sig_handler);
444                     putty_signal(SIGFPE, fatal_sig_handler);
445                     putty_signal(SIGPIPE, fatal_sig_handler);
446                     putty_signal(SIGALRM, fatal_sig_handler);
447                     putty_signal(SIGTERM, fatal_sig_handler);
448                     putty_signal(SIGSEGV, fatal_sig_handler);
449                     putty_signal(SIGUSR1, fatal_sig_handler);
450                     putty_signal(SIGUSR2, fatal_sig_handler);
451 #ifdef SIGBUS
452                     putty_signal(SIGBUS, fatal_sig_handler);
453 #endif
454 #ifdef SIGPOLL
455                     putty_signal(SIGPOLL, fatal_sig_handler);
456 #endif
457 #ifdef SIGPROF
458                     putty_signal(SIGPROF, fatal_sig_handler);
459 #endif
460 #ifdef SIGSYS
461                     putty_signal(SIGSYS, fatal_sig_handler);
462 #endif
463 #ifdef SIGTRAP
464                     putty_signal(SIGTRAP, fatal_sig_handler);
465 #endif
466 #ifdef SIGVTALRM
467                     putty_signal(SIGVTALRM, fatal_sig_handler);
468 #endif
469 #ifdef SIGXCPU
470                     putty_signal(SIGXCPU, fatal_sig_handler);
471 #endif
472 #ifdef SIGXFSZ
473                     putty_signal(SIGXFSZ, fatal_sig_handler);
474 #endif
475 #ifdef SIGIO
476                     putty_signal(SIGIO, fatal_sig_handler);
477 #endif
478                     setup_utmp(pty->name, display);
479                 }
480             }
481         }
482     } else {
483         close(pipefd[0]);
484         pty_utmp_helper_pid = pid;
485         pty_utmp_helper_pipe = pipefd[1];
486     }
487 #endif
488
489     /* Drop privs. */
490     {
491 #ifndef HAVE_NO_SETRESUID
492         int gid = getgid(), uid = getuid();
493         int setresgid(gid_t, gid_t, gid_t);
494         int setresuid(uid_t, uid_t, uid_t);
495         setresgid(gid, gid, gid);
496         setresuid(uid, uid, uid);
497 #else
498         setgid(getgid());
499         setuid(getuid());
500 #endif
501     }
502 }
503
504 int pty_real_select_result(Pty pty, int event, int status)
505 {
506     char buf[4096];
507     int ret;
508     int finished = FALSE;
509
510     if (event < 0) {
511         /*
512          * We've been called because our child process did
513          * something. `status' tells us what.
514          */
515         if ((WIFEXITED(status) || WIFSIGNALED(status))) {
516             /*
517              * The primary child process died. We could keep
518              * the terminal open for remaining subprocesses to
519              * output to, but conventional wisdom seems to feel
520              * that that's the Wrong Thing for an xterm-alike,
521              * so we bail out now (though we don't necessarily
522              * _close_ the window, depending on the state of
523              * Close On Exit). This would be easy enough to
524              * change or make configurable if necessary.
525              */
526             pty->exit_code = status;
527             pty->child_dead = TRUE;
528             del234(ptys_by_pid, pty);
529             finished = TRUE;
530         }
531     } else {
532         if (event == 1) {
533
534             ret = read(pty->master_fd, buf, sizeof(buf));
535
536             /*
537              * Clean termination condition is that either ret == 0, or ret
538              * < 0 and errno == EIO. Not sure why the latter, but it seems
539              * to happen. Boo.
540              */
541             if (ret == 0 || (ret < 0 && errno == EIO)) {
542                 /*
543                  * We assume a clean exit if the pty has closed but the
544                  * actual child process hasn't. The only way I can
545                  * imagine this happening is if it detaches itself from
546                  * the pty and goes daemonic - in which case the
547                  * expected usage model would precisely _not_ be for
548                  * the pterm window to hang around!
549                  */
550                 finished = TRUE;
551                 if (!pty->child_dead)
552                     pty->exit_code = 0;
553             } else if (ret < 0) {
554                 perror("read pty master");
555                 exit(1);
556             } else if (ret > 0) {
557                 from_backend(pty->frontend, 0, buf, ret);
558             }
559         }
560     }
561
562     if (finished && !pty->finished) {
563         uxsel_del(pty->master_fd);
564         pty_close(pty);
565         pty->master_fd = -1;
566
567         pty->finished = TRUE;
568
569         /*
570          * This is a slight layering-violation sort of hack: only
571          * if we're not closing on exit (COE is set to Never, or to
572          * Only On Clean and it wasn't a clean exit) do we output a
573          * `terminated' message.
574          */
575         if (pty->cfg.close_on_exit == FORCE_OFF ||
576             (pty->cfg.close_on_exit == AUTO && pty->exit_code != 0)) {
577             char message[512];
578             if (WIFEXITED(pty->exit_code))
579                 sprintf(message, "\r\n[pterm: process terminated with exit"
580                         " code %d]\r\n", WEXITSTATUS(pty->exit_code));
581             else if (WIFSIGNALED(pty->exit_code))
582 #ifdef HAVE_NO_STRSIGNAL
583                 sprintf(message, "\r\n[pterm: process terminated on signal"
584                         " %d]\r\n", WTERMSIG(pty->exit_code));
585 #else
586                 sprintf(message, "\r\n[pterm: process terminated on signal"
587                         " %d (%.400s)]\r\n", WTERMSIG(pty->exit_code),
588                         strsignal(WTERMSIG(pty->exit_code)));
589 #endif
590             from_backend(pty->frontend, 0, message, strlen(message));
591         }
592
593         notify_remote_exit(pty->frontend);
594     }
595
596     return !finished;
597 }
598
599 int pty_select_result(int fd, int event)
600 {
601     int ret = TRUE;
602     Pty pty;
603
604     if (fd == pty_signal_pipe[0]) {
605         pid_t pid;
606         int ipid;
607         int status;
608         char c[1];
609
610         read(pty_signal_pipe[0], c, 1); /* ignore its value; it'll be `x' */
611
612         do {
613             pid = waitpid(-1, &status, WNOHANG);
614
615             ipid = pid;
616             pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
617
618             if (pty)
619                 ret = ret && pty_real_select_result(pty, -1, status);
620         } while (pid > 0);
621     } else {
622         pty = find234(ptys_by_fd, &fd, pty_find_by_fd);
623
624         if (pty)
625             ret = ret && pty_real_select_result(pty, event, 0);
626     }
627
628     return ret;
629 }
630
631 static void pty_uxsel_setup(Pty pty)
632 {
633     uxsel_set(pty->master_fd, 1, pty_select_result);
634
635     /*
636      * In principle this only needs calling once for all pty
637      * backend instances, but it's simplest just to call it every
638      * time; uxsel won't mind.
639      */
640     uxsel_set(pty_signal_pipe[0], 1, pty_select_result);
641 }
642
643 /*
644  * Called to set up the pty.
645  * 
646  * Returns an error message, or NULL on success.
647  *
648  * Also places the canonical host name into `realhost'. It must be
649  * freed by the caller.
650  */
651 static const char *pty_init(void *frontend, void **backend_handle, Config *cfg,
652                             char *host, int port, char **realhost, int nodelay,
653                             int keepalive)
654 {
655     int slavefd;
656     pid_t pid, pgrp;
657 #ifndef NOT_X_WINDOWS                  /* for Mac OS X native compilation */
658     long windowid;
659 #endif
660     Pty pty;
661
662     if (single_pty) {
663         pty = single_pty;
664     } else {
665         pty = snew(struct pty_tag);
666         pty->master_fd = pty->slave_fd = -1;
667 #ifndef OMIT_UTMP
668         pty_stamped_utmp = FALSE;
669 #endif
670     }
671
672     pty->frontend = frontend;
673     *backend_handle = NULL;            /* we can't sensibly use this, sadly */
674
675     pty->cfg = *cfg;                   /* structure copy */
676     pty->term_width = cfg->width;
677     pty->term_height = cfg->height;
678
679     if (pty->master_fd < 0)
680         pty_open_master(pty);
681
682     /*
683      * Set the backspace character to be whichever of ^H and ^? is
684      * specified by bksp_is_delete.
685      */
686     {
687         struct termios attrs;
688         tcgetattr(pty->master_fd, &attrs);
689         attrs.c_cc[VERASE] = cfg->bksp_is_delete ? '\177' : '\010';
690         tcsetattr(pty->master_fd, TCSANOW, &attrs);
691     }
692
693 #ifndef OMIT_UTMP
694     /*
695      * Stamp utmp (that is, tell the utmp helper process to do so),
696      * or not.
697      */
698     if (!cfg->stamp_utmp) {
699         close(pty_utmp_helper_pipe);   /* just let the child process die */
700         pty_utmp_helper_pipe = -1;
701     } else {
702         char *location = get_x_display(pty->frontend);
703         int len = strlen(location)+1, pos = 0;   /* +1 to include NUL */
704         while (pos < len) {
705             int ret = write(pty_utmp_helper_pipe, location+pos, len - pos);
706             if (ret < 0) {
707                 perror("pterm: writing to utmp helper process");
708                 close(pty_utmp_helper_pipe);   /* arrgh, just give up */
709                 pty_utmp_helper_pipe = -1;
710                 break;
711             }
712             pos += ret;
713         }
714     }
715 #endif
716
717 #ifndef NOT_X_WINDOWS                  /* for Mac OS X native compilation */
718     windowid = get_windowid(pty->frontend);
719 #endif
720
721     /*
722      * Fork and execute the command.
723      */
724     pid = fork();
725     if (pid < 0) {
726         perror("fork");
727         exit(1);
728     }
729
730     if (pid == 0) {
731         int i;
732         /*
733          * We are the child.
734          */
735
736         slavefd = pty_open_slave(pty);
737         if (slavefd < 0) {
738             perror("slave pty: open");
739             _exit(1);
740         }
741
742         close(pty->master_fd);
743         fcntl(slavefd, F_SETFD, 0);    /* don't close on exec */
744         dup2(slavefd, 0);
745         dup2(slavefd, 1);
746         dup2(slavefd, 2);
747         setsid();
748         ioctl(slavefd, TIOCSCTTY, 1);
749         pgrp = getpid();
750         tcsetpgrp(slavefd, pgrp);
751         setpgid(pgrp, pgrp);
752         close(open(pty->name, O_WRONLY, 0));
753         setpgid(pgrp, pgrp);
754         /* Close everything _else_, for tidiness. */
755         for (i = 3; i < 1024; i++)
756             close(i);
757         {
758             char term_env_var[10 + sizeof(cfg->termtype)];
759             sprintf(term_env_var, "TERM=%s", cfg->termtype);
760             putenv(term_env_var);
761         }
762 #ifndef NOT_X_WINDOWS                  /* for Mac OS X native compilation */
763         {
764             char windowid_env_var[40];
765             sprintf(windowid_env_var, "WINDOWID=%ld", windowid);
766             putenv(windowid_env_var);
767         }
768 #endif
769         {
770             char *e = cfg->environmt;
771             char *var, *varend, *val, *varval;
772             while (*e) {
773                 var = e;
774                 while (*e && *e != '\t') e++;
775                 varend = e;
776                 if (*e == '\t') e++;
777                 val = e;
778                 while (*e) e++;
779                 e++;
780
781                 varval = dupprintf("%.*s=%s", varend-var, var, val);
782                 putenv(varval);
783                 /*
784                  * We must not free varval, since putenv links it
785                  * into the environment _in place_. Weird, but
786                  * there we go. Memory usage will be rationalised
787                  * as soon as we exec anyway.
788                  */
789             }
790         }
791
792         /*
793          * SIGINT and SIGQUIT may have been set to ignored by our
794          * parent, particularly by things like sh -c 'pterm &' and
795          * some window managers. SIGCHLD, meanwhile, was blocked
796          * during pt_main() startup. Reverse all this for our child
797          * process.
798          */
799         putty_signal(SIGINT, SIG_DFL);
800         putty_signal(SIGQUIT, SIG_DFL);
801         block_signal(SIGCHLD, 0);
802         if (pty_argv)
803             execvp(pty_argv[0], pty_argv);
804         else {
805             char *shell = getenv("SHELL");
806             char *shellname;
807             if (cfg->login_shell) {
808                 char *p = strrchr(shell, '/');
809                 shellname = snewn(2+strlen(shell), char);
810                 p = p ? p+1 : shell;
811                 sprintf(shellname, "-%s", p);
812             } else
813                 shellname = shell;
814             execl(getenv("SHELL"), shellname, (void *)NULL);
815         }
816
817         /*
818          * If we're here, exec has gone badly foom.
819          */
820         perror("exec");
821         _exit(127);
822     } else {
823         pty->child_pid = pid;
824         pty->child_dead = FALSE;
825         pty->finished = FALSE;
826         if (pty->slave_fd > 0)
827             close(pty->slave_fd);
828         if (!ptys_by_pid)
829             ptys_by_pid = newtree234(pty_compare_by_pid);
830         add234(ptys_by_pid, pty);
831     }
832
833     if (pty_signal_pipe[0] < 0 && pipe(pty_signal_pipe) < 0) {
834         perror("pipe");
835         exit(1);
836     }
837     pty_uxsel_setup(pty);
838
839     *backend_handle = pty;
840
841     return NULL;
842 }
843
844 static void pty_reconfig(void *handle, Config *cfg)
845 {
846     Pty pty = (Pty)handle;
847     /*
848      * We don't have much need to reconfigure this backend, but
849      * unfortunately we do need to pick up the setting of Close On
850      * Exit so we know whether to give a `terminated' message.
851      */
852     pty->cfg = *cfg;                   /* structure copy */
853 }
854
855 /*
856  * Stub routine (never called in pterm).
857  */
858 static void pty_free(void *handle)
859 {
860     Pty pty = (Pty)handle;
861
862     /* Either of these may fail `not found'. That's fine with us. */
863     del234(ptys_by_pid, pty);
864     del234(ptys_by_fd, pty);
865
866     sfree(pty);
867 }
868
869 /*
870  * Called to send data down the pty.
871  */
872 static int pty_send(void *handle, char *buf, int len)
873 {
874     Pty pty = (Pty)handle;
875
876     if (pty->master_fd < 0)
877         return 0;                      /* ignore all writes if fd closed */
878
879     while (len > 0) {
880         int ret = write(pty->master_fd, buf, len);
881         if (ret < 0) {
882             perror("write pty master");
883             exit(1);
884         }
885         buf += ret;
886         len -= ret;
887     }
888     return 0;
889 }
890
891 static void pty_close(Pty pty)
892 {
893     if (pty->master_fd >= 0) {
894         close(pty->master_fd);
895         pty->master_fd = -1;
896     }
897 #ifndef OMIT_UTMP
898     if (pty_utmp_helper_pipe >= 0) {
899         close(pty_utmp_helper_pipe);   /* this causes utmp to be cleaned up */
900         pty_utmp_helper_pipe = -1;
901     }
902 #endif
903 }
904
905 /*
906  * Called to query the current socket sendability status.
907  */
908 static int pty_sendbuffer(void *handle)
909 {
910     /* Pty pty = (Pty)handle; */
911     return 0;
912 }
913
914 /*
915  * Called to set the size of the window
916  */
917 static void pty_size(void *handle, int width, int height)
918 {
919     Pty pty = (Pty)handle;
920     struct winsize size;
921
922     pty->term_width = width;
923     pty->term_height = height;
924
925     size.ws_row = (unsigned short)pty->term_height;
926     size.ws_col = (unsigned short)pty->term_width;
927     size.ws_xpixel = (unsigned short) pty->term_width *
928         font_dimension(pty->frontend, 0);
929     size.ws_ypixel = (unsigned short) pty->term_height *
930         font_dimension(pty->frontend, 1);
931     ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
932     return;
933 }
934
935 /*
936  * Send special codes.
937  */
938 static void pty_special(void *handle, Telnet_Special code)
939 {
940     /* Pty pty = (Pty)handle; */
941     /* Do nothing! */
942     return;
943 }
944
945 /*
946  * Return a list of the special codes that make sense in this
947  * protocol.
948  */
949 static const struct telnet_special *pty_get_specials(void *handle)
950 {
951     /* Pty pty = (Pty)handle; */
952     /*
953      * Hmm. When I get round to having this actually usable, it
954      * might be quite nice to have the ability to deliver a few
955      * well chosen signals to the child process - SIGINT, SIGTERM,
956      * SIGKILL at least.
957      */
958     return NULL;
959 }
960
961 static Socket pty_socket(void *handle)
962 {
963     /* Pty pty = (Pty)handle; */
964     return NULL;                       /* shouldn't ever be needed */
965 }
966
967 static int pty_sendok(void *handle)
968 {
969     /* Pty pty = (Pty)handle; */
970     return 1;
971 }
972
973 static void pty_unthrottle(void *handle, int backlog)
974 {
975     /* Pty pty = (Pty)handle; */
976     /* do nothing */
977 }
978
979 static int pty_ldisc(void *handle, int option)
980 {
981     /* Pty pty = (Pty)handle; */
982     return 0;                          /* neither editing nor echoing */
983 }
984
985 static void pty_provide_ldisc(void *handle, void *ldisc)
986 {
987     /* Pty pty = (Pty)handle; */
988     /* This is a stub. */
989 }
990
991 static void pty_provide_logctx(void *handle, void *logctx)
992 {
993     /* Pty pty = (Pty)handle; */
994     /* This is a stub. */
995 }
996
997 static int pty_exitcode(void *handle)
998 {
999     Pty pty = (Pty)handle;
1000     if (!pty->finished)
1001         return -1;                     /* not dead yet */
1002     else
1003         return pty->exit_code;
1004 }
1005
1006 static int pty_cfg_info(void *handle)
1007 {
1008     /* Pty pty = (Pty)handle; */
1009     return 0;
1010 }
1011
1012 Backend pty_backend = {
1013     pty_init,
1014     pty_free,
1015     pty_reconfig,
1016     pty_send,
1017     pty_sendbuffer,
1018     pty_size,
1019     pty_special,
1020     pty_get_specials,
1021     pty_socket,
1022     pty_exitcode,
1023     pty_sendok,
1024     pty_ldisc,
1025     pty_provide_ldisc,
1026     pty_provide_logctx,
1027     pty_unthrottle,
1028     pty_cfg_info,
1029     1
1030 };