• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 19448983682

17 Nov 2025 11:32PM UTC coverage: 72.503% (-0.2%) from 72.719%
19448983682

push

github

web-flow
core/unit: unit_process_job() tweaks (#39753)

6 of 8 new or added lines in 1 file covered. (75.0%)

3363 existing lines in 68 files now uncovered.

308308 of 425234 relevant lines covered (72.5%)

1141671.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

41.64
/src/basic/terminal-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fcntl.h>
4
#include <linux/kd.h>
5
#include <linux/magic.h>
6
#include <linux/tiocl.h>
7
#include <linux/vt.h>
8
#include <poll.h>
9
#include <signal.h>
10
#include <stdlib.h>
11
#include <sys/inotify.h>
12
#include <sys/ioctl.h>
13
#include <sys/sysmacros.h>
14
#include <termios.h>
15
#include <time.h>
16
#include <unistd.h>
17

18
#include "alloc-util.h"
19
#include "ansi-color.h"
20
#include "chase.h"
21
#include "devnum-util.h"
22
#include "errno-util.h"
23
#include "extract-word.h"
24
#include "fd-util.h"
25
#include "fileio.h"
26
#include "fs-util.h"
27
#include "hexdecoct.h"
28
#include "inotify-util.h"
29
#include "io-util.h"
30
#include "log.h"
31
#include "namespace-util.h"
32
#include "parse-util.h"
33
#include "path-util.h"
34
#include "proc-cmdline.h"
35
#include "process-util.h"
36
#include "signal-util.h"
37
#include "socket-util.h"
38
#include "stat-util.h"
39
#include "stdio-util.h"
40
#include "string-util.h"
41
#include "strv.h"
42
#include "terminal-util.h"
43
#include "time-util.h"
44
#include "utf8.h"
45

46
/* How much to wait for a reply to a terminal sequence */
47
#define CONSOLE_REPLY_WAIT_USEC  (333 * USEC_PER_MSEC)
48

49
static volatile unsigned cached_columns = 0;
50
static volatile unsigned cached_lines = 0;
51

52
static volatile int cached_on_tty = -1;
53
static volatile int cached_on_dev_null = -1;
54

55
bool isatty_safe(int fd) {
5,174,687✔
56
        assert(fd >= 0);
5,174,687✔
57

58
        if (isatty(fd))
5,174,687✔
59
                return true;
60

61
        /* Linux/glibc returns EIO for hung up TTY on isatty(). Which is wrong, the thing doesn't stop being
62
         * a TTY after all, just because it is temporarily hung up. Let's work around this here, until this
63
         * is fixed in glibc. See: https://sourceware.org/bugzilla/show_bug.cgi?id=32103 */
64
        if (errno == EIO)
5,129,336✔
65
                return true;
66

67
        /* Be resilient if we're working on stdio, since they're set up by parent process. */
68
        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
5,129,327✔
69

70
        return false;
71
}
72

73
int chvt(int vt) {
×
74
        _cleanup_close_ int fd = -EBADF;
×
75

76
        /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
77
         * if that's configured. */
78

79
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
×
80
        if (fd < 0)
×
81
                return fd;
82

83
        if (vt <= 0) {
×
84
                int tiocl[2] = {
×
85
                        TIOCL_GETKMSGREDIRECT,
86
                        0
87
                };
88

89
                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
×
90
                        return -errno;
×
91

92
                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
×
93
        }
94

95
        return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
×
96
}
97

98
int read_one_char(FILE *f, char *ret, usec_t t, bool echo, bool *need_nl) {
4✔
99
        _cleanup_free_ char *line = NULL;
4✔
100
        struct termios old_termios;
4✔
101
        int r, fd;
4✔
102

103
        assert(ret);
4✔
104

105
        if (!f)
4✔
106
                f = stdin;
×
107

108
        /* If this is a terminal, then switch canonical mode off, so that we can read a single
109
         * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
110
         * nicely.) If 'echo' is false we'll also disable ECHO mode so that the pressed key is not made
111
         * visible to the user. */
112
        fd = fileno(f);
4✔
113
        if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
4✔
114
                struct termios new_termios = old_termios;
×
115

116
                new_termios.c_lflag &= ~(ICANON|(echo ? 0 : ECHO));
×
117
                new_termios.c_cc[VMIN] = 1;
×
118
                new_termios.c_cc[VTIME] = 0;
×
119

120
                if (tcsetattr(fd, TCSANOW, &new_termios) >= 0) {
×
121
                        char c;
×
122

123
                        if (t != USEC_INFINITY) {
×
124
                                if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
×
125
                                        (void) tcsetattr(fd, TCSANOW, &old_termios);
×
126
                                        return -ETIMEDOUT;
×
127
                                }
128
                        }
129

130
                        r = safe_fgetc(f, &c);
×
131
                        (void) tcsetattr(fd, TCSANOW, &old_termios);
×
132
                        if (r < 0)
×
133
                                return r;
134
                        if (r == 0)
×
135
                                return -EIO;
136

137
                        if (need_nl)
×
138
                                *need_nl = c != '\n';
×
139

140
                        *ret = c;
×
141
                        return 0;
×
142
                }
143
        }
144

145
        if (t != USEC_INFINITY && fd >= 0) {
4✔
146
                /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
147
                 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
148
                 * anyway, as the data is either already in the stream or cannot possible be placed there
149
                 * while we access the stream */
150

151
                if (fd_wait_for_event(fd, POLLIN, t) <= 0)
4✔
152
                        return -ETIMEDOUT;
153
        }
154

155
        /* If this is not a terminal, then read a full line instead */
156

157
        r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
4✔
158
        if (r < 0)
4✔
159
                return r;
160
        if (r == 0)
4✔
161
                return -EIO;
162

163
        if (strlen(line) != 1)
3✔
164
                return -EBADMSG;
165

166
        if (need_nl)
1✔
167
                *need_nl = false;
1✔
168

169
        *ret = line[0];
1✔
170
        return 0;
1✔
171
}
172

173
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
174

175
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
×
176
        int r;
×
177

178
        assert(ret);
×
179
        assert(replies);
×
180
        assert(fmt);
×
181

182
        for (;;) {
×
183
                va_list ap;
×
184
                char c;
×
185
                bool need_nl = true;
×
186

187
                fputs(ansi_highlight(), stdout);
×
188

189
                putchar('\r');
×
190

191
                va_start(ap, fmt);
×
192
                vprintf(fmt, ap);
×
193
                va_end(ap);
×
194

195
                fputs(ansi_normal(), stdout);
×
196

197
                fflush(stdout);
×
198

199
                r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, /* echo= */ true, &need_nl);
×
200
                if (r < 0) {
×
201

202
                        if (r == -ETIMEDOUT)
×
203
                                continue;
×
204

205
                        if (r == -EBADMSG) {
×
206
                                puts("Bad input, please try again.");
×
207
                                continue;
×
208
                        }
209

210
                        putchar('\n');
×
211
                        return r;
×
212
                }
213

214
                if (need_nl)
×
215
                        putchar('\n');
×
216

217
                if (strchr(replies, c)) {
×
218
                        *ret = c;
×
219
                        return 0;
×
220
                }
221

222
                puts("Read unexpected character, please try again.");
×
223
        }
224
}
225

226
typedef enum CompletionResult{
227
        COMPLETION_ALREADY,       /* the input string is already complete */
228
        COMPLETION_FULL,          /* completed the input string to be complete now */
229
        COMPLETION_PARTIAL,       /* completed the input string so that is still incomplete */
230
        COMPLETION_NONE,          /* found no matching completion */
231
        _COMPLETION_RESULT_MAX,
232
        _COMPLETION_RESULT_INVALID = -EINVAL,
233
        _COMPLETION_RESULT_ERRNO_MAX = -ERRNO_MAX,
234
} CompletionResult;
235

236
static CompletionResult pick_completion(const char *string, char *const*completions, char **ret) {
×
237
        _cleanup_free_ char *found = NULL;
×
238
        bool partial = false;
×
239

240
        string = strempty(string);
×
241

242
        STRV_FOREACH(c, completions) {
×
243

244
                /* Ignore entries that are not actually completions */
245
                if (!startswith(*c, string))
×
246
                        continue;
×
247

248
                /* Store first completion that matches */
249
                if (!found) {
×
250
                        found = strdup(*c);
×
251
                        if (!found)
×
252
                                return -ENOMEM;
253

254
                        continue;
×
255
                }
256

257
                /* If there's another completion that works truncate the one we already found by common
258
                 * prefix */
259
                size_t n = str_common_prefix(found, *c);
×
260
                if (n == SIZE_MAX)
×
261
                        continue;
×
262

263
                found[n] = 0;
×
264
                partial = true;
×
265
        }
266

267
        *ret = TAKE_PTR(found);
×
268

269
        if (!*ret)
×
270
                return COMPLETION_NONE;
271
        if (partial)
×
272
                return COMPLETION_PARTIAL;
273

274
        return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
×
275
}
276

277
static void clear_by_backspace(size_t n) {
×
278
        /* Erase the specified number of character cells backwards on the terminal */
279
        for (size_t i = 0; i < n; i++)
×
280
                fputs("\b \b", stdout);
×
281
}
×
282

283
int ask_string_full(
7✔
284
                char **ret,
285
                GetCompletionsCallback get_completions,
286
                void *userdata,
287
                const char *text, ...) {
288

289
        va_list ap;
7✔
290
        int r;
7✔
291

292
        assert(ret);
7✔
293
        assert(text);
7✔
294

295
        /* Output the prompt */
296
        fputs(ansi_highlight(), stdout);
14✔
297
        va_start(ap, text);
7✔
298
        vprintf(text, ap);
7✔
299
        va_end(ap);
7✔
300
        fputs(ansi_normal(), stdout);
14✔
301
        fflush(stdout);
7✔
302

303
        _cleanup_free_ char *string = NULL;
7✔
304
        size_t n = 0;
7✔
305

306
        /* Do interactive logic only if stdin + stdout are connected to the same place. And yes, we could use
307
         * STDIN_FILENO and STDOUT_FILENO here, but let's be overly correct for once, after all libc allows
308
         * swapping out stdin/stdout. */
309
        int fd_input = fileno(stdin);
7✔
310
        int fd_output = fileno(stdout);
7✔
311
        if (fd_input < 0 || fd_output < 0 || same_fd(fd_input, fd_output) <= 0)
7✔
312
                goto fallback;
7✔
313

314
        /* Try to disable echo, which also tells us if this even is a terminal */
315
        struct termios old_termios;
×
316
        if (tcgetattr(fd_input, &old_termios) < 0)
×
317
                goto fallback;
×
318

319
        struct termios new_termios = old_termios;
×
320
        termios_disable_echo(&new_termios);
×
321
        if (tcsetattr(fd_input, TCSANOW, &new_termios) < 0)
×
322
                return -errno;
×
323

324
        for (;;) {
×
325
                int c = fgetc(stdin);
×
326

327
                /* On EOF or NUL, end the request, don't output anything anymore */
328
                if (IN_SET(c, EOF, 0))
×
329
                        break;
330

331
                /* On Return also end the request, but make this visible */
332
                if (IN_SET(c, '\n', '\r')) {
×
333
                        fputc('\n', stdout);
×
334
                        break;
335
                }
336

337
                if (c == '\t') {
×
338
                        /* Tab */
339

340
                        _cleanup_strv_free_ char **completions = NULL;
×
341
                        if (get_completions) {
×
342
                                r = get_completions(string, &completions, userdata);
×
343
                                if (r < 0)
×
344
                                        goto fail;
×
345
                        }
346

347
                        _cleanup_free_ char *new_string = NULL;
×
348
                        CompletionResult cr = pick_completion(string, completions, &new_string);
×
349
                        if (cr < 0) {
×
350
                                r = cr;
×
351
                                goto fail;
×
352
                        }
353
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_FULL)) {
×
354
                                /* Output the new suffix we learned */
355
                                fputs(ASSERT_PTR(startswith(new_string, strempty(string))), stdout);
×
356

357
                                /* And update the whole string */
358
                                free_and_replace(string, new_string);
×
359
                                n = strlen(string);
×
360
                        }
361
                        if (cr == COMPLETION_NONE)
×
362
                                fputc('\a', stdout); /* BEL */
×
363

364
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_ALREADY)) {
×
365
                                /* If this worked only partially, or if the user hit TAB even though we were
366
                                 * complete already, then show the remaining options (in the latter case just
367
                                 * the one). */
368
                                fputc('\n', stdout);
×
369

370
                                _cleanup_strv_free_ char **filtered = strv_filter_prefix(completions, string);
×
371
                                if (!filtered) {
×
372
                                        r = -ENOMEM;
×
373
                                        goto fail;
×
374
                                }
375

376
                                r = show_menu(filtered,
×
377
                                              /* n_columns= */ SIZE_MAX,
378
                                              /* column_width= */ SIZE_MAX,
379
                                              /* ellipsize_percentage= */ 0,
380
                                              /* grey_prefix=*/ string,
381
                                              /* with_numbers= */ false);
382
                                if (r < 0)
×
383
                                        goto fail;
×
384

385
                                /* Show the prompt again */
386
                                fputs(ansi_highlight(), stdout);
×
387
                                va_start(ap, text);
×
388
                                vprintf(text, ap);
×
389
                                va_end(ap);
×
390
                                fputs(ansi_normal(), stdout);
×
391
                                fputs(string, stdout);
×
392
                        }
