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

systemd / systemd / 25409762285

05 May 2026 08:45PM UTC coverage: 72.658% (-0.02%) from 72.674%
25409762285

push

github

web-flow
Couple of coverity fixes (#41951)

0 of 11 new or added lines in 2 files covered. (0.0%)

2705 existing lines in 63 files now uncovered.

326249 of 449021 relevant lines covered (72.66%)

1212712.0 hits per line

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

44.05
/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 "pidref.h"
35
#include "proc-cmdline.h"
36
#include "process-util.h"
37
#include "signal-util.h"
38
#include "socket-util.h"
39
#include "stat-util.h"
40
#include "stdio-util.h"
41
#include "string-util.h"
42
#include "strv.h"
43
#include "terminal-util.h"
44
#include "time-util.h"
45
#include "utf8.h"
46

47
/* How much to wait when reading/writing ANSI sequences from/to the console */
48
#define CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC (333 * USEC_PER_MSEC)
49

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

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

56
bool isatty_safe(int fd) {
7,990,203✔
57
        assert(fd >= 0);
7,990,203✔
58

59
        if (isatty(fd))
7,990,203✔
60
                return true;
61

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

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

71
        return false;
72
}
73

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

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

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

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

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

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

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

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

104
        assert(ret);
4✔
105

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

174
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
175

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

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

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

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

190
                putchar('\r');
×
191

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

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

198
                fflush(stdout);
×
199

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

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

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

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

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

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

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

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

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

241
        string = strempty(string);
7✔
242

243
        STRV_FOREACH(c, completions) {
860✔
244

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

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

255
                        continue;
4✔
256
                }
257

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

264
                found[n] = 0;
849✔
265
                partial = true;
849✔
266
        }
267

268
        *ret = TAKE_PTR(found);
7✔
269

270
        if (!*ret)
7✔
271
                return COMPLETION_NONE;
272
        if (partial)
4✔
273
                return COMPLETION_PARTIAL;
274

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

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

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

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

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

296
        _cleanup_free_ char *string = NULL;
7✔
297
        size_t n = 0;
7✔
298

299
        if (get_completions) {
7✔
300
                /* Figure out what string to preselect the query with */
UNCOV
301
                _cleanup_strv_free_ char **completions = NULL;
×
302
                r = get_completions("", GET_COMPLETIONS_PRESELECT, &completions, userdata);
7✔
303
                if (r < 0)
7✔
304
                        return r;
305

306
                CompletionResult cr = pick_completion(string, completions, &string);
7✔
307
                if (cr < 0)
7✔
308
                        return cr;
309

310
                n = strlen_ptr(string);
11✔
311
        }
312

313
        /* Output the prompt */
314
        fputs(ansi_highlight(), stdout);
14✔
315
        va_start(ap, text);
7✔
316
        vprintf(text, ap);
7✔
317
        va_end(ap);
7✔
318
        fputs(ansi_normal(), stdout);
14✔
319
        if (string)
7✔
320
                fputs(string, stdout);
4✔
321
        fflush(stdout);
7✔
322

323
        /* Do interactive logic only if stdin + stdout are connected to the same place. And yes, we could use
324
         * STDIN_FILENO and STDOUT_FILENO here, but let's be overly correct for once, after all libc allows
325
         * swapping out stdin/stdout. */
326
        int fd_input = fileno(stdin);
7✔
327
        int fd_output = fileno(stdout);
7✔
328
        struct termios old_termios = TERMIOS_NULL;
7✔
329
        CLEANUP_TERMIOS_RESET(fd_input, old_termios);
7✔
330

331
        if (fd_input < 0 || fd_output < 0 || same_fd(fd_input, fd_output) <= 0)
7✔
332
                goto fallback;
7✔
333

334
        /* Try to disable echo, which also tells us if this even is a terminal */
UNCOV
335
        if (tcgetattr(fd_input, &old_termios) < 0) {
×
UNCOV
336
                old_termios = TERMIOS_NULL;
×
337
                goto fallback;
×
338
        }
339

UNCOV
340
        struct termios new_termios = old_termios;
×
UNCOV
341
        termios_disable_echo(&new_termios);
×
342
        if (tcsetattr(fd_input, TCSANOW, &new_termios) < 0)
×
UNCOV
343
                return -errno;
×
344

345
        for (;;) {
×
346
                int c = fgetc(stdin);
×
347

348
                /* On EOF or NUL, end the request, don't output anything anymore */
UNCOV
349
                if (IN_SET(c, EOF, 0))
×
350
                        break;
351

352
                /* On Return also end the request, but make this visible */
353
                if (IN_SET(c, '\n', '\r')) {
×
354
                        fputc('\n', stdout);
×
355
                        break;
356
                }
357

358
                if (c == '\t') {
×
359
                        /* Tab */
360

361
                        _cleanup_strv_free_ char **completions = NULL;
×
362
                        if (get_completions) {
×
UNCOV
363
                                r = get_completions(string, /* flags= */ 0, &completions, userdata);
×
364
                                if (r < 0)
×
365
                                        return r;
366
                        }
367

UNCOV
368
                        _cleanup_free_ char *new_string = NULL;
×
UNCOV
369
                        CompletionResult cr = pick_completion(string, completions, &new_string);
×
UNCOV
370
                        if (cr < 0)
×
371
                                return cr;
UNCOV
372
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_FULL)) {
×
373
                                /* Output the new suffix we learned */
374
                                fputs(ASSERT_PTR(startswith(new_string, strempty(string))), stdout);
×
375

376
                                /* And update the whole string */
377
                                free_and_replace(string, new_string);
×
UNCOV
378
                                n = strlen(string);
×
379
                        }
UNCOV
380
                        if (cr == COMPLETION_NONE)
×
UNCOV
381
                                fputc('\a', stdout); /* BEL */
×
382

383
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_ALREADY)) {
×
384
                                /* If this worked only partially, or if the user hit TAB even though we were
385
                                 * complete already, then show the remaining options (in the latter case just
386
                                 * the one). */
387
                                fputc('\n', stdout);
×
388

389
                                _cleanup_strv_free_ char **filtered = strv_filter_prefix(completions, string);
×
390
                                if (!filtered)
×
391
                                        return -ENOMEM;
392

UNCOV
393
                                r = show_menu(filtered,
×
394
                                              /* n_columns= */ SIZE_MAX,
395
                                              /* column_width= */ SIZE_MAX,
396
                                              /* ellipsize_percentage= */ 0,
397
                                              /* grey_prefix= */ string,
398
                                              /* with_numbers= */ false);
399
                                if (r < 0)
×
400
                                        return r;
401

402
                                /* Show the prompt again */
403
                                fputs(ansi_highlight(), stdout);
×
404
                                va_start(ap, text);
×
UNCOV
405
                                vprintf(text, ap);
×
406
                                va_end(ap);
×
407
                                fputs(ansi_normal(), stdout);
×
UNCOV
408
                                fputs(string, stdout);
×
409
                        }
410

UNCOV
411
                } else if (IN_SET(c, '\b', 127)) {
×
412
                        /* Backspace */
413

414
                        if (n == 0)
×
415
                                fputc('\a', stdout); /* BEL */
×
416
                        else {
417
                                size_t m = utf8_last_length(string, n);
×
418

419
                                char *e = string + n - m;
×
UNCOV
420
                                clear_by_backspace(utf8_console_width(e));
×
421

UNCOV
422
                                *e = 0;
×
UNCOV
423
                                n -= m;
×
424
                        }
425

426
                } else if (c == 21) {
×
427
                        /* Ctrl-u → erase all input */
428

UNCOV
429
                        clear_by_backspace(utf8_console_width(string));
×
430
                        if (string)
×
UNCOV
431
                                string[n = 0] = 0;
×
432
                        else
433
                                assert(n == 0);
×
434

UNCOV
435
                } else if (c == 4) {
×
436
                        /* Ctrl-d → cancel this field input */
437

438
                        return -ECANCELED;
439

UNCOV
440
                } else if (char_is_cc(c) || n >= LINE_MAX)
×
441
                        /* refuse control characters and too long strings */
442
                        fputc('\a', stdout); /* BEL */
×
443
                else {
444
                        /* Regular char */
445

UNCOV
446
                        if (!GREEDY_REALLOC(string, n+2))
×
447
                                return -ENOMEM;
448

449
                        string[n++] = (char) c;
×
UNCOV
450
                        string[n] = 0;
×
451

UNCOV
452
                        fputc(c, stdout);
×
453
                }
454

UNCOV
455
                fflush(stdout);
×
456
        }
457

UNCOV
458
        if (!string) {
×
UNCOV
459
                string = strdup("");
×
UNCOV
460
                if (!string)
×
461
                        return -ENOMEM;
462
        }
463

UNCOV
464
        *ret = TAKE_PTR(string);
×
UNCOV
465
        return 0;
×
466

467
fallback:
7✔
468
        /* A simple fallback without TTY magic */
469
        string = mfree(string);
7✔
470
        r = read_line(stdin, LONG_LINE_MAX, &string);
7✔
471
        if (r < 0)
7✔
472
                return r;
473
        if (r == 0)
7✔
474
                return -EIO;
475

476
        *ret = TAKE_PTR(string);
7✔
477
        return 0;
7✔
478
}
479

480
bool any_key_to_proceed(void) {
×
481

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

486
        fputc('\n', stdout);
×
UNCOV
487
        fputs(ansi_highlight_magenta(), stdout);
×
UNCOV
488
        fputs("-- Press any key to proceed --", stdout);
×
UNCOV
489
        fputs(ansi_normal(), stdout);
×
490
        fputc('\n', stdout);
×
491
        fflush(stdout);
×
492

493
        char key = 0;
×
UNCOV
494
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
×
495

496
        fputc('\n', stdout);
×
UNCOV
497
        fflush(stdout);
×
498

UNCOV
499
        return key != 'q';
×
500
}
501

UNCOV
502
static size_t widest_list_element(char *const*l) {
×
503
        size_t w = 0;
×
504

505
        /* Returns the largest console width of all elements in 'l' */
506

UNCOV
507
        STRV_FOREACH(i, l)
×
508
                w = MAX(w, utf8_console_width(*i));
×
509

UNCOV
510
        return w;
×
511
}
512

