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

systemd / systemd / 15079507752

16 May 2025 10:18PM UTC coverage: 72.276% (+0.009%) from 72.267%
15079507752

push

github

YHNdnzj
sd-bus: drop a bunch of 'else'

With the new US taxes on bits and bytes let's reduce our footprint a
bit.

11 of 19 new or added lines in 1 file covered. (57.89%)

4028 existing lines in 76 files now uncovered.

298564 of 413090 relevant lines covered (72.28%)

700985.27 hits per line

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

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

3
#include <errno.h>
4
#include <fcntl.h>
5
#include <limits.h>
6
#include <linux/kd.h>
7
#include <linux/tiocl.h>
8
#include <linux/vt.h>
9
#include <poll.h>
10
#include <signal.h>
11
#include <stdarg.h>
12
#include <stddef.h>
13
#include <stdlib.h>
14
#include <sys/inotify.h>
15
#include <sys/ioctl.h>
16
#include <sys/sysmacros.h>
17
#include <sys/time.h>
18
#include <sys/types.h>
19
#include <sys/utsname.h>
20
#include <termios.h>
21
#include <unistd.h>
22

23
#include "alloc-util.h"
24
#include "ansi-color.h"
25
#include "chase.h"
26
#include "constants.h"
27
#include "devnum-util.h"
28
#include "env-util.h"
29
#include "errno-list.h"
30
#include "extract-word.h"
31
#include "fd-util.h"
32
#include "fileio.h"
33
#include "fs-util.h"
34
#include "glyph-util.h"
35
#include "hexdecoct.h"
36
#include "inotify-util.h"
37
#include "io-util.h"
38
#include "log.h"
39
#include "macro.h"
40
#include "missing_magic.h"
41
#include "namespace-util.h"
42
#include "parse-util.h"
43
#include "path-util.h"
44
#include "proc-cmdline.h"
45
#include "process-util.h"
46
#include "signal-util.h"
47
#include "socket-util.h"
48
#include "stat-util.h"
49
#include "stdio-util.h"
50
#include "string-table.h"
51
#include "string-util.h"
52
#include "strv.h"
53
#include "terminal-util.h"
54
#include "time-util.h"
55
#include "user-util.h"
56
#include "utf8.h"
57

58
#define ANSI_RESET_CURSOR                          \
59
        "\033?25h"     /* turn on cursor */        \
60
        "\033?12l"     /* reset cursor blinking */ \
61
        "\033 1q"      /* reset cursor style */
62

63
static volatile unsigned cached_columns = 0;
64
static volatile unsigned cached_lines = 0;
65

66
static volatile int cached_on_tty = -1;
67
static volatile int cached_on_dev_null = -1;
68

69
bool isatty_safe(int fd) {
5,469,707✔
70
        assert(fd >= 0);
5,469,707✔
71

72
        if (isatty(fd))
5,469,707✔
73
                return true;
74

75
        /* Linux/glibc returns EIO for hung up TTY on isatty(). Which is wrong, the thing doesn't stop being
76
         * a TTY after all, just because it is temporarily hung up. Let's work around this here, until this
77
         * is fixed in glibc. See: https://sourceware.org/bugzilla/show_bug.cgi?id=32103 */
78
        if (errno == EIO)
5,420,269✔
79
                return true;
80

81
        /* Be resilient if we're working on stdio, since they're set up by parent process. */
82
        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
5,420,260✔
83

84
        return false;
85
}
86

UNCOV
87
int chvt(int vt) {
×
88
        _cleanup_close_ int fd = -EBADF;
×
89

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

93
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
×
UNCOV
94
        if (fd < 0)
×
95
                return fd;
96

UNCOV
97
        if (vt <= 0) {
×
98
                int tiocl[2] = {
×
99
                        TIOCL_GETKMSGREDIRECT,
100
                        0
101
                };
102

UNCOV
103
                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
×
104
                        return -errno;
×
105

UNCOV
106
                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
×
107
        }
108

UNCOV
109
        return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
×
110
}
111

112
int read_one_char(FILE *f, char *ret, usec_t t, bool echo, bool *need_nl) {
10✔
113
        _cleanup_free_ char *line = NULL;
10✔
114
        struct termios old_termios;
10✔
115
        int r, fd;
10✔
116

117
        assert(ret);
10✔
118

119
        if (!f)
10✔
UNCOV
120
                f = stdin;
×
121

122
        /* If this is a terminal, then switch canonical mode off, so that we can read a single
123
         * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
124
         * nicely.) If 'echo' is false we'll also disable ECHO mode so that the pressed key is not made
125
         * visible to the user. */
126
        fd = fileno(f);
10✔
127
        if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
10✔
UNCOV
128
                struct termios new_termios = old_termios;
×
129

130
                new_termios.c_lflag &= ~(ICANON|(echo ? 0 : ECHO));
×
UNCOV
131
                new_termios.c_cc[VMIN] = 1;
×
132
                new_termios.c_cc[VTIME] = 0;
×
133

134
                if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
×
135
                        char c;
×
136

UNCOV
137
                        if (t != USEC_INFINITY) {
×
UNCOV
138
                                if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
×
139
                                        (void) tcsetattr(fd, TCSADRAIN, &old_termios);
×
140
                                        return -ETIMEDOUT;
×
141
                                }
142
                        }
143

UNCOV
144
                        r = safe_fgetc(f, &c);
×
UNCOV
145
                        (void) tcsetattr(fd, TCSADRAIN, &old_termios);
×
146
                        if (r < 0)
×
147
                                return r;
UNCOV
148
                        if (r == 0)
×
149
                                return -EIO;
150

UNCOV
151
                        if (need_nl)
×
UNCOV
152
                                *need_nl = c != '\n';
×
153

UNCOV
154
                        *ret = c;
×
UNCOV
155
                        return 0;
×
156
                }
157
        }
158

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

165
                if (fd_wait_for_event(fd, POLLIN, t) <= 0)
4✔
166
                        return -ETIMEDOUT;
167
        }
168

169
        /* If this is not a terminal, then read a full line instead */
170

171
        r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
10✔
172
        if (r < 0)
10✔
173
                return r;
174
        if (r == 0)
10✔
175
                return -EIO;
176

177
        if (strlen(line) != 1)
8✔
178
                return -EBADMSG;
179

180
        if (need_nl)
1✔
181
                *need_nl = false;
1✔
182

183
        *ret = line[0];
1✔
184
        return 0;
1✔
185
}
186

187
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
188

189
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
×
UNCOV
190
        int r;
×
191

192
        assert(ret);
×
193
        assert(replies);
×
194
        assert(fmt);
×
195

196
        for (;;) {
×
UNCOV
197
                va_list ap;
×
198
                char c;
×
UNCOV
199
                bool need_nl = true;
×
200

201
                fputs(ansi_highlight(), stdout);
×
202

UNCOV
203
                putchar('\r');
×
204

UNCOV
205
                va_start(ap, fmt);
×
206
                vprintf(fmt, ap);
×
UNCOV
207
                va_end(ap);
×
208

209
                fputs(ansi_normal(), stdout);
×
210

211
                fflush(stdout);
×
212

UNCOV
213
                r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, /* echo= */ true, &need_nl);
×
214
                if (r < 0) {
×
215

216
                        if (r == -ETIMEDOUT)
×
UNCOV
217
                                continue;
×
218

219
                        if (r == -EBADMSG) {
×
220
                                puts("Bad input, please try again.");
×
UNCOV
221
                                continue;
×
222
                        }
223

224
                        putchar('\n');
×
UNCOV
225
                        return r;
×
226
                }
227

228
                if (need_nl)
×
UNCOV
229
                        putchar('\n');
×
230

231
                if (strchr(replies, c)) {
×
UNCOV
232
                        *ret = c;
×
UNCOV
233
                        return 0;
×
234
                }
235

UNCOV
236
                puts("Read unexpected character, please try again.");
×
237
        }
238
}
239

240
typedef enum CompletionResult{
241
        COMPLETION_ALREADY,       /* the input string is already complete */
242
        COMPLETION_FULL,          /* completed the input string to be complete now */
243
        COMPLETION_PARTIAL,       /* completed the input string so that is still incomplete */
244
        COMPLETION_NONE,          /* found no matching completion */
245
        _COMPLETION_RESULT_MAX,
246
        _COMPLETION_RESULT_INVALID = -EINVAL,
247
        _COMPLETION_RESULT_ERRNO_MAX = -ERRNO_MAX,
248
} CompletionResult;
249