393

394
                } else if (IN_SET(c, '\b', 127)) {
×
395
                        /* Backspace */
396

397
                        if (n == 0)
×
398
                                fputc('\a', stdout); /* BEL */
×
399
                        else {
400
                                size_t m = utf8_last_length(string, n);
×
401

402
                                char *e = string + n - m;
×
403
                                clear_by_backspace(utf8_console_width(e));
×
404

405
                                *e = 0;
×
406
                                n -= m;
×
407
                        }
408

409
                } else if (c == 21) {
×
410
                        /* Ctrl-u → erase all input */
411

412
                        clear_by_backspace(utf8_console_width(string));
×
413
                        if (string)
×
414
                                string[n = 0] = 0;
×
415
                        else
416
                                assert(n == 0);
×
417

418
                } else if (c == 4) {
×
419
                        /* Ctrl-d → cancel this field input */
420

421
                        r = -ECANCELED;
×
422
                        goto fail;
×
423

424
                } else if (char_is_cc(c) || n >= LINE_MAX)
×
425
                        /* refuse control characters and too long strings */
426
                        fputc('\a', stdout); /* BEL */
×
427
                else {
428
                        /* Regular char */
429

430
                        if (!GREEDY_REALLOC(string, n+2)) {
×
431
                                r = -ENOMEM;
×
432
                                goto fail;
×
433
                        }
434

435
                        string[n++] = (char) c;
×
436
                        string[n] = 0;
×
437

438
                        fputc(c, stdout);
×
439
                }
440

441
                fflush(stdout);
×
442
        }
443

444
        if (tcsetattr(fd_input, TCSANOW, &old_termios) < 0)
×
445
                return -errno;
×
446

447
        if (!string) {
×
448
                string = strdup("");
×
449
                if (!string)
×
450
                        return -ENOMEM;
451
        }
452

453
        *ret = TAKE_PTR(string);
×
454
        return 0;
×
455

456
fail:
×
457
        (void) tcsetattr(fd_input, TCSANOW, &old_termios);
×
458
        return r;
×
459

460
fallback:
7✔
461
        /* A simple fallback without TTY magic */
462
        r = read_line(stdin, LONG_LINE_MAX, &string);
7✔
463
        if (r < 0)
7✔
464
                return r;
465
        if (r == 0)
7✔
466
                return -EIO;
467

468
        *ret = TAKE_PTR(string);
7✔
469
        return 0;
7✔
470
}
471

472
bool any_key_to_proceed(void) {
×
473

474
        /* Insert a new line here as well as to when the user inputs, as this is also used during the boot up
475
         * sequence when status messages may be interleaved with the current program output. This ensures
476
         * that the status messages aren't appended on the same line as this message. */
477

478
        fputc('\n', stdout);
×
479
        fputs(ansi_highlight_magenta(), stdout);
×
480
        fputs("-- Press any key to proceed --", stdout);
×
481
        fputs(ansi_normal(), stdout);
×
482
        fputc('\n', stdout);
×
483
        fflush(stdout);
×
484

485
        char key = 0;
×
486
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
×
487

488
        fputc('\n', stdout);
×
489
        fflush(stdout);
×
490

491
        return key != 'q';
×
492
}
493

494
static size_t widest_list_element(char *const*l) {
×
495
        size_t w = 0;
×
496

497
        /* Returns the largest console width of all elements in 'l' */
498

499
        STRV_FOREACH(i, l)
×
500
                w = MAX(w, utf8_console_width(*i));
×
501

502
        return w;
×
503
}
504

505
int show_menu(char **x,
×
506
              size_t n_columns,
507
              size_t column_width,
508
              unsigned ellipsize_percentage,
509
              const char *grey_prefix,
510
              bool with_numbers) {
511

512
        assert(n_columns > 0);
×
513

514
        if (n_columns == SIZE_MAX)
×
515
                n_columns = 3;
×
516

517
        if (column_width == SIZE_MAX) {
×
518
                size_t widest = widest_list_element(x);
×
519

520
                /* If not specified, derive column width from screen width */
521
                size_t column_max = (columns()-1) / n_columns;
×
522

523
                /* Subtract room for numbers */
524
                if (with_numbers && column_max > 6)
×
525
                        column_max -= 6;
×
526

527
                /* If columns would get too tight let's make this a linear list instead. */
528
                if (column_max < 10 && widest > 10) {
×
529
                        n_columns = 1;
×
530
                        column_max = columns()-1;
×
531

532
                        if (with_numbers && column_max > 6)
×
533
                                column_max -= 6;
×
534
                }
535

536
                column_width = CLAMP(widest+1, 10U, column_max);
×
537
        }
538

539
        size_t n = strv_length(x);
×
540
        size_t per_column = DIV_ROUND_UP(n, n_columns);
×
541

542
        size_t break_lines = lines();
×
543
        if (break_lines > 2)
×
544
                break_lines--;
×
545

546
        /* The first page gets two extra lines, since we want to show
547
         * a title */
548
        size_t break_modulo = break_lines;
×
549
        if (break_modulo > 3)
×
550
                break_modulo -= 3;
×
551

552
        for (size_t i = 0; i < per_column; i++) {
×
553

554
                for (size_t j = 0; j < n_columns; j++) {
×
555
                        _cleanup_free_ char *e = NULL;
×
556

557
                        if (j * per_column + i >= n)
×
558
                                break;
559

560
                        e = ellipsize(x[j * per_column + i], column_width, ellipsize_percentage);
×
561
                        if (!e)
×
562
                                return -ENOMEM;
×
563

564
                        if (with_numbers)
×
565
                                printf("%s%4zu)%s ",
×
566
                                       ansi_grey(),
567
                                       j * per_column + i + 1,
568
                                       ansi_normal());
569

570
                        if (grey_prefix && startswith(e, grey_prefix)) {
×
571
                                size_t k = MIN(strlen(grey_prefix), column_width);
×
572
                                printf("%s%.*s%s",
×
573
                                       ansi_grey(),
574
                                       (int) k, e,
575
                                       ansi_normal());
576
                                printf("%-*s",
×
577
                                       (int) (column_width - k), e+k);
×
578
                        } else
579
                                printf("%-*s", (int) column_width, e);
×
580
                }
581

582
                putchar('\n');
×
583

584
                /* on the first screen we reserve 2 extra lines for the title */
585
                if (i % break_lines == break_modulo)
×
586
                        if (!any_key_to_proceed())
×
587
                                return 0;
588
        }
589

590
        return 0;
591
}
592

593
int open_terminal(const char *name, int mode) {
45,161✔
594
        _cleanup_close_ int fd = -EBADF;
45,161✔
595

596
        /*
597
         * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
598
         * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
599
         * times.
600
         *
601
         * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
602
         */
603

604
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
45,161✔
605

606
        for (unsigned c = 0;; c++) {
×
607
                fd = open(name, mode, 0);
45,161✔
608
                if (fd >= 0)
45,161✔
609
                        break;
610

611
                if (errno != EIO)
1,191✔
612
                        return -errno;
1,191✔
613

614
                /* Max 1s in total */
615
                if (c >= 20)
×
616
                        return -EIO;
617

618
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
619
        }
620

621
        if (!isatty_safe(fd))
43,970✔
622
                return -ENOTTY;
1✔
623

624
        return TAKE_FD(fd);
625
}
626

627
int acquire_terminal(
191✔
628
                const char *name,
629
                AcquireTerminalFlags flags,
630
                usec_t timeout) {
631

632
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
191✔
633
        usec_t ts = USEC_INFINITY;
191✔
634
        int r, wd = -1;
191✔
635

636
        assert(name);
191✔
637

638
        AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
191✔
639
        assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
191✔
640
        assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
191✔
641

642
        /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
643
         * acquire it, so that we don't lose any event.
644
         *
645
         * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
646
         * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
647
         * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
648
         * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
649
         * probably should not do anyway.) */
650

651
        if (mode == ACQUIRE_TERMINAL_WAIT) {
×
652
                notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
191✔
653
                if (notify < 0)
191✔
654
                        return -errno;
×
655

656
                wd = inotify_add_watch(notify, name, IN_CLOSE);
191✔
657
                if (wd < 0)
191✔
UNCOV
658
                        return -errno;
×
659

660
                if (timeout != USEC_INFINITY)
191✔
661
                        ts = now(CLOCK_MONOTONIC);
×
662
        }
663

664
        /* If we are called with ACQUIRE_TERMINAL_WATCH_SIGTERM we'll unblock SIGTERM during ppoll() temporarily */
665
        sigset_t poll_ss;
191✔
666
        assert_se(sigprocmask(SIG_SETMASK, /* newset= */ NULL, &poll_ss) >= 0);
191✔
667
        if (flags & ACQUIRE_TERMINAL_WATCH_SIGTERM) {
191✔
668
                assert_se(sigismember(&poll_ss, SIGTERM) > 0);
1✔
669
                assert_se(sigdelset(&poll_ss, SIGTERM) >= 0);
1✔
670
        }
671

