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