UNCOV
250
static CompletionResult pick_completion(const char *string, char *const*completions, char **ret) {
×
251
        _cleanup_free_ char *found = NULL;
×
UNCOV
252
        bool partial = false;
×
253

254
        string = strempty(string);
×
255

UNCOV
256
        STRV_FOREACH(c, completions) {
×
257

258
                /* Ignore entries that are not actually completions */
259
                if (!startswith(*c, string))
×
260
                        continue;
×
261

262
                /* Store first completion that matches */
263
                if (!found) {
×
UNCOV
264
                        found = strdup(*c);
×
UNCOV
265
                        if (!found)
×
266
                                return -ENOMEM;
267

268
                        continue;
×
269
                }
270

271
                /* If there's another completion that works truncate the one we already found by common
272
                 * prefix */
273
                size_t n = str_common_prefix(found, *c);
×
UNCOV
274
                if (n == SIZE_MAX)
×
UNCOV
275
                        continue;
×
276

UNCOV
277
                found[n] = 0;
×
278
                partial = true;
×
279
        }
280

UNCOV
281
        *ret = TAKE_PTR(found);
×
282

283
        if (!*ret)
×
284
                return COMPLETION_NONE;
UNCOV
285
        if (partial)
×
286
                return COMPLETION_PARTIAL;
287

288
        return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
×
289
}
290

UNCOV
291
static void clear_by_backspace(size_t n) {
×
292
        /* Erase the specified number of character cells backwards on the terminal */
UNCOV
293
        for (size_t i = 0; i < n; i++)
×
UNCOV
294
                fputs("\b \b", stdout);
×
UNCOV
295
}
×
296

297
int ask_string_full(
7✔
298
                char **ret,
299
                GetCompletionsCallback get_completions,
300
                void *userdata,
301
                const char *text, ...) {
302

303
        va_list ap;
7✔
304
        int r;
7✔
305

306
        assert(ret);
7✔
307
        assert(text);
7✔
308

309
        /* Output the prompt */
310
        fputs(ansi_highlight(), stdout);
14✔
311
        va_start(ap, text);
7✔
312
        vprintf(text, ap);
7✔
313
        va_end(ap);
7✔
314
        fputs(ansi_normal(), stdout);
14✔
315
        fflush(stdout);
7✔
316

317
        _cleanup_free_ char *string = NULL;
7✔
318
        size_t n = 0;
7✔
319

320
        /* Do interactive logic only if stdin + stdout are connected to the same place. And yes, we could use
321
         * STDIN_FILENO and STDOUT_FILENO here, but let's be overly correct for once, after all libc allows
322
         * swapping out stdin/stdout. */
323
        int fd_input = fileno(stdin);
7✔
324
        int fd_output = fileno(stdout);
7✔
325
        if (fd_input < 0 || fd_output < 0 || same_fd(fd_input, fd_output) <= 0)
7✔
326
                goto fallback;
7✔
327

328
        /* Try to disable echo, which also tells us if this even is a terminal */
329
        struct termios old_termios;
×
330
        if (tcgetattr(fd_input, &old_termios) < 0)
×
331
                goto fallback;
×
332

333
        struct termios new_termios = old_termios;
×
334
        termios_disable_echo(&new_termios);
×
UNCOV
335
        if (tcsetattr(fd_input, TCSADRAIN, &new_termios) < 0)
×
UNCOV
336
                return -errno;
×
337

UNCOV
338
        for (;;) {
×
UNCOV
339
                int c = fgetc(stdin);
×
340

341
                /* On EOF or NUL, end the request, don't output anything anymore */
342
                if (IN_SET(c, EOF, 0))
×
343
                        break;
344

345
                /* On Return also end the request, but make this visible */
346
                if (IN_SET(c, '\n', '\r')) {
×
UNCOV
347
                        fputc('\n', stdout);
×
348
                        break;
349
                }
350

351
                if (c == '\t') {
×
352
                        /* Tab */
353

UNCOV
354
                        _cleanup_strv_free_ char **completions = NULL;
×
UNCOV
355
                        if (get_completions) {
×
356
                                r = get_completions(string, &completions, userdata);
×
357
                                if (r < 0)
×
358
                                        goto fail;
×
359
                        }
360

UNCOV
361
                        _cleanup_free_ char *new_string = NULL;
×
362
                        CompletionResult cr = pick_completion(string, completions, &new_string);
×
UNCOV
363
                        if (cr < 0) {
×
364
                                r = cr;
×
UNCOV
365
                                goto fail;
×
366
                        }
367
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_FULL)) {
×
368
                                /* Output the new suffix we learned */
UNCOV
369
                                fputs(ASSERT_PTR(startswith(new_string, strempty(string))), stdout);
×
370

371
                                /* And update the whole string */
UNCOV
372
                                free_and_replace(string, new_string);
×
373
                                n = strlen(string);
×
374
                        }
UNCOV
375
                        if (cr == COMPLETION_NONE)
×
UNCOV
376
                                fputc('\a', stdout); /* BEL */
×
377

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

UNCOV
384
                                _cleanup_strv_free_ char **filtered = strv_filter_prefix(completions, string);
×
385
                                if (!filtered) {
×
UNCOV
386
                                        r = -ENOMEM;
×
UNCOV
387
                                        goto fail;
×
388
                                }
389

UNCOV
390
                                r = show_menu(filtered,
×
391
                                              /* n_columns= */ SIZE_MAX,
392
                                              /* column_width= */ SIZE_MAX,
393
                                              /* ellipsize_percentage= */ 0,
394
                                              /* grey_prefix=*/ string,
395
                                              /* with_numbers= */ false);
396
                                if (r < 0)
×
397
                                        goto fail;
×
398

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

UNCOV
408
                } else if (IN_SET(c, '\b', 127)) {
×
409
                        /* Backspace */
410

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

UNCOV
416
                                char *e = string + n - m;
×
UNCOV
417
                                clear_by_backspace(utf8_console_width(e));
×
418

UNCOV
419
                                *e = 0;
×
UNCOV
420
                                n -= m;
×
421
                        }
422

423
                } else if (c == 21) {
×
424
                        /* Ctrl-u → erase all input */
425

UNCOV
426
                        clear_by_backspace(utf8_console_width(string));
×
427
                        if (string)
×
UNCOV
428
                                string[n = 0] = 0;
×
429
                        else
430
                                assert(n == 0);
×
431

UNCOV
432
                } else if (c == 4) {
×
433
                        /* Ctrl-d → cancel this field input */
434

435
                        r = -ECANCELED;
×
UNCOV
436
                        goto fail;
×
437

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

444
                        if (!GREEDY_REALLOC(string, n+2)) {
×
445
                                r = -ENOMEM;
×
UNCOV
446
                                goto fail;
×
447
                        }
448

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

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

UNCOV
455
                fflush(stdout);
×
456
        }
457

458
        if (tcsetattr(fd_input, TCSADRAIN, &old_termios) < 0)
×
UNCOV
459
                return -errno;
×
460

UNCOV
461
        if (!string) {
×
462
                string = strdup("");
×
463
                if (!string)
×
464
                        return -ENOMEM;
465
        }
466

467
        *ret = TAKE_PTR(string);
×
UNCOV
468
        return 0;
×
469

UNCOV
470
fail:
×
UNCOV
471
        (void) tcsetattr(fd_input, TCSADRAIN, &old_termios);
×
UNCOV
472
        return r;
×
473

474
fallback:
7✔
475
        /* A simple fallback without TTY magic */
476
        r = read_line(stdin, LONG_LINE_MAX, &string);
7✔
477
        if (r < 0)
7✔
478
                return r;
479
        if (r == 0)
7✔
480
                return -EIO;
481

482
        *ret = TAKE_PTR(string);
7✔
483
        return 0;
7✔
484
}
485