672
        for (;;) {
191✔
673
                if (notify >= 0) {
191✔
674
                        r = flush_fd(notify);
191✔
675
                        if (r < 0)
191✔
676
                                return r;
×
677
                }
678

679
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
680
                 * to figure out if we successfully became the controlling process of the tty */
681
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
191✔
682
                if (fd < 0)
191✔
683
                        return fd;
684

685
                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
686
                struct sigaction sa_old;
191✔
687
                assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
191✔
688

689
                /* First, try to get the tty */
690
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
191✔
691

692
                /* Reset signal handler to old value */
693
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
191✔
694

695
                /* Success? Exit the loop now! */
696
                if (r >= 0)
191✔
697
                        break;
698

699
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
700
                if (r != -EPERM)
×
701
                        return r;
702

703
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
×
704
                                                          * into a success. Note that EPERM is also returned if we
705
                                                          * already are the owner of the TTY. */
706
                        break;
707

708
                if (mode != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
×
709
                        return r;
710

711
                assert(notify >= 0);
×
712
                assert(wd >= 0);
×
713

714
                for (;;) {
×
715
                        usec_t left;
×
716
                        if (timeout == USEC_INFINITY)
×
717
                                left = USEC_INFINITY;
718
                        else {
719
                                assert(ts != USEC_INFINITY);
×
720

721
                                usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
722
                                if (n >= timeout)
×
723
                                        return -ETIMEDOUT;
×
724

725
                                left = timeout - n;
×
726
                        }
727

728
                        r = ppoll_usec_full(
×
729
                                        &(struct pollfd) {
×
730
                                                .fd = notify,
731
                                                .events = POLLIN,
732
                                        },
733
                                        /* n_fds = */ 1,
734
                                        left,
735
                                        &poll_ss);
736
                        if (r < 0)
×
737
                                return r;
738
                        if (r == 0)
×
739
                                return -ETIMEDOUT;
740

741
                        union inotify_event_buffer buffer;
×
742
                        ssize_t l;
×
743
                        l = read(notify, &buffer, sizeof(buffer));
×
744
                        if (l < 0) {
×
745
                                if (ERRNO_IS_TRANSIENT(errno))
×
746
                                        continue;
×
747

748
                                return -errno;
×
749
                        }
750

751
                        FOREACH_INOTIFY_EVENT(e, buffer, l) {
×
752
                                if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
×
753
                                        break;
754

755
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
×
756
                                        return -EIO;
×
757
                        }
758

759
                        break;
×
760
                }
761

762
                /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
763
                 * we do this after sleeping, so that we don't enter an endless loop. */
764
                fd = safe_close(fd);
×
765
        }
766

767
        return TAKE_FD(fd);
191✔
768
}
769

770
int release_terminal(void) {
58✔
771
        _cleanup_close_ int fd = -EBADF;
58✔
772
        int r;
58✔
773

774
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
58✔
775
        if (fd < 0)
58✔
776
                return -errno;
36✔
777

778
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
779
         * by our own TIOCNOTTY */
780
        struct sigaction sa_old;
22✔
781
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
22✔
782

783
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
22✔
784

785
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
22✔
786

787
        return r;
788
}
789

790
int terminal_new_session(void) {
5✔
791

792
        /* Make us the new session leader, and set stdin tty to be our controlling terminal.
793
         *
794
         * Why stdin? Well, the ctty logic is relevant for signal delivery mostly, i.e. if people hit C-c
795
         * or the line is hung up. Such events are basically just a form of input, via a side channel
796
         * (that side channel being signal delivery, i.e. SIGINT, SIGHUP et al). Hence we focus on input,
797
         * not output here. */
798

799
        if (!isatty_safe(STDIN_FILENO))
5✔
800
                return -ENXIO;
801

802
        (void) setsid();
4✔
803
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
4✔
804
}
805

806
void terminal_detach_session(void) {
57✔
807
        (void) setsid();
57✔
808
        (void) release_terminal();
57✔
809
}
57✔
810

811
int terminal_vhangup_fd(int fd) {
101✔
812
        assert(fd >= 0);
101✔
813
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
101✔
814
}
815

816
int terminal_vhangup(const char *tty) {
×
817
        _cleanup_close_ int fd = -EBADF;
×
818

819
        assert(tty);
×
820

821
        fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
×
822
        if (fd < 0)
×
823
                return fd;
824

825
        return terminal_vhangup_fd(fd);
×
826
}
827

828
int vt_disallocate(const char *tty_path) {
51✔
829
        assert(tty_path);
51✔
830

831
        /* Deallocate the VT if possible. If not possible (i.e. because it is the active one), at least clear
832
         * it entirely (including the scrollback buffer). */
833

834
        int ttynr = vtnr_from_tty(tty_path);
51✔
835
        if (ttynr > 0) {
51✔
836
                _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
51✔
837
                if (fd < 0)
51✔
838
                        return fd;
839

840
                /* Try to deallocate */
841
                if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
51✔
842
                        return 0;
843
                if (errno != EBUSY)
51✔
844
                        return -errno;
×
845
        }
846

847
        /* So this is not a VT (in which case we cannot deallocate it), or we failed to deallocate. Let's at
848
         * least clear the screen. */
849

850
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
102✔
851
        if (fd2 < 0)
51✔
852
                return fd2;
853

854
        return loop_write_full(fd2,
51✔
855
                               "\033[r"   /* clear scrolling region */
856
                               "\033[H"   /* move home */
857
                               "\033[3J"  /* clear screen including scrollback, requires Linux 2.6.40 */
858
                               "\033c",   /* reset to initial state */
859
                               SIZE_MAX,
860
                               100 * USEC_PER_MSEC);
861
}
862

863
static int vt_default_utf8(void) {
902✔
864
        _cleanup_free_ char *b = NULL;
902✔
865
        int r;
902✔
866

867
        /* Read the default VT UTF8 setting from the kernel */
868

869
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
902✔
870
        if (r < 0)
902✔
871
                return r;
872

873
        return parse_boolean(b);
500✔
874
}
875

876
static int vt_reset_keyboard(int fd) {
451✔
877
        int r, kb;
451✔
878

879
        assert(fd >= 0);
451✔
880

881
        /* If we can't read the default, then default to Unicode. It's 2024 after all. */
882
        r = vt_default_utf8();
451✔
883
        if (r < 0)
451✔
884
                log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
201✔
885

886
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
451✔
887
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
451✔
888
}
889

890
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
451✔
891
        struct termios termios;
451✔
892
        int r;
451✔
893

894
        /* Set terminal to some sane defaults */
895

896
        assert(fd >= 0);
451✔
897

898
        /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
899
         * and we don't interfere with that. */
900

901
        /* Disable exclusive mode, just in case */
902
        if (ioctl(fd, TIOCNXCL) < 0)
451✔
903
                log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
2✔
904

905
        /* Switch to text mode */
906
        if (switch_to_text)
451✔
907
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
219✔
908
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
168✔
909

910
        /* Set default keyboard mode */
911
        r = vt_reset_keyboard(fd);
451✔
912
        if (r < 0)
451✔
913
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
352✔
914

915
        if (tcgetattr(fd, &termios) < 0) {
451✔
916
                r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
2✔
917
                goto finish;
2✔
918
        }
919

920
        /* We only reset the stuff that matters to the software. How
921
         * hardware is set up we don't touch assuming that somebody
922
         * else will do that for us */
923

924
        termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
449✔
925
        termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
449✔
926
        termios.c_oflag |= ONLCR | OPOST;
449✔
927
        termios.c_cflag |= CREAD;
449✔
928
        termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
449✔
929

930
        termios.c_cc[VINTR]    =   03;  /* ^C */
449✔
931
        termios.c_cc[VQUIT]    =  034;  /* ^\ */
449✔
932
        termios.c_cc[VERASE]   = 0177;
449✔
933
        termios.c_cc[VKILL]    =  025;  /* ^X */
449✔
934
        termios.c_cc[VEOF]     =   04;  /* ^D */
449✔
935
        termios.c_cc[VSTART]   =  021;  /* ^Q */
449✔
936
        termios.c_cc[VSTOP]    =  023;  /* ^S */
449✔
937
        termios.c_cc[VSUSP]    =  032;  /* ^Z */
449✔
938
        termios.c_cc[VLNEXT]   =  026;  /* ^V */
449✔
939
        termios.c_cc[VWERASE]  =  027;  /* ^W */
449✔
940
        termios.c_cc[VREPRINT] =  022;  /* ^R */
449✔
941
        termios.c_cc[VEOL]     =    0;
449✔
942
        termios.c_cc[VEOL2]    =    0;
449✔
943

944
        termios.c_cc[VTIME]  = 0;
449✔
945
        termios.c_cc[VMIN]   = 1;
449✔
946

947
        r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
449✔
948
        if (r < 0)
×
949
                log_debug_errno(r, "Failed to set terminal parameters: %m");
×
950

951
finish:
×
952
        /* Just in case, flush all crap out */
953
        (void) tcflush(fd, TCIOFLUSH);
451✔
954

955
        return r;
451✔
956
}
957

958
int terminal_reset_ansi_seq(int fd) {
444✔
959
        int r, k;
444✔
960

961
        assert(fd >= 0);
444✔
962

963
        if (getenv_terminal_is_dumb())
444✔
964
                return 0;
965

966
        r = fd_nonblock(fd, true);
×
967
        if (r < 0)
×
968
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
969

970
        k = loop_write_full(fd,
×
971
                            "\033[!p"      /* soft terminal reset */
972
                            "\033]104\007" /* reset colors */
973
                            "\033[?7h"     /* enable line-wrapping */
974
                            "\033[1G"      /* place cursor at beginning of current line */
975
                            "\033[0J",     /* erase till end of screen */
976
                            SIZE_MAX,
977
                            100 * USEC_PER_MSEC);
978
        if (k < 0)
×
979
                log_debug_errno(k, "Failed to reset terminal through ANSI sequences: %m");
×
980

981
        if (r > 0) {
×
982
                r = fd_nonblock(fd, false);
×
983
                if (r < 0)
×
984
                        log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
×
985
        }
986

987
        return k < 0 ? k : r;
×
988
}
989

990
void reset_dev_console_fd(int fd, bool switch_to_text) {
37✔
991
        int r;
37✔
992

993
        assert(fd >= 0);
37✔
994

995
        _cleanup_close_ int lock_fd = lock_dev_console();
37✔
996
        if (lock_fd < 0)
37✔
997
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
998

999
        r = terminal_reset_ioctl(fd, switch_to_text);
37✔
1000
        if (r < 0)
37✔
1001
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
×
1002

1003
        unsigned rows, cols;
37✔
1004
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
37✔
1005
        if (r < 0)
37✔
1006
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
×
1007
        else if (r > 0) {
37✔
1008
                r = terminal_set_size_fd(fd, NULL, rows, cols);
37✔
1009
                if (r < 0)
37✔
1010
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
×
1011
        } else
1012
                (void) terminal_fix_size(fd, fd);
×
1013

1014
        r = terminal_reset_ansi_seq(fd);
37✔
1015
        if (r < 0)
37✔
1016
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
37✔
1017
}
37✔
1018

1019
int lock_dev_console(void) {
583✔
1020
        _cleanup_close_ int fd = -EBADF;
583✔
1021
        int r;
583✔
1022

1023
        /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
1024
         * pty in /dev/console, in which case it should be fine to lock the target TTY. */
1025
        fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
583✔
1026
        if (fd < 0)
583✔
1027
                return fd;
1028

1029
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
583✔
1030
        if (r < 0)
583✔
1031
                return r;
×
1032

1033
        return TAKE_FD(fd);
1034
}
1035

1036
int make_console_stdio(void) {
×
1037
        int fd, r;
×
1038

1039
        /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
1040
         * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
1041
         * is specified on the kernel command line. */
1042

1043
        fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
×
1044
        if (fd < 0) {
×
1045
                log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
×
1046

1047
                r = make_null_stdio();
×
1048
                if (r < 0)
×
1049
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
×
1050

1051
        } else {
1052
                reset_dev_console_fd(fd, /* switch_to_text= */ true);
×
1053

1054
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
×
1055
                if (r < 0)
×
1056
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
×
1057
        }
1058

1059
        reset_terminal_feature_caches();
×
1060
        return 0;
×
1061
}
1062

1063
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
313✔
1064
        assert(tty);
313✔
1065

1066
        tty = skip_dev_prefix(tty);
313✔
1067

1068
        const char *e = startswith(tty, "tty");
