File: brltty-pty.c

package info (click to toggle)
brltty 6.8-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 35,776 kB
  • sloc: ansic: 150,447; java: 13,484; sh: 9,667; xml: 5,702; tcl: 2,634; makefile: 2,328; awk: 713; lisp: 366; python: 321; ml: 301
file content (516 lines) | stat: -rw-r--r-- 12,296 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/*
 * BRLTTY - A background process providing access to the console screen (when in
 *          text mode) for a blind person using a refreshable braille display.
 *
 * Copyright (C) 1995-2025 by The BRLTTY Developers.
 *
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU Lesser General Public License, as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any
 * later version. Please see the file LICENSE-LGPL for details.
 *
 * Web Page: http://brltty.app/
 *
 * This software is maintained by Dave Mielke <dave@mielke.cc>.
 */

/* not done yet:
 * parent: terminal type list
 * screen: resize
 */

#include "prologue.h"

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <sys/wait.h>
#include <sys/ioctl.h>

#include "log.h"
#include "cmdline.h"
#include "pty_object.h"
#include "pty_terminal.h"
#include "parse.h"
#include "file.h"
#include "async_handle.h"
#include "async_wait.h"
#include "async_io.h"
#include "async_signal.h"

static int opt_driverDirectives;
static int opt_showPath;
static char *opt_asUser;
static char *opt_asGroup;
static char *opt_workingDirectory;
static char *opt_homeDirectory;

static int opt_logInput;
static int opt_logOutput;
static int opt_logSequences;
static int opt_logUnexpected;

BEGIN_OPTION_TABLE(programOptions)
  { .word = "driver-directives",
    .letter = 'x',
    .setting.flag = &opt_driverDirectives,
    .description = strtext("write driver directives to standard error")
  },

  { .word = "show-path",
    .letter = 'p',
    .setting.flag = &opt_showPath,
    .description = strtext("show the absolute path to the pty slave")
  },

  { .word = "user",
    .letter = 'u',
    .argument = "user",
    .setting.string = &opt_asUser,
    .description = strtext("the name or number of the user to run as")
  },

  { .word = "group",
    .letter = 'g',
    .argument = "group",
    .setting.string = &opt_asGroup,
    .description = strtext("the name or number of the group to run as")
  },

  { .word = "working-directory",
    .letter = 'd',
    .argument = "path",
    .setting.string = &opt_workingDirectory,
    .description = strtext("the directory to change to")
  },

  { .word = "home-directory",
    .letter = 'D',
    .argument = "path",
    .setting.string = &opt_homeDirectory,
    .description = strtext("the home directory to use")
  },

  { .word = "log-input",
    .letter = 'I',
    .setting.flag = &opt_logInput,
    .description = strtext("log input written to the pty slave")
  },

  { .word = "log-output",
    .letter = 'O',
    .setting.flag = &opt_logOutput,
    .description = strtext("log output received from the pty slave that isn't an escape sequence or a special character")
  },

  { .word = "log-sequences",
    .letter = 'S',
    .setting.flag = &opt_logSequences,
    .description = strtext("log escape sequences and special characters received from the pty slave")
  },

  { .word = "log-unexpected",
    .letter = 'U',
    .setting.flag = &opt_logUnexpected,
    .description = strtext("log unexpected input/output")
  },
END_OPTION_TABLE(programOptions)

static void writeDriverDirective (const char *format, ...) PRINTF(1, 2);

static void
writeDriverDirective (const char *format, ...) {
  if (opt_driverDirectives) {
    va_list args;
    va_start(args, format);

    {
      FILE *stream = stderr;
      vfprintf(stream, format, args);
      fputc('\n', stream);
      fflush(stream);
    }

    va_end(args);
  }
}

static int
setWindowSize (int tty, size_t columns, size_t lines) {
  struct winsize size = {
    .ws_col = columns,
    .ws_row = lines,
  };

  if (ioctl(tty, TIOCSWINSZ, &size) != -1) return 1;
  logSystemError("ioctl[TIOCSWINSZ]");
  return 0;
}

static int
setEnvironmentString (const char *variable, const char *string) {
  int result = setenv(variable, string, 1);
  if (result != -1) return 1;

  logSystemError("setenv");
  return 0;
}

static int
setEnvironmentInteger (const char *variable, int integer) {
  char string[0X10];
  snprintf(string, sizeof(string), "%d", integer);
  return setEnvironmentString(variable, string);
}