486
bool any_key_to_proceed(void) {
6✔
487

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

492
        fputc('\n', stdout);
6✔
493
        fputs(ansi_highlight_magenta(), stdout);
12✔
494
        fputs("-- Press any key to proceed --", stdout);
6✔
495
        fputs(ansi_normal(), stdout);
12✔
496
        fputc('\n', stdout);
6✔
497
        fflush(stdout);
6✔
498

499
        char key = 0;
6✔
500
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
6✔
501

502
        fputc('\n', stdout);
6✔
503
        fflush(stdout);
6✔
504

505
        return key != 'q';
6✔
506
}
507

508
static size_t widest_list_element(char *const*l) {
×
509
        size_t w = 0;
×
510

511
        /* Returns the largest console width of all elements in 'l' */
512

UNCOV
513
        STRV_FOREACH(i, l)
×
514
                w = MAX(w, utf8_console_width(*i));
×
515

UNCOV
516
        return w;
×
517
}
518

UNCOV
519
int show_menu(char **x,
×
520
              size_t n_columns,
521
              size_t column_width,
522
              unsigned ellipsize_percentage,
523
              const char *grey_prefix,
524
              bool with_numbers) {
525

526
        assert(n_columns > 0);
×
527

UNCOV
528
        if (n_columns == SIZE_MAX)
×
UNCOV
529
                n_columns = 3;
×
530

UNCOV
531
        if (column_width == SIZE_MAX) {
×
UNCOV
532
                size_t widest = widest_list_element(x);
×
533

534
                /* If not specified, derive column width from screen width */
UNCOV
535
                size_t column_max = (columns()-1) / n_columns;
×
536

537
                /* Subtract room for numbers */
538
                if (with_numbers && column_max > 6)
×
539
                        column_max -= 6;
×
540

541
                /* If columns would get too tight let's make this a linear list instead. */
542
                if (column_max < 10 && widest > 10) {
×
UNCOV
543
                        n_columns = 1;
×
UNCOV
544
                        column_max = columns()-1;
×
545

UNCOV
546
                        if (with_numbers && column_max > 6)
×
UNCOV
547
                                column_max -= 6;
×
548
                }
549

UNCOV
550
                column_width = CLAMP(widest+1, 10U, column_max);
×
551
        }
552

553
        size_t n = strv_length(x);
×
UNCOV
554
        size_t per_column = DIV_ROUND_UP(n, n_columns);
×
555

UNCOV
556
        size_t break_lines = lines();
×
557
        if (break_lines > 2)
×
558
                break_lines--;
×
559

560
        /* The first page gets two extra lines, since we want to show
561
         * a title */
UNCOV
562
        size_t break_modulo = break_lines;
×
563
        if (break_modulo > 3)
×
564
                break_modulo -= 3;
×
565

566
        for (size_t i = 0; i < per_column; i++) {
×
567

UNCOV
568
                for (size_t j = 0; j < n_columns; j++) {
×
569
                        _cleanup_free_ char *e = NULL;
×
570

571
                        if (j * per_column + i >= n)
×
572
                                break;
573

574
                        e = ellipsize(x[j * per_column + i], column_width, ellipsize_percentage);
×
UNCOV
575
                        if (!e)
×
UNCOV
576
                                return -ENOMEM;
×
577

UNCOV
578
                        if (with_numbers)
×
579
                                printf("%s%4zu)%s ",
×
580
                                       ansi_grey(),
581
                                       j * per_column + i + 1,
582
                                       ansi_normal());
583

UNCOV
584
                        if (grey_prefix && startswith(e, grey_prefix)) {
×
585
                                size_t k = MIN(strlen(grey_prefix), column_width);
×
586
                                printf("%s%.*s%s",
×
587
                                       ansi_grey(),
588
                                       (int) k, e,
589
                                       ansi_normal());
UNCOV
590
                                printf("%-*s",
×
591
                                       (int) (column_width - k), e+k);
×
592
                        } else
UNCOV
593
                                printf("%-*s", (int) column_width, e);
×
594
                }
595

UNCOV
596
                putchar('\n');
×
597

598
                /* on the first screen we reserve 2 extra lines for the title */
UNCOV
599
                if (i % break_lines == break_modulo)
×
UNCOV
600
                        if (!any_key_to_proceed())
×
601
                                return 0;
602
        }
603

604
        return 0;
605
}
606

607
int open_terminal(const char *name, int mode) {
49,931✔
608
        _cleanup_close_ int fd = -EBADF;
49,931✔
609

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

618
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
49,931✔
619

UNCOV
620
        for (unsigned c = 0;; c++) {
×
621
                fd = open(name, mode, 0);
49,931✔
622
                if (fd >= 0)
49,931✔
623
                        break;
624

625
                if (errno != EIO)
2,277✔
626
                        return -errno;
2,277✔
627

628
                /* Max 1s in total */
UNCOV
629
                if (c >= 20)
×
630
                        return -EIO;
631

UNCOV
632
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
633
        }
634

635
        if (!isatty_safe(fd))
47,654✔
UNCOV
636
                return -ENOTTY;
×
637

638
        return TAKE_FD(fd);
639
}
640