UNCOV
513
int show_menu(char **x,
×
514
              size_t n_columns,
515
              size_t column_width,
516
              unsigned ellipsize_percentage,
517
              const char *grey_prefix,
518
              bool with_numbers) {
519

520
        assert(n_columns > 0);
×
521

UNCOV
522
        if (n_columns == SIZE_MAX)
×
523
                n_columns = 3;
×
524

UNCOV
525
        if (column_width == SIZE_MAX) {
×
UNCOV
526
                size_t widest = widest_list_element(x);
×
527

528
                /* If not specified, derive column width from screen width */
UNCOV
529
                size_t column_max = (columns()-1) / n_columns;
×
530

531
                /* Subtract room for numbers */
UNCOV
532
                if (with_numbers && column_max > 6)
×
533
                        column_max -= 6;
×
534

535
                /* If columns would get too tight let's make this a linear list instead. */
UNCOV
536
                if (column_max < 10 && widest > 10) {
×
UNCOV
537
                        n_columns = 1;
×
UNCOV
538
                        column_max = columns()-1;
×
539

540
                        if (with_numbers && column_max > 6)
×
541
                                column_max -= 6;
×
542
                }
543

UNCOV
544
                column_width = CLAMP(widest+1, 10U, column_max);
×
545
        }
546

UNCOV
547
        size_t n = strv_length(x);
×
548
        size_t per_column = DIV_ROUND_UP(n, n_columns);
×
549

UNCOV
550
        size_t break_lines = lines();
×
551
        if (break_lines > 2)
×
552
                break_lines--;
×
553

554
        /* The first page gets two extra lines, since we want to show
555
         * a title */
556
        size_t break_modulo = break_lines;
×
UNCOV
557
        if (break_modulo > 3)
×
UNCOV
558
                break_modulo -= 3;
×
559

UNCOV
560
        for (size_t i = 0; i < per_column; i++) {
×
561

562
                for (size_t j = 0; j < n_columns; j++) {
×
563
                        _cleanup_free_ char *e = NULL;
×
564

UNCOV
565
                        if (j * per_column + i >= n)
×
566
                                break;
567

568
                        e = ellipsize(x[j * per_column + i], column_width, ellipsize_percentage);
×
UNCOV
569
                        if (!e)
×
570
                                return -ENOMEM;
×
571

UNCOV
572
                        if (with_numbers)
×
573
                                printf("%s%4zu)%s ",
×
574
                                       ansi_grey(),
575
                                       j * per_column + i + 1,
576
                                       ansi_normal());
577

UNCOV
578
                        if (grey_prefix && startswith(e, grey_prefix)) {
×
UNCOV
579
                                size_t k = MIN(strlen(grey_prefix), column_width);
×
UNCOV
580
                                printf("%s%.*s%s",
×
581
                                       ansi_grey(),
582
                                       (int) k, e,
583
                                       ansi_normal());
UNCOV
584
                                printf("%-*s",
×
UNCOV
585
                                       (int) (column_width - k), e+k);
×
586
                        } else
UNCOV
587
                                printf("%-*s", (int) column_width, e);
×
588
                }
589

UNCOV
590
                putchar('\n');
×
591

592
                /* on the first screen we reserve 2 extra lines for the title */
UNCOV
593
                if (i % break_lines == break_modulo)
×
UNCOV
594
                        if (!any_key_to_proceed())
×
595
                                return 0;
596
        }
597

598
        return 0;
599
}
600

601
int open_terminal(const char *name, int mode) {
42,876✔
602
        _cleanup_close_ int fd = -EBADF;
42,876✔
603

604
        /*
605
         * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
606
         * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
607
         * times.
608
         *
609
         * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
610
         */
611

612
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
42,876✔
613

UNCOV
614
        for (unsigned c = 0;; c++) {
×
615
                fd = open(name, mode, 0);
42,876✔
616
                if (fd >= 0)
42,876✔
617
                        break;
618

619
                if (errno != EIO)
122✔
620
                        return -errno;
122✔
621

622
                /* Max 1s in total */
UNCOV
623
                if (c >= 20)
×
624
                        return -EIO;
625

UNCOV
626
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
627
        }
628

629
        if (!isatty_safe(fd))
42,754✔
630
                return -ENOTTY;
1✔
631

632
        return TAKE_FD(fd);
633
}
634

635
int acquire_terminal(
227✔
636
                const char *name,
637
                AcquireTerminalFlags flags,
638
                usec_t timeout) {
639

640
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
227✔
641
        usec_t ts = USEC_INFINITY;
227✔
642
        int r, wd = -1;
227✔
643

644
        assert(name);
227✔
645

646
        AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
227✔
647
        assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
227✔
648
        assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
227✔
649

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

659
        if (mode == ACQUIRE_TERMINAL_WAIT) {
×
660
                notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
227✔
661
                if (notify < 0)
227✔
UNCOV
662
                        return -errno;
×
663

664
                wd = inotify_add_watch(notify, name, IN_CLOSE);
227✔
665
                if (wd < 0)
227✔
666
                        return -errno;
36✔
667

668
                if (timeout != USEC_INFINITY)
191✔
UNCOV
669
                        ts = now(CLOCK_MONOTONIC);
×
670
        }
671

672
        /* If we are called with ACQUIRE_TERMINAL_WATCH_SIGTERM we'll unblock SIGTERM during ppoll() temporarily */
673
        sigset_t poll_ss;
191✔
674
        assert_se(sigprocmask(SIG_SETMASK, /* newset= */ NULL, &poll_ss) >= 0);
191✔
675
        if (flags & ACQUIRE_TERMINAL_WATCH_SIGTERM) {
191✔
676
                assert_se(sigismember(&poll_ss, SIGTERM) > 0);
1✔
677
                assert_se(sigdelset(&poll_ss, SIGTERM) >= 0);
1✔
678
        }
679

680
        for (;;) {
191✔
681
                if (notify >= 0) {
191✔
682
                        r = flush_fd(notify);
191✔
683
                        if (r < 0)
191✔
UNCOV
684
                                return r;
×
685
                }
686

687
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
688
                 * to figure out if we successfully became the controlling process of the tty */
689
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
191✔
690
                if (fd < 0)
191✔
691
                        return fd;
692

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

697
                /* First, try to get the tty */
698
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
191✔
699

700
                /* Reset signal handler to old value */
701
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
191✔
702

703
                /* Success? Exit the loop now! */
704
                if (r >= 0)
191✔
705
                        break;
706

707
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
UNCOV
708
                if (r != -EPERM)
×
709
                        return r;
710

UNCOV
711
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
×
712
                                                          * into a success. Note that EPERM is also returned if we
713
                                                          * already are the owner of the TTY. */
714
                        break;
715

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

719
                assert(notify >= 0);
×
720
                assert(wd >= 0);
×
721

UNCOV
722
                for (;;) {
×
UNCOV
723
                        usec_t left;
×
UNCOV
724
                        if (timeout == USEC_INFINITY)
×
725
                                left = USEC_INFINITY;
726
                        else {
727
                                assert(ts != USEC_INFINITY);
×
728

729
                                usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
UNCOV
730
                                if (n >= timeout)
×
UNCOV
731
                                        return -ETIMEDOUT;
×
732

733
                                left = timeout - n;
×
734
                        }
735

736
                        r = ppoll_usec_full(
×
737
                                        &(struct pollfd) {
×
738
                                                .fd = notify,
739
                                                .events = POLLIN,
740
                                        },
741
                                        /* n_fds= */ 1,
742
                                        left,
743
                                        &poll_ss);
UNCOV
744
                        if (r < 0)
×
745
                                return r;
746
                        if (r == 0)
×
747
                                return -ETIMEDOUT;
748

UNCOV
749
                        union inotify_event_buffer buffer;
×
750
                        ssize_t l;
×
UNCOV
751
                        l = read(notify, &buffer, sizeof(buffer));
×
UNCOV
752
                        if (l < 0) {
×
UNCOV
753
                                if (ERRNO_IS_TRANSIENT(errno))
×
UNCOV
754
                                        continue;
×
755

UNCOV
756
                                return -errno;
×
757
                        }
758

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

UNCOV
763
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
×
UNCOV
764
                                        return -EIO;
×
765
                        }
766

UNCOV
767
                        break;
×
768
                }
769

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

775
        return TAKE_FD(fd);
191✔
776
}
777

778
int release_terminal(void) {
64✔
779
        _cleanup_close_ int fd = -EBADF;
64✔
780
        int r;
64✔
781

782
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
64✔
783
        if (fd < 0)
64✔
784
                return -errno;
42✔
785

786
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
787
         * by our own TIOCNOTTY */
788
        struct sigaction sa_old;
22✔
789
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
22✔
790

791
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
22✔
792

793
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
22✔
794

795
        return r;
796
}
797

798
int terminal_new_session(void) {
5✔
799

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

807
        if (!isatty_safe(STDIN_FILENO))
5✔
808
                return -ENXIO;
809

810
        (void) setsid();
4✔
811
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
4✔
812
}
813

814
void terminal_detach_session(void) {
63✔
815
        (void) setsid();
63✔
816
        (void) release_terminal();
63✔
817
}
63✔
818

819
int terminal_vhangup_fd(int fd) {
99✔
820
        assert(fd >= 0);
99✔
821
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
99✔
822
}
823

UNCOV
824
int terminal_vhangup(const char *tty) {
×
UNCOV
825
        _cleanup_close_ int fd = -EBADF;
×
826

UNCOV
827
        assert(tty);
×
828

UNCOV
829
        fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
×
UNCOV
830
        if (fd < 0)
×
831
                return fd;
832

UNCOV
833
        return terminal_vhangup_fd(fd);
×
834
}
835

836
int vt_disallocate(const char *tty_path) {
53✔
837
        assert(tty_path);
53✔
838

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

842
        int ttynr = vtnr_from_tty(tty_path);
53✔
843
        if (ttynr > 0) {
53✔
844
                _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
53✔
845
                if (fd < 0)
53✔
846
                        return fd;
847

848
                /* Try to deallocate */
849
                if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
53✔
850
                        return 0;
851
                if (errno != EBUSY)
53✔
UNCOV
852
                        return -errno;
×
853
        }
854

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

858
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
106✔
859
        if (fd2 < 0)
53✔
860
                return fd2;
861

862
        return loop_write_full(fd2,
53✔
863
                               "\033[r"   /* clear scrolling region */
864
                               "\033[H"   /* move home */
865
                               "\033[3J"  /* clear screen including scrollback, requires Linux 2.6.40 */
866
                               "\033c",   /* reset to initial state */
867
                               SIZE_MAX,
868
                               CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
869
}
870

871
static int vt_default_utf8(void) {
896✔
872
        _cleanup_free_ char *b = NULL;
896✔
873
        int r;
896✔
874

875
        /* Read the default VT UTF8 setting from the kernel */
876

877
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
896✔
878
        if (r < 0)
896✔
879
                return r;
880

881
        return parse_boolean(b);
508✔
882
}
883

884
static int vt_reset_keyboard(int fd) {
448✔
885
        int r, kb;
448✔
886

887
        assert(fd >= 0);
448✔
888

889
        /* If we can't read the default, then default to Unicode. It's 2024 after all. */
890
        r = vt_default_utf8();
448✔
891
        if (r < 0)
448✔
892
                log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
194✔
893

894
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
448✔
895
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
448✔
896
}
897

898
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
448✔
899
        struct termios termios;
448✔
900
        int r;
448✔
901

902
        /* Set terminal to some sane defaults */
903

904
        assert(fd >= 0);
448✔
905

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

909
        /* Disable exclusive mode, just in case */
910
        if (ioctl(fd, TIOCNXCL) < 0)
448✔
911
                log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
2✔
912

913
        /* Switch to text mode */
914
        if (switch_to_text)
448✔
915
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
217✔
916
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
164✔
917

918
        /* Set default keyboard mode */
919
        r = vt_reset_keyboard(fd);
448✔
920
        if (r < 0)
448✔
921
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
345✔
922

923
        if (tcgetattr(fd, &termios) < 0) {
448✔
924
                r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
2✔
925
                goto finish;
2✔
926
        }
927

928
        /* We only reset the stuff that matters to the software. How
929
         * hardware is set up we don't touch assuming that somebody
930
         * else will do that for us */
931

932
        termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
446✔
933
        termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
446✔
934
        termios.c_oflag |= ONLCR | OPOST;
446✔
935
        termios.c_cflag |= CREAD;
446✔
936
        termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
446✔
937

938
        termios.c_cc[VINTR]    =   03;  /* ^C */
446✔
939
        termios.c_cc[VQUIT]    =  034;  /* ^\ */
446✔
940
        termios.c_cc[VERASE]   = 0177;
446✔
941
        termios.c_cc[VKILL]    =  025;  /* ^X */
446✔
942
        termios.c_cc[VEOF]     =   04;  /* ^D */
446✔
943
        termios.c_cc[VSTART]   =  021;  /* ^Q */
446✔
944
        termios.c_cc[VSTOP]    =  023;  /* ^S */
446✔
945
        termios.c_cc[VSUSP]    =  032;  /* ^Z */
446✔
946
        termios.c_cc[VLNEXT]   =  026;  /* ^V */
446✔
947
        termios.c_cc[VWERASE]  =  027;  /* ^W */
446✔
948
        termios.c_cc[VREPRINT] =  022;  /* ^R */
446✔
949
        termios.c_cc[VEOL]     =    0;
446✔
950
        termios.c_cc[VEOL2]    =    0;
446✔
951

952
        termios.c_cc[VTIME]  = 0;
446✔
953
        termios.c_cc[VMIN]   = 1;
446✔
954

955
        r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
446✔
UNCOV
956
        if (r < 0)
×
UNCOV
957
                log_debug_errno(r, "Failed to set terminal parameters: %m");
×
958

959
finish:
×
960
        /* Just in case, flush all crap out */
961
        (void) tcflush(fd, TCIOFLUSH);
448✔
962

963
        return r;
448✔
964
}
965