static int
setEnvironmentVariables (size_t *columns, size_t *lines) {
  if (!setEnvironmentString("TERM_PROGRAM", programName)) return 0;
  if (!setEnvironmentString("TERM_PROGRAM_VERSION", PACKAGE_VERSION)) return 0;

  {
    static const char *const variables[] = {
      /* screen */ "STY", "WINDOW",
      /* tmux   */ "TMUX",
    };

    const char *const *variable = variables;
    const char *const *end = variable + ARRAY_COUNT(variables);

    while (variable < end) {
      if (unsetenv(*variable) == -1) {
        logSystemError("unsetenv");
      }

      variable += 1;
    }
  }

  if (getConsoleSize(columns, lines)) {
    if (!setEnvironmentInteger("COLUMNS", *columns)) return 0;
    if (!setEnvironmentInteger("LINES", *lines)) return 0;
  } else {
    *columns = 0;
    *lines = 0;
  }

  return setEnvironmentString("TERM", ptyGetTerminalType());
}

static PtyObject *ptyObject = NULL;

static int
prepareChild (void) {
  setsid();
  ptyCloseMaster(ptyObject);

  size_t columns, lines;
  if (setEnvironmentVariables(&columns, &lines)) {
    int tty;
    if (!ptyOpenSlave(ptyObject, &tty)) return 0;
    setWindowSize(tty, columns, lines);

    {
      int keep = 0;

      for (int fd=0; fd<=2; fd+=1) {
        if (fd == tty) {
          keep = 1;
        } else {
          int result = dup2(tty, fd);

          if (result == -1) {
            logSystemError("dup2");
            return 0;
          }
        }
      }

      if (!keep) close(tty);
    }
  }

  return 1;
}

static int
runChild (char **command) {
  char *defaultCommand[2];

  if (!(command && *command)) {
    char *shell = getenv("SHELL");
    if (!(shell && *shell)) shell = "/bin/sh";

    defaultCommand[0] = shell;
    defaultCommand[1] = NULL;

    command = defaultCommand;
  }

  if (prepareChild()) {
    int result = execvp(*command, command);

    if (result == -1) {
      switch (errno) {
        case ENOENT:
          logMessage(LOG_ERR, "%s: %s", gettext("command not found"), *command);
          return PROG_EXIT_SEMANTIC;

        default:
          logSystemError("execvp");
          break;
      }
    } else {
      logMessage(LOG_ERR, "unexpected return from execvp");
    }
  }

  return PROG_EXIT_FATAL;
}

static unsigned char parentIsQuitting;
static unsigned char childHasTerminated;
static unsigned char slaveHasBeenClosed;

static
ASYNC_CONDITION_TESTER(parentTerminationTester) {
  if (parentIsQuitting) return 1;
  return childHasTerminated && slaveHasBeenClosed;
}

static void
parentQuitMonitor (int signalNumber) {
  parentIsQuitting = 1;
}

static void
windowSizeMonitor (int signalNumber) {
  size_t columns, lines;

  if (getConsoleSize(&columns, &lines)) {
    setWindowSize(ptyGetMaster(ptyObject), columns, lines);
    ptyResizeTerminal(lines, columns);
  }
}

static void
childTerminationMonitor (int signalNumber) {
  childHasTerminated = 1;
}

static int
installSignalHandlers (void) {
  if (!asyncHandleSignal(SIGTERM, parentQuitMonitor, NULL)) return 0;
  if (!asyncHandleSignal(SIGINT, parentQuitMonitor, NULL)) return 0;
  if (!asyncHandleSignal(SIGQUIT, parentQuitMonitor, NULL)) return 0;
  if (!asyncHandleSignal(SIGWINCH, windowSizeMonitor, NULL)) return 0;
  return asyncHandleSignal(SIGCHLD, childTerminationMonitor, NULL);
}

static
ASYNC_MONITOR_CALLBACK(standardInputMonitor) {
  if (ptyProcessTerminalInput(ptyObject)) return 1;

  parentIsQuitting = 1;
  return 0;
}

static
ASYNC_INPUT_CALLBACK(ptyInputHandler) {
  if (!(parameters->error || parameters->end)) {
    size_t length = parameters->length;

    if (!ptyProcessTerminalOutput(parameters->buffer, length)) {
      parentIsQuitting = 1;
    }

    return length;
  }

  slaveHasBeenClosed = 1;
  return 0;
}

static int
reapExitStatus (pid_t pid) {
  while (1) {
    int status;
    pid_t result = waitpid(pid, &status, 0);

    if (result == -1) {
      if (errno == EINTR) continue;
      logSystemError("waitpid");
      break;
    }

    if (WIFEXITED(status)) return WEXITSTATUS(status);
    if (WIFSIGNALED(status)) return 0X80 | WTERMSIG(status);

    #ifdef WCOREDUMP
    if (WCOREDUMP(status)) return 0X80 | WTERMSIG(status);
    #endif /* WCOREDUMP */

    #ifdef WIFSTOPPED
    if (WIFSTOPPED(status)) continue;
    #endif /* WIFSTOPPED */

    #ifdef WIFCONTINUED
    if (WIFCONTINUED(status)) continue;
    #endif /* WIFCONTINUED */
  }

  return PROG_EXIT_FATAL;
}