641
int acquire_terminal(
366✔
642
                const char *name,
643
                AcquireTerminalFlags flags,
644
                usec_t timeout) {
645

646
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
366✔
647
        usec_t ts = USEC_INFINITY;
366✔
648
        int r, wd = -1;
366✔
649

650
        assert(name);
366✔
651

652
        AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
366✔
653
        assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
366✔
654
        assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
366✔
655

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

UNCOV
665
        if (mode == ACQUIRE_TERMINAL_WAIT) {
×
666
                notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
366✔
667
                if (notify < 0)
366✔
UNCOV
668
                        return -errno;
×
669

670
                wd = inotify_add_watch(notify, name, IN_CLOSE);
366✔
671
                if (wd < 0)
366✔
672
                        return -errno;
21✔
673

674
                if (timeout != USEC_INFINITY)
345✔
UNCOV
675
                        ts = now(CLOCK_MONOTONIC);
×
676
        }
677

678
        /* If we are called with ACQUIRE_TERMINAL_WATCH_SIGTERM we'll unblock SIGTERM during ppoll() temporarily */
679
        sigset_t poll_ss;
345✔
680
        assert_se(sigprocmask(SIG_SETMASK, /* newset= */ NULL, &poll_ss) >= 0);
345✔
681
        if (flags & ACQUIRE_TERMINAL_WATCH_SIGTERM) {
345✔
UNCOV
682
                assert_se(sigismember(&poll_ss, SIGTERM) > 0);
×
UNCOV
683
                assert_se(sigdelset(&poll_ss, SIGTERM) >= 0);
×
684
        }
685

686
        for (;;) {
345✔
687
                if (notify >= 0) {
345✔
688
                        r = flush_fd(notify);
345✔
689
                        if (r < 0)
345✔
UNCOV
690
                                return r;
×
691
                }
692

693
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
694
                 * to figure out if we successfully became the controlling process of the tty */
695
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
345✔
696
                if (fd < 0)
345✔
697
                        return fd;
698

699
                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
700
                struct sigaction sa_old;
345✔
701
                assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
345✔
702

703
                /* First, try to get the tty */
704
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
345✔
705

706
                /* Reset signal handler to old value */
707
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
345✔
708

709
                /* Success? Exit the loop now! */
710
                if (r >= 0)
345✔
711
                        break;
712

713
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
UNCOV
714
                if (r != -EPERM)
×
715
                        return r;
716

717
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
×
718
                                                          * into a success. Note that EPERM is also returned if we
719
                                                          * already are the owner of the TTY. */
720
                        break;
721

UNCOV
722
                if (mode != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
×
723
                        return r;
724

725
                assert(notify >= 0);
×
UNCOV
726
                assert(wd >= 0);
×
727

728
                for (;;) {
×
UNCOV
729
                        usec_t left;
×
730
                        if (timeout == USEC_INFINITY)
×
731
                                left = USEC_INFINITY;
732
                        else {
UNCOV
733
                                assert(ts != USEC_INFINITY);
×
734

UNCOV
735
                                usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
UNCOV
736
                                if (n >= timeout)
×
737
                                        return -ETIMEDOUT;
×
738

UNCOV
739
                                left = timeout - n;
×
740
                        }
741

UNCOV
742
                        r = ppoll_usec_full(
×
UNCOV
743
                                        &(struct pollfd) {
×
744
                                                .fd = notify,
745
                                                .events = POLLIN,
746
                                        },
747
                                        /* n_pollfds = */ 1,
748
                                        left,
749
                                        &poll_ss);
750
                        if (r < 0)
×
751
                                return r;
752
                        if (r == 0)
×
753
                                return -ETIMEDOUT;
754

755
                        union inotify_event_buffer buffer;
×
UNCOV
756
                        ssize_t l;
×
757
                        l = read(notify, &buffer, sizeof(buffer));
×
UNCOV
758
                        if (l < 0) {
×
UNCOV
759
                                if (ERRNO_IS_TRANSIENT(errno))
×
760
                                        continue;
×
761

UNCOV
762
                                return -errno;
×
763
                        }
764

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

UNCOV
769
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
×
UNCOV
770
                                        return -EIO;
×
771
                        }
772

773
                        break;
×
774
                }
775

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

781
        return TAKE_FD(fd);
345✔
782
}
783

784
int release_terminal(void) {
64✔
785
        _cleanup_close_ int fd = -EBADF;
64✔
786
        int r;
64✔
787

788
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
64✔
789
        if (fd < 0)
64✔
790
                return -errno;
44✔
791

792
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
793
         * by our own TIOCNOTTY */
794
        struct sigaction sa_old;
20✔
795
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
20✔
796

797
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
20✔
798

799
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
20✔
800

801
        return r;
802
}
803

804
int terminal_new_session(void) {
5✔
805

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

813
        if (!isatty_safe(STDIN_FILENO))
5✔
814
                return -ENXIO;
815

816
        (void) setsid();
4✔
817
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
4✔
818
}
819

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

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

UNCOV
828
        assert(tty);
×
829

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

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

837
int vt_disallocate(const char *tty_path) {
84✔
838
        assert(tty_path);
84✔
839

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

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

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

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

859
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
168✔
860
        if (fd2 < 0)
84✔
861
                return fd2;
862

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

873
static int vt_default_utf8(void) {
694✔
874
        _cleanup_free_ char *b = NULL;
694✔
875
        int r;
694✔
876

877
        /* Read the default VT UTF8 setting from the kernel */
878

879
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
694✔
880
        if (r < 0)
694✔
881
                return r;
882

883
        return parse_boolean(b);
380✔
884
}
885

886
static int vt_reset_keyboard(int fd) {
347✔
887
        int r, kb;
347✔
888

889
        assert(fd >= 0);
347✔
890

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

896
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
347✔
897
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
347✔
898
}
899

900
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
347✔
901
        struct termios termios;
347✔
902
        int r;
347✔
903

904
        /* Set terminal to some sane defaults */
905

906
        assert(fd >= 0);
347✔
907

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

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

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

920
        /* Set default keyboard mode */
921
        r = vt_reset_keyboard(fd);
347✔
922
        if (r < 0)
347✔
923
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
182✔
924

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

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

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

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

954
        termios.c_cc[VTIME]  = 0;
345✔
955
        termios.c_cc[VMIN]   = 1;
345✔
956

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

UNCOV
961
finish:
×
962
        /* Just in case, flush all crap out */
963
        (void) tcflush(fd, TCIOFLUSH);
347✔
964

965
        return r;
347✔
966
}
967

968
static int terminal_reset_ansi_seq(int fd) {
341✔
969
        int r, k;
341✔
970

971
        assert(fd >= 0);
341✔
972

973
        if (getenv_terminal_is_dumb())
341✔
974
                return 0;
975

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

UNCOV
980
        k = loop_write_full(fd,
×
981
                            ANSI_RESET_CURSOR
982
                            "\033[!p"      /* soft terminal reset */
983
                            "\033]104\007" /* reset colors */
984
                            "\033[?7h"     /* enable line-wrapping */
985
                            "\033[1G"      /* place cursor at beginning of current line */
986
                            "\033[0J",     /* erase till end of screen */
987
                            SIZE_MAX,
988
                            100 * USEC_PER_MSEC);
UNCOV
989
        if (k < 0)
×
UNCOV
990
                log_debug_errno(k, "Failed to reset terminal through ANSI sequences: %m");
×
991

UNCOV
992
        if (r > 0) {
×
UNCOV
993
                r = fd_nonblock(fd, false);
×
UNCOV
994
                if (r < 0)
×
UNCOV
995
                        log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
×
996
        }
997

UNCOV
998
        return k < 0 ? k : r;
×
999
}
1000

1001
void reset_dev_console_fd(int fd, bool switch_to_text) {
33✔
1002
        int r;
33✔
1003

1004
        assert(fd >= 0);
33✔
1005

1006
        _cleanup_close_ int lock_fd = lock_dev_console();
33✔
1007
        if (lock_fd < 0)
33✔
UNCOV
1008
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
1009

1010
        r = terminal_reset_ioctl(fd, switch_to_text);
33✔
1011
        if (r < 0)
33✔
UNCOV
1012
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
×
1013

1014
        unsigned rows, cols;
33✔
1015
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
33✔
1016
        if (r < 0)
33✔
UNCOV
1017
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
×
1018
        else if (r > 0) {
33✔
1019
                r = terminal_set_size_fd(fd, NULL, rows, cols);
33✔
1020
                if (r < 0)
33✔
UNCOV
1021
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
×
1022
        } else
UNCOV
1023
                (void) terminal_fix_size(fd, fd);
×
1024

1025
        r = terminal_reset_ansi_seq(fd);
33✔
1026
        if (r < 0)
33✔
1027
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
33✔
1028
}
33✔
1029

1030
int lock_dev_console(void) {
925✔
1031
        _cleanup_close_ int fd = -EBADF;
925✔
1032
        int r;
925✔
1033

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

1040
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
925✔
1041
        if (r < 0)
925✔
UNCOV
1042
                return r;
×
1043

1044
        return TAKE_FD(fd);
1045
}
1046

1047
int make_console_stdio(void) {
×
1048
        int fd, r;
×
1049

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

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

1058
                r = make_null_stdio();
×
1059
                if (r < 0)
×
1060
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
×
1061

1062
        } else {
1063
                reset_dev_console_fd(fd, /* switch_to_text= */ true);
×
1064

UNCOV
1065
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
×
UNCOV
1066
                if (r < 0)
×
UNCOV
1067
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
×
1068
        }
1069

UNCOV
1070
        reset_terminal_feature_caches();
×
UNCOV
1071
        return 0;
×
1072
}
1073

1074
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
313✔
1075
        assert(tty);
313✔
1076

1077
        tty = skip_dev_prefix(tty);
313✔
1078

1079
        const char *e = startswith(tty, "tty");
313✔
1080
        if (!e)
313✔
1081
                return -EINVAL;
1082

1083
        return safe_atou(e, ret);
272✔
1084
}
1085

1086
int vtnr_from_tty(const char *tty) {
196✔
1087
        unsigned u;
196✔
1088
        int r;
196✔
1089

1090
        assert(tty);
196✔
1091

1092
        r = vtnr_from_tty_raw(tty, &u);
196✔
1093
        if (r < 0)
196✔
1094
                return r;
196✔
1095
        if (!vtnr_is_valid(u))
196✔
1096
                return -ERANGE;
1097

1098
        return (int) u;
196✔
1099
}
1100

1101
bool tty_is_vc(const char *tty) {
117✔
1102
        assert(tty);
117✔
1103

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

1109
        return vtnr_from_tty_raw(tty, /* ret = */ NULL) >= 0;
117✔
1110
}
1111

1112
bool tty_is_console(const char *tty) {
401✔
1113
        assert(tty);
401✔
1114

1115
        return streq(skip_dev_prefix(tty), "console");
401✔
1116
}
1117

1118
int resolve_dev_console(char **ret) {
305✔
1119
        int r;
305✔
1120

1121
        assert(ret);
305✔
1122

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

1128
        _cleanup_free_ char *chased = NULL;
305✔
1129
        r = chase("/dev/console", /* root= */ NULL, /* flags= */ 0,  &chased, /* ret_fd= */ NULL);
305✔
1130
        if (r < 0)
305✔
1131
                return r;
1132
        if (!path_equal(chased, "/dev/console")) {
305✔
1133
                *ret = TAKE_PTR(chased);
152✔
1134
                return 0;
152✔
1135
        }
1136

1137
        r = path_is_read_only_fs("/sys");
153✔
1138
        if (r < 0)
153✔
1139
                return r;
1140
        if (r > 0)
153✔
1141
                return -ENOMEDIUM;
1142

1143
        _cleanup_free_ char *active = NULL;
153✔
1144
        r = read_one_line_file("/sys/class/tty/console/active", &active);
153✔
1145
        if (r < 0)
153✔
1146
                return r;
1147

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

1155
        if (streq(tty, "tty0")) {
153✔
1156
                active = mfree(active);
×
1157

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

UNCOV
1163
                tty = active;
×
1164
        }
1165

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

1171
        *ret = TAKE_PTR(path);
153✔
1172
        return 0;
153✔
1173
}
1174

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