966
int terminal_reset_ansi_seq(int fd) {
441✔
UNCOV
967
        _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
×
968
        int r;
441✔
969

970
        assert(fd >= 0);
441✔
971

972
        if (getenv_terminal_is_dumb())
441✔
973
                return 0;
974

UNCOV
975
        r = fd_nonblock(fd, true);
×
UNCOV
976
        if (r < 0)
×
UNCOV
977
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
UNCOV
978
        if (r > 0)
×
UNCOV
979
                nonblock_reset = fd;
×
980

UNCOV
981
        r = loop_write_full(fd,
×
982
                            "\033[!p"              /* soft terminal reset */
983
                            ANSI_OSC "104" ANSI_ST /* reset color palette via OSC 104 */
984
                            ANSI_NORMAL            /* reset colors */
985
                            "\033[?7h"             /* enable line-wrapping */
986
                            "\033[1G"              /* place cursor at beginning of current line */
987
                            "\033[0J",             /* erase till end of screen */
988
                            SIZE_MAX,
989
                            CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
990
        if (r < 0)
×
991
                log_debug_errno(r, "Failed to reset terminal through ANSI sequences: %m");
441✔
992

993
        return r;
994
}
995

996
void reset_dev_console_fd(int fd, bool switch_to_text) {
36✔
997
        int r;
36✔
998

999
        assert(fd >= 0);
36✔
1000

1001
        _cleanup_close_ int lock_fd = lock_dev_console();
36✔
1002
        if (lock_fd < 0)
36✔
UNCOV
1003
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
1004

1005
        r = terminal_reset_ioctl(fd, switch_to_text);
36✔
1006
        if (r < 0)
36✔
UNCOV
1007
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
×
1008

1009
        unsigned rows, cols;
36✔
1010
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
36✔
1011
        if (r < 0)
36✔
UNCOV
1012
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
×
1013
        else if (r > 0) {
36✔
1014
                r = terminal_set_size_fd(fd, NULL, rows, cols);
17✔
1015
                if (r < 0)
17✔
UNCOV
1016
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
×
1017
        } else
1018
                (void) terminal_fix_size(fd, fd);
19✔
1019

1020
        r = terminal_reset_ansi_seq(fd);
36✔
1021
        if (r < 0)
36✔
1022
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
36✔
1023
}
36✔
1024

1025
int lock_dev_console(void) {
585✔
1026
        _cleanup_close_ int fd = -EBADF;
585✔
1027
        int r;
585✔
1028

1029
        /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
1030
         * pty in /dev/console, in which case it should be fine to lock the target TTY. */
1031
        fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
585✔
1032
        if (fd < 0)
585✔
1033
                return fd;
1034

1035
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
585✔
1036
        if (r < 0)
585✔
1037
                return r;
×
1038

1039
        return TAKE_FD(fd);
1040
}
1041

UNCOV
1042
int make_console_stdio(void) {
×
1043
        int fd, r;
×
1044

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

1049
        fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
×
UNCOV
1050
        if (fd < 0) {
×
UNCOV
1051
                log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
×
1052

UNCOV
1053
                r = make_null_stdio();
×
UNCOV
1054
                if (r < 0)
×
UNCOV
1055
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
×
1056

1057
        } else {
UNCOV
1058
                reset_dev_console_fd(fd, /* switch_to_text= */ true);
×
1059

UNCOV
1060
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
×
UNCOV
1061
                if (r < 0)
×
UNCOV
1062
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
×
1063
        }
1064

UNCOV
1065
        reset_terminal_feature_caches();
×
UNCOV
1066
        return 0;
×
1067
}
1068

1069
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
311✔
1070
        assert(tty);
311✔
1071

1072
        tty = skip_dev_prefix(tty);
311✔
1073

1074
        const char *e = startswith(tty, "tty");
311✔
1075
        if (!e)
311✔
1076
                return -EINVAL;
1077

1078
        return safe_atou(e, ret);
272✔
1079
}
1080

1081
int vtnr_from_tty(const char *tty) {
183✔
1082
        unsigned u;
183✔
1083
        int r;
183✔
1084

1085
        assert(tty);
183✔
1086

1087
        r = vtnr_from_tty_raw(tty, &u);
183✔
1088
        if (r < 0)
183✔
1089
                return r;
183✔
1090
        if (!vtnr_is_valid(u))
183✔
1091
                return -ERANGE;
1092

1093
        return (int) u;
183✔
1094
}
1095

1096
bool tty_is_vc(const char *tty) {
128✔
1097
        assert(tty);
128✔
1098

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

1104
        return vtnr_from_tty_raw(tty, /* ret= */ NULL) >= 0;
128✔
1105
}
1106

1107
bool tty_is_console(const char *tty) {
484✔
1108
        assert(tty);
484✔
1109

1110
        return streq(skip_dev_prefix(tty), "console");
484✔
1111
}
1112

1113
int resolve_dev_console(char **ret) {
179✔
1114
        int r;
179✔
1115

1116
        assert(ret);
179✔
1117

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

1123
        _cleanup_free_ char *chased = NULL;
179✔
1124
        r = chase("/dev/console", /* root= */ NULL, /* flags= */ 0, &chased, /* ret_fd= */ NULL);
179✔
1125
        if (r < 0)
179✔
1126
                return r;
1127
        if (!path_equal(chased, "/dev/console")) {
179✔
1128
                *ret = TAKE_PTR(chased);
80✔
1129
                return 0;
80✔
1130
        }
1131

1132
        r = path_is_read_only_fs("/sys");
99✔
1133
        if (r < 0)
99✔
1134
                return r;
1135
        if (r > 0)
99✔
1136
                return -ENOMEDIUM;
1137

1138
        _cleanup_free_ char *active = NULL;
99✔
1139
        r = read_one_line_file("/sys/class/tty/console/active", &active);
99✔
1140
        if (r < 0)
99✔
1141
                return r;
1142
        if (r == 0)
99✔
1143
                return -ENXIO;
1144

1145
        /* If multiple log outputs are configured the last one is what /dev/console points to */
1146
        const char *tty = strrchr(active, ' ');
99✔
1147
        if (tty)
99✔
UNCOV
1148
                tty++;
×
1149
        else
1150
                tty = active;
1151

1152
        if (streq(tty, "tty0")) {
99✔
UNCOV
1153
                active = mfree(active);
×
1154

1155
                /* Get the active VC (e.g. tty1) */
UNCOV
1156
                r = read_one_line_file("/sys/class/tty/tty0/active", &active);
×
1157
                if (r < 0)
×
1158
                        return r;
1159
                if (r == 0)
×
1160
                        return -ENXIO;
1161

1162
                tty = active;
×
1163
        }
1164

1165
        _cleanup_free_ char *path = NULL;
99✔
1166
        path = path_join("/dev", tty);
99✔
1167
        if (!path)
99✔
1168
                return -ENOMEM;
1169

1170
        *ret = TAKE_PTR(path);
99✔
1171
        return 0;
99✔
1172
}
1173

1174
int get_kernel_consoles(char ***ret) {
1✔
UNCOV
1175
        _cleanup_strv_free_ char **l = NULL;
×
1176
        _cleanup_free_ char *line = NULL;
1✔
1177
        int r;
1✔
1178

1179
        assert(ret);
1✔
1180

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

UNCOV
1186
        r = read_one_line_file("/sys/class/tty/console/active", &line);
×
1187
        if (r < 0)
×
1188
                return r;
1189

UNCOV
1190
        for (const char *p = line;;) {
×
UNCOV
1191
                _cleanup_free_ char *tty = NULL, *path = NULL;
×
1192

1193
                r = extract_first_word(&p, &tty, NULL, 0);
×
1194
                if (r < 0)
×
1195
                        return r;
UNCOV
1196
                if (r == 0)
×
1197
                        break;
1198

1199
                if (streq(tty, "tty0")) {
×
UNCOV
1200
                        tty = mfree(tty);
×
UNCOV
1201
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
1202
                        if (r < 0)
×
1203
                                return r;
UNCOV
1204
                        if (r == 0) {
×
UNCOV
1205
                                log_debug("No VT active, skipping /dev/tty0.");
×
UNCOV
1206
                                continue;
×
1207
                        }
1208
                }
1209

UNCOV
1210
                path = path_join("/dev", tty);
×
UNCOV
1211
                if (!path)
×
1212
                        return -ENOMEM;
1213

UNCOV
1214
                if (access(path, F_OK) < 0) {
×
1215
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
×
1216
                        continue;
×
1217
                }
1218

UNCOV
1219
                r = strv_consume(&l, TAKE_PTR(path));
×
1220
                if (r < 0)
×
1221
                        return r;
1222
        }
1223

UNCOV
1224
        if (strv_isempty(l)) {
×
UNCOV
1225
                log_debug("No devices found for system console");
×
UNCOV
1226
                goto fallback;
×
1227
        }
1228

UNCOV
1229
        *ret = TAKE_PTR(l);
×
UNCOV
1230
        return strv_length(*ret);
×
1231

1232
fallback:
1✔
1233
        r = strv_extend(&l, "/dev/console");
1✔
1234
        if (r < 0)
1✔
1235
                return r;
1236

1237
        *ret = TAKE_PTR(l);
1✔
1238
        return 0;
1✔
1239
}
1240

1241
bool tty_is_vc_resolve(const char *tty) {
53✔
1242
        _cleanup_free_ char *resolved = NULL;
53✔
1243

1244
        assert(tty);
53✔
1245

1246
        if (streq(skip_dev_prefix(tty), "console")) {
53✔
1247
                if (resolve_dev_console(&resolved) < 0)
1✔
1248
                        return false;
1249

1250
                tty = resolved;
1✔
1251
        }
1252

1253
        return tty_is_vc(tty);
53✔
1254
}
1255

1256
int fd_columns(int fd) {
1,450✔
1257
        struct winsize ws = {};
1,450✔
1258

1259
        if (fd < 0)
1,450✔
1260
                return -EBADF;
1261

1262
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1,450✔
1263
                return -errno;
1,450✔
1264

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

UNCOV
1268
        return ws.ws_col;
×
1269
}
1270

1271
int getenv_columns(void) {
1,751✔
1272
        int r;
1,751✔
1273

1274
        const char *e = getenv("COLUMNS");
1,751✔
1275
        if (!e)
1,751✔
1276
                return -ENXIO;
1,751✔
1277

1278
        unsigned c;
2✔
1279
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
2✔
1280
        if (r < 0)
2✔
1281
                return r;
1282

1283
        return (int) c;
2✔
1284
}
1285

1286
unsigned columns(void) {
289,038✔
1287

1288
        if (cached_columns > 0)
289,038✔
1289
                return cached_columns;
287,586✔
1290

1291
        int c = getenv_columns();
1,452✔
1292
        if (c < 0) {
1,452✔
1293
                c = fd_columns(STDOUT_FILENO);
1,450✔
1294
                if (c < 0)
1,450✔
1295
                        c = 80;
1296
        }
1297

1298
        assert(c > 0);
2✔
1299

1300
        cached_columns = c;
1,452✔
1301
        return cached_columns;
1,452✔
1302
}
1303