313✔
1069
        if (!e)
313✔
1070
                return -EINVAL;
1071

1072
        return safe_atou(e, ret);
272✔
1073
}
1074

1075
int vtnr_from_tty(const char *tty) {
183✔
1076
        unsigned u;
183✔
1077
        int r;
183✔
1078

1079
        assert(tty);
183✔
1080

1081
        r = vtnr_from_tty_raw(tty, &u);
183✔
1082
        if (r < 0)
183✔
1083
                return r;
183✔
1084
        if (!vtnr_is_valid(u))
183✔
1085
                return -ERANGE;
1086

1087
        return (int) u;
183✔
1088
}
1089

1090
bool tty_is_vc(const char *tty) {
130✔
1091
        assert(tty);
130✔
1092

1093
        /* NB: for >= 0 values no range check is conducted here, on the assumption that the caller will
1094
         * either extract vtnr through vtnr_from_tty() later where ERANGE would be reported, or doesn't care
1095
         * about whether it's strictly valid, but only asking "does this fall into the vt category?", for which
1096
         * "yes" seems to be a better answer. */
1097

1098
        return vtnr_from_tty_raw(tty, /* ret = */ NULL) >= 0;
130✔
1099
}
1100

1101
bool tty_is_console(const char *tty) {
450✔
1102
        assert(tty);
450✔
1103

1104
        return streq(skip_dev_prefix(tty), "console");
450✔
1105
}
1106

1107
int resolve_dev_console(char **ret) {
182✔
1108
        int r;
182✔
1109

1110
        assert(ret);
182✔
1111

1112
        /* Resolve where /dev/console is pointing to. If /dev/console is a symlink (like in container
1113
         * managers), we'll just resolve the symlink. If it's a real device node, we'll use if
1114
         * /sys/class/tty/tty0/active, but only if /sys/ is actually ours (i.e. not read-only-mounted which
1115
         * is a sign for container setups). */
1116

1117
        _cleanup_free_ char *chased = NULL;
182✔
1118
        r = chase("/dev/console", /* root= */ NULL, /* flags= */ 0,  &chased, /* ret_fd= */ NULL);
182✔
1119
        if (r < 0)
182✔
1120
                return r;
1121
        if (!path_equal(chased, "/dev/console")) {
182✔
1122
                *ret = TAKE_PTR(chased);
83✔
1123
                return 0;
83✔
1124
        }
1125

1126
        r = path_is_read_only_fs("/sys");
99✔
1127
        if (r < 0)
99✔
1128
                return r;
1129
        if (r > 0)
99✔
1130
                return -ENOMEDIUM;
1131

1132
        _cleanup_free_ char *active = NULL;
99✔
1133
        r = read_one_line_file("/sys/class/tty/console/active", &active);
99✔
1134
        if (r < 0)
99✔
1135
                return r;
1136

1137
        /* If multiple log outputs are configured the last one is what /dev/console points to */
1138
        const char *tty = strrchr(active, ' ');
99✔
1139
        if (tty)
99✔
1140
                tty++;
×
1141
        else
1142
                tty = active;
1143

1144
        if (streq(tty, "tty0")) {
99✔
1145
                active = mfree(active);
×
1146

1147
                /* Get the active VC (e.g. tty1) */
1148
                r = read_one_line_file("/sys/class/tty/tty0/active", &active);
×
1149
                if (r < 0)
×
1150
                        return r;
1151

1152
                tty = active;
×
1153
        }
1154

1155
        _cleanup_free_ char *path = NULL;
99✔
1156
        path = path_join("/dev", tty);
99✔
1157
        if (!path)
99✔
1158
                return -ENOMEM;
1159

1160
        *ret = TAKE_PTR(path);
99✔
1161
        return 0;
99✔
1162
}
1163

1164
int get_kernel_consoles(char ***ret) {
1✔
1165
        _cleanup_strv_free_ char **l = NULL;
×
1166
        _cleanup_free_ char *line = NULL;
1✔
1167
        int r;
1✔
1168

1169
        assert(ret);
1✔
1170

1171
        /* If /sys/ is mounted read-only this means we are running in some kind of container environment.
1172
         * In that case /sys/ would reflect the host system, not us, hence ignore the data we can read from it. */
1173
        if (path_is_read_only_fs("/sys") > 0)
1✔
1174
                goto fallback;
1✔
1175

1176
        r = read_one_line_file("/sys/class/tty/console/active", &line);
×
1177
        if (r < 0)
×
1178
                return r;
1179

1180
        for (const char *p = line;;) {
×
1181
                _cleanup_free_ char *tty = NULL, *path = NULL;
×
1182

1183
                r = extract_first_word(&p, &tty, NULL, 0);
×
1184
                if (r < 0)
×
1185
                        return r;
1186
                if (r == 0)
×
1187
                        break;
1188

1189
                if (streq(tty, "tty0")) {
×
1190
                        tty = mfree(tty);
×
1191
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
1192
                        if (r < 0)
×
1193
                                return r;
1194
                }
1195

1196
                path = path_join("/dev", tty);
×
1197
                if (!path)
×
1198
                        return -ENOMEM;
1199

1200
                if (access(path, F_OK) < 0) {
×
1201
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
×
1202
                        continue;
×
1203
                }
1204

1205
                r = strv_consume(&l, TAKE_PTR(path));
×
1206
                if (r < 0)
×
1207
                        return r;
1208
        }
1209

1210
        if (strv_isempty(l)) {
×
1211
                log_debug("No devices found for system console");
×
1212
                goto fallback;
×
1213
        }
1214

1215
        *ret = TAKE_PTR(l);
×
1216
        return strv_length(*ret);
×
1217

1218
fallback:
1✔
1219
        r = strv_extend(&l, "/dev/console");
1✔
1220
        if (r < 0)
1✔
1221
                return r;
1222

1223
        *ret = TAKE_PTR(l);
1✔
1224
        return 0;
1✔
1225
}
1226

1227
bool tty_is_vc_resolve(const char *tty) {
51✔
1228
        _cleanup_free_ char *resolved = NULL;
51✔
1229

1230
        assert(tty);
51✔
1231

1232
        if (streq(skip_dev_prefix(tty), "console")) {
51✔
1233
                if (resolve_dev_console(&resolved) < 0)
1✔
1234
                        return false;
1235

1236
                tty = resolved;
1✔
1237
        }
1238

1239
        return tty_is_vc(tty);
51✔
1240
}
1241

1242
int fd_columns(int fd) {
1,342✔
1243
        struct winsize ws = {};
1,342✔
1244

1245
        if (fd < 0)
1,342✔
1246
                return -EBADF;
1247

1248
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1,342✔
1249
                return -errno;
1,342✔
1250

1251
        if (ws.ws_col <= 0)
×
1252
                return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
1253

1254
        return ws.ws_col;
×
1255
}
1256

1257
int getenv_columns(void) {
1,603✔
1258
        int r;
1,603✔
1259

1260
        const char *e = getenv("COLUMNS");
1,603✔
1261
        if (!e)
1,603✔
1262
                return -ENXIO;
1,603✔
1263

1264
        unsigned c;
1✔
1265
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
1✔
1266
        if (r < 0)
1✔
1267
                return r;
1268

1269
        return (int) c;
1✔
1270
}
1271

1272
unsigned columns(void) {
231,383✔
1273

1274
        if (cached_columns > 0)
231,383✔
1275
                return cached_columns;
230,040✔
1276

1277
        int c = getenv_columns();
1,343✔
1278
        if (c < 0) {
1,343✔
1279
                c = fd_columns(STDOUT_FILENO);
1,342✔
1280
                if (c < 0)
1,342✔
1281
                        c = 80;
1282
        }
1283

1284
        assert(c > 0);
1✔
1285

1286
        cached_columns = c;
1,343✔
1287
        return cached_columns;
1,343✔
1288
}
1289

1290
int fd_lines(int fd) {
194✔
1291
        struct winsize ws = {};
194✔
1292

1293
        if (fd < 0)
194✔
1294
                return -EBADF;
1295

1296
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
194✔
1297
                return -errno;
194✔
1298

1299
        if (ws.ws_row <= 0)
×
1300
                return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
1301

1302
        return ws.ws_row;
×
1303
}
1304

1305
unsigned lines(void) {
194✔
1306
        const char *e;
194✔
1307
        int l;
194✔
1308

1309
        if (cached_lines > 0)
194✔
1310
                return cached_lines;
×
1311

1312
        l = 0;
194✔
1313
        e = getenv("LINES");
194✔
1314
        if (e)
194✔
1315
                (void) safe_atoi(e, &l);
×
1316

1317
        if (l <= 0 || l > USHRT_MAX) {
194✔
1318
                l = fd_lines(STDOUT_FILENO);
194✔
1319
                if (l <= 0)
194✔
1320
                        l = 24;
194✔
1321
        }
1322

1323
        cached_lines = l;
194✔
1324
        return cached_lines;
194✔
1325
}
1326

1327
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
559✔
1328
        struct winsize ws;
559✔
1329

1330
        assert(fd >= 0);
559✔
1331

1332
        if (!ident)
559✔
1333
                ident = "TTY";
79✔
1334

1335
        if (rows == UINT_MAX && cols == UINT_MAX)
559✔
1336
                return 0;
559✔
1337

1338
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
418✔
1339
                return log_debug_errno(errno,
×
1340
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1341
                                       ident);
1342

1343
        if (rows == UINT_MAX)
418✔
1344
                rows = ws.ws_row;
×
1345
        else if (rows > USHRT_MAX)
418✔
1346
                rows = USHRT_MAX;
×
1347

1348
        if (cols == UINT_MAX)
418✔
1349
                cols = ws.ws_col;
×
1350
        else if (cols > USHRT_MAX)
418✔
1351
                cols = USHRT_MAX;
×
1352

1353
        if (rows == ws.ws_row && cols == ws.ws_col)
418✔
1354
                return 0;
1355

1356
        ws.ws_row = rows;
136✔
1357
        ws.ws_col = cols;
136✔
1358

1359
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
136✔
1360
                return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
×
1361

1362
        return 0;
1363
}
1364

1365
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
517✔
1366
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
517✔
1367
        unsigned rows = UINT_MAX, cols = UINT_MAX;
517✔
1368
        int r;
517✔
1369

1370
        assert(tty);
517✔
1371

1372
        if (!ret_rows && !ret_cols)
517✔
1373
                return 0;
1374

1375
        tty = skip_dev_prefix(tty);
517✔
1376
        if (path_startswith(tty, "pts/"))
517✔
1377
                return -EMEDIUMTYPE;
1378
        if (!in_charset(tty, ALPHANUMERICAL))
517✔
1379
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
×
1380
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1381

1382
        rowskey = strjoin("systemd.tty.rows.", tty);
517✔
1383
        if (!rowskey)
517✔
1384
                return -ENOMEM;
1385

1386
        colskey = strjoin("systemd.tty.columns.", tty);
517✔
1387
        if (!colskey)
517✔
1388
                return -ENOMEM;
1389

1390
        r = proc_cmdline_get_key_many(/* flags = */ 0,
517✔
1391
                                      rowskey, &rowsvalue,
1392
                                      colskey, &colsvalue);
1393
        if (r < 0)
517✔
1394
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
×
1395

1396
        if (rowsvalue) {
517✔
1397
                r = safe_atou(rowsvalue, &rows);
418✔
1398
                if (r < 0)
418✔
1399
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
×
1400
        }
1401

1402
        if (colsvalue) {
517✔
1403
                r = safe_atou(colsvalue, &cols);
418✔
1404
                if (r < 0)
418✔
1405
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
×
1406
        }
1407

1408
        if (ret_rows)