1180
        assert(ret);
1✔
1181

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

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

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

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

1200
                if (streq(tty, "tty0")) {
×
1201
                        tty = mfree(tty);
×
UNCOV
1202
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
UNCOV
1203
                        if (r < 0)
×
1204
                                return r;
1205
                }
1206

UNCOV
1207
                path = path_join("/dev", tty);
×
UNCOV
1208
                if (!path)
×
1209
                        return -ENOMEM;
1210

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

1216
                r = strv_consume(&l, TAKE_PTR(path));
×
UNCOV
1217
                if (r < 0)
×
1218
                        return r;
1219
        }
1220

UNCOV
1221
        if (strv_isempty(l)) {
×
UNCOV
1222
                log_debug("No devices found for system console");
×
UNCOV
1223
                goto fallback;
×
1224
        }
1225

UNCOV
1226
        *ret = TAKE_PTR(l);
×
UNCOV
1227
        return strv_length(*ret);
×
1228

1229
fallback:
1✔
1230
        r = strv_extend(&l, "/dev/console");
1✔
1231
        if (r < 0)
1✔
1232
                return r;
1233

1234
        *ret = TAKE_PTR(l);
1✔
1235
        return 0;
1✔
1236
}
1237

1238
bool tty_is_vc_resolve(const char *tty) {
50✔
1239
        _cleanup_free_ char *resolved = NULL;
50✔
1240

1241
        assert(tty);
50✔
1242

1243
        if (streq(skip_dev_prefix(tty), "console")) {
50✔
1244
                if (resolve_dev_console(&resolved) < 0)
2✔
1245
                        return false;
1246

1247
                tty = resolved;
2✔
1248
        }
1249

1250
        return tty_is_vc(tty);
50✔
1251
}
1252

1253
const char* default_term_for_tty(const char *tty) {
66✔
1254
        return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
66✔
1255
}
1256

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

1260
        if (fd < 0)
1,228✔
1261
                return -EBADF;
1262

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

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

UNCOV
1269
        return ws.ws_col;
×
1270
}
1271

1272
int getenv_columns(void) {
1,424✔
1273
        int r;
1,424✔
1274

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

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

1284
        return (int) c;
1✔
1285
}
1286

1287
unsigned columns(void) {
205,182✔
1288

1289
        if (cached_columns > 0)
205,182✔
1290
                return cached_columns;
203,953✔
1291

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

1299
        assert(c > 0);
1✔
1300

1301
        cached_columns = c;
1,229✔
1302
        return cached_columns;
1,229✔
1303
}
1304

1305
int fd_lines(int fd) {
156✔
1306
        struct winsize ws = {};
156✔
1307

1308
        if (fd < 0)
156✔
1309
                return -EBADF;
1310

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

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

UNCOV
1317
        return ws.ws_row;
×
1318
}
1319

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

1324
        if (cached_lines > 0)
156✔
UNCOV
1325
                return cached_lines;
×
1326

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

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

1338
        cached_lines = l;
156✔
1339
        return cached_lines;
156✔
1340
}
1341

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

1345
        assert(fd >= 0);
1,095✔
1346

1347
        if (!ident)
1,095✔
1348
                ident = "TTY";
65✔
1349

1350
        if (rows == UINT_MAX && cols == UINT_MAX)
1,095✔
1351
                return 0;
1,095✔
1352

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

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

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

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

1371
        ws.ws_row = rows;
366✔
1372
        ws.ws_col = cols;
366✔
1373

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

1377
        return 0;
1378
}
1379

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

1385
        assert(tty);
1,063✔
1386

1387
        if (!ret_rows && !ret_cols)
1,063✔
1388
                return 0;
1389

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

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

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

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

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

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

1423
        if (ret_rows)
1,063✔
1424
                *ret_rows = rows;
1,063✔
1425
        if (ret_cols)
1,063✔
1426
                *ret_cols = cols;
1,063✔
1427

1428
        return rows != UINT_MAX || cols != UINT_MAX;
1,063✔
1429
}
1430

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

1437
void reset_terminal_feature_caches(void) {
14✔
1438
        cached_columns = 0;
14✔
1439
        cached_lines = 0;
14✔
1440

1441
        cached_on_tty = -1;
14✔
1442
        cached_on_dev_null = -1;
14✔
1443

1444
        reset_ansi_feature_caches();
14✔
1445
}
14✔
1446

1447
bool on_tty(void) {
7,337,663✔
1448

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

1455
        if (cached_on_tty < 0)
7,337,663✔
1456
                cached_on_tty =
46,169✔
1457
                        isatty_safe(STDOUT_FILENO) &&
46,184✔
1458
                        isatty_safe(STDERR_FILENO);
15✔
1459

1460
        return cached_on_tty;
7,337,663✔
1461
}
1462

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

1467
        assert(fd >= 0);
421✔
1468
        assert(ret);
421✔
1469

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

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

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

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

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

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

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

1501
        assert(pid >= 0);
3,132✔
1502

1503
        p = procfs_file_alloca(pid, "stat");
15,364✔
1504
        r = read_one_line_file(p, &line);
3,132✔
1505
        if (r < 0)
3,132✔
1506
                return r;
1507

1508
        p = strrchr(line, ')');
3,132✔
1509
        if (!p)
3,132✔
1510
                return -EIO;
1511

1512
        p++;
3,132✔
1513

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

1523
        if (devnum_is_zero(ttynr))
3,132✔
1524
                return -ENXIO;
1525

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

1529
        return 0;
1530
}
1531

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

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

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

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

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

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

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

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

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

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

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

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

1590
        return 0;
1591
}
1592

1593
int ptsname_malloc(int fd, char **ret) {
117✔
1594
        size_t l = 100;
117✔
1595

1596
        assert(fd >= 0);
117✔
1597
        assert(ret);
117✔
1598

1599
        for (;;) {
117✔
1600
                char *c;
117✔
1601

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

1606
                if (ptsname_r(fd, c, l) == 0) {
117✔
1607
                        *ret = c;
117✔
1608
                        return 0;
117✔
1609
                }
1610
                if (errno != ERANGE) {
×
UNCOV
1611
                        free(c);
×
UNCOV
1612
                        return -errno;
×
1613
                }
1614

UNCOV
1615
                free(c);
×
1616

UNCOV
1617
                if (l > SIZE_MAX / 2)
×
1618
                        return -ENOMEM;
1619

UNCOV
1620
                l *= 2;
×
1621
        }
1622
}
1623

1624
int openpt_allocate(int flags, char **ret_peer_path) {
121✔
1625
        _cleanup_close_ int fd = -EBADF;
121✔
1626
        int r;
121✔
1627

1628
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
121✔
1629
        if (fd < 0)
121✔
UNCOV
1630
                return -errno;
×
1631

1632
        _cleanup_free_ char *p = NULL;
121✔
1633
        if (ret_peer_path) {
121✔
1634
                r = ptsname_malloc(fd, &p);
117✔
1635
                if (r < 0)
117✔
1636
                        return r;
1637

1638
                if (!path_startswith(p, "/dev/pts/"))
117✔
1639
                        return -EINVAL;
1640
        }
1641

1642
        if (unlockpt(fd) < 0)
121✔
UNCOV
1643
                return -errno;
×
1644

1645
        if (ret_peer_path)
121✔
1646
                *ret_peer_path = TAKE_PTR(p);
117✔
1647

1648
        return TAKE_FD(fd);
1649
}
1650

UNCOV
1651
static int ptsname_namespace(int pty, char **ret) {
×
UNCOV
1652
        int no = -1;
×
1653

1654
        assert(pty >= 0);
×
UNCOV
1655
        assert(ret);
×
1656

1657
        /* Like ptsname(), but doesn't assume that the path is
1658
         * accessible in the local namespace. */
1659

1660
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
UNCOV
1661
                return -errno;
×
1662

UNCOV
1663
        if (no < 0)
×
1664
                return -EIO;
1665

UNCOV
1666
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
UNCOV
1667
                return -ENOMEM;
×
1668

1669
        return 0;
1670
}
1671