1304
int fd_lines(int fd) {
210✔
1305
        struct winsize ws = {};
210✔
1306

1307
        if (fd < 0)
210✔
1308
                return -EBADF;
1309

1310
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
210✔
1311
                return -errno;
210✔
1312

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

UNCOV
1316
        return ws.ws_row;
×
1317
}
1318

1319
unsigned lines(void) {
210✔
1320
        const char *e;
210✔
1321
        int l;
210✔
1322

1323
        if (cached_lines > 0)
210✔
UNCOV
1324
                return cached_lines;
×
1325

1326
        l = 0;
210✔
1327
        e = getenv("LINES");
210✔
1328
        if (e)
210✔
UNCOV
1329
                (void) safe_atoi(e, &l);
×
1330

1331
        if (l <= 0 || l > USHRT_MAX) {
210✔
1332
                l = fd_lines(STDOUT_FILENO);
210✔
1333
                if (l <= 0)
210✔
1334
                        l = 24;
210✔
1335
        }
1336

1337
        cached_lines = l;
210✔
1338
        return cached_lines;
210✔
1339
}
1340

1341
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
546✔
1342
        struct winsize ws;
546✔
1343

1344
        assert(fd >= 0);
546✔
1345

1346
        if (!ident)
546✔
1347
                ident = "TTY";
67✔
1348

1349
        if (rows == UINT_MAX && cols == UINT_MAX)
546✔
1350
                return 0;
546✔
1351

1352
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
141✔
UNCOV
1353
                return log_debug_errno(errno,
×
1354
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1355
                                       ident);
1356

1357
        if (rows == UINT_MAX)
141✔
UNCOV
1358
                rows = ws.ws_row;
×
1359
        else if (rows > USHRT_MAX)
141✔
UNCOV
1360
                rows = USHRT_MAX;
×
1361

1362
        if (cols == UINT_MAX)
141✔
UNCOV
1363
                cols = ws.ws_col;
×
1364
        else if (cols > USHRT_MAX)
141✔
UNCOV
1365
                cols = USHRT_MAX;
×
1366

1367
        if (rows == ws.ws_row && cols == ws.ws_col)
141✔
1368
                return 0;
1369

1370
        ws.ws_row = rows;
137✔
1371
        ws.ws_col = cols;
137✔
1372

1373
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
137✔
UNCOV
1374
                return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
×
1375

1376
        return 0;
1377
}
1378

1379
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
515✔
1380
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
515✔
1381
        unsigned rows = UINT_MAX, cols = UINT_MAX;
515✔
1382
        int r;
515✔
1383

1384
        assert(tty);
515✔
1385

1386
        if (!ret_rows && !ret_cols)
515✔
1387
                return 0;
1388

1389
        tty = skip_dev_prefix(tty);
515✔
1390
        if (path_startswith(tty, "pts/"))
515✔
1391
                return -EMEDIUMTYPE;
1392
        if (!in_charset(tty, ALPHANUMERICAL))
515✔
UNCOV
1393
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
×
1394
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1395

1396
        rowskey = strjoin("systemd.tty.rows.", tty);
515✔
1397
        if (!rowskey)
515✔
1398
                return -ENOMEM;
1399

1400
        colskey = strjoin("systemd.tty.columns.", tty);
515✔
1401
        if (!colskey)
515✔
1402
                return -ENOMEM;
1403

1404
        r = proc_cmdline_get_key_many(/* flags= */ 0,
515✔
1405
                                      rowskey, &rowsvalue,
1406
                                      colskey, &colsvalue);
1407
        if (r < 0)
515✔
UNCOV
1408
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
×
1409

1410
        if (rowsvalue) {
515✔
1411
                r = safe_atou(rowsvalue, &rows);
141✔
1412
                if (r < 0)
141✔
UNCOV
1413
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
×
1414
        }
1415

1416
        if (colsvalue) {
515✔
1417
                r = safe_atou(colsvalue, &cols);
141✔
1418
                if (r < 0)
141✔
UNCOV
1419
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
×
1420
        }
1421

1422
        if (ret_rows)
515✔
1423
                *ret_rows = rows;
515✔
1424
        if (ret_cols)
515✔
1425
                *ret_cols = cols;
515✔
1426

1427
        return rows != UINT_MAX || cols != UINT_MAX;
515✔
1428
}
1429

1430
/* intended to be used as a SIGWINCH sighandler */
UNCOV
1431
void columns_lines_cache_reset(int signum) {
×
UNCOV
1432
        cached_columns = 0;
×
UNCOV
1433
        cached_lines = 0;
×
UNCOV
1434
}
×
1435

1436
void reset_terminal_feature_caches(void) {
24✔
1437
        cached_columns = 0;
24✔
1438
        cached_lines = 0;
24✔
1439

1440
        cached_on_tty = -1;
24✔
1441
        cached_on_dev_null = -1;
24✔
1442

1443
        reset_ansi_feature_caches();
24✔
1444
}
24✔
1445

1446
bool on_tty(void) {
7,497,258✔
1447

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

1454
        if (cached_on_tty < 0)
7,497,258✔
1455
                cached_on_tty =
34,577✔
1456
                        isatty_safe(STDOUT_FILENO) &&
34,614✔
1457
                        isatty_safe(STDERR_FILENO);
37✔
1458

1459
        return cached_on_tty;
7,497,258✔
1460
}
1461

1462
int getttyname_malloc(int fd, char **ret) {
579✔
1463
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
579✔
1464
        int r;
579✔
1465

1466
        assert(fd >= 0);
579✔
1467
        assert(ret);
579✔
1468

1469
        r = ttyname_r(fd, path, sizeof path); /* positive error */
579✔
1470
        assert(r >= 0);
579✔
1471
        if (r == ERANGE)
579✔
1472
                return -ENAMETOOLONG;
579✔
1473
        if (r > 0)
579✔
1474
                return -r;
572✔
1475

1476
        return strdup_to(ret, skip_dev_prefix(path));
7✔
1477
}
1478

1479
int getttyname_harder(int fd, char **ret) {
24✔
1480
        _cleanup_free_ char *s = NULL;
24✔
1481
        int r;
24✔
1482

1483
        assert(ret);
24✔
1484

1485
        r = getttyname_malloc(fd, &s);
24✔
1486
        if (r < 0)
24✔
1487
                return r;
1488

UNCOV
1489
        if (streq(s, "tty"))
×
UNCOV
1490
                return get_ctty(0, NULL, ret);
×
1491

UNCOV
1492
        *ret = TAKE_PTR(s);
×
UNCOV
1493
        return 0;
×
1494
}
1495

1496
int get_ctty_devnr(pid_t pid, dev_t *ret) {
5,536✔
1497
        _cleanup_free_ char *line = NULL;
5,536✔
1498
        unsigned long ttynr;
5,536✔
1499
        const char *p;
5,536✔
1500
        int r;
5,536✔
1501

1502
        assert(pid >= 0);
5,536✔
1503

1504
        p = procfs_file_alloca(pid, "stat");
27,340✔
1505
        r = read_one_line_file(p, &line);
5,536✔
1506
        if (r < 0)
5,536✔
1507
                return r;
1508

1509
        p = strrchr(line, ')');
5,536✔
1510
        if (!p)
5,536✔
1511
                return -EIO;
1512

1513
        p++;
5,536✔
1514

1515
        if (sscanf(p, " "
5,536✔
1516
                   "%*c "  /* state */
1517
                   "%*d "  /* ppid */
1518
                   "%*d "  /* pgrp */
1519
                   "%*d "  /* session */
1520
                   "%lu ", /* ttynr */
1521
                   &ttynr) != 1)
1522
                return -EIO;
1523

1524
        if (devnum_is_zero(ttynr))
5,536✔
1525
                return -ENXIO;
1526

1527
        if (ret)
4✔
1528
                *ret = (dev_t) ttynr;
2✔
1529

1530
        return 0;
1531
}
1532

1533
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
31✔
1534
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
31✔
1535
        _cleanup_free_ char *buf = NULL;
31✔
1536
        const char *fn = NULL, *w;
31✔
1537
        dev_t devnr;
31✔
1538
        int r;
31✔
1539

1540
        r = get_ctty_devnr(pid, &devnr);
31✔
1541
        if (r < 0)
31✔
1542
                return r;
1543

1544
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
2✔
1545
        if (r < 0) {
2✔
1546
                struct stat st;
2✔
1547

1548
                if (r != -ENOENT) /* No symlink for this in /dev/char/? */
2✔
UNCOV
1549
                        return r;
×
1550

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

1559
                if (stat(pty, &st) < 0) {
2✔
UNCOV
1560
                        if (errno != ENOENT)
×
UNCOV
1561
                                return -errno;
×
1562

1563
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
2✔
1564
                        fn = pty;
1565

1566
                if (!fn) {
1567
                        /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1568
                         * symlink in /dev/char/. Let's return something vaguely useful. */
UNCOV
1569
                        r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
×
UNCOV
1570
                        if (r < 0)
×
1571
                                return r;
1572

UNCOV
1573
                        fn = buf;
×
1574
                }
1575
        } else
UNCOV
1576
                fn = buf;
×
1577

1578
        w = path_startswith(fn, "/dev/");
2✔
1579
        if (!w)
2✔
1580
                return -EINVAL;
1581

1582
        if (ret) {
2✔
1583
                r = strdup_to(ret, w);
2✔
1584
                if (r < 0)
2✔
1585
                        return r;
1586
        }
1587

1588
        if (ret_devnr)
2✔
UNCOV
1589
                *ret_devnr = devnr;
×
1590

1591
        return 0;
1592
}
1593

1594
int ptsname_malloc(int fd, char **ret) {
138✔
1595
        assert(fd >= 0);
138✔
1596
        assert(ret);
138✔
1597

UNCOV
1598
        for (size_t l = 50;;) {
×
UNCOV
1599
                _cleanup_free_ char *c = NULL;
×
1600

1601
                c = new(char, l);
138✔
1602
                if (!c)
138✔
1603
                        return -ENOMEM;
1604

1605
                if (ptsname_r(fd, c, l) >= 0) {
138✔
1606
                        *ret = TAKE_PTR(c);
138✔
1607
                        return 0;
138✔
1608
                }
UNCOV
1609
                if (errno != ERANGE)
×
UNCOV
1610
                        return -errno;
×
1611

UNCOV
1612
                if (!MUL_ASSIGN_SAFE(&l, 2))
×
1613
                        return -ENOMEM;
1614
        }
1615
}
1616

1617
int openpt_allocate(int flags, char **ret_peer_path) {
142✔
1618
        _cleanup_close_ int fd = -EBADF;
142✔
1619
        int r;
142✔
1620

1621
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
142✔
1622
        if (fd < 0)
142✔
UNCOV
1623
                return -errno;
×
1624

1625
        _cleanup_free_ char *p = NULL;
142✔
1626
        if (ret_peer_path) {
142✔
1627
                r = ptsname_malloc(fd, &p);
138✔
1628
                if (r < 0)
138✔
1629
                        return r;
1630

1631
                if (!path_startswith(p, "/dev/pts/"))
138✔
1632
                        return -EINVAL;
1633
        }
1634

1635
        if (unlockpt(fd) < 0)
142✔
1636
                return -errno;
×
1637

1638
        if (ret_peer_path)
142✔
1639
                *ret_peer_path = TAKE_PTR(p);
138✔
1640

1641
        return TAKE_FD(fd);
1642
}
1643