517✔
1409
                *ret_rows = rows;
517✔
1410
        if (ret_cols)
517✔
1411
                *ret_cols = cols;
517✔
1412

1413
        return rows != UINT_MAX || cols != UINT_MAX;
517✔
1414
}
1415

1416
/* intended to be used as a SIGWINCH sighandler */
1417
void columns_lines_cache_reset(int signum) {
×
1418
        cached_columns = 0;
×
1419
        cached_lines = 0;
×
1420
}
×
1421

1422
void reset_terminal_feature_caches(void) {
14✔
1423
        cached_columns = 0;
14✔
1424
        cached_lines = 0;
14✔
1425

1426
        cached_on_tty = -1;
14✔
1427
        cached_on_dev_null = -1;
14✔
1428

1429
        reset_ansi_feature_caches();
14✔
1430
}
14✔
1431

1432
bool on_tty(void) {
7,412,880✔
1433

1434
        /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
1435
         * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
1436
         * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
1437
         * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
1438
         * terminal functionality when outputting stuff, even if the input is piped to us. */
1439

1440
        if (cached_on_tty < 0)
7,412,880✔
1441
                cached_on_tty =
32,448✔
1442
                        isatty_safe(STDOUT_FILENO) &&
32,479✔
1443
                        isatty_safe(STDERR_FILENO);
31✔
1444

1445
        return cached_on_tty;
7,412,880✔
1446
}
1447

1448
int getttyname_malloc(int fd, char **ret) {
532✔
1449
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
532✔
1450
        int r;
532✔
1451

1452
        assert(fd >= 0);
532✔
1453
        assert(ret);
532✔
1454

1455
        r = ttyname_r(fd, path, sizeof path); /* positive error */
532✔
1456
        assert(r >= 0);
532✔
1457
        if (r == ERANGE)
532✔
1458
                return -ENAMETOOLONG;
532✔
1459
        if (r > 0)
532✔
1460
                return -r;
525✔
1461

1462
        return strdup_to(ret, skip_dev_prefix(path));
7✔
1463
}
1464

1465
int getttyname_harder(int fd, char **ret) {
24✔
1466
        _cleanup_free_ char *s = NULL;
24✔
1467
        int r;
24✔
1468

1469
        r = getttyname_malloc(fd, &s);
24✔
1470
        if (r < 0)
24✔
1471
                return r;
1472

1473
        if (streq(s, "tty"))
×
1474
                return get_ctty(0, NULL, ret);
×
1475

1476
        *ret = TAKE_PTR(s);
×
1477
        return 0;
×
1478
}
1479

1480
int get_ctty_devnr(pid_t pid, dev_t *ret) {
4,422✔
1481
        _cleanup_free_ char *line = NULL;
4,422✔
1482
        unsigned long ttynr;
4,422✔
1483
        const char *p;
4,422✔
1484
        int r;
4,422✔
1485

1486
        assert(pid >= 0);
4,422✔
1487

1488
        p = procfs_file_alloca(pid, "stat");
21,770✔
1489
        r = read_one_line_file(p, &line);
4,422✔
1490
        if (r < 0)
4,422✔
1491
                return r;
1492

1493
        p = strrchr(line, ')');
4,422✔
1494
        if (!p)
4,422✔
1495
                return -EIO;
1496

1497
        p++;
4,422✔
1498

1499
        if (sscanf(p, " "
4,422✔
1500
                   "%*c "  /* state */
1501
                   "%*d "  /* ppid */
1502
                   "%*d "  /* pgrp */
1503
                   "%*d "  /* session */
1504
                   "%lu ", /* ttynr */
1505
                   &ttynr) != 1)
1506
                return -EIO;
1507

1508
        if (devnum_is_zero(ttynr))
4,422✔
1509
                return -ENXIO;
1510

1511
        if (ret)
4✔
1512
                *ret = (dev_t) ttynr;
2✔
1513

1514
        return 0;
1515
}
1516

1517
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
31✔
1518
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
31✔
1519
        _cleanup_free_ char *buf = NULL;
31✔
1520
        const char *fn = NULL, *w;
31✔
1521
        dev_t devnr;
31✔
1522
        int r;
31✔
1523

1524
        r = get_ctty_devnr(pid, &devnr);
31✔
1525
        if (r < 0)
31✔
1526
                return r;
1527

1528
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
2✔
1529
        if (r < 0) {
2✔
1530
                struct stat st;
2✔
1531

1532
                if (r != -ENOENT) /* No symlink for this in /dev/char/? */
2✔
1533
                        return r;
×
1534

1535
                /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
1536
                 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
1537
                 * assume this is a PTY for a moment, and check if the device node this would then map to in
1538
                 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
1539
                 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
1540
                 * the minor number of the pty. */
1541
                xsprintf(pty, "/dev/pts/%u", minor(devnr));
2✔
1542

1543
                if (stat(pty, &st) < 0) {
2✔
1544
                        if (errno != ENOENT)
×
1545
                                return -errno;
×
1546

1547
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
2✔
1548
                        fn = pty;
1549

1550
                if (!fn) {
1551
                        /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1552
                         * symlink in /dev/char/. Let's return something vaguely useful. */
1553
                        r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
×
1554
                        if (r < 0)
×
1555
                                return r;
1556

1557
                        fn = buf;
×
1558
                }
1559
        } else
1560
                fn = buf;
×
1561

1562
        w = path_startswith(fn, "/dev/");
2✔
1563
        if (!w)
2✔
1564
                return -EINVAL;
1565

1566
        if (ret) {
2✔
1567
                r = strdup_to(ret, w);
2✔
1568
                if (r < 0)
2✔
1569
                        return r;
1570
        }
1571

1572
        if (ret_devnr)
2✔
1573
                *ret_devnr = devnr;
×
1574

1575
        return 0;
1576
}
1577

1578
int ptsname_malloc(int fd, char **ret) {
137✔
1579
        assert(fd >= 0);
137✔
1580
        assert(ret);
137✔
1581

1582
        for (size_t l = 50;;) {
×
1583
                _cleanup_free_ char *c = NULL;
×
1584

1585
                c = new(char, l);
137✔
1586
                if (!c)
137✔
1587
                        return -ENOMEM;
1588

1589
                if (ptsname_r(fd, c, l) >= 0) {
137✔
1590
                        *ret = TAKE_PTR(c);
137✔
1591
                        return 0;
137✔
1592
                }
1593
                if (errno != ERANGE)
×
1594
                        return -errno;
×
1595

1596
                if (!MUL_ASSIGN_SAFE(&l, 2))
×
1597
                        return -ENOMEM;
1598
        }
1599
}
1600

1601
int openpt_allocate(int flags, char **ret_peer_path) {
141✔
1602
        _cleanup_close_ int fd = -EBADF;
141✔
1603
        int r;
141✔
1604

1605
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
141✔
1606
        if (fd < 0)
141✔
1607
                return -errno;
×
1608

1609
        _cleanup_free_ char *p = NULL;
141✔
1610
        if (ret_peer_path) {
141✔
1611
                r = ptsname_malloc(fd, &p);
137✔
1612
                if (r < 0)
137✔
1613
                        return r;
1614

1615
                if (!path_startswith(p, "/dev/pts/"))
137✔
1616
                        return -EINVAL;
1617
        }
1618

1619
        if (unlockpt(fd) < 0)
141✔
1620
                return -errno;
×
1621

1622
        if (ret_peer_path)
141✔
1623
                *ret_peer_path = TAKE_PTR(p);
137✔
1624

1625
        return TAKE_FD(fd);
1626
}
1627

1628
static int ptsname_namespace(int pty, char **ret) {
×
1629
        int no = -1;
×
1630

1631
        assert(pty >= 0);
×
1632
        assert(ret);
×
1633

1634
        /* Like ptsname(), but doesn't assume that the path is
1635
         * accessible in the local namespace. */
1636

1637
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
1638
                return -errno;
×
1639

1640
        if (no < 0)
×
1641
                return -EIO;
1642

1643
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
1644
                return -ENOMEM;
×
1645

1646
        return 0;
1647
}
1648

1649
int openpt_allocate_in_namespace(
×
1650
                const PidRef *pidref,
1651
                int flags,
1652
                char **ret_peer_path) {
1653

1654
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
1655
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
1656
        int r;
×
1657

1658
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
×
1659
        if (r < 0)
×
1660
                return r;
1661

1662
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
1663
                return -errno;
×
1664

1665
        r = namespace_fork(
×
1666
                        "(sd-openptns)",
1667
                        "(sd-openpt)",
1668
                        /* except_fds= */ NULL,
1669
                        /* n_except_fds= */ 0,
1670
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1671
                        pidnsfd,
1672
                        mntnsfd,
1673
                        /* netns_fd= */ -EBADF,
1674
                        usernsfd,
1675
                        rootfd,
1676
                        /* ret_pid= */ NULL);
1677
        if (r < 0)
×
1678
                return r;
1679
        if (r == 0) {
×
1680
                pair[0] = safe_close(pair[0]);
×
1681

1682
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1683
                if (fd < 0)
×
1684
                        _exit(EXIT_FAILURE);
×
1685

1686
                if (send_one_fd(pair[1], fd, 0) < 0)
×
1687
                        _exit(EXIT_FAILURE);
×
1688

1689
                _exit(EXIT_SUCCESS);
×
1690
        }
1691

1692
        pair[1] = safe_close(pair[1]);
×
1693

1694
        fd = receive_one_fd(pair[0], 0);
×
1695
        if (fd < 0)
×
1696
                return fd;
1697

1698
        if (ret_peer_path) {
×
1699
                r = ptsname_namespace(fd, ret_peer_path);
×
1700
                if (r < 0)
×
1701
                        return r;
×
1702
        }
1703

1704
        return TAKE_FD(fd);
1705
}
1706

1707
static bool on_dev_null(void) {
39,225✔
1708
        struct stat dst, ost, est;
39,225✔
1709

1710
        if (cached_on_dev_null >= 0)
39,225✔
1711
                return cached_on_dev_null;
6,889✔
1712

1713
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
32,336✔
1714
                cached_on_dev_null = false;
1✔
1715
        else
1716
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
36,170✔
1717

1718
        return cached_on_dev_null;
32,336✔
1719
}
1720

1721
bool getenv_terminal_is_dumb(void) {
12,329✔
1722
        const char *e;
12,329✔
1723

1724
        e = getenv("TERM");
12,329✔
1725
        if (!e)
12,329✔
1726
                return true;
1727

1728
        return streq(e, "dumb");
1,290✔
1729
}
1730

1731
bool terminal_is_dumb(void) {
39,248✔
1732
        if (!on_tty() && !on_dev_null())
39,248✔
1733
                return true;
1734

1735
        return getenv_terminal_is_dumb();
144✔
1736
}
1737

1738
bool dev_console_colors_enabled(void) {
×
1739
        _cleanup_free_ char *s = NULL;
×
1740
        ColorMode m;
×
1741

1742
        /* Returns true if we assume that color is supported on /dev/console.
1743
         *
1744
         * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1745
         * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1746
         * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1747
         * colors_enabled() operates. */
1748

1749
        m = parse_systemd_colors();
×
1750
        if (m >= 0)
×
1751
                return m;
×
1752

1753
        if (getenv("NO_COLOR"))
×
1754
                return false;
1755

1756
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
1757
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1758

1759
        return !streq_ptr(s, "dumb");
×
1760
}
1761