static int
runParent (pid_t child) {
  int exitStatus = PROG_EXIT_FATAL;
  AsyncHandle ptyInputHandle;

  parentIsQuitting = 0;
  childHasTerminated = 0;
  slaveHasBeenClosed = 0;

  if (asyncReadFile(&ptyInputHandle, ptyGetMaster(ptyObject), 1, ptyInputHandler, NULL)) {
    AsyncHandle standardInputHandle;

    if (asyncMonitorFileInput(&standardInputHandle, STDIN_FILENO, standardInputMonitor, NULL)) {
      if (installSignalHandlers()) {
        if (!isatty(2)) {
          unsigned char level = LOG_NOTICE;
          ptySetTerminalLogLevel(level);
          ptySetLogLevel(ptyObject, level);
        }

        if (ptyBeginTerminal(ptyObject, opt_driverDirectives)) {
          writeDriverDirective("path %s", ptyGetPath(ptyObject));

          asyncAwaitCondition(INT_MAX, parentTerminationTester, NULL);
          if (!parentIsQuitting) exitStatus = reapExitStatus(child);

          ptyEndTerminal();
        }
      }

      asyncCancelRequest(standardInputHandle);
    }

    asyncCancelRequest(ptyInputHandle);
  }

  return exitStatus;
}

int
main (int argc, char *argv[]) {
  int exitStatus = PROG_EXIT_FATAL;

  {
    const CommandLineDescriptor descriptor = {
      .options = &programOptions,
      .applicationName = "brltty-pty",

      .usage = {
        .purpose = strtext("Run a shell or terminal manager within a pty (virtual terminal) and export its screen via a shared memory segment so that brltty can read it via its Terminal Emulator screen driver."),
        .parameters = "[command [arg ...]]",
      }
    };

    PROCESS_OPTIONS(descriptor, argc, argv);
  }

  ptySetLogTerminalInput(opt_logInput);
  ptySetLogTerminalOutput(opt_logOutput);
  ptySetLogTerminalSequences(opt_logSequences);
  ptySetLogUnexpectedTerminalIO(opt_logUnexpected);

  if (!isatty(STDIN_FILENO)) {
    logMessage(LOG_ERR, "%s", gettext("standard input isn't a terminal"));
    return PROG_EXIT_SEMANTIC;
  }

  if (!isatty(STDOUT_FILENO)) {
    logMessage(LOG_ERR, "%s", gettext("standard output isn't a terminal"));
    return PROG_EXIT_SEMANTIC;
  }

  {
    uid_t user = 0;
    gid_t group = 0;

    if (*opt_asUser) {
      if (!validateUser(&user, opt_asUser, &group)) {
        logMessage(LOG_ERR, "unknown user: %s", opt_asUser);
        return PROG_EXIT_SEMANTIC;
      }
    }

    if (*opt_asGroup) {
      if (!validateGroup(&group, opt_asGroup)) {
        logMessage(LOG_ERR, "unknown group: %s", opt_asGroup);
        return PROG_EXIT_SEMANTIC;
      }
    }

    if (group) {
      if (setregid(group, group) == -1) {
        logSystemError("setregid");
        return PROG_EXIT_FATAL;
      }
    }

    if (user) {
      if (setreuid(user, user) == -1) {
        logSystemError("setreuid");
        return PROG_EXIT_FATAL;
      }
    }
  }

  if (*opt_workingDirectory) {
    if (chdir(opt_workingDirectory) == -1) {
      logMessage(LOG_ERR, "can't change to directory: %s: %s", opt_workingDirectory, strerror(errno));
      return PROG_EXIT_FATAL;
    }
  }

  if (*opt_homeDirectory) {
    if (!setEnvironmentString("HOME", opt_homeDirectory)) {
      return PROG_EXIT_FATAL;
    }
  }

  if ((ptyObject = ptyNewObject())) {
    ptySetLogInput(ptyObject, opt_logInput);
    const char *ttyPath = ptyGetPath(ptyObject);

    if (opt_showPath) {
      FILE *stream = stderr;
      fprintf(stream, "%s\n", ttyPath);
      fflush(stream);
    }

    pid_t child = fork();
    switch (child) {
      case -1:
        logSystemError("fork");
        break;

      case 0:
        _exit(runChild(argv));

      default:
        exitStatus = runParent(child);
        break;
    }

    ptyDestroyObject(ptyObject);
    ptyObject = NULL;
  }

  return exitStatus;
}