UNCOV
1644
static int ptsname_namespace(int pty, char **ret) {
×
UNCOV
1645
        int no = -1;
×
1646

UNCOV
1647
        assert(pty >= 0);
×
1648
        assert(ret);
×
1649

1650
        /* Like ptsname(), but doesn't assume that the path is
1651
         * accessible in the local namespace. */
1652

1653
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
1654
                return -errno;
×
1655

UNCOV
1656
        if (no < 0)
×
1657
                return -EIO;
1658

1659
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
UNCOV
1660
                return -ENOMEM;
×
1661

1662
        return 0;
1663
}
1664

UNCOV
1665
int openpt_allocate_in_namespace(
×
1666
                const PidRef *pidref,
1667
                int flags,
1668
                char **ret_peer_path) {
1669

UNCOV
1670
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
UNCOV
1671
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
UNCOV
1672
        int r;
×
1673

1674
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd= */ NULL, &usernsfd, &rootfd);
×
UNCOV
1675
        if (r < 0)
×
1676
                return log_debug_errno(r, "Failed to open namespaces of PID "PID_FMT": %m", pidref->pid);
×
1677

UNCOV
1678
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
1679
                return -errno;
×
1680

1681
        r = namespace_fork(
×
1682
                        "(sd-openptns)",
1683
                        "(sd-openpt)",
1684
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1685
                        pidnsfd,
1686
                        mntnsfd,
1687
                        /* netns_fd= */ -EBADF,
1688
                        usernsfd,
1689
                        rootfd,
1690
                        /* ret= */ NULL);
1691
        if (r < 0)
×
1692
                return r;
UNCOV
1693
        if (r == 0) {
×
UNCOV
1694
                pair[0] = safe_close(pair[0]);
×
1695

1696
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1697
                if (fd < 0)
×
1698
                        _exit(EXIT_FAILURE);
×
1699

UNCOV
1700
                if (send_one_fd(pair[1], fd, 0) < 0)
×
UNCOV
1701
                        _exit(EXIT_FAILURE);
×
1702

UNCOV
1703
                _exit(EXIT_SUCCESS);
×
1704
        }
1705

UNCOV
1706
        pair[1] = safe_close(pair[1]);
×
1707

UNCOV
1708
        fd = receive_one_fd(pair[0], 0);
×
UNCOV
1709
        if (fd < 0)
×
1710
                return fd;
1711

UNCOV
1712
        if (ret_peer_path) {
×
UNCOV
1713
                r = ptsname_namespace(fd, ret_peer_path);
×
UNCOV
1714
                if (r < 0)
×
UNCOV
1715
                        return r;
×
1716
        }
1717

1718
        return TAKE_FD(fd);
1719
}
1720

1721
static bool on_dev_null(void) {
42,081✔
1722
        struct stat dst, ost, est;
42,081✔
1723

1724
        if (cached_on_dev_null >= 0)
42,081✔
1725
                return cached_on_dev_null;
7,632✔
1726

1727
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
34,449✔
1728
                cached_on_dev_null = false;
1✔
1729
        else
1730
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
38,913✔
1731

1732
        return cached_on_dev_null;
34,449✔
1733
}
1734

UNCOV
1735
bool term_env_valid(const char *term) {
×
1736
        /* Checks if the specified $TERM value is suitable for propagation, i.e. is not empty, not set to
1737
         * "unknown" (as is common in CI), and only contains characters valid in terminal type names.
1738
         * Valid $TERM values are things like "xterm-256color", "linux", "screen.xterm-256color", i.e.
1739
         * alphanumeric characters, hyphens, underscores, dots, and plus signs. */
UNCOV
1740
        return !isempty(term) &&
×
UNCOV
1741
                !streq(term, "unknown") &&
×
UNCOV
1742
                in_charset(term, ALPHANUMERICAL "-_+.");
×
1743
}
1744

1745
bool getenv_terminal_is_dumb(void) {
14,812✔
1746
        const char *e;
14,812✔
1747

1748
        e = getenv("TERM");
14,812✔
1749
        if (!e)
14,812✔
1750
                return true;
1751

1752
        return streq(e, "dumb");
1,528✔
1753
}
1754

1755
bool terminal_is_dumb(void) {
42,118✔
1756
        if (!on_tty() && !on_dev_null())
42,118✔
1757
                return true;
1758

1759
        return getenv_terminal_is_dumb();
59✔
1760
}
1761

UNCOV
1762
bool dev_console_colors_enabled(void) {
×
1763
        _cleanup_free_ char *s = NULL;
×
1764
        ColorMode m;
×
1765

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

UNCOV
1773
        m = parse_systemd_colors();
×
UNCOV
1774
        if (m >= 0)
×
1775
                return m;
×
1776

1777
        if (getenv("NO_COLOR"))
×
1778
                return false;
1779

1780
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
UNCOV
1781
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1782

1783
        return !streq_ptr(s, "dumb");
×
1784
}
1785

1786
int vt_restore(int fd) {
×
1787

UNCOV
1788
        static const struct vt_mode mode = {
×
1789
                .mode = VT_AUTO,
1790
        };
1791

1792
        int r, ret = 0;
×
1793

1794
        assert(fd >= 0);
×
1795

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

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

UNCOV
1802
        r = vt_reset_keyboard(fd);
×
UNCOV
1803
        if (r < 0)
×
UNCOV
1804
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1805

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

1809
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1810
        if (r < 0)
×
UNCOV
1811
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1812

1813
        return ret;
1814
}
1815

UNCOV
1816
int vt_release(int fd, bool restore) {
×
UNCOV
1817
        assert(fd >= 0);
×
1818

1819
        /* This function releases the VT by acknowledging the VT-switch signal
1820
         * sent by the kernel and optionally reset the VT in text and auto
1821
         * VT-switching modes. */
1822

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

UNCOV
1826
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
UNCOV
1827
                return -errno;
×
1828

UNCOV
1829
        if (restore)
×
UNCOV
1830
                return vt_restore(fd);
×
1831

1832
        return 0;
1833
}
1834

1835
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
231,425✔
1836
        /* Note that this will initialize output variables only when there's something to output.
1837
         * The caller must pre-initialize to "" or NULL as appropriate. */
1838

1839
        if (priority <= LOG_ERR) {
231,425✔
1840
                if (on)
7,445✔
1841
                        *on = ansi_highlight_red();
14,890✔
1842
                if (off)
7,445✔
1843
                        *off = ansi_normal();
14,890✔
1844
                if (highlight)
7,445✔
UNCOV
1845
                        *highlight = ansi_highlight();
×
1846

1847
        } else if (priority <= LOG_WARNING) {
223,980✔
1848
                if (on)
997✔
1849
                        *on = ansi_highlight_yellow();
997✔
1850
                if (off)
997✔
1851
                        *off = ansi_normal();
1,994✔
1852
                if (highlight)
997✔
UNCOV
1853
                        *highlight = ansi_highlight();
×
1854

1855
        } else if (priority <= LOG_NOTICE) {
222,983✔
1856
                if (on)
1,115✔
1857
                        *on = ansi_highlight();
2,230✔
1858
                if (off)
1,115✔
1859
                        *off = ansi_normal();
2,230✔
1860
                if (highlight)
1,115✔
UNCOV
1861
                        *highlight = ansi_highlight_red();
×
1862

1863
        } else if (priority >= LOG_DEBUG) {
221,868✔
1864
                if (on)
171,870✔
1865
                        *on = ansi_grey();
171,870✔
1866
                if (off)
171,870✔
1867
                        *off = ansi_normal();
343,740✔
1868
                if (highlight)
171,870✔
1869
                        *highlight = ansi_highlight_red();
×
1870
        }
1871
}
231,425✔
1872

1873
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
1874
        assert(fd >= 0);
×
1875

1876
        char cursor_position[STRLEN("\x1B[" ";" "H") + DECIMAL_STR_MAX(unsigned) * 2 + 1];
×
UNCOV
1877
        xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
×
1878

1879
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1880
}
1881

1882
static int terminal_verify_same(int input_fd, int output_fd) {
×
1883
        int r;
×
1884

UNCOV
1885
        assert(input_fd >= 0);
×
1886
        assert(output_fd >= 0);
×
1887

1888
        /* Validates that the specified fds reference the same TTY */
1889

1890
        if (input_fd != output_fd) {
×
UNCOV
1891
                struct stat sti;
×
UNCOV
1892
                if (fstat(input_fd, &sti) < 0)
×
UNCOV
1893
                        return -errno;
×
1894

1895
                r = stat_verify_char(&sti); /* TTYs are character devices */
×
UNCOV
1896
                if (r < 0)
×
1897
                        return r;
1898

UNCOV
1899
                struct stat sto;
×
UNCOV
1900
                if (fstat(output_fd, &sto) < 0)
×
UNCOV
1901
                        return -errno;
×
1902

UNCOV
1903
                r = stat_verify_char(&sto);
×
UNCOV
1904
                if (r < 0)
×
1905
                        return r;
1906

UNCOV
1907
                if (sti.st_rdev != sto.st_rdev)
×
1908
                        return -ENOLINK;
1909
        }
1910

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

1914
        return 0;
1915
}
1916

1917
typedef enum CursorPositionState {
1918
        CURSOR_TEXT,
1919
        CURSOR_ESCAPE,
1920
        CURSOR_ROW,
1921
        CURSOR_COLUMN,
1922
} CursorPositionState;
1923

1924
typedef struct CursorPositionContext {
1925
        CursorPositionState state;
1926
        unsigned row, column;
1927
} CursorPositionContext;
1928

1929
static int scan_cursor_position_response(
×
1930
                CursorPositionContext *context,
1931
                const char *buf,
1932
                size_t size,
1933
                size_t *ret_processed) {
1934

1935
        assert(context);
×
1936
        assert(buf);
×
1937
        assert(ret_processed);
×
1938

1939
        for (size_t i = 0; i < size; i++) {
×
UNCOV
1940
                char c = buf[i];
×
1941

UNCOV
1942
                switch (context->state) {
×
1943

1944
                case CURSOR_TEXT:
×
UNCOV
1945
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
1946
                        break;
×
1947

UNCOV
1948
                case CURSOR_ESCAPE:
×
UNCOV
1949
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
1950
                        break;
×
1951

1952
                case CURSOR_ROW:
×
1953
                        if (c == ';')
×
1954
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
1955
                        else {
UNCOV
1956
                                int d = undecchar(c);
×
1957

1958
                                /* We read a decimal character, let's suffix it to the number we so far read,
1959
                                 * but let's do an overflow check first. */
UNCOV
1960
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
UNCOV
1961
                                        context->state = CURSOR_TEXT;
×
1962
                                else
1963
                                        context->row = context->row * 10 + d;
×
1964
                        }
1965
                        break;
1966

UNCOV
1967
                case CURSOR_COLUMN:
×
UNCOV
1968
                        if (c == 'R') {
×
UNCOV
1969
                                if (context->column > 0) {
×
UNCOV
1970
                                        *ret_processed = i + 1;
×
UNCOV
1971
                                        return 1; /* success! */
×
1972
                                }
1973

UNCOV
1974
                                context->state = CURSOR_TEXT;
×
1975
                        } else {
1976
                                int d = undecchar(c);
×
1977

1978
                                /* As above, add the decimal character to our column number */
UNCOV
1979
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
1980
                                        context->state = CURSOR_TEXT;
×
1981
                                else
UNCOV
1982
                                        context->column = context->column * 10 + d;
×
1983
                        }
1984

1985
                        break;
1986
                }
1987

1988
                /* Reset any positions we might have picked up */
1989
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
1990
                        context->row = context->column = 0;
×
1991
        }
1992

UNCOV
1993
        *ret_processed = size;
×
UNCOV
1994
        return 0; /* all good, but not enough data yet */
×
1995
}
1996