1762
int vt_restore(int fd) {
×
1763

1764
        static const struct vt_mode mode = {
×
1765
                .mode = VT_AUTO,
1766
        };
1767

1768
        int r, ret = 0;
×
1769

1770
        assert(fd >= 0);
×
1771

1772
        if (!isatty_safe(fd))
×
1773
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to restore the VT for an fd that does not refer to a terminal.");
×
1774

1775
        if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
×
1776
                RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT to text mode, ignoring: %m"));
×
1777

1778
        r = vt_reset_keyboard(fd);
×
1779
        if (r < 0)
×
1780
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1781

1782
        if (ioctl(fd, VT_SETMODE, &mode) < 0)
×
1783
                RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"));
×
1784

1785
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1786
        if (r < 0)
×
1787
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1788

1789
        return ret;
1790
}
1791

1792
int vt_release(int fd, bool restore) {
×
1793
        assert(fd >= 0);
×
1794

1795
        /* This function releases the VT by acknowledging the VT-switch signal
1796
         * sent by the kernel and optionally reset the VT in text and auto
1797
         * VT-switching modes. */
1798

1799
        if (!isatty_safe(fd))
×
1800
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to release the VT for an fd that does not refer to a terminal.");
×
1801

1802
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
1803
                return -errno;
×
1804

1805
        if (restore)
×
1806
                return vt_restore(fd);
×
1807

1808
        return 0;
1809
}
1810

1811
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
195,377✔
1812
        /* Note that this will initialize output variables only when there's something to output.
1813
         * The caller must pre-initialize to "" or NULL as appropriate. */
1814

1815
        if (priority <= LOG_ERR) {
195,377✔
1816
                if (on)
6,402✔
1817
                        *on = ansi_highlight_red();
12,804✔
1818
                if (off)
6,402✔
1819
                        *off = ansi_normal();
12,804✔
1820
                if (highlight)
6,402✔
1821
                        *highlight = ansi_highlight();
×
1822

1823
        } else if (priority <= LOG_WARNING) {
188,975✔
1824
                if (on)
878✔
1825
                        *on = ansi_highlight_yellow();
878✔
1826
                if (off)
878✔
1827
                        *off = ansi_normal();
1,756✔
1828
                if (highlight)
878✔
1829
                        *highlight = ansi_highlight();
×
1830

1831
        } else if (priority <= LOG_NOTICE) {
188,097✔
1832
                if (on)
892✔
1833
                        *on = ansi_highlight();
1,784✔
1834
                if (off)
892✔
1835
                        *off = ansi_normal();
1,784✔
1836
                if (highlight)
892✔
1837
                        *highlight = ansi_highlight_red();
×
1838

1839
        } else if (priority >= LOG_DEBUG) {
187,205✔
1840
                if (on)
146,842✔
1841
                        *on = ansi_grey();
146,842✔
1842
                if (off)
146,842✔
1843
                        *off = ansi_normal();
293,684✔
1844
                if (highlight)
146,842✔
1845
                        *highlight = ansi_highlight_red();
×
1846
        }
1847
}
195,377✔
1848

1849
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
1850
        assert(fd >= 0);
×
1851

1852
        char cursor_position[STRLEN("\x1B[" ";" "H") + DECIMAL_STR_MAX(unsigned) * 2 + 1];
×
1853
        xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
×
1854

1855
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1856
}
1857

1858
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1859
        assert(input_fd >= 0);
1✔
1860
        assert(output_fd >= 0);
1✔
1861

1862
        /* Validates that the specified fds reference the same TTY */
1863

1864
        if (input_fd != output_fd) {
1✔
1865
                struct stat sti;
1✔
1866
                if (fstat(input_fd, &sti) < 0)
1✔
1867
                        return -errno;
1✔
1868

1869
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
1870
                        return -ENOTTY;
1871

1872
                struct stat sto;
1✔
1873
                if (fstat(output_fd, &sto) < 0)
1✔
1874
                        return -errno;
×
1875

1876
                if (!S_ISCHR(sto.st_mode))
1✔
1877
                        return -ENOTTY;
1878

1879
                if (sti.st_rdev != sto.st_rdev)
×
1880
                        return -ENOLINK;
1881
        }
1882

1883
        if (!isatty_safe(input_fd)) /* The check above was just for char device, but now let's ensure it's actually a tty */
×
1884
                return -ENOTTY;
×
1885

1886
        return 0;
1887
}
1888

1889
typedef enum CursorPositionState {
1890
        CURSOR_TEXT,
1891
        CURSOR_ESCAPE,
1892
        CURSOR_ROW,
1893
        CURSOR_COLUMN,
1894
} CursorPositionState;
1895

1896
typedef struct CursorPositionContext {
1897
        CursorPositionState state;
1898
        unsigned row, column;
1899
} CursorPositionContext;
1900

1901
static int scan_cursor_position_response(
×
1902
                CursorPositionContext *context,
1903
                const char *buf,
1904
                size_t size,
1905
                size_t *ret_processed) {
1906

1907
        assert(context);
×
1908
        assert(buf);
×
1909
        assert(ret_processed);
×
1910

1911
        for (size_t i = 0; i < size; i++) {
×
1912
                char c = buf[i];
×
1913

1914
                switch (context->state) {
×
1915

1916
                case CURSOR_TEXT:
×
1917
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
1918
                        break;
×
1919

1920
                case CURSOR_ESCAPE:
×
1921
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
1922
                        break;
×
1923

1924
                case CURSOR_ROW:
×
1925
                        if (c == ';')
×
1926
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
1927
                        else {
1928
                                int d = undecchar(c);
×
1929

1930
                                /* We read a decimal character, let's suffix it to the number we so far read,
1931
                                 * but let's do an overflow check first. */
1932
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
1933
                                        context->state = CURSOR_TEXT;
×
1934
                                else
1935
                                        context->row = context->row * 10 + d;
×
1936
                        }
1937
                        break;
1938

1939
                case CURSOR_COLUMN:
×
1940
                        if (c == 'R') {
×
1941
                                if (context->column > 0) {
×
1942
                                        *ret_processed = i + 1;
×
1943
                                        return 1; /* success! */
×
1944
                                }
1945

1946
                                context->state = CURSOR_TEXT;
×
1947
                        } else {
1948
                                int d = undecchar(c);
×
1949

1950
                                /* As above, add the decimal character to our column number */
1951
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
1952
                                        context->state = CURSOR_TEXT;
×
1953
                                else
1954
                                        context->column = context->column * 10 + d;
×
1955
                        }
1956

1957
                        break;
1958
                }
1959

1960
                /* Reset any positions we might have picked up */
1961
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
1962
                        context->row = context->column = 0;
×
1963
        }
1964

1965
        *ret_processed = size;
×
1966
        return 0; /* all good, but not enough data yet */
×
1967
}
1968

1969
int terminal_get_cursor_position(
×
1970
                int input_fd,
1971
                int output_fd,
1972
                unsigned *ret_row,
1973
                unsigned *ret_column) {
1974

1975
        _cleanup_close_ int nonblock_input_fd = -EBADF;
×
1976
        int r;
×
1977

1978
        assert(input_fd >= 0);
×
1979
        assert(output_fd >= 0);
×
1980

1981
        if (terminal_is_dumb())
×
1982
                return -EOPNOTSUPP;
1983

1984
        r = terminal_verify_same(input_fd, output_fd);
×
1985
        if (r < 0)
×
1986
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
1987

1988
        struct termios old_termios;
×
1989
        if (tcgetattr(input_fd, &old_termios) < 0)
×
1990
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
1991

1992
        struct termios new_termios = old_termios;
×
1993
        termios_disable_echo(&new_termios);
×
1994

1995
        if (tcsetattr(input_fd, TCSANOW, &new_termios) < 0)
×
1996
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
×
1997

1998
        /* Request cursor position (DSR/CPR) */
1999
        r = loop_write(output_fd, "\x1B[6n", SIZE_MAX);
×
2000
        if (r < 0)
×
2001
                goto finish;
×
2002

2003
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read() should someone
2004
         * else process the POLLIN. */
2005

2006
        nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2007
        if (r < 0)
×
2008
                goto finish;
×
2009

2010
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2011
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2012
        size_t buf_full = 0;
×
2013
        CursorPositionContext context = {};
×
2014

2015
        for (bool first = true;; first = false) {
×
2016
                if (buf_full == 0) {
×
2017
                        usec_t n = now(CLOCK_MONOTONIC);
×
2018
                        if (n >= end) {
×
2019
                                r = -EOPNOTSUPP;
×
2020
                                goto finish;
×
2021
                        }
2022

2023
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2024
                        if (r < 0)
×
2025
                                goto finish;
×
2026
                        if (r == 0) {
×
2027
                                r = -EOPNOTSUPP;
×
2028
                                goto finish;
×
2029
                        }
2030

2031
                        /* On the first try, read multiple characters, i.e. the shortest valid
2032
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2033
                         * unnecessarily drop too many characters from the input queue. */
2034
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2035
                        if (l < 0) {
×
2036
                                if (errno == EAGAIN)
×
2037
                                        continue;
×
2038

2039
                                r = -errno;
×
2040
                                goto finish;
×
2041
                        }
2042

2043
                        assert((size_t) l <= sizeof(buf));
×
2044
                        buf_full = l;
2045
                }
2046

2047
                size_t processed;
×
2048
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2049
                if (r < 0)
×
2050
                        goto finish;
×
2051

2052
                assert(processed <= buf_full);
×
2053
                buf_full -= processed;
×
2054
                memmove(buf, buf + processed, buf_full);
×
2055

2056
                if (r > 0) {
×
2057
                        /* Superficial validity check */
2058
                        if (context.row >= 32766 || context.column >= 32766) {
×
2059
                                r = -ENODATA;
×
2060
                                goto finish;
×
2061
                        }
2062

2063
                        if (ret_row)
×
2064
                                *ret_row = context.row;
×
2065
                        if (ret_column)
×
2066
                                *ret_column = context.column;
×
2067

2068
                        r = 0;
×
2069
                        goto finish;
×
2070
                }
2071
        }
2072

2073
finish:
×
2074
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSANOW, &old_termios)));
×
2075
        return r;
2076
}
2077

2078
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
421✔
2079
        int r = 0;
421✔
2080

2081
        assert(fd >= 0);
421✔
2082
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
421✔
2083

2084
        /* Resets the terminal comprehensively, i.e. via both ioctl()s and via ANSI sequences, but do so only
2085
         * if $TERM is unset or set to "dumb" */
2086

2087
        if (!isatty_safe(fd))
421✔
2088
                return -ENOTTY;
421✔
2089

2090
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
414✔
2091

2092
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
414✔
2093
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
408✔
2094
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
407✔
2095

2096
        return r;
2097
}
2098

2099
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
7✔
2100
        assert(fd >= 0);
7✔
2101

2102
        _cleanup_close_ int lock_fd = lock_dev_console();
7✔
2103
        if (lock_fd < 0)
7✔
2104
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
2105

2106
        return terminal_reset_defensive(fd, flags);
7✔
2107
}
2108

2109
void termios_disable_echo(struct termios *termios) {
1✔
2110
        assert(termios);
1✔
2111

2112
        termios->c_lflag &= ~(ICANON|ECHO);
1✔
2113
        termios->c_cc[VMIN] = 1;
1✔
2114
        termios->c_cc[VTIME] = 0;
1✔
2115
}
1✔
2116

2117
typedef enum BackgroundColorState {
2118
        BACKGROUND_TEXT,
2119
        BACKGROUND_ESCAPE,
2120
        BACKGROUND_BRACKET,
2121
        BACKGROUND_FIRST_ONE,
2122
        BACKGROUND_SECOND_ONE,
2123
        BACKGROUND_SEMICOLON,
2124
        BACKGROUND_R,
2125
        BACKGROUND_G,
2126
        BACKGROUND_B,
2127
        BACKGROUND_RED,
2128
        BACKGROUND_GREEN,
2129
        BACKGROUND_BLUE,
2130
        BACKGROUND_STRING_TERMINATOR,
2131
} BackgroundColorState;
2132