1672
int openpt_allocate_in_namespace(
×
1673
                const PidRef *pidref,
1674
                int flags,
1675
                char **ret_peer_path) {
1676

UNCOV
1677
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
1678
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
1679
        int r;
×
1680

1681
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
×
UNCOV
1682
        if (r < 0)
×
1683
                return r;
1684

UNCOV
1685
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
UNCOV
1686
                return -errno;
×
1687

UNCOV
1688
        r = namespace_fork(
×
1689
                        "(sd-openptns)",
1690
                        "(sd-openpt)",
1691
                        /* except_fds= */ NULL,
1692
                        /* n_except_fds= */ 0,
1693
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1694
                        pidnsfd,
1695
                        mntnsfd,
1696
                        /* netns_fd= */ -EBADF,
1697
                        usernsfd,
1698
                        rootfd,
1699
                        /* ret_pid= */ NULL);
1700
        if (r < 0)
×
1701
                return r;
1702
        if (r == 0) {
×
1703
                pair[0] = safe_close(pair[0]);
×
1704

1705
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
UNCOV
1706
                if (fd < 0)
×
UNCOV
1707
                        _exit(EXIT_FAILURE);
×
1708

UNCOV
1709
                if (send_one_fd(pair[1], fd, 0) < 0)
×
1710
                        _exit(EXIT_FAILURE);
×
1711

UNCOV
1712
                _exit(EXIT_SUCCESS);
×
1713
        }
1714

1715
        pair[1] = safe_close(pair[1]);
×
1716

1717
        fd = receive_one_fd(pair[0], 0);
×
UNCOV
1718
        if (fd < 0)
×
1719
                return fd;
1720

UNCOV
1721
        if (ret_peer_path) {
×
UNCOV
1722
                r = ptsname_namespace(fd, ret_peer_path);
×
UNCOV
1723
                if (r < 0)
×
UNCOV
1724
                        return r;
×
1725
        }
1726

1727
        return TAKE_FD(fd);
1728
}
1729

1730
static bool on_dev_null(void) {
56,052✔
1731
        struct stat dst, ost, est;
56,052✔
1732

1733
        if (cached_on_dev_null >= 0)
56,052✔
1734
                return cached_on_dev_null;
9,952✔
1735

1736
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
46,100✔
1737
                cached_on_dev_null = false;
1✔
1738
        else
1739
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
49,928✔
1740

1741
        return cached_on_dev_null;
46,100✔
1742
}
1743

1744
bool getenv_terminal_is_dumb(void) {
12,883✔
1745
        const char *e;
12,883✔
1746

1747
        e = getenv("TERM");
12,883✔
1748
        if (!e)
12,883✔
1749
                return true;
1750

1751
        return streq(e, "dumb");
11,811✔
1752
}
1753

1754
bool terminal_is_dumb(void) {
56,059✔
1755
        if (!on_tty() && !on_dev_null())
56,059✔
1756
                return true;
1757

1758
        return getenv_terminal_is_dumb();
196✔
1759
}
1760

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

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

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

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

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

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

UNCOV
1785
int vt_restore(int fd) {
×
1786

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

1791
        int r, ret = 0;
×
1792

UNCOV
1793
        assert(fd >= 0);
×
1794

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

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

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

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

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

1812
        return ret;
1813
}
1814

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

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

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

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

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

1831
        return 0;
1832
}
1833

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

1838
        if (priority <= LOG_ERR) {
176,511✔
1839
                if (on)
6,385✔
1840
                        *on = ansi_highlight_red();
12,770✔
1841
                if (off)
6,385✔
1842
                        *off = ansi_normal();
12,770✔
1843
                if (highlight)
6,385✔
UNCOV
1844
                        *highlight = ansi_highlight();
×
1845

1846
        } else if (priority <= LOG_WARNING) {
170,126✔
1847
                if (on)
966✔
1848
                        *on = ansi_highlight_yellow();
966✔
1849
                if (off)
966✔
1850
                        *off = ansi_normal();
1,932✔
1851
                if (highlight)
966✔
UNCOV
1852
                        *highlight = ansi_highlight();
×
1853

1854
        } else if (priority <= LOG_NOTICE) {
169,160✔
1855
                if (on)
870✔
1856
                        *on = ansi_highlight();
1,740✔
1857
                if (off)
870✔
1858
                        *off = ansi_normal();
1,740✔
1859
                if (highlight)
870✔
UNCOV
1860
                        *highlight = ansi_highlight_red();
×
1861

1862
        } else if (priority >= LOG_DEBUG) {
168,290✔
1863
                if (on)
128,886✔
1864
                        *on = ansi_grey();
128,886✔
1865
                if (off)
128,886✔
1866
                        *off = ansi_normal();
257,772✔
1867
                if (highlight)
128,886✔
1868
                        *highlight = ansi_highlight_red();
×
1869
        }
1870
}
176,511✔
1871

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

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

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

1881
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
321✔
1882
        int r = 0;
321✔
1883

1884
        assert(fd >= 0);
321✔
1885
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
321✔
1886

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

1890
        if (!isatty_safe(fd))
321✔
1891
                return -ENOTTY;
321✔
1892

1893
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
314✔
1894

1895
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
314✔
1896
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
308✔
1897
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
308✔
1898

1899
        return r;
1900
}
1901

1902
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
6✔
1903
        assert(fd >= 0);
6✔
1904

1905
        _cleanup_close_ int lock_fd = lock_dev_console();
6✔
1906
        if (lock_fd < 0)
6✔
UNCOV
1907
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
1908

1909
        return terminal_reset_defensive(fd, flags);
6✔
1910
}
1911

UNCOV
1912
void termios_disable_echo(struct termios *termios) {
×
UNCOV
1913
        assert(termios);
×
1914

UNCOV
1915
        termios->c_lflag &= ~(ICANON|ECHO);
×
UNCOV
1916
        termios->c_cc[VMIN] = 1;
×
UNCOV
1917
        termios->c_cc[VTIME] = 0;
×
UNCOV
1918
}
×
1919

1920
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1921
        assert(input_fd >= 0);
1✔
1922
        assert(output_fd >= 0);
1✔
1923

1924
        /* Validates that the specified fds reference the same TTY */
1925

1926
        if (input_fd != output_fd) {
1✔
1927
                struct stat sti;
1✔
1928
                if (fstat(input_fd, &sti) < 0)
1✔
1929
                        return -errno;
1✔
1930

1931
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
1932
                        return -ENOTTY;
1933

1934
                struct stat sto;
1✔
1935
                if (fstat(output_fd, &sto) < 0)
1✔
UNCOV
1936
                        return -errno;
×
1937

1938
                if (!S_ISCHR(sto.st_mode))
1✔
1939
                        return -ENOTTY;
1940

UNCOV
1941
                if (sti.st_rdev != sto.st_rdev)
×
1942
                        return -ENOLINK;
1943
        }
1944

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

1948
        return 0;
1949
}
1950

1951
typedef enum BackgroundColorState {
1952
        BACKGROUND_TEXT,
1953
        BACKGROUND_ESCAPE,
1954
        BACKGROUND_BRACKET,
1955
        BACKGROUND_FIRST_ONE,
1956
        BACKGROUND_SECOND_ONE,
1957
        BACKGROUND_SEMICOLON,
1958
        BACKGROUND_R,
1959
        BACKGROUND_G,
1960
        BACKGROUND_B,
1961
        BACKGROUND_RED,
1962
        BACKGROUND_GREEN,
1963
        BACKGROUND_BLUE,
1964
        BACKGROUND_STRING_TERMINATOR,
1965
} BackgroundColorState;
1966

1967
typedef struct BackgroundColorContext {
1968
        BackgroundColorState state;
1969
        uint32_t red, green, blue;
1970
        unsigned red_bits, green_bits, blue_bits;
1971
} BackgroundColorContext;
1972