1997
int terminal_get_cursor_position(
×
1998
                int input_fd,
1999
                int output_fd,
2000
                unsigned *ret_row,
2001
                unsigned *ret_column) {
2002

UNCOV
2003
        _cleanup_close_ int nonblock_input_fd = -EBADF;
×
2004
        int r;
×
2005

UNCOV
2006
        assert(input_fd >= 0);
×
2007
        assert(output_fd >= 0);
×
2008

UNCOV
2009
        if (getenv_terminal_is_dumb())
×
2010
                return -EOPNOTSUPP;
2011

UNCOV
2012
        r = terminal_verify_same(input_fd, output_fd);
×
UNCOV
2013
        if (r < 0)
×
2014
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2015

2016
        /* Failure to reset the terminal is ignored here and in similar cases below.
2017
         * We already have our result; if cleanup fails it doesn't change the validity of the result. */
UNCOV
2018
        struct termios old_termios = TERMIOS_NULL;
×
UNCOV
2019
        CLEANUP_TERMIOS_RESET(input_fd, old_termios);
×
2020

2021
        if (tcgetattr(input_fd, &old_termios) < 0)
×
2022
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
2023

UNCOV
2024
        struct termios new_termios = old_termios;
×
2025
        termios_disable_echo(&new_termios);
×
2026

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

2030
        /* Request cursor position (DSR/CPR) */
2031
        r = loop_write(output_fd, "\x1B[6n", SIZE_MAX);
×
2032
        if (r < 0)
×
2033
                return r;
2034

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

UNCOV
2038
        nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2039
        if (r < 0)
×
2040
                return r;
2041

UNCOV
2042
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
×
UNCOV
2043
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
UNCOV
2044
        size_t buf_full = 0;
×
2045
        CursorPositionContext context = {};
×
2046

2047
        for (bool first = true;; first = false) {
×
2048
                if (buf_full == 0) {
×
UNCOV
2049
                        usec_t n = now(CLOCK_MONOTONIC);
×
2050
                        if (n >= end)
×
UNCOV
2051
                                return -EOPNOTSUPP;
×
2052

2053
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
UNCOV
2054
                        if (r < 0)
×
2055
                                return r;
UNCOV
2056
                        if (r == 0)
×
2057
                                return -EOPNOTSUPP;
2058

2059
                        /* On the first try, read multiple characters, i.e. the shortest valid
2060
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2061
                         * unnecessarily drop too many characters from the input queue. */
2062
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2063
                        if (l < 0) {
×
2064
                                if (errno == EAGAIN)
×
UNCOV
2065
                                        continue;
×
2066

UNCOV
2067
                                return -errno;
×
2068
                        }
2069

UNCOV
2070
                        assert((size_t) l <= sizeof(buf));
×
2071
                        buf_full = l;
2072
                }
2073

2074
                size_t processed;
×
UNCOV
2075
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
UNCOV
2076
                if (r < 0)
×
2077
                        return r;
2078

UNCOV
2079
                assert(processed <= buf_full);
×
UNCOV
2080
                buf_full -= processed;
×
UNCOV
2081
                memmove(buf, buf + processed, buf_full);
×
2082

UNCOV
2083
                if (r > 0) {
×
2084
                        /* Superficial validity check */
UNCOV
2085
                        if (context.row >= 32766 || context.column >= 32766)
×
2086
                                return -ENODATA;
2087

UNCOV
2088
                        if (ret_row)
×
UNCOV
2089
                                *ret_row = context.row;
×
UNCOV
2090
                        if (ret_column)
×
UNCOV
2091
                                *ret_column = context.column;
×
2092

2093
                        return 0;
2094
                }
2095
        }
2096
}
2097

2098
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
419✔
2099
        int r = 0;
419✔
2100

2101
        assert(fd >= 0);
419✔
2102
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
419✔
2103

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

2107
        if (!isatty_safe(fd))
419✔
2108
                return -ENOTTY;
419✔
2109

2110
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
412✔
2111

2112
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
412✔
2113
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
406✔
2114
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
405✔
2115

2116
        return r;
2117
}
2118

2119
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
7✔
2120
        assert(fd >= 0);
7✔
2121

2122
        _cleanup_close_ int lock_fd = lock_dev_console();
7✔
2123
        if (lock_fd < 0)
7✔
UNCOV
2124
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
2125

2126
        return terminal_reset_defensive(fd, flags);
7✔
2127
}
2128

2129
void termios_disable_echo(struct termios *termios) {
1✔
2130
        assert(termios);
1✔
2131

2132
        termios->c_lflag &= ~(ICANON|ECHO);
1✔
2133
        termios->c_cc[VMIN] = 1;
1✔
2134
        termios->c_cc[VTIME] = 0;
1✔
2135
}
1✔
2136

2137
static bool termios_is_null(const struct termios *t) {
9✔
2138
        if (!t)
9✔
2139
                return true;
2140

2141
        return t->c_iflag == UINT_MAX &&
17✔
2142
               t->c_oflag == UINT_MAX &&
8✔
2143
               t->c_cflag == UINT_MAX &&
26✔
2144
               t->c_lflag == UINT_MAX;
8✔
2145
}
2146

2147
void termios_reset(const TermiosResetContext *c) {
311✔
2148
        assert(c);
311✔
2149

2150
        PROTECT_ERRNO;
311✔
2151

2152
        if (c->fd && *c->fd >= 0 && !termios_is_null(c->termios))
311✔
2153
                (void) tcsetattr(*c->fd, TCSANOW, c->termios);
1✔
2154
}
311✔
2155

2156
typedef enum BackgroundColorState {
2157
        BACKGROUND_TEXT,
2158
        BACKGROUND_ESCAPE,
2159
        BACKGROUND_BRACKET,
2160
        BACKGROUND_FIRST_ONE,
2161
        BACKGROUND_SECOND_ONE,
2162
        BACKGROUND_SEMICOLON,
2163
        BACKGROUND_R,
2164
        BACKGROUND_G,
2165
        BACKGROUND_B,
2166
        BACKGROUND_RED,
2167
        BACKGROUND_GREEN,
2168
        BACKGROUND_BLUE,
2169
        BACKGROUND_STRING_TERMINATOR,
2170
} BackgroundColorState;
2171

2172
typedef struct BackgroundColorContext {
2173
        BackgroundColorState state;
2174
        uint32_t red, green, blue;
2175
        unsigned red_bits, green_bits, blue_bits;
2176
} BackgroundColorContext;
2177

2178
static int scan_background_color_response(
×
2179
                BackgroundColorContext *context,
2180
                const char *buf,
2181
                size_t size,
2182
                size_t *ret_processed) {
2183

2184
        assert(context);
×
2185
        assert(buf);
×
2186
        assert(ret_processed);
×
2187

2188
        for (size_t i = 0; i < size; i++) {
×
2189
                char c = buf[i];
×
2190

UNCOV
2191
                switch (context->state) {
×
2192

2193
                case BACKGROUND_TEXT:
×
2194
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
UNCOV
2195
                        break;
×
2196

2197
                case BACKGROUND_ESCAPE:
×
2198
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
UNCOV
2199
                        break;
×
2200

2201
                case BACKGROUND_BRACKET:
×
2202
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
UNCOV
2203
                        break;
×
2204

2205
                case BACKGROUND_FIRST_ONE:
×
2206
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
UNCOV
2207
                        break;
×
2208

2209
                case BACKGROUND_SECOND_ONE:
×
2210
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
UNCOV
2211
                        break;
×
2212

2213
                case BACKGROUND_SEMICOLON:
×
2214
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
UNCOV
2215
                        break;
×
2216

2217
                case BACKGROUND_R:
×
2218
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
UNCOV
2219
                        break;
×
2220

2221
                case BACKGROUND_G:
×
UNCOV
2222
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
UNCOV
2223
                        break;
×
2224

UNCOV
2225
                case BACKGROUND_B:
×
2226
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
2227
                        break;
×
2228

UNCOV
2229
                case BACKGROUND_RED:
×
2230
                        if (c == '/')
×
2231
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2232
                        else {
UNCOV
2233
                                int d = unhexchar(c);
×
2234
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
2235
                                        context->state = BACKGROUND_TEXT;
×
2236
                                else {
UNCOV
2237
                                        context->red = (context->red << 4) | d;
×
UNCOV
2238
                                        context->red_bits += 4;
×
2239
                                }
2240
                        }
2241
                        break;
2242

2243
                case BACKGROUND_GREEN:
×
2244
                        if (c == '/')
×
UNCOV
2245
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2246
                        else {
2247
                                int d = unhexchar(c);
×
2248
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
2249
                                        context->state = BACKGROUND_TEXT;
×
2250
                                else {
2251
                                        context->green = (context->green << 4) | d;
×
2252
                                        context->green_bits += 4;
×
2253
                                }
2254
                        }
2255
                        break;
2256

UNCOV
2257
                case BACKGROUND_BLUE:
×
UNCOV
2258
                        if (c == '\x07') {
×
UNCOV
2259
                                if (context->blue_bits > 0) {
×
UNCOV
2260
                                        *ret_processed = i + 1;
×
2261
                                        return 1; /* success! */
×
2262
                                }
2263

2264
                                context->state = BACKGROUND_TEXT;
×
UNCOV
2265
                        } else if (c == '\x1b')
×
UNCOV
2266
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2267
                        else {
2268
                                int d = unhexchar(c);
×
UNCOV
2269
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
UNCOV
2270
                                        context->state = BACKGROUND_TEXT;
×
2271
                                else {
UNCOV
2272
                                        context->blue = (context->blue << 4) | d;
×
2273
                                        context->blue_bits += 4;
×
2274
                                }
2275
                        }
2276
                        break;
2277

UNCOV
2278
                case BACKGROUND_STRING_TERMINATOR:
×
UNCOV
2279
                        if (c == '\\') {
×
2280
                                *ret_processed = i + 1;
×
2281
                                return 1; /* success! */
×
2282
                        }
2283

UNCOV
2284
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
UNCOV
2285
                        break;
×
2286

2287
                }
2288

2289
                /* Reset any colors we might have picked up */
UNCOV
2290
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2291
                        /* reset color */
UNCOV
2292
                        context->red = context->green = context->blue = 0;
×
UNCOV
2293
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2294
                }
2295
        }
2296

UNCOV
2297
        *ret_processed = size;
×
2298
        return 0; /* all good, but not enough data yet */
×
2299
}
2300

2301
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
172✔
2302
        int r;
172✔
2303

2304
        assert(ret_red);
172✔
2305
        assert(ret_green);
172✔
2306
        assert(ret_blue);
172✔
2307

2308
        if (!colors_enabled())
172✔
2309
                return -EOPNOTSUPP;
172✔
2310

2311
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
UNCOV
2312
        if (r < 0)
×
2313
                return r;
2314

UNCOV
2315
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2316
                /* Linux console is black */
2317
                *ret_red = *ret_green = *ret_blue = 0.0;
×
UNCOV
2318
                return 0;
×
2319
        }
2320

2321
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2322
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2323
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
172✔
UNCOV
2324
        if (r < 0)
×
2325
                return r;
2326

2327
        struct termios old_termios = TERMIOS_NULL;
×
2328
        CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
×
2329

UNCOV
2330
        if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
×
2331
                return -errno;
×
2332

2333
        struct termios new_termios = old_termios;
×
2334
        termios_disable_echo(&new_termios);
×
2335

UNCOV
2336
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
×
2337
                return -errno;
×
2338

UNCOV
2339
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
2340
        if (r < 0)
×
2341
                return r;
2342

UNCOV
2343
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
×
UNCOV
2344
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
UNCOV
2345
        size_t buf_full = 0;
×
2346
        BackgroundColorContext context = {};
×
2347