2133
typedef struct BackgroundColorContext {
2134
        BackgroundColorState state;
2135
        uint32_t red, green, blue;
2136
        unsigned red_bits, green_bits, blue_bits;
2137
} BackgroundColorContext;
2138

2139
static int scan_background_color_response(
×
2140
                BackgroundColorContext *context,
2141
                const char *buf,
2142
                size_t size,
2143
                size_t *ret_processed) {
2144

2145
        assert(context);
×
2146
        assert(buf);
×
2147
        assert(ret_processed);
×
2148

2149
        for (size_t i = 0; i < size; i++) {
×
2150
                char c = buf[i];
×
2151

2152
                switch (context->state) {
×
2153

2154
                case BACKGROUND_TEXT:
×
2155
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2156
                        break;
×
2157

2158
                case BACKGROUND_ESCAPE:
×
2159
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
2160
                        break;
×
2161

2162
                case BACKGROUND_BRACKET:
×
2163
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
2164
                        break;
×
2165

2166
                case BACKGROUND_FIRST_ONE:
×
2167
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
2168
                        break;
×
2169

2170
                case BACKGROUND_SECOND_ONE:
×
2171
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
2172
                        break;
×
2173

2174
                case BACKGROUND_SEMICOLON:
×
2175
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
2176
                        break;
×
2177

2178
                case BACKGROUND_R:
×
2179
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
2180
                        break;
×
2181

2182
                case BACKGROUND_G:
×
2183
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
2184
                        break;
×
2185

2186
                case BACKGROUND_B:
×
2187
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
2188
                        break;
×
2189

2190
                case BACKGROUND_RED:
×
2191
                        if (c == '/')
×
2192
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2193
                        else {
2194
                                int d = unhexchar(c);
×
2195
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
2196
                                        context->state = BACKGROUND_TEXT;
×
2197
                                else {
2198
                                        context->red = (context->red << 4) | d;
×
2199
                                        context->red_bits += 4;
×
2200
                                }
2201
                        }
2202
                        break;
2203

2204
                case BACKGROUND_GREEN:
×
2205
                        if (c == '/')
×
2206
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2207
                        else {
2208
                                int d = unhexchar(c);
×
2209
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
2210
                                        context->state = BACKGROUND_TEXT;
×
2211
                                else {
2212
                                        context->green = (context->green << 4) | d;
×
2213
                                        context->green_bits += 4;
×
2214
                                }
2215
                        }
2216
                        break;
2217

2218
                case BACKGROUND_BLUE:
×
2219
                        if (c == '\x07') {
×
2220
                                if (context->blue_bits > 0) {
×
2221
                                        *ret_processed = i + 1;
×
2222
                                        return 1; /* success! */
×
2223
                                }
2224

2225
                                context->state = BACKGROUND_TEXT;
×
2226
                        } else if (c == '\x1b')
×
2227
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2228
                        else {
2229
                                int d = unhexchar(c);
×
2230
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
2231
                                        context->state = BACKGROUND_TEXT;
×
2232
                                else {
2233
                                        context->blue = (context->blue << 4) | d;
×
2234
                                        context->blue_bits += 4;
×
2235
                                }
2236
                        }
2237
                        break;
2238

2239
                case BACKGROUND_STRING_TERMINATOR:
×
2240
                        if (c == '\\') {
×
2241
                                *ret_processed = i + 1;
×
2242
                                return 1; /* success! */
×
2243
                        }
2244

2245
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2246
                        break;
×
2247

2248
                }
2249

2250
                /* Reset any colors we might have picked up */
2251
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2252
                        /* reset color */
2253
                        context->red = context->green = context->blue = 0;
×
2254
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2255
                }
2256
        }
2257

2258
        *ret_processed = size;
×
2259
        return 0; /* all good, but not enough data yet */
×
2260
}
2261

2262
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
158✔
2263
        _cleanup_close_ int nonblock_input_fd = -EBADF;
158✔
2264
        int r;
158✔
2265

2266
        assert(ret_red);
158✔
2267
        assert(ret_green);
158✔
2268
        assert(ret_blue);
158✔
2269

2270
        if (!colors_enabled())
158✔
2271
                return -EOPNOTSUPP;
2272

2273
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
2274
        if (r < 0)
×
2275
                return r;
2276

2277
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2278
                /* Linux console is black */
2279
                *ret_red = *ret_green = *ret_blue = 0.0;
×
2280
                return 0;
×
2281
        }
2282

2283
        struct termios old_termios;
×
2284
        if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
×
2285
                return -errno;
×
2286

2287
        struct termios new_termios = old_termios;
×
2288
        termios_disable_echo(&new_termios);
×
2289

2290
        if (tcsetattr(STDIN_FILENO, TCSANOW, &new_termios) < 0)
×
2291
                return -errno;
×
2292

2293
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
2294
        if (r < 0)
×
2295
                goto finish;
×
2296

2297
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read() should someone
2298
         * else process the POLLIN. */
2299

2300
        nonblock_input_fd = r = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2301
        if (r < 0)
×
2302
                goto finish;
×
2303

2304
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2305
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
2306
        size_t buf_full = 0;
×
2307
        BackgroundColorContext context = {};
×
2308

2309
        for (bool first = true;; first = false) {
×
2310
                if (buf_full == 0) {
×
2311
                        usec_t n = now(CLOCK_MONOTONIC);
×
2312
                        if (n >= end) {
×
2313
                                r = -EOPNOTSUPP;
×
2314
                                goto finish;
×
2315
                        }
2316

2317
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2318
                        if (r < 0)
×
2319
                                goto finish;
×
2320
                        if (r == 0) {
×
2321
                                r = -EOPNOTSUPP;
×
2322
                                goto finish;
×
2323
                        }
2324

2325
                        /* On the first try, read multiple characters, i.e. the shortest valid
2326
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2327
                         * unnecessarily drop too many characters from the input queue. */
2328
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2329
                        if (l < 0) {
×
2330
                                if (errno == EAGAIN)
×
2331
                                        continue;
×
2332
                                r = -errno;
×
2333
                                goto finish;
×
2334
                        }
2335

2336
                        assert((size_t) l <= sizeof(buf));
×
2337
                        buf_full = l;
2338
                }
2339

2340
                size_t processed;
×
2341
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
2342
                if (r < 0)
×
2343
                        goto finish;
×
2344

2345
                assert(processed <= buf_full);
×
2346
                buf_full -= processed;
×
2347
                memmove(buf, buf + processed, buf_full);
×
2348

2349
                if (r > 0) {
×
2350
                        assert(context.red_bits > 0);
×
2351
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
2352
                        assert(context.green_bits > 0);
×
2353
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
2354
                        assert(context.blue_bits > 0);
×
2355
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
2356
                        r = 0;
×
2357
                        goto finish;
×
2358
                }
2359
        }
2360

2361
finish:
×
2362
        RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSANOW, &old_termios)));
×
2363
        return r;
2364
}
2365

2366
int terminal_get_size_by_dsr(
104✔
2367
                int input_fd,
2368
                int output_fd,
2369
                unsigned *ret_rows,
2370
                unsigned *ret_columns) {
2371

2372
        _cleanup_close_ int nonblock_input_fd = -EBADF;
104✔
2373
        int r;
104✔
2374

2375
        assert(input_fd >= 0);
104✔
2376
        assert(output_fd >= 0);
104✔
2377

2378
        /* Tries to determine the terminal dimension by means of ANSI sequences rather than TIOCGWINSZ
2379
         * ioctl(). Why bother with this? The ioctl() information is often incorrect on serial terminals
2380
         * (since there's no handshake or protocol to determine the right dimensions in RS232), but since the
2381
         * ANSI sequences are interpreted by the final terminal instead of an intermediary tty driver they
2382
         * should be more accurate.
2383
         *
2384
         * Unfortunately there's no direct ANSI sequence to query terminal dimensions. But we can hack around
2385
         * it: we position the cursor briefly at an absolute location very far down and very far to the
2386
         * right, and then read back where we actually ended up. Because cursor locations are capped at the
2387
         * terminal width/height we should then see the right values. In order to not risk integer overflows
2388
         * in terminal applications we'll use INT16_MAX-1 as location to jump to — hopefully a value that is
2389
         * large enough for any real-life terminals, but small enough to not overflow anything or be
2390
         * recognized as a "niche" value. (Note that the dimension fields in "struct winsize" are 16bit only,
2391
         * too). */
2392

2393
        if (terminal_is_dumb())
104✔
2394
                return -EOPNOTSUPP;
2395

2396
        r = terminal_verify_same(input_fd, output_fd);
×
2397
        if (r < 0)
×
2398
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2399

2400
        struct termios old_termios;
×
2401
        if (tcgetattr(input_fd, &old_termios) < 0)
×
2402
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
2403

2404
        struct termios new_termios = old_termios;
×
2405
        termios_disable_echo(&new_termios);
×
2406

2407
        if (tcsetattr(input_fd, TCSANOW, &new_termios) < 0)
×
2408
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
×
2409

2410
        unsigned saved_row = 0, saved_column = 0;
×
2411

2412
        r = loop_write(output_fd,
×
2413
                       "\x1B[6n"           /* Request cursor position (DSR/CPR) */
2414
                       "\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
2415
                       "\x1B[6n",          /* Request cursor position again */
2416
                       SIZE_MAX);
2417
        if (r < 0)
×
2418
                goto finish;
×
2419

2420
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read() should someone
2421
         * else process the POLLIN. */
2422

2423
        nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2424
        if (r < 0)
×
2425
                goto finish;
×
2426

2427
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2428
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2429
        size_t buf_full = 0;
×
2430
        CursorPositionContext context = {};
×
2431

2432
        for (bool first = true;; first = false) {
×
2433
                if (buf_full == 0) {
×
2434
                        usec_t n = now(CLOCK_MONOTONIC);
×
2435
                        if (n >= end) {
×
2436
                                r = -EOPNOTSUPP;
×
2437
                                goto finish;
×
2438
                        }
2439

2440
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2441
                        if (r < 0)
×
2442
                                goto finish;
×
2443
                        if (r == 0) {
×
2444
                                r = -EOPNOTSUPP;
×
2445
                                goto finish;
×
2446
                        }
2447

2448
                        /* On the first try, read multiple characters, i.e. the shortest valid
2449
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2450
                         * unnecessarily drop too many characters from the input queue. */
2451
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2452
                        if (l < 0) {
×
2453
                                if (errno == EAGAIN)
×
2454
                                        continue;
×
2455

2456
                                r = -errno;
×
2457
                                goto finish;
×
2458
                        }
2459

2460
                        assert((size_t) l <= sizeof(buf));
×
2461
                        buf_full = l;
2462
                }
2463

2464
                size_t processed;
×
2465
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2466
                if (r < 0)
×
2467
                        goto finish;
×
2468

2469
                assert(processed <= buf_full);
×
2470
                buf_full -= processed;
×
2471
                memmove(buf, buf + processed, buf_full);
×
2472

2473
                if (r > 0) {
×
2474
                        if (saved_row == 0) {
×
2475
                                assert(saved_column == 0);
×
2476

2477
                                /* First sequence, this is the cursor position before we set it somewhere
2478
                                 * into the void at the bottom right. Let's save where we are so that we can
2479
                                 * return later. */
2480

2481
                                /* Superficial validity checks */
2482
                                if (context.row <= 0 || context.column <= 0 || context.row >= 32766 || context.column >= 32766) {
×
2483
                                        r = -ENODATA;
×
2484
                                        goto finish;
×
2485
                                }
2486

2487
                                saved_row = context.row;
×
2488
                                saved_column = context.column;
×
2489

2490
                                /* Reset state */
2491
                                context = (CursorPositionContext) {};
×
2492
                        } else {
2493
                                /* Second sequence, this is the cursor position after we set it somewhere
2494
                                 * into the void at the bottom right. */
2495

2496
                                /* Superficial validity checks (no particular reason to check for < 4, it's
2497
                                 * just a way to look for unreasonably small values) */
2498
                                if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766) {
×
2499
                                        r = -ENODATA;
×
2500
                                        goto finish;
×
2501
                                }
2502

2503
                                if (ret_rows)
×
2504
                                        *ret_rows = context.row;
×
2505
                                if (ret_columns)
×
2506
                                        *ret_columns = context.column;
×
2507

2508
                                r = 0;
×
2509
                                goto finish;
×
2510
                        }
2511
                }
2512
        }