1973
static int scan_background_color_response(
×
1974
                BackgroundColorContext *context,
1975
                const char *buf,
1976
                size_t size,
1977
                size_t *ret_processed) {
1978

UNCOV
1979
        assert(context);
×
1980
        assert(buf);
×
1981
        assert(ret_processed);
×
1982

UNCOV
1983
        for (size_t i = 0; i < size; i++) {
×
1984
                char c = buf[i];
×
1985

1986
                switch (context->state) {
×
1987

1988
                case BACKGROUND_TEXT:
×
1989
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
1990
                        break;
×
1991

1992
                case BACKGROUND_ESCAPE:
×
1993
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
1994
                        break;
×
1995

1996
                case BACKGROUND_BRACKET:
×
1997
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
1998
                        break;
×
1999

2000
                case BACKGROUND_FIRST_ONE:
×
2001
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
2002
                        break;
×
2003

2004
                case BACKGROUND_SECOND_ONE:
×
2005
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
2006
                        break;
×
2007

2008
                case BACKGROUND_SEMICOLON:
×
2009
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
2010
                        break;
×
2011

2012
                case BACKGROUND_R:
×
2013
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
2014
                        break;
×
2015

2016
                case BACKGROUND_G:
×
2017
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
2018
                        break;
×
2019

2020
                case BACKGROUND_B:
×
2021
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
2022
                        break;
×
2023

2024
                case BACKGROUND_RED:
×
2025
                        if (c == '/')
×
UNCOV
2026
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2027
                        else {
UNCOV
2028
                                int d = unhexchar(c);
×
UNCOV
2029
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
2030
                                        context->state = BACKGROUND_TEXT;
×
2031
                                else {
2032
                                        context->red = (context->red << 4) | d;
×
UNCOV
2033
                                        context->red_bits += 4;
×
2034
                                }
2035
                        }
2036
                        break;
2037

2038
                case BACKGROUND_GREEN:
×
2039
                        if (c == '/')
×
UNCOV
2040
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2041
                        else {
UNCOV
2042
                                int d = unhexchar(c);
×
UNCOV
2043
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
2044
                                        context->state = BACKGROUND_TEXT;
×
2045
                                else {
2046
                                        context->green = (context->green << 4) | d;
×
2047
                                        context->green_bits += 4;
×
2048
                                }
2049
                        }
2050
                        break;
2051

UNCOV
2052
                case BACKGROUND_BLUE:
×
2053
                        if (c == '\x07') {
×
2054
                                if (context->blue_bits > 0) {
×
2055
                                        *ret_processed = i + 1;
×
UNCOV
2056
                                        return 1; /* success! */
×
2057
                                }
2058

2059
                                context->state = BACKGROUND_TEXT;
×
UNCOV
2060
                        } else if (c == '\x1b')
×
2061
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2062
                        else {
UNCOV
2063
                                int d = unhexchar(c);
×
UNCOV
2064
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
UNCOV
2065
                                        context->state = BACKGROUND_TEXT;
×
2066
                                else {
2067
                                        context->blue = (context->blue << 4) | d;
×
2068
                                        context->blue_bits += 4;
×
2069
                                }
2070
                        }
2071
                        break;
2072

UNCOV
2073
                case BACKGROUND_STRING_TERMINATOR:
×
UNCOV
2074
                        if (c == '\\') {
×
2075
                                *ret_processed = i + 1;
×
2076
                                return 1; /* success! */
×
2077
                        }
2078

UNCOV
2079
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
UNCOV
2080
                        break;
×
2081

2082
                }
2083

2084
                /* Reset any colors we might have picked up */
UNCOV
2085
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2086
                        /* reset color */
UNCOV
2087
                        context->red = context->green = context->blue = 0;
×
2088
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2089
                }
2090
        }
2091

UNCOV
2092
        *ret_processed = size;
×
UNCOV
2093
        return 0; /* all good, but not enough data yet */
×
2094
}
2095

2096
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
125✔
2097
        _cleanup_close_ int nonblock_input_fd = -EBADF;
125✔
2098
        int r;
125✔
2099

2100
        assert(ret_red);
125✔
2101
        assert(ret_green);
125✔
2102
        assert(ret_blue);
125✔
2103

2104
        if (!colors_enabled())
125✔
2105
                return -EOPNOTSUPP;
2106

UNCOV
2107
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
UNCOV
2108
        if (r < 0)
×
2109
                return r;
2110

2111
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2112
                /* Linux console is black */
UNCOV
2113
                *ret_red = *ret_green = *ret_blue = 0.0;
×
UNCOV
2114
                return 0;
×
2115
        }
2116

2117
        struct termios old_termios;
×
UNCOV
2118
        if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
×
2119
                return -errno;
×
2120

UNCOV
2121
        struct termios new_termios = old_termios;
×
2122
        termios_disable_echo(&new_termios);
×
2123

UNCOV
2124
        if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) < 0)
×
2125
                return -errno;
×
2126

2127
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
UNCOV
2128
        if (r < 0)
×
UNCOV
2129
                goto finish;
×
2130

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

UNCOV
2134
        nonblock_input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
UNCOV
2135
        if (nonblock_input_fd < 0)
×
2136
                return nonblock_input_fd;
2137

2138
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2139
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
UNCOV
2140
        size_t buf_full = 0;
×
2141
        BackgroundColorContext context = {};
×
2142

2143
        for (bool first = true;; first = false) {
×
2144
                if (buf_full == 0) {
×
2145
                        usec_t n = now(CLOCK_MONOTONIC);
×
2146
                        if (n >= end) {
×
UNCOV
2147
                                r = -EOPNOTSUPP;
×
UNCOV
2148
                                goto finish;
×
2149
                        }
2150

2151
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2152
                        if (r < 0)
×
2153
                                goto finish;
×
2154
                        if (r == 0) {
×
UNCOV
2155
                                r = -EOPNOTSUPP;
×
UNCOV
2156
                                goto finish;
×
2157
                        }
2158

2159
                        /* On the first try, read multiple characters, i.e. the shortest valid
2160
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2161
                         * unnecessarily drop too many characters from the input queue. */
2162
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2163
                        if (l < 0) {
×
2164
                                if (errno == EAGAIN)
×
2165
                                        continue;
×
UNCOV
2166
                                r = -errno;
×
UNCOV
2167
                                goto finish;
×
2168
                        }
2169

UNCOV
2170
                        assert((size_t) l <= sizeof(buf));
×
2171
                        buf_full = l;
2172
                }
2173

2174
                size_t processed;
×
2175
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
UNCOV
2176
                if (r < 0)
×
2177
                        goto finish;
×
2178

2179
                assert(processed <= buf_full);
×
UNCOV
2180
                buf_full -= processed;
×
2181
                memmove(buf, buf + processed, buf_full);
×
2182

2183
                if (r > 0) {
×
2184
                        assert(context.red_bits > 0);
×
2185
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
2186
                        assert(context.green_bits > 0);
×
2187
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
2188
                        assert(context.blue_bits > 0);
×
2189
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
UNCOV
2190
                        r = 0;
×
UNCOV
2191
                        goto finish;
×
2192
                }
2193
        }
2194

UNCOV
2195
finish:
×
UNCOV
2196
        RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios)));
×
2197
        return r;
2198
}
2199

2200
typedef enum CursorPositionState {
2201
        CURSOR_TEXT,
2202
        CURSOR_ESCAPE,
2203
        CURSOR_ROW,
2204
        CURSOR_COLUMN,
2205
} CursorPositionState;
2206

2207
typedef struct CursorPositionContext {
2208
        CursorPositionState state;
2209
        unsigned row, column;
2210
} CursorPositionContext;
2211

UNCOV
2212
static int scan_cursor_position_response(
×
2213
                CursorPositionContext *context,
2214
                const char *buf,
2215
                size_t size,
2216
                size_t *ret_processed) {
2217

UNCOV
2218
        assert(context);
×
2219
        assert(buf);
×
2220
        assert(ret_processed);
×
2221

2222
        for (size_t i = 0; i < size; i++) {
×
UNCOV
2223
                char c = buf[i];
×
2224

2225
                switch (context->state) {
×
2226

UNCOV
2227
                case CURSOR_TEXT:
×
2228
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
2229
                        break;
×
2230

UNCOV
2231
                case CURSOR_ESCAPE:
×
2232
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
2233
                        break;
×
2234

UNCOV
2235
                case CURSOR_ROW:
×
2236
                        if (c == ';')
×
UNCOV
2237
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
2238
                        else {
UNCOV
2239
                                int d = undecchar(c);
×
2240

2241
                                /* We read a decimal character, let's suffix it to the number we so far read,
2242
                                 * but let's do an overflow check first. */
2243
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
UNCOV
2244
                                        context->state = CURSOR_TEXT;
×
2245
                                else
UNCOV
2246
                                        context->row = context->row * 10 + d;
×
2247
                        }
2248
                        break;
2249

2250
                case CURSOR_COLUMN:
×
2251
                        if (c == 'R') {
×
UNCOV
2252
                                if (context->column > 0) {
×
2253
                                        *ret_processed = i + 1;
×
UNCOV
2254
                                        return 1; /* success! */
×
2255
                                }
2256

UNCOV
2257
                                context->state = CURSOR_TEXT;
×
2258
                        } else {
UNCOV
2259
                                int d = undecchar(c);
×
2260

2261
                                /* As above, add the decimal character to our column number */
2262
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
UNCOV
2263
                                        context->state = CURSOR_TEXT;
×
2264
                                else
UNCOV
2265
                                        context->column = context->column * 10 + d;
×
2266
                        }
2267

2268
                        break;
2269
                }
2270

2271
                /* Reset any positions we might have picked up */
2272
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
UNCOV
2273
                        context->row = context->column = 0;
×
2274
        }
2275

2276
        *ret_processed = size;
×
UNCOV
2277
        return 0; /* all good, but not enough data yet */
×
2278
}
2279

2280
int terminal_get_size_by_dsr(
170✔
2281
                int input_fd,
2282
                int output_fd,
2283
                unsigned *ret_rows,
2284
                unsigned *ret_columns) {
2285

2286
        _cleanup_close_ int nonblock_input_fd = -EBADF;
170✔
2287

2288
        assert(input_fd >= 0);
170✔
2289
        assert(output_fd >= 0);
170✔
2290

2291
        int r;
170✔
2292

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

2308
        if (terminal_is_dumb())
170✔
2309
                return -EOPNOTSUPP;
2310

UNCOV
2311
        r = terminal_verify_same(input_fd, output_fd);
×
2312
        if (r < 0)
×
2313
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2314

UNCOV
2315
        struct termios old_termios;
×
2316
        if (tcgetattr(input_fd, &old_termios) < 0)
×
2317
                return log_debug_errno(errno, "Failed to to get terminal settings: %m");
×
2318

UNCOV
2319
        struct termios new_termios = old_termios;
×
2320
        termios_disable_echo(&new_termios);
×
2321

UNCOV
2322
        if (tcsetattr(input_fd, TCSADRAIN, &new_termios) < 0)
×
2323
                return log_debug_errno(errno, "Failed to to set new terminal settings: %m");
×
2324

UNCOV
2325
        unsigned saved_row = 0, saved_column = 0;
×
2326

UNCOV
2327
        r = loop_write(output_fd,
×
2328
                       "\x1B[6n"           /* Request cursor position (DSR/CPR) */
2329
                       "\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
2330
                       "\x1B[6n",          /* Request cursor position again */
2331
                       SIZE_MAX);
UNCOV
2332
        if (r < 0)
×
2333
                goto finish;
×
2334

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

UNCOV
2338
        nonblock_input_fd = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2339
        if (nonblock_input_fd < 0)
×
2340
                return nonblock_input_fd;
2341

UNCOV
2342
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2343
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2344
        size_t buf_full = 0;
×
2345
        CursorPositionContext context = {};
×
2346

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

UNCOV
2355
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2356
                        if (r < 0)
×
2357
                                goto finish;
×
2358
                        if (r == 0) {
×
2359
                                r = -EOPNOTSUPP;
×
2360
                                goto finish;
×
2361
                        }
2362

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

UNCOV
2371
                                r = -errno;
×
2372
                                goto finish;
×
2373
                        }
2374

UNCOV
2375
                        assert((size_t) l <= sizeof(buf));
×
2376
                        buf_full = l;
2377
                }
2378

UNCOV
2379
                size_t processed;
×
2380
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2381
                if (r < 0)
×
2382
                        goto finish;
×
2383

UNCOV
2384
                assert(processed <= buf_full);
×
2385
                buf_full -= processed;
×
2386
                memmove(buf, buf + processed, buf_full);
×
2387

UNCOV
2388
                if (r > 0) {
×
2389
                        if (saved_row == 0) {
×
2390
                                assert(saved_column == 0);
×
2391

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

2396
                                /* Superficial validity checks */
UNCOV
2397
                                if (context.row <= 0 || context.column <= 0 || context.row >= 32766 || context.column >= 32766) {
×
2398
                                        r = -ENODATA;
×
2399
                                        goto finish;
×
2400
                                }
2401

UNCOV
2402
                                saved_row = context.row;
×
2403
                                saved_column = context.column;
×
2404

2405
                                /* Reset state */
UNCOV
2406
                                context = (CursorPositionContext) {};
×
2407
                        } else {
2408
                                /* Second sequence, this is the cursor position after we set it somewhere
2409
                                 * into the void at the bottom right. */
2410

2411
                                /* Superficial validity checks (no particular reason to check for < 4, it's
2412
                                 * just a way to look for unreasonably small values) */
UNCOV
2413
                                if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766) {
×
2414
                                        r = -ENODATA;
×
2415
                                        goto finish;
×
2416
                                }
2417

UNCOV
2418
                                if (ret_rows)
×
2419
                                        *ret_rows = context.row;
×
2420
                                if (ret_columns)
×
2421
                                        *ret_columns = context.column;
×
2422

UNCOV
2423
                                r = 0;
×
2424
                                goto finish;
×
2425
                        }
2426
                }
2427
        }
2428

UNCOV
2429
finish:
×
2430
        /* Restore cursor position */
UNCOV
2431
        if (saved_row > 0 && saved_column > 0)
×
2432
                RET_GATHER(r, terminal_set_cursor_position(output_fd, saved_row, saved_column));
×
2433

UNCOV
2434
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSADRAIN, &old_termios)));
×
2435
        return r;
2436
}
2437

2438
int terminal_fix_size(int input_fd, int output_fd) {
1✔
2439
        unsigned rows, columns;
1✔
2440
        int r;
1✔
2441

2442
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences */
2443

2444
        r = terminal_verify_same(input_fd, output_fd);
1✔
2445
        if (r < 0)
1✔
2446
                return r;
1✔
2447

UNCOV
2448
        struct winsize ws = {};
×
2449
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
×
2450
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
×
2451

UNCOV
2452
        r = terminal_get_size_by_dsr(input_fd, output_fd, &rows, &columns);
×
2453
        if (r < 0)
×
2454
                return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
×
2455

UNCOV
2456
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
2457
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2458
                return 0;
×
2459
        }
2460

UNCOV
2461
        ws.ws_col = columns;
×
2462
        ws.ws_row = rows;
×
2463

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

UNCOV
2467
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2468
        return 1;
2469
}
2470

2471
int terminal_is_pty_fd(int fd) {
3✔
2472
        int r;
3✔
2473

2474
        assert(fd >= 0);
3✔
2475

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

2478
        if (!isatty_safe(fd))
3✔
2479
                return false;
3✔
2480

2481
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2✔
2482
        if (r != 0)
2✔
2483
                return r;
2484

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

UNCOV
2488
        int v;
×
2489
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
×
2490
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
2491
                        return false;
2492

UNCOV
2493
                return -errno;
×
2494
        }
2495

2496
        return true;
2497
}
2498

2499
int pty_open_peer(int fd, int mode) {
20✔
2500
        assert(fd >= 0);
20✔
2501

2502
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2503
         *
2504
         * This is safe to be called on TTYs from other namespaces. */
2505

2506
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
20✔
2507

2508
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
UNCOV
2509
        for (unsigned c = 0;; c++) {
×
2510
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
20✔
2511
                if (peer_fd >= 0)
20✔
2512
                        return peer_fd;
2513

UNCOV
2514
                if (errno != EIO)
×
2515
                        return -errno;
×
2516

2517
                /* Max 1s in total */
UNCOV
2518
                if (c >= 20)
×
2519
                        return -EIO;
2520

UNCOV
2521
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2522
        }
2523
}
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