2348
        for (bool first = true;; first = false) {
×
2349
                if (buf_full == 0) {
×
2350
                        usec_t n = now(CLOCK_MONOTONIC);
×
UNCOV
2351
                        if (n >= end)
×
UNCOV
2352
                                return -EOPNOTSUPP;
×
2353

UNCOV
2354
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
UNCOV
2355
                        if (r < 0)
×
2356
                                return r;
2357
                        if (r == 0)
×
2358
                                return -EOPNOTSUPP;
2359

2360
                        /* On the first try, read multiple characters, i.e. the shortest valid
2361
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2362
                         * unnecessarily drop too many characters from the input queue. */
2363
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2364
                        if (l < 0) {
×
UNCOV
2365
                                if (errno == EAGAIN)
×
2366
                                        continue;
×
2367
                                return -errno;
×
2368
                        }
2369

2370
                        assert((size_t) l <= sizeof(buf));
×
2371
                        buf_full = l;
2372
                }
2373

UNCOV
2374
                size_t processed;
×
UNCOV
2375
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
UNCOV
2376
                if (r < 0)
×
2377
                        return r;
2378

UNCOV
2379
                assert(processed <= buf_full);
×
UNCOV
2380
                buf_full -= processed;
×
UNCOV
2381
                memmove(buf, buf + processed, buf_full);
×
2382

UNCOV
2383
                if (r > 0) {
×
2384
                        assert(context.red_bits > 0);
×
UNCOV
2385
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
UNCOV
2386
                        assert(context.green_bits > 0);
×
UNCOV
2387
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
UNCOV
2388
                        assert(context.blue_bits > 0);
×
UNCOV
2389
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
2390
                        return 0;
×
2391
                }
2392
        }
2393
}
2394

2395
/* Determine terminal dimensions by means of ANSI sequences: save the cursor via DECSC, position it far
2396
 * to the bottom right (clamped to actual terminal dimensions), read back via DSR where we ended up, and
2397
 * restore cursor via DECRC. Only needs a single DSR round-trip, and always restores the cursor regardless
2398
 * of whether the response is received.
2399
 *
2400
 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
UNCOV
2401
static int terminal_query_size_by_dsr(
×
2402
                int nonblock_input_fd,
2403
                int output_fd,
2404
                unsigned *ret_rows,
2405
                unsigned *ret_columns) {
2406

2407
        int r;
×
2408

2409
        assert(nonblock_input_fd >= 0);
×
2410
        assert(output_fd >= 0);
×
2411

2412
        /* Use DECSC/DECRC to save/restore cursor instead of querying position via DSR. This way the cursor
2413
         * is always restored — even on timeout — and we only need one DSR response instead of two. */
2414
        r = loop_write_full(output_fd,
×
2415
                            "\x1B" "7"              /* DECSC: save cursor position */
2416
                            "\x1B[32766;32766H"     /* CUP: position cursor far to the right and to the bottom, staying within 16bit signed range */
2417
                            "\x1B[6n"               /* DSR: request cursor position (CPR) */
2418
                            "\x1B" "8",             /* DECRC: restore cursor position */
2419
                            SIZE_MAX,
2420
                            CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2421
        if (r < 0)
×
UNCOV
2422
                return r;
×
2423

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

2429
        for (bool first = true;; first = false) {
×
2430
                if (buf_full == 0) {
×
UNCOV
2431
                        usec_t n = now(CLOCK_MONOTONIC);
×
2432
                        if (n >= end)
×
UNCOV
2433
                                return -EOPNOTSUPP;
×
2434

2435
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
UNCOV
2436
                        if (r < 0)
×
2437
                                return r;
UNCOV
2438
                        if (r == 0)
×
2439
                                return -EOPNOTSUPP;
2440

2441
                        /* On the first try, read multiple characters, i.e. the shortest valid
2442
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2443
                         * unnecessarily drop too many characters from the input queue. */
2444
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2445
                        if (l < 0) {
×
2446
                                if (errno == EAGAIN)
×
UNCOV
2447
                                        continue;
×
2448

UNCOV
2449
                                return -errno;
×
2450
                        }
2451

UNCOV
2452
                        assert((size_t) l <= sizeof(buf));
×
2453
                        buf_full = l;
2454
                }
2455

2456
                size_t processed;
×
2457
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
UNCOV
2458
                if (r < 0)
×
2459
                        return r;
2460

UNCOV
2461
                assert(processed <= buf_full);
×
UNCOV
2462
                buf_full -= processed;
×
UNCOV
2463
                memmove(buf, buf + processed, buf_full);
×
2464

UNCOV
2465
                if (r > 0) {
×
2466
                        /* Superficial validity checks (no particular reason to check for < 4, it's
2467
                         * just a way to look for unreasonably small values) */
UNCOV
2468
                        if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766)
×
2469
                                return -ENODATA;
2470

UNCOV
2471
                        if (ret_rows)
×
UNCOV
2472
                                *ret_rows = context.row;
×
UNCOV
2473
                        if (ret_columns)
×
UNCOV
2474
                                *ret_columns = context.column;
×
2475

2476
                        return 0;
2477
                }
2478
        }
2479
}
2480

2481
/* Common setup for ANSI terminal queries: validate the fds, open a non-blocking input fd, and configure
2482
 * termios with echo and canonical mode disabled. Caller must restore termios and close the fd when done. */
2483
static int terminal_prepare_query(
302✔
2484
                int input_fd,
2485
                int output_fd,
2486
                int *ret_nonblock_fd,
2487
                struct termios *ret_saved_termios) {
2488

2489
        int r;
302✔
2490

2491
        assert(input_fd >= 0);
302✔
2492
        assert(output_fd >= 0);
302✔
2493
        assert(ret_nonblock_fd);
302✔
2494
        assert(ret_saved_termios);
302✔
2495

2496
        /* Use getenv_terminal_is_dumb() instead of terminal_is_dumb() here since we operate on an
2497
         * explicitly passed fd, not on stdio. terminal_is_dumb() additionally checks on_tty() which
2498
         * tests whether *stderr* is a tty — that's irrelevant when we're querying a directly opened
2499
         * terminal such as /dev/console. */
2500
        if (getenv_terminal_is_dumb())
302✔
2501
                return -EOPNOTSUPP;
302✔
2502

2503
        r = terminal_verify_same(input_fd, output_fd);
×
UNCOV
2504
        if (r < 0)
×
2505
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2506

2507
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2508
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2509
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
302✔
UNCOV
2510
        if (r < 0)
×
2511
                return r;
2512

UNCOV
2513
        if (tcgetattr(nonblock_input_fd, ret_saved_termios) < 0)
×
UNCOV
2514
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
2515

UNCOV
2516
        struct termios new_termios = *ret_saved_termios;
×
UNCOV
2517
        termios_disable_echo(&new_termios);
×
2518

UNCOV
2519
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
×
UNCOV
2520
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
×
2521

UNCOV
2522
        *ret_nonblock_fd = TAKE_FD(nonblock_input_fd);
×
UNCOV
2523
        return 0;
×
2524
}
2525

2526
/*
2527
 * See https://terminalguide.namepad.de/seq/csi_st-18/,
2528
 * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_.
2529
 */
2530
#define CSI18_Q  "\x1B[18t"               /* Report the size of the text area in characters */
2531
#define CSI18_Rp "\x1B[8;"                /* Reply prefix */
2532
#define CSI18_R0 CSI18_Rp "1;1t"          /* Shortest reply */
2533
#define CSI18_R1 CSI18_Rp "32766;32766t"  /* Longest reply */
2534

UNCOV
2535
static int scan_text_area_size_response(
×
2536
                const char *buf,
2537
                size_t size,
2538
                unsigned *ret_rows,
2539
                unsigned *ret_columns) {
2540

2541
        assert(buf);
×
2542
        assert(ret_rows);
×
UNCOV
2543
        assert(ret_columns);
×
2544

2545
        /* Check if we have enough space for the shortest possible answer. */
UNCOV
2546
        if (size < STRLEN(CSI18_R0))
×
UNCOV
2547
                return -EAGAIN;
×
2548

2549
        /* Check if the terminating sequence is present */
UNCOV
2550
        if (buf[size - 1] != 't')
×
2551
                return -EAGAIN;
2552

UNCOV
2553
        unsigned short rows, columns;
×
2554
        if (sscanf(buf, CSI18_Rp "%hu;%hut", &rows, &columns) != 2)
×
2555
                return -EINVAL;
2556

2557
        *ret_rows = rows;
×
UNCOV
2558
        *ret_columns = columns;
×
2559
        return 0;
×
2560
}
2561

2562
/* Determine terminal dimensions by means of an ANSI CSI 18 sequence.
2563
 *
2564
 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
2565
static int terminal_query_size_by_csi18(
×
2566
                int nonblock_input_fd,
2567
                int output_fd,
2568
                unsigned *ret_rows,
2569
                unsigned *ret_columns) {
2570

UNCOV
2571
        int r;
×
2572

2573
        assert(nonblock_input_fd >= 0);
×
UNCOV
2574
        assert(output_fd >= 0);
×
2575

UNCOV
2576
        r = loop_write_full(output_fd, CSI18_Q, SIZE_MAX, CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
×
UNCOV
2577
        if (r < 0)
×
UNCOV
2578
                return r;
×
2579

UNCOV
2580
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
×
2581
        char buf[STRLEN(CSI18_R1)];
×
2582
        size_t bytes = 0;
×
2583

2584
        for (;;) {
×
2585
                usec_t n = now(CLOCK_MONOTONIC);
×
UNCOV
2586
                if (n >= end)
×
2587
                        return -EOPNOTSUPP;
2588

2589
                r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
UNCOV
2590
                if (r < 0)
×
2591
                        return r;
2592
                if (r == 0)
×
2593
                        return -EOPNOTSUPP;
2594

2595
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2596
                 * read byte by byte, since we don't want to read too much and drop characters from the input
2597
                 * queue. */
UNCOV
2598
                ssize_t l = read(nonblock_input_fd, buf + bytes, bytes == 0 ? STRLEN(CSI18_R0) : 1);
×
UNCOV
2599
                if (l < 0) {
×
UNCOV
2600
                        if (errno == EAGAIN)
×
UNCOV
2601
                                continue;
×
UNCOV
2602
                        return -errno;
×
2603
                }
2604

UNCOV
2605
                assert((size_t) l <= sizeof(buf) - bytes);
×
UNCOV
2606
                bytes += l;
×
2607

UNCOV
2608
                r = scan_text_area_size_response(buf, bytes, ret_rows, ret_columns);
×
UNCOV
2609
                if (r != -EAGAIN)
×
2610
                        return r;
2611

UNCOV
2612
                if (bytes == sizeof(buf))
×
2613
                        return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2614
                                             * answer with a terminator in the allotted space. Something is
2615
                                             * wrong, possibly some unrelated bytes got injected into the
2616
                                             * answer. */
2617
        }
2618
}
2619

2620
int terminal_get_size(
302✔
2621
                int input_fd,
2622
                int output_fd,
2623
                unsigned *ret_rows,
2624
                unsigned *ret_columns,
2625
                bool try_dsr,
2626
                bool try_csi18) {
2627

2628
        _cleanup_close_ int nonblock_input_fd = -EBADF;
302✔
2629
        struct termios old_termios = TERMIOS_NULL;
302✔
2630
        CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
302✔
2631
        _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
302✔
2632
        int r;
302✔
2633

2634
        assert(try_dsr || try_csi18);
302✔
2635

2636
        r = terminal_prepare_query(input_fd, output_fd, &nonblock_input_fd, &old_termios);
302✔
2637
        if (r < 0)
302✔
2638
                return r;
2639

2640
        /* Put the output fd in non-blocking mode with a write timeout, to avoid blocking indefinitely on
2641
         * write if the terminal is not consuming data (e.g. serial console with flow control). */
2642
        r = fd_nonblock(output_fd, true);
×
UNCOV
2643
        if (r < 0)
×
UNCOV
2644
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
UNCOV
2645
        if (r > 0)
×
2646
                nonblock_reset = output_fd;
×
2647

2648
        /* Flush any stale input that might confuse the response parsers. */
UNCOV
2649
        (void) tcflush(nonblock_input_fd, TCIFLUSH);
×
2650

UNCOV
2651
        if (try_csi18) {
×
2652
                r = terminal_query_size_by_csi18(nonblock_input_fd, output_fd, ret_rows, ret_columns);
×
UNCOV
2653
                if (r >= 0)
×
2654
                        return r;
2655

2656
                /* Query failed. Flush any outstanding input. */
UNCOV
2657
                (void) tcflush(nonblock_input_fd, TCIFLUSH);
×
2658

UNCOV
2659
                if (!IN_SET(r, -EOPNOTSUPP, -EINVAL))
×
2660
                        return r;
2661
        }
2662

UNCOV
2663
        if (try_dsr) {
×
UNCOV
2664
                r = terminal_query_size_by_dsr(nonblock_input_fd, output_fd, ret_rows, ret_columns);
×
UNCOV
2665
                if (r >= 0)
×
2666
                        return r;
2667

2668
                /* Query failed. Flush any outstanding input. */
UNCOV
2669
                (void) tcflush(nonblock_input_fd, TCIFLUSH);
×
2670
        }
2671

2672
        return r;
2673
}
2674

2675
int terminal_fix_size(int input_fd, int output_fd) {
20✔
2676
        unsigned rows, columns;
20✔
2677
        int r;
20✔
2678

2679
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences.
2680
         *
2681
         * Why bother with this? The ioctl() information is often incorrect on serial terminals (since
2682
         * there's no handshake or protocol to determine the right dimensions in RS232), but since the ANSI
2683
         * sequences are interpreted by the final terminal instead of an intermediary tty driver they should
2684
         * be more accurate.
2685
         */
2686

2687
        struct winsize ws = {};
20✔
2688
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
20✔
2689
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
1✔
2690

2691
        r = terminal_get_size(input_fd, output_fd, &rows, &columns, /* try_dsr= */ true, /* try_csi18= */ true);
19✔
2692
        if (r < 0)
19✔
2693
                return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
19✔
2694

UNCOV
2695
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
UNCOV
2696
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2697
                return 0;
2698
        }
2699

UNCOV
2700
        ws.ws_col = columns;
×
2701
        ws.ws_row = rows;
×
2702

UNCOV
2703
        if (ioctl(output_fd, TIOCSWINSZ, &ws) < 0)
×
UNCOV
2704
                return log_debug_errno(errno, "Failed to update terminal dimensions, ignoring: %m");
×
2705

UNCOV
2706
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2707
        return 1;
2708
}
2709

2710
#define MAX_TERMINFO_LENGTH 64
2711
/* python -c 'print("".join(hex(ord(i))[2:] for i in "name").upper())' */
2712
#define DCS_TERMINFO_Q ANSI_DCS "+q" "6E616D65" ANSI_ST
2713
/* The answer is either 0+r… (invalid) or 1+r… (OK). */
2714
#define DCS_TERMINFO_R0 ANSI_DCS "0+r" ANSI_ST
2715
#define DCS_TERMINFO_R1 ANSI_DCS "1+r" "6E616D65" "=" /* This is followed by Pt ST. */
2716
assert_cc(STRLEN(DCS_TERMINFO_R0) <= STRLEN(DCS_TERMINFO_R1 ANSI_ST));
2717

2718
static int scan_terminfo_response(
×
2719
                const char *buf,
2720
                size_t size,
2721
                char **ret_name) {
UNCOV
2722
        int r;
×
2723

2724
        assert(buf);
×
2725
        assert(ret_name);
×
2726

2727
        /* Check if we have enough space for the shortest possible answer. */
UNCOV
2728
        if (size < STRLEN(DCS_TERMINFO_R0))
×
2729
                return -EAGAIN;
×
2730

2731
        /* Check if the terminating sequence is present */
2732
        if (memcmp(buf + size - STRLEN(ANSI_ST), ANSI_ST, STRLEN(ANSI_ST)) != 0)
×
2733
                return -EAGAIN;
2734

UNCOV
2735
        if (size <= STRLEN(DCS_TERMINFO_R1 ANSI_ST))
×
2736
                return -EINVAL;  /* The answer is invalid or empty */
2737

UNCOV
2738
        if (memcmp(buf, DCS_TERMINFO_R1, STRLEN(DCS_TERMINFO_R1)) != 0)
×
2739
                return -EINVAL;  /* The answer is not valid */
2740

UNCOV
2741
        _cleanup_free_ void *dec = NULL;
×
UNCOV
2742
        size_t dec_size;
×
UNCOV
2743
        r = unhexmem_full(buf + STRLEN(DCS_TERMINFO_R1), size - STRLEN(DCS_TERMINFO_R1 ANSI_ST),
×
2744
                          /* secure= */ false,
2745
                          &dec, &dec_size);
UNCOV
2746
        if (r < 0)
×
2747
                return r;
2748

UNCOV
2749
        assert(((const char *) dec)[dec_size] == '\0'); /* unhexmem appends NUL for our convenience */
×
UNCOV
2750
        if (memchr(dec, '\0', dec_size) || string_has_cc(dec, NULL) || !filename_is_valid(dec))
×
2751
                return -EUCLEAN;
2752

UNCOV
2753
        *ret_name = TAKE_PTR(dec);
×
UNCOV
2754
        return 0;
×
2755
}
2756

2757
int terminal_get_terminfo_by_dcs(int fd, char **ret_name) {
2✔
2758
        int r;
2✔
2759

2760
        assert(fd >= 0);
2✔
2761
        assert(ret_name);
2✔
2762

2763
        /* Note: fd must be in non-blocking read-write mode! */
2764

2765
        struct termios old_termios = TERMIOS_NULL;
2✔
2766
        CLEANUP_TERMIOS_RESET(fd, old_termios);
2✔
2767

2768
        if (tcgetattr(fd, &old_termios) < 0)
2✔
2769
                return -errno;
1✔
2770

2771
        struct termios new_termios = old_termios;
1✔
2772
        termios_disable_echo(&new_termios);
1✔
2773

2774
        if (tcsetattr(fd, TCSANOW, &new_termios) < 0)
1✔
UNCOV
2775
                return -errno;
×
2776

2777
        r = loop_write(fd, DCS_TERMINFO_Q, SIZE_MAX);
1✔
2778
        if (r < 0)
1✔
2779
                return r;
2780

2781
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
1✔
2782
        char buf[STRLEN(DCS_TERMINFO_R1) + MAX_TERMINFO_LENGTH + STRLEN(ANSI_ST)];
1✔
2783
        size_t bytes = 0;
1✔
2784

2785
        for (;;) {
1✔
2786
                usec_t n = now(CLOCK_MONOTONIC);
1✔
2787
                if (n >= end)
1✔
2788
                        return -EOPNOTSUPP;
2789

2790
                r = fd_wait_for_event(fd, POLLIN, usec_sub_unsigned(end, n));
2✔
2791
                if (r < 0)
1✔
2792
                        return r;
2793
                if (r == 0)
1✔
2794
                        return -EOPNOTSUPP;
2795

2796
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2797
                 * read byte by byte, since we don't want to read too much and drop characters from the input
2798
                 * queue. */
UNCOV
2799
                ssize_t l = read(fd, buf + bytes, bytes == 0 ? STRLEN(DCS_TERMINFO_R0) : 1);
×
UNCOV
2800
                if (l < 0) {
×
UNCOV
2801
                        if (errno == EAGAIN)
×
UNCOV
2802
                                continue;
×
UNCOV
2803
                        return -errno;
×
2804
                }
2805

UNCOV
2806
                assert((size_t) l <= sizeof(buf) - bytes);
×
UNCOV
2807
                bytes += l;
×
2808

UNCOV
2809
                r = scan_terminfo_response(buf, bytes, ret_name);
×
UNCOV
2810
                if (r != -EAGAIN)
×
2811
                        return r;
2812

2813
                if (bytes == sizeof(buf))
×
2814
                        return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2815
                                             * answer with a terminator in the allotted space. Something is
2816
                                             * wrong, possibly some unrelated bytes got injected into the
2817
                                             * answer. */
2818
        }
2819
}
2820

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

2826
        assert(filename_is_valid(name));
5✔
2827

2828
        _cleanup_free_ char *p = path_join("/usr/share/terminfo", CHAR_TO_STR(name[0]), name);
10✔
2829
        if (!p)
5✔
UNCOV
2830
                return log_oom_debug();
×
2831

2832
        r = RET_NERRNO(access(p, F_OK));
5✔
2833
        if (r == -ENOENT)
1✔
2834
                return false;
2835
        if (r < 0)
4✔
UNCOV
2836
                return r;
×
2837
        return true;
2838
}
2839

2840
int query_term_for_tty(const char *tty, char **ret_term) {
53✔
2841
        _cleanup_free_ char *dcs_term = NULL;
53✔
2842
        int r;
53✔
2843

2844
        assert(tty);
53✔
2845
        assert(ret_term);
53✔
2846

2847
        if (tty_is_vc_resolve(tty))
53✔
2848
                return strdup_to(ret_term, "linux");
50✔
2849

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

2853
        _cleanup_close_ int tty_fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
56✔
2854
        if (tty_fd < 0)
3✔
2855
                return log_debug_errno(tty_fd, "Failed to open %s to query terminfo: %m", tty);
2✔
2856

2857
        r = terminal_get_terminfo_by_dcs(tty_fd, &dcs_term);
1✔
2858
        if (r < 0)
1✔
2859
                return log_debug_errno(r, "Failed to query %s for terminfo: %m", tty);
1✔
2860

UNCOV
2861
        r = have_terminfo_file(dcs_term);
×
UNCOV
2862
        if (r < 0)
×
UNCOV
2863
                return log_debug_errno(r, "Failed to look for terminfo %s: %m", dcs_term);
×
UNCOV
2864
        if (r == 0)
×
UNCOV
2865
                return log_info_errno(SYNTHETIC_ERRNO(ENODATA),
×
2866
                                      "Terminfo %s not found for %s.", dcs_term, tty);
2867

UNCOV
2868
        *ret_term = TAKE_PTR(dcs_term);
×
UNCOV
2869
        return 0;
×
2870
}
2871

2872
int terminal_is_pty_fd(int fd) {
3✔
2873
        int r;
3✔
2874

2875
        assert(fd >= 0);
3✔
2876

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

2879
        if (!isatty_safe(fd))
3✔
2880
                return false;
3✔
2881

2882
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2✔
2883
        if (r != 0)
2✔
2884
                return r;
2885

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

UNCOV
2889
        int v;
×
UNCOV
2890
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
×
UNCOV
2891
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
2892
                        return false;
2893

UNCOV
2894
                return -errno;
×
2895
        }
2896

2897
        return true;
2898
}
2899

2900
int pty_open_peer(int fd, int mode) {
27✔
2901
        assert(fd >= 0);
27✔
2902

2903
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2904
         *
2905
         * This is safe to be called on TTYs from other namespaces. */
2906

2907
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
27✔
2908

2909
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
UNCOV
2910
        for (unsigned c = 0;; c++) {
×
2911
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
27✔
2912
                if (peer_fd >= 0)
27✔
2913
                        return peer_fd;
2914

UNCOV
2915
                if (errno != EIO)
×
UNCOV
2916
                        return -errno;
×
2917

2918
                /* Max 1s in total */
UNCOV
2919
                if (c >= 20)
×
2920
                        return -EIO;
2921

UNCOV
2922
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2923
        }
2924
}
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