2513

2514
finish:
×
2515
        /* Restore cursor position */
2516
        if (saved_row > 0 && saved_column > 0)
×
2517
                RET_GATHER(r, terminal_set_cursor_position(output_fd, saved_row, saved_column));
×
2518

2519
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSANOW, &old_termios)));
×
2520
        return r;
2521
}
2522

2523
int terminal_fix_size(int input_fd, int output_fd) {
1✔
2524
        unsigned rows, columns;
1✔
2525
        int r;
1✔
2526

2527
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences */
2528

2529
        r = terminal_verify_same(input_fd, output_fd);
1✔
2530
        if (r < 0)
1✔
2531
                return r;
1✔
2532

2533
        struct winsize ws = {};
×
2534
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
×
2535
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
×
2536

2537
        r = terminal_get_size_by_dsr(input_fd, output_fd, &rows, &columns);
×
2538
        if (r < 0)
×
2539
                return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
×
2540

2541
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
2542
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2543
                return 0;
×
2544
        }
2545

2546
        ws.ws_col = columns;
×
2547
        ws.ws_row = rows;
×
2548

2549
        if (ioctl(output_fd, TIOCSWINSZ, &ws) < 0)
×
2550
                return log_debug_errno(errno, "Failed to update terminal dimensions, ignoring: %m");
×
2551

2552
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2553
        return 1;
2554
}
2555

2556
#define MAX_TERMINFO_LENGTH 64
2557
/* python -c 'print("".join(hex(ord(i))[2:] for i in "name").upper())' */
2558
#define DCS_TERMINFO_Q ANSI_DCS "+q" "6E616D65" ANSI_ST
2559
/* The answer is either 0+r… (invalid) or 1+r… (OK). */
2560
#define DCS_TERMINFO_R0 ANSI_DCS "0+r" ANSI_ST
2561
#define DCS_TERMINFO_R1 ANSI_DCS "1+r" "6E616D65" "=" /* This is followed by Pt ST. */
2562
assert_cc(STRLEN(DCS_TERMINFO_R0) <= STRLEN(DCS_TERMINFO_R1 ANSI_ST));
2563

2564
static int scan_terminfo_response(
×
2565
                const char *buf,
2566
                size_t size,
2567
                char **ret_name) {
2568
        int r;
×
2569

2570
        assert(buf);
×
2571
        assert(ret_name);
×
2572

2573
        /* Check if we have enough space for the shortest possible answer. */
2574
        if (size < STRLEN(DCS_TERMINFO_R0))
×
2575
                return -EAGAIN;
×
2576

2577
        /* Check if the terminating sequence is present */
2578
        if (memcmp(buf + size - STRLEN(ANSI_ST), ANSI_ST, STRLEN(ANSI_ST)) != 0)
×
2579
                return -EAGAIN;
2580

2581
        if (size <= STRLEN(DCS_TERMINFO_R1 ANSI_ST))
×
2582
                return -EINVAL;  /* The answer is invalid or empty */
2583

2584
        if (memcmp(buf, DCS_TERMINFO_R1, STRLEN(DCS_TERMINFO_R1)) != 0)
×
2585
                return -EINVAL;  /* The answer is not valid */
2586

2587
        _cleanup_free_ void *dec = NULL;
×
2588
        size_t dec_size;
×
2589
        r = unhexmem_full(buf + STRLEN(DCS_TERMINFO_R1), size - STRLEN(DCS_TERMINFO_R1 ANSI_ST),
×
2590
                          /* secure= */ false,
2591
                          &dec, &dec_size);
2592
        if (r < 0)
×
2593
                return r;
2594

2595
        assert(((const char *) dec)[dec_size] == '\0'); /* unhexmem appends NUL for our convenience */
×
2596
        if (memchr(dec, '\0', dec_size) || string_has_cc(dec, NULL) || !filename_is_valid(dec))
×
2597
                return -EUCLEAN;
2598

2599
        *ret_name = TAKE_PTR(dec);
×
2600
        return 0;
×
2601
}
2602

2603
int terminal_get_terminfo_by_dcs(int fd, char **ret_name) {
2✔
2604
        int r;
2✔
2605

2606
        assert(fd >= 0);
2✔
2607
        assert(ret_name);
2✔
2608

2609
        /* Note: fd must be in non-blocking read-write mode! */
2610

2611
        struct termios old_termios;
2✔
2612
        if (tcgetattr(fd, &old_termios) < 0)
2✔
2613
                return -errno;
1✔
2614

2615
        struct termios new_termios = old_termios;
1✔
2616
        termios_disable_echo(&new_termios);
1✔
2617

2618
        if (tcsetattr(fd, TCSANOW, &new_termios) < 0)
1✔
2619
                return -errno;
×
2620

2621
        r = loop_write(fd, DCS_TERMINFO_Q, SIZE_MAX);
1✔
2622
        if (r < 0)
1✔
2623
                goto finish;
×
2624

2625
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
1✔
2626
        char buf[STRLEN(DCS_TERMINFO_R1) + MAX_TERMINFO_LENGTH + STRLEN(ANSI_ST)];
1✔
2627
        size_t bytes = 0;
1✔
2628

2629
        for (;;) {
1✔
2630
                usec_t n = now(CLOCK_MONOTONIC);
1✔
2631
                if (n >= end) {
1✔
2632
                        r = -EOPNOTSUPP;
2633
                        break;
2634
                }
2635

2636
                r = fd_wait_for_event(fd, POLLIN, usec_sub_unsigned(end, n));
2✔
2637
                if (r < 0)
1✔
2638
                        break;
2639
                if (r == 0) {
1✔
2640
                        r = -EOPNOTSUPP;
2641
                        break;
2642
                }
2643

2644
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2645
                 * read byte by byte, since we don't want to read too much and drop characters from the input
2646
                 * queue. */
2647
                ssize_t l = read(fd, buf + bytes, bytes == 0 ? STRLEN(DCS_TERMINFO_R0) : 1);
×
2648
                if (l < 0) {
×
2649
                        if (errno == EAGAIN)
×
2650
                                continue;
×
2651
                        r = -errno;
×
2652
                        break;
×
2653
                }
2654

2655
                assert((size_t) l <= sizeof(buf) - bytes);
×
2656
                bytes += l;
×
2657

2658
                r = scan_terminfo_response(buf, bytes, ret_name);
×
2659
                if (r != -EAGAIN)
×
2660
                        break;
2661

2662
                if (bytes == sizeof(buf)) {
×
2663
                        r = -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2664
                                          * answer with a terminator in the allotted space. Something is
2665
                                          * wrong, possibly some unrelated bytes got injected into the
2666
                                          * answer. */
2667
                        break;
2668
                }
2669
        }
2670

2671
finish:
×
2672
        /* We ignore failure here. We already got a reply and if cleanup fails, we can't help that. */
2673
        (void) tcsetattr(fd, TCSANOW, &old_termios);
1✔
2674
        return r;
1✔
2675
}
2676

2677
int have_terminfo_file(const char *name) {
5✔
2678
        /* This is a heuristic check if we have the file, using the directory layout used on
2679
         * current Linux systems. Checks for other layouts can be added later if appropriate. */
2680
        int r;
5✔
2681

2682
        assert(filename_is_valid(name));
5✔
2683

2684
        _cleanup_free_ char *p = path_join("/usr/share/terminfo", CHAR_TO_STR(name[0]), name);
10✔
2685
        if (!p)
5✔
2686
                return log_oom_debug();
×
2687

2688
        r = RET_NERRNO(access(p, F_OK));
5✔
2689
        if (r == -ENOENT)
1✔
2690
                return false;
2691
        if (r < 0)
4✔
2692
                return r;
×
2693
        return true;
2694
}
2695

2696
int query_term_for_tty(const char *tty, char **ret_term) {
51✔
2697
        _cleanup_free_ char *dcs_term = NULL;
51✔
2698
        int r;
51✔
2699

2700
        assert(tty);
51✔
2701
        assert(ret_term);
51✔
2702

2703
        if (tty_is_vc_resolve(tty))
51✔
2704
                return strdup_to(ret_term, "linux");
48✔
2705

2706
        /* Try to query the terminal implementation that we're on. This will not work in all
2707
         * cases, which is fine, since this is intended to be used as a fallback. */
2708

2709
        _cleanup_close_ int tty_fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
54✔
2710
        if (tty_fd < 0)
3✔
2711
                return log_debug_errno(tty_fd, "Failed to open %s to query terminfo: %m", tty);
2✔
2712

2713
        r = terminal_get_terminfo_by_dcs(tty_fd, &dcs_term);
1✔
2714
        if (r < 0)
1✔
2715
                return log_debug_errno(r, "Failed to query %s for terminfo: %m", tty);
1✔
2716

2717
        r = have_terminfo_file(dcs_term);
×
2718
        if (r < 0)
×
2719
                return log_debug_errno(r, "Failed to look for terminfo %s: %m", dcs_term);
×
2720
        if (r == 0)
×
2721
                return log_info_errno(SYNTHETIC_ERRNO(ENODATA),
×
2722
                                      "Terminfo %s not found for %s.", dcs_term, tty);
2723

2724
        *ret_term = TAKE_PTR(dcs_term);
×
2725
        return 0;
×
2726
}
2727

2728
int terminal_is_pty_fd(int fd) {
3✔
2729
        int r;
3✔
2730

2731
        assert(fd >= 0);
3✔
2732

2733
        /* Returns true if we are looking at a pty, i.e. if it's backed by the /dev/pts/ file system */
2734

2735
        if (!isatty_safe(fd))
3✔
2736
                return false;
3✔
2737

2738
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2✔
2739
        if (r != 0)
2✔
2740
                return r;
2741

2742
        /* The ptmx device is weird, it exists twice, once inside and once outside devpts. To detect the
2743
         * latter case, let's fire off an ioctl() that only works on ptmx devices. */
2744

2745
        int v;
×
2746
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
×
2747
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
2748
                        return false;
2749

2750
                return -errno;
×
2751
        }
2752

2753
        return true;
2754
}
2755

2756
int pty_open_peer(int fd, int mode) {
25✔
2757
        assert(fd >= 0);
25✔
2758

2759
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2760
         *
2761
         * This is safe to be called on TTYs from other namespaces. */
2762

2763
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
25✔
2764

2765
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
2766
        for (unsigned c = 0;; c++) {
×
2767
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
25✔
2768
                if (peer_fd >= 0)
25✔
2769
                        return peer_fd;
2770

2771
                if (errno != EIO)
×
2772
                        return -errno;
×
2773

2774
                /* Max 1s in total */
2775
                if (c >= 20)
×
2776
                        return -EIO;
2777

2778
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2779
        }
2780
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc