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

systemd / systemd / 14895667988

07 May 2025 08:57PM UTC coverage: 72.225% (-0.007%) from 72.232%
14895667988

push

github

yuwata
network: log_link_message_debug_errno() automatically append %m if necessary

Follow-up for d28746ef5.
Fixes CID#1609753.

0 of 1 new or added line in 1 file covered. (0.0%)

20297 existing lines in 338 files now uncovered.

297407 of 411780 relevant lines covered (72.22%)

695716.85 hits per line

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

44.37
/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
static volatile unsigned cached_columns = 0;
59
static volatile unsigned cached_lines = 0;
60

61
static volatile int cached_on_tty = -1;
62
static volatile int cached_on_dev_null = -1;
63
static volatile int cached_color_mode = _COLOR_MODE_INVALID;
64
static volatile int cached_underline_enabled = -1;
65

66
bool isatty_safe(int fd) {
5,454,170✔
67
        assert(fd >= 0);
5,454,170✔
68

69
        if (isatty(fd))
5,454,170✔
70
                return true;
71

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

78
        /* Be resilient if we're working on stdio, since they're set up by parent process. */
79
        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
5,405,258✔
80

81
        return false;
82
}
83

84
int chvt(int vt) {
×
UNCOV
85
        _cleanup_close_ int fd = -EBADF;
×
86

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

90
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
×
UNCOV
91
        if (fd < 0)
×
92
                return fd;
93

94
        if (vt <= 0) {
×
UNCOV
95
                int tiocl[2] = {
×
96
                        TIOCL_GETKMSGREDIRECT,
97
                        0
98
                };
99

100
                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
×
UNCOV
101
                        return -errno;
×
102

UNCOV
103
                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
×
104
        }
105

UNCOV
106
        return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
×
107
}
108

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

114
        assert(ret);
10✔
115

116
        if (!f)
10✔
UNCOV
117
                f = stdin;
×
118

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

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

131
                if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
×
UNCOV
132
                        char c;
×
133

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

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

148
                        if (need_nl)
×
UNCOV
149
                                *need_nl = c != '\n';
×
150

151
                        *ret = c;
×
UNCOV
152
                        return 0;
×
153
                }
154
        }
155

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

162
                if (fd_wait_for_event(fd, POLLIN, t) <= 0)
4✔
163
                        return -ETIMEDOUT;
164
        }
165

166
        /* If this is not a terminal, then read a full line instead */
167

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

174
        if (strlen(line) != 1)
8✔
175
                return -EBADMSG;
176

177
        if (need_nl)
1✔
178
                *need_nl = false;
1✔
179

180
        *ret = line[0];
1✔
181
        return 0;
1✔
182
}
183

184
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
185

186
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
×
UNCOV
187
        int r;
×
188

189
        assert(ret);
×
190
        assert(replies);
×
UNCOV
191
        assert(fmt);
×
192

193
        for (;;) {
×
194
                va_list ap;
×
195
                char c;
×
UNCOV
196
                bool need_nl = true;
×
197

UNCOV
198
                fputs(ansi_highlight(), stdout);
×
199

UNCOV
200
                putchar('\r');
×
201

202
                va_start(ap, fmt);
×
203
                vprintf(fmt, ap);
×
UNCOV
204
                va_end(ap);
×
205

UNCOV
206
                fputs(ansi_normal(), stdout);
×
207

UNCOV
208
                fflush(stdout);
×
209

210
                r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, /* echo= */ true, &need_nl);
×
UNCOV
211
                if (r < 0) {
×
212

213
                        if (r == -ETIMEDOUT)
×
UNCOV
214
                                continue;
×
215

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

221
                        putchar('\n');
×
UNCOV
222
                        return r;
×
223
                }
224

225
                if (need_nl)
×
UNCOV
226
                        putchar('\n');
×
227

228
                if (strchr(replies, c)) {
×
229
                        *ret = c;
×
UNCOV
230
                        return 0;
×
231
                }
232

UNCOV
233
                puts("Read unexpected character, please try again.");
×
234
        }
235
}
236

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

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

UNCOV
251
        string = strempty(string);
×
252

UNCOV
253
        STRV_FOREACH(c, completions) {
×
254

255
                /* Ignore entries that are not actually completions */
256
                if (!startswith(*c, string))
×
UNCOV
257
                        continue;
×
258

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

UNCOV
265
                        continue;
×
266
                }
267

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

274
                found[n] = 0;
×
UNCOV
275
                partial = true;
×
276
        }
277

UNCOV
278
        *ret = TAKE_PTR(found);
×
279

UNCOV
280
        if (!*ret)
×
281
                return COMPLETION_NONE;
UNCOV
282
        if (partial)
×
283
                return COMPLETION_PARTIAL;
284

UNCOV
285
        return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
×
286
}
287

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

294
int ask_string_full(
7✔
295
                char **ret,
296
                GetCompletionsCallback get_completions,
297
                void *userdata,
298
                const char *text, ...) {
299

300
        va_list ap;
7✔
301
        int r;
7✔
302

303
        assert(ret);
7✔
304
        assert(text);
7✔
305

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

314
        _cleanup_free_ char *string = NULL;
7✔
315
        size_t n = 0;
7✔
316

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

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

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

335
        for (;;) {
×
UNCOV
336
                int c = fgetc(stdin);
×
337

338
                /* On EOF or NUL, end the request, don't output anything anymore */
UNCOV
339
                if (IN_SET(c, EOF, 0))
×
340
                        break;
341

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

UNCOV
348
                if (c == '\t') {
×
349
                        /* Tab */
350

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

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

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

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

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

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

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

UNCOV
405
                } else if (IN_SET(c, '\b', 127)) {
×
406
                        /* Backspace */
407

408
                        if (n == 0)
×
UNCOV
409
                                fputc('\a', stdout); /* BEL */
×
410
                        else {
UNCOV
411
                                size_t m = utf8_last_length(string, n);
×
412

413
                                char *e = string + n - m;
×
UNCOV
414
                                clear_by_backspace(utf8_console_width(e));
×
415

416
                                *e = 0;
×
UNCOV
417
                                n -= m;
×
418
                        }
419

UNCOV
420
                } else if (c == 21) {
×
421
                        /* Ctrl-u → erase all input */
422

423
                        clear_by_backspace(utf8_console_width(string));
×
424
                        if (string)
×
UNCOV
425
                                string[n = 0] = 0;
×
426
                        else
UNCOV
427
                                assert(n == 0);
×
428

UNCOV
429
                } else if (c == 4) {
×
430
                        /* Ctrl-d → cancel this field input */
431

432
                        r = -ECANCELED;
×
UNCOV
433
                        goto fail;
×
434

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

441
                        if (!GREEDY_REALLOC(string, n+2)) {
×
442
                                r = -ENOMEM;
×
UNCOV
443
                                goto fail;
×
444
                        }
445

446
                        string[n++] = (char) c;
×
UNCOV
447
                        string[n] = 0;
×
448

UNCOV
449
                        fputc(c, stdout);
×
450
                }
451

UNCOV
452
                fflush(stdout);
×
453
        }
454

455
        if (tcsetattr(fd_input, TCSADRAIN, &old_termios) < 0)
×
UNCOV
456
                return -errno;
×
457

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

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

467
fail:
×
468
        (void) tcsetattr(fd_input, TCSADRAIN, &old_termios);
×
UNCOV
469
        return r;
×
470

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

479
        *ret = TAKE_PTR(string);
7✔
480
        return 0;
7✔
481
}
482

483
bool any_key_to_proceed(void) {
6✔
484

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

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

496
        char key = 0;
6✔
497
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
6✔
498

499
        fputc('\n', stdout);
6✔
500
        fflush(stdout);
6✔
501

502
        return key != 'q';
6✔
503
}
504

505
static size_t widest_list_element(char *const*l) {
×
UNCOV
506
        size_t w = 0;
×
507

508
        /* Returns the largest console width of all elements in 'l' */
509

510
        STRV_FOREACH(i, l)
×
UNCOV
511
                w = MAX(w, utf8_console_width(*i));
×
512

UNCOV
513
        return w;
×
514
}
515

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

UNCOV
523
        assert(n_columns > 0);
×
524

525
        if (n_columns == SIZE_MAX)
×
UNCOV
526
                n_columns = 3;
×
527

528
        if (column_width == SIZE_MAX) {
×
UNCOV
529
                size_t widest = widest_list_element(x);
×
530

531
                /* If not specified, derive column width from screen width */
UNCOV
532
                size_t column_max = (columns()-1) / n_columns;
×
533

534
                /* Subtract room for numbers */
535
                if (with_numbers && column_max > 6)
×
UNCOV
536
                        column_max -= 6;
×
537

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

543
                        if (with_numbers && column_max > 6)
×
UNCOV
544
                                column_max -= 6;
×
545
                }
546

UNCOV
547
                column_width = CLAMP(widest+1, 10U, column_max);
×
548
        }
549

550
        size_t n = strv_length(x);
×
UNCOV
551
        size_t per_column = DIV_ROUND_UP(n, n_columns);
×
552

553
        size_t break_lines = lines();
×
554
        if (break_lines > 2)
×
UNCOV
555
                break_lines--;
×
556

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

UNCOV
563
        for (size_t i = 0; i < per_column; i++) {
×
564

565
                for (size_t j = 0; j < n_columns; j++) {
×
UNCOV
566
                        _cleanup_free_ char *e = NULL;
×
567

UNCOV
568
                        if (j * per_column + i >= n)
×
569
                                break;
570

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

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

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

UNCOV
593
                putchar('\n');
×
594

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

601
        return 0;
602
}
603

604
int open_terminal(const char *name, int mode) {
54,788✔
605
        _cleanup_close_ int fd = -EBADF;
54,788✔
606

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

615
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
54,788✔
616

UNCOV
617
        for (unsigned c = 0;; c++) {
×
618
                fd = open(name, mode, 0);
54,788✔
619
                if (fd >= 0)
54,788✔
620
                        break;
621

622
                if (errno != EIO)
7,663✔
623
                        return -errno;
7,663✔
624

625
                /* Max 1s in total */
UNCOV
626
                if (c >= 20)
×
627
                        return -EIO;
628

UNCOV
629
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
630
        }
631

632
        if (!isatty_safe(fd))
47,125✔
UNCOV
633
                return -ENOTTY;
×
634

635
        return TAKE_FD(fd);
636
}
637

638
int acquire_terminal(
343✔
639
                const char *name,
640
                AcquireTerminalFlags flags,
641
                usec_t timeout) {
642

643
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
343✔
644
        usec_t ts = USEC_INFINITY;
343✔
645
        int r, wd = -1;
343✔
646

647
        assert(name);
343✔
648

649
        AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
343✔
650
        assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
343✔
651
        assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
343✔
652

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

662
        if (mode == ACQUIRE_TERMINAL_WAIT) {
663
                notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
343✔
664
                if (notify < 0)
343✔
UNCOV
665
                        return -errno;
×
666

667
                wd = inotify_add_watch(notify, name, IN_CLOSE);
343✔
668
                if (wd < 0)
343✔
UNCOV
669
                        return -errno;
×
670

671
                if (timeout != USEC_INFINITY)
343✔
UNCOV
672
                        ts = now(CLOCK_MONOTONIC);
×
673
        }
674

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

683
        for (;;) {
343✔
684
                if (notify >= 0) {
343✔
685
                        r = flush_fd(notify);
343✔
686
                        if (r < 0)
343✔
UNCOV
687
                                return r;
×
688
                }
689

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

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

700
                /* First, try to get the tty */
701
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
343✔
702

703
                /* Reset signal handler to old value */
704
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
343✔
705

706
                /* Success? Exit the loop now! */
707
                if (r >= 0)
343✔
708
                        break;
709

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

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

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

722
                assert(notify >= 0);
×
UNCOV
723
                assert(wd >= 0);
×
724

725
                for (;;) {
×
726
                        usec_t left;
×
UNCOV
727
                        if (timeout == USEC_INFINITY)
×
728
                                left = USEC_INFINITY;
729
                        else {
UNCOV
730
                                assert(ts != USEC_INFINITY);
×
731

732
                                usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
733
                                if (n >= timeout)
×
UNCOV
734
                                        return -ETIMEDOUT;
×
735

UNCOV
736
                                left = timeout - n;
×
737
                        }
738

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

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

UNCOV
759
                                return -errno;
×
760
                        }
761

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

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

UNCOV
770
                        break;
×
771
                }
772

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

778
        return TAKE_FD(fd);
343✔
779
}
780

781
int release_terminal(void) {
64✔
782
        _cleanup_close_ int fd = -EBADF;
64✔
783
        int r;
64✔
784

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

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

794
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
20✔
795

796
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
20✔
797

798
        return r;
799
}
800

801
int terminal_new_session(void) {
5✔
802

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

810
        if (!isatty_safe(STDIN_FILENO))
5✔
811
                return -ENXIO;
812

813
        (void) setsid();
4✔
814
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
4✔
815
}
816

817
int terminal_vhangup_fd(int fd) {
157✔
818
        assert(fd >= 0);
157✔
819
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
157✔
820
}
821

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

UNCOV
825
        assert(tty);
×
826

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

UNCOV
831
        return terminal_vhangup_fd(fd);
×
832
}
833

834
int vt_disallocate(const char *tty_path) {
85✔
835
        assert(tty_path);
85✔
836

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

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

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

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

856
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
170✔
857
        if (fd2 < 0)
85✔
858
                return fd2;
859

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

869
static int vt_default_utf8(void) {
686✔
870
        _cleanup_free_ char *b = NULL;
686✔
871
        int r;
686✔
872

873
        /* Read the default VT UTF8 setting from the kernel */
874

875
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
686✔
876
        if (r < 0)
686✔
877
                return r;
878

879
        return parse_boolean(b);
384✔
880
}
881

882
static int vt_reset_keyboard(int fd) {
343✔
883
        int r, kb;
343✔
884

885
        assert(fd >= 0);
343✔
886

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

892
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
343✔
893
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
343✔
894
}
895

896
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
343✔
897
        struct termios termios;
343✔
898
        int r;
343✔
899

900
        /* Set terminal to some sane defaults */
901

902
        assert(fd >= 0);
343✔
903

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

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

911
        /* Switch to text mode */
912
        if (switch_to_text)
343✔
913
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
162✔
914
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
77✔
915

916
        /* Set default keyboard mode */
917
        r = vt_reset_keyboard(fd);
343✔
918
        if (r < 0)
343✔
919
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
176✔
920

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

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

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

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

950
        termios.c_cc[VTIME]  = 0;
341✔
951
        termios.c_cc[VMIN]   = 1;
341✔
952

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

UNCOV
957
finish:
×
958
        /* Just in case, flush all crap out */
959
        (void) tcflush(fd, TCIOFLUSH);
343✔
960

961
        return r;
343✔
962
}
963

964
static int terminal_reset_ansi_seq(int fd) {
337✔
965
        int r, k;
337✔
966

967
        assert(fd >= 0);
337✔
968

969
        if (getenv_terminal_is_dumb())
337✔
970
                return 0;
971

972
        r = fd_nonblock(fd, true);
×
973
        if (r < 0)
×
UNCOV
974
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
975

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

987
        if (r > 0) {
×
988
                r = fd_nonblock(fd, false);
×
989
                if (r < 0)
×
UNCOV
990
                        log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
×
991
        }
992

UNCOV
993
        return k < 0 ? k : r;
×
994
}
995

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

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

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

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

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

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

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

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

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

1039
        return TAKE_FD(fd);
1040
}
1041

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

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

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

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

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

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

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

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

1072
        tty = skip_dev_prefix(tty);
315✔
1073

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

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

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

1085
        assert(tty);
197✔
1086

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

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

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

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

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

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

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

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

1116
        assert(ret);
302✔
1117

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

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

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

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

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

1150
        if (streq(tty, "tty0")) {
153✔
UNCOV
1151
                active = mfree(active);
×
1152

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

UNCOV
1158
                tty = active;
×
1159
        }
1160

1161
        _cleanup_free_ char *path = NULL;
153✔
1162
        path = path_join("/dev", tty);
153✔
1163
        if (!path)
153✔
1164
                return -ENOMEM;
1165

1166
        *ret = TAKE_PTR(path);
153✔
1167
        return 0;
153✔
1168
}
1169

1170
int get_kernel_consoles(char ***ret) {
1✔
UNCOV
1171
        _cleanup_strv_free_ char **l = NULL;
×
1172
        _cleanup_free_ char *line = NULL;
1✔
1173
        int r;
1✔
1174

1175
        assert(ret);
1✔
1176

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

1182
        r = read_one_line_file("/sys/class/tty/console/active", &line);
×
UNCOV
1183
        if (r < 0)
×
1184
                return r;
1185

1186
        for (const char *p = line;;) {
×
UNCOV
1187
                _cleanup_free_ char *tty = NULL, *path = NULL;
×
1188

1189
                r = extract_first_word(&p, &tty, NULL, 0);
×
UNCOV
1190
                if (r < 0)
×
1191
                        return r;
UNCOV
1192
                if (r == 0)
×
1193
                        break;
1194

1195
                if (streq(tty, "tty0")) {
×
1196
                        tty = mfree(tty);
×
1197
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
UNCOV
1198
                        if (r < 0)
×
1199
                                return r;
1200
                }
1201

1202
                path = path_join("/dev", tty);
×
UNCOV
1203
                if (!path)
×
1204
                        return -ENOMEM;
1205

1206
                if (access(path, F_OK) < 0) {
×
1207
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
×
UNCOV
1208
                        continue;
×
1209
                }
1210

1211
                r = strv_consume(&l, TAKE_PTR(path));
×
UNCOV
1212
                if (r < 0)
×
1213
                        return r;
1214
        }
1215

1216
        if (strv_isempty(l)) {
×
1217
                log_debug("No devices found for system console");
×
UNCOV
1218
                goto fallback;
×
1219
        }
1220

1221
        *ret = TAKE_PTR(l);
×
UNCOV
1222
        return strv_length(*ret);
×
1223

1224
fallback:
1✔
1225
        r = strv_extend(&l, "/dev/console");
1✔
1226
        if (r < 0)
1✔
1227
                return r;
1228

1229
        *ret = TAKE_PTR(l);
1✔
1230
        return 0;
1✔
1231
}
1232

1233
bool tty_is_vc_resolve(const char *tty) {
52✔
1234
        _cleanup_free_ char *resolved = NULL;
52✔
1235

1236
        assert(tty);
52✔
1237

1238
        if (streq(skip_dev_prefix(tty), "console")) {
52✔
1239
                if (resolve_dev_console(&resolved) < 0)
2✔
1240
                        return false;
1241

1242
                tty = resolved;
2✔
1243
        }
1244

1245
        return tty_is_vc(tty);
52✔
1246
}
1247

1248
const char* default_term_for_tty(const char *tty) {
68✔
1249
        return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
68✔
1250
}
1251

1252
int fd_columns(int fd) {
1,224✔
1253
        struct winsize ws = {};
1,224✔
1254

1255
        if (fd < 0)
1,224✔
1256
                return -EBADF;
1257

1258
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1,224✔
1259
                return -errno;
1,224✔
1260

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

UNCOV
1264
        return ws.ws_col;
×
1265
}
1266

1267
int getenv_columns(void) {
1,399✔
1268
        int r;
1,399✔
1269

1270
        const char *e = getenv("COLUMNS");
1,399✔
1271
        if (!e)
1,399✔
1272
                return -ENXIO;
1,399✔
1273

1274
        unsigned c;
1✔
1275
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
1✔
1276
        if (r < 0)
1✔
1277
                return r;
1278

1279
        return (int) c;
1✔
1280
}
1281

1282
unsigned columns(void) {
198,110✔
1283

1284
        if (cached_columns > 0)
198,110✔
1285
                return cached_columns;
196,885✔
1286

1287
        int c = getenv_columns();
1,225✔
1288
        if (c < 0) {
1,225✔
1289
                c = fd_columns(STDOUT_FILENO);
1,224✔
1290
                if (c < 0)
1,224✔
1291
                        c = 80;
1292
        }
1293

1294
        assert(c > 0);
1✔
1295

1296
        cached_columns = c;
1,225✔
1297
        return cached_columns;
1,225✔
1298
}
1299

1300
int fd_lines(int fd) {
155✔
1301
        struct winsize ws = {};
155✔
1302

1303
        if (fd < 0)
155✔
1304
                return -EBADF;
1305

1306
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
155✔
1307
                return -errno;
155✔
1308

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

UNCOV
1312
        return ws.ws_row;
×
1313
}
1314

1315
unsigned lines(void) {
155✔
1316
        const char *e;
155✔
1317
        int l;
155✔
1318

1319
        if (cached_lines > 0)
155✔
UNCOV
1320
                return cached_lines;
×
1321

1322
        l = 0;
155✔
1323
        e = getenv("LINES");
155✔
1324
        if (e)
155✔
UNCOV
1325
                (void) safe_atoi(e, &l);
×
1326

1327
        if (l <= 0 || l > USHRT_MAX) {
155✔
1328
                l = fd_lines(STDOUT_FILENO);
155✔
1329
                if (l <= 0)
155✔
1330
                        l = 24;
155✔
1331
        }
1332

1333
        cached_lines = l;
155✔
1334
        return cached_lines;
155✔
1335
}
1336

1337
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
1,091✔
1338
        struct winsize ws;
1,091✔
1339

1340
        assert(fd >= 0);
1,091✔
1341

1342
        if (!ident)
1,091✔
1343
                ident = "TTY";
65✔
1344

1345
        if (rows == UINT_MAX && cols == UINT_MAX)
1,091✔
1346
                return 0;
1,091✔
1347

1348
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
892✔
UNCOV
1349
                return log_debug_errno(errno,
×
1350
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1351
                                       ident);
1352

1353
        if (rows == UINT_MAX)
892✔
UNCOV
1354
                rows = ws.ws_row;
×
1355
        else if (rows > USHRT_MAX)
892✔
UNCOV
1356
                rows = USHRT_MAX;
×
1357

1358
        if (cols == UINT_MAX)
892✔
UNCOV
1359
                cols = ws.ws_col;
×
1360
        else if (cols > USHRT_MAX)
892✔
UNCOV
1361
                cols = USHRT_MAX;
×
1362

1363
        if (rows == ws.ws_row && cols == ws.ws_col)
892✔
1364
                return 0;
1365

1366
        ws.ws_row = rows;
366✔
1367
        ws.ws_col = cols;
366✔
1368

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

1372
        return 0;
1373
}
1374

1375
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
1,059✔
1376
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
1,059✔
1377
        unsigned rows = UINT_MAX, cols = UINT_MAX;
1,059✔
1378
        int r;
1,059✔
1379

1380
        assert(tty);
1,059✔
1381

1382
        if (!ret_rows && !ret_cols)
1,059✔
1383
                return 0;
1384

1385
        tty = skip_dev_prefix(tty);
1,059✔
1386
        if (path_startswith(tty, "pts/"))
1,059✔
1387
                return -EMEDIUMTYPE;
1388
        if (!in_charset(tty, ALPHANUMERICAL))
1,059✔
UNCOV
1389
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
×
1390
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1391

1392
        rowskey = strjoin("systemd.tty.rows.", tty);
1,059✔
1393
        if (!rowskey)
1,059✔
1394
                return -ENOMEM;
1395

1396
        colskey = strjoin("systemd.tty.columns.", tty);
1,059✔
1397
        if (!colskey)
1,059✔
1398
                return -ENOMEM;
1399

1400
        r = proc_cmdline_get_key_many(/* flags = */ 0,
1,059✔
1401
                                      rowskey, &rowsvalue,
1402
                                      colskey, &colsvalue);
1403
        if (r < 0)
1,059✔
UNCOV
1404
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
×
1405

1406
        if (rowsvalue) {
1,059✔
1407
                r = safe_atou(rowsvalue, &rows);
892✔
1408
                if (r < 0)
892✔
UNCOV
1409
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
×
1410
        }
1411

1412
        if (colsvalue) {
1,059✔
1413
                r = safe_atou(colsvalue, &cols);
892✔
1414
                if (r < 0)
892✔
UNCOV
1415
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
×
1416
        }
1417

1418
        if (ret_rows)
1,059✔
1419
                *ret_rows = rows;
1,059✔
1420
        if (ret_cols)
1,059✔
1421
                *ret_cols = cols;
1,059✔
1422

1423
        return rows != UINT_MAX || cols != UINT_MAX;
1,059✔
1424
}
1425

1426
/* intended to be used as a SIGWINCH sighandler */
1427
void columns_lines_cache_reset(int signum) {
×
1428
        cached_columns = 0;
×
1429
        cached_lines = 0;
×
UNCOV
1430
}
×
1431

1432
void reset_terminal_feature_caches(void) {
14✔
1433
        cached_columns = 0;
14✔
1434
        cached_lines = 0;
14✔
1435

1436
        cached_color_mode = _COLOR_MODE_INVALID;
14✔
1437
        cached_underline_enabled = -1;
14✔
1438
        cached_on_tty = -1;
14✔
1439
        cached_on_dev_null = -1;
14✔
1440
}
14✔
1441

1442
bool on_tty(void) {
7,336,010✔
1443

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

1450
        if (cached_on_tty < 0)
7,336,010✔
1451
                cached_on_tty =
45,585✔
1452
                        isatty_safe(STDOUT_FILENO) &&
45,600✔
1453
                        isatty_safe(STDERR_FILENO);
15✔
1454

1455
        return cached_on_tty;
7,336,010✔
1456
}
1457

1458
int getttyname_malloc(int fd, char **ret) {
408✔
1459
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
408✔
1460
        int r;
408✔
1461

1462
        assert(fd >= 0);
408✔
1463
        assert(ret);
408✔
1464

1465
        r = ttyname_r(fd, path, sizeof path); /* positive error */
408✔
1466
        assert(r >= 0);
408✔
1467
        if (r == ERANGE)
408✔
1468
                return -ENAMETOOLONG;
408✔
1469
        if (r > 0)
408✔
1470
                return -r;
401✔
1471

1472
        return strdup_to(ret, skip_dev_prefix(path));
7✔
1473
}
1474

1475
int getttyname_harder(int fd, char **ret) {
22✔
1476
        _cleanup_free_ char *s = NULL;
22✔
1477
        int r;
22✔
1478

1479
        r = getttyname_malloc(fd, &s);
22✔
1480
        if (r < 0)
22✔
1481
                return r;
1482

1483
        if (streq(s, "tty"))
×
UNCOV
1484
                return get_ctty(0, NULL, ret);
×
1485

1486
        *ret = TAKE_PTR(s);
×
UNCOV
1487
        return 0;
×
1488
}
1489

1490
int get_ctty_devnr(pid_t pid, dev_t *ret) {
3,115✔
1491
        _cleanup_free_ char *line = NULL;
3,115✔
1492
        unsigned long ttynr;
3,115✔
1493
        const char *p;
3,115✔
1494
        int r;
3,115✔
1495

1496
        assert(pid >= 0);
3,115✔
1497

1498
        p = procfs_file_alloca(pid, "stat");
15,279✔
1499
        r = read_one_line_file(p, &line);
3,115✔
1500
        if (r < 0)
3,115✔
1501
                return r;
1502

1503
        p = strrchr(line, ')');
3,115✔
1504
        if (!p)
3,115✔
1505
                return -EIO;
1506

1507
        p++;
3,115✔
1508

1509
        if (sscanf(p, " "
3,115✔
1510
                   "%*c "  /* state */
1511
                   "%*d "  /* ppid */
1512
                   "%*d "  /* pgrp */
1513
                   "%*d "  /* session */
1514
                   "%lu ", /* ttynr */
1515
                   &ttynr) != 1)
1516
                return -EIO;
1517

1518
        if (devnum_is_zero(ttynr))
3,115✔
1519
                return -ENXIO;
1520

1521
        if (ret)
4✔
1522
                *ret = (dev_t) ttynr;
2✔
1523

1524
        return 0;
1525
}
1526

1527
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
30✔
1528
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
30✔
1529
        _cleanup_free_ char *buf = NULL;
30✔
1530
        const char *fn = NULL, *w;
30✔
1531
        dev_t devnr;
30✔
1532
        int r;
30✔
1533

1534
        r = get_ctty_devnr(pid, &devnr);
30✔
1535
        if (r < 0)
30✔
1536
                return r;
1537

1538
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
2✔
1539
        if (r < 0) {
2✔
1540
                struct stat st;
2✔
1541

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

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

1553
                if (stat(pty, &st) < 0) {
2✔
1554
                        if (errno != ENOENT)
×
UNCOV
1555
                                return -errno;
×
1556

1557
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
2✔
1558
                        fn = pty;
1559

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

UNCOV
1567
                        fn = buf;
×
1568
                }
1569
        } else
UNCOV
1570
                fn = buf;
×
1571

1572
        w = path_startswith(fn, "/dev/");
2✔
1573
        if (!w)
2✔
1574
                return -EINVAL;
1575

1576
        if (ret) {
2✔
1577
                r = strdup_to(ret, w);
2✔
1578
                if (r < 0)
2✔
1579
                        return r;
1580
        }
1581

1582
        if (ret_devnr)
2✔
UNCOV
1583
                *ret_devnr = devnr;
×
1584

1585
        return 0;
1586
}
1587

1588
int ptsname_malloc(int fd, char **ret) {
116✔
1589
        size_t l = 100;
116✔
1590

1591
        assert(fd >= 0);
116✔
1592
        assert(ret);
116✔
1593

1594
        for (;;) {
116✔
1595
                char *c;
116✔
1596

1597
                c = new(char, l);
116✔
1598
                if (!c)
116✔
1599
                        return -ENOMEM;
1600

1601
                if (ptsname_r(fd, c, l) == 0) {
116✔
1602
                        *ret = c;
116✔
1603
                        return 0;
116✔
1604
                }
1605
                if (errno != ERANGE) {
×
1606
                        free(c);
×
UNCOV
1607
                        return -errno;
×
1608
                }
1609

UNCOV
1610
                free(c);
×
1611

UNCOV
1612
                if (l > SIZE_MAX / 2)
×
1613
                        return -ENOMEM;
1614

UNCOV
1615
                l *= 2;
×
1616
        }
1617
}
1618

1619
int openpt_allocate(int flags, char **ret_peer_path) {
120✔
1620
        _cleanup_close_ int fd = -EBADF;
120✔
1621
        int r;
120✔
1622

1623
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
120✔
1624
        if (fd < 0)
120✔
UNCOV
1625
                return -errno;
×
1626

1627
        _cleanup_free_ char *p = NULL;
120✔
1628
        if (ret_peer_path) {
120✔
1629
                r = ptsname_malloc(fd, &p);
116✔
1630
                if (r < 0)
116✔
1631
                        return r;
1632

1633
                if (!path_startswith(p, "/dev/pts/"))
116✔
1634
                        return -EINVAL;
1635
        }
1636

1637
        if (unlockpt(fd) < 0)
120✔
UNCOV
1638
                return -errno;
×
1639

1640
        if (ret_peer_path)
120✔
1641
                *ret_peer_path = TAKE_PTR(p);
116✔
1642

1643
        return TAKE_FD(fd);
1644
}
1645

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

1649
        assert(pty >= 0);
×
UNCOV
1650
        assert(ret);
×
1651

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

1655
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
UNCOV
1656
                return -errno;
×
1657

UNCOV
1658
        if (no < 0)
×
1659
                return -EIO;
1660

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

1664
        return 0;
1665
}
1666

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

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

1676
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
×
UNCOV
1677
        if (r < 0)
×
1678
                return r;
1679

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

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

1700
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1701
                if (fd < 0)
×
UNCOV
1702
                        _exit(EXIT_FAILURE);
×
1703

1704
                if (send_one_fd(pair[1], fd, 0) < 0)
×
UNCOV
1705
                        _exit(EXIT_FAILURE);
×
1706

UNCOV
1707
                _exit(EXIT_SUCCESS);
×
1708
        }
1709

UNCOV
1710
        pair[1] = safe_close(pair[1]);
×
1711

1712
        fd = receive_one_fd(pair[0], 0);
×
UNCOV
1713
        if (fd < 0)
×
1714
                return fd;
1715

1716
        if (ret_peer_path) {
×
1717
                r = ptsname_namespace(fd, ret_peer_path);
×
1718
                if (r < 0)
×
UNCOV
1719
                        return r;
×
1720
        }
1721

1722
        return TAKE_FD(fd);
1723
}
1724

1725
static bool on_dev_null(void) {
55,411✔
1726
        struct stat dst, ost, est;
55,411✔
1727

1728
        if (cached_on_dev_null >= 0)
55,411✔
1729
                return cached_on_dev_null;
9,895✔
1730

1731
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
45,516✔
1732
                cached_on_dev_null = false;
1✔
1733
        else
1734
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
49,343✔
1735

1736
        return cached_on_dev_null;
45,516✔
1737
}
1738

1739
bool getenv_terminal_is_dumb(void) {
12,889✔
1740
        const char *e;
12,889✔
1741

1742
        e = getenv("TERM");
12,889✔
1743
        if (!e)
12,889✔
1744
                return true;
1745

1746
        return streq(e, "dumb");
11,820✔
1747
}
1748

1749
bool terminal_is_dumb(void) {
55,418✔
1750
        if (!on_tty() && !on_dev_null())
55,418✔
1751
                return true;
1752

1753
        return getenv_terminal_is_dumb();
198✔
1754
}
1755

1756
static const char* const color_mode_table[_COLOR_MODE_MAX] = {
1757
        [COLOR_OFF]   = "off",
1758
        [COLOR_16]    = "16",
1759
        [COLOR_256]   = "256",
1760
        [COLOR_24BIT] = "24bit",
1761
};
1762

1763
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_24BIT);
27✔
1764

1765
static ColorMode parse_systemd_colors(void) {
13,792✔
1766
        const char *e;
13,792✔
1767

1768
        e = getenv("SYSTEMD_COLORS");
13,792✔
1769
        if (!e)
13,792✔
1770
                return _COLOR_MODE_INVALID;
1771

1772
        ColorMode m = color_mode_from_string(e);
13✔
1773
        if (m < 0)
13✔
1774
                return log_debug_errno(m, "Failed to parse $SYSTEMD_COLORS value '%s', ignoring: %m", e);
2✔
1775

1776
        return m;
1777
}
1778

1779
static ColorMode get_color_mode_impl(void) {
13,792✔
1780
        /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1781
         * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors, and COLOR_24BIT for
1782
         * unrestricted color output. */
1783

1784
        /* First, we check $SYSTEMD_COLORS, which is the explicit way to change the mode. */
1785
        ColorMode m = parse_systemd_colors();
13,792✔
1786
        if (m >= 0)
13,792✔
1787
                return m;
1788

1789
        /* Next, check for the presence of $NO_COLOR; value is ignored. */
1790
        if (getenv("NO_COLOR"))
13,781✔
1791
                return COLOR_OFF;
1792

1793
        /* If the above didn't work, we turn colors off unless we are on a TTY. And if we are on a TTY we
1794
         * turn it off if $TERM is set to "dumb". There's one special tweak though: if we are PID 1 then we
1795
         * do not check whether we are connected to a TTY, because we don't keep /dev/console open
1796
         * continuously due to fear of SAK, and hence things are a bit weird. */
1797
        if (getpid_cached() == 1 ? getenv_terminal_is_dumb() : terminal_is_dumb())
13,779✔
1798
                return COLOR_OFF;
1799

1800
        /* We failed to figure out any reason to *disable* colors. Let's see how many colors we shall use. */
UNCOV
1801
        if (STRPTR_IN_SET(getenv("COLORTERM"),
×
1802
                          "truecolor",
1803
                          "24bit"))
UNCOV
1804
                return COLOR_24BIT;
×
1805

1806
        /* Note that the Linux console can only display 16 colors. We still enable 256 color mode
1807
         * even for PID1 output though (which typically goes to the Linux console), since the Linux
1808
         * console is able to parse the 256 color sequences and automatically map them to the closest
1809
         * color in the 16 color palette (since kernel 3.16). Doing 256 colors is nice for people who
1810
         * invoke systemd in a container or via a serial link or such, and use a true 256 color
1811
         * terminal to do so. */
1812
        return COLOR_256;
1813
}
1814

1815
ColorMode get_color_mode(void) {
1,165,084✔
1816
        if (cached_color_mode < 0)
1,165,084✔
1817
                cached_color_mode = get_color_mode_impl();
13,792✔
1818

1819
        return cached_color_mode;
1,165,084✔
1820
}
1821

1822
bool dev_console_colors_enabled(void) {
×
1823
        _cleanup_free_ char *s = NULL;
×
UNCOV
1824
        ColorMode m;
×
1825

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

1833
        m = parse_systemd_colors();
×
1834
        if (m >= 0)
×
UNCOV
1835
                return m;
×
1836

UNCOV
1837
        if (getenv("NO_COLOR"))
×
1838
                return false;
1839

1840
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
UNCOV
1841
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1842

UNCOV
1843
        return !streq_ptr(s, "dumb");
×
1844
}
1845

1846
bool underline_enabled(void) {
444,650✔
1847

1848
        if (cached_underline_enabled < 0) {
444,650✔
1849

1850
                /* The Linux console doesn't support underlining, turn it off, but only there. */
1851

1852
                if (colors_enabled())
2,705✔
1853
                        cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1✔
1854
                else
1855
                        cached_underline_enabled = false;
2,704✔
1856
        }
1857

1858
        return cached_underline_enabled;
444,650✔
1859
}
1860

UNCOV
1861
int vt_restore(int fd) {
×
1862

UNCOV
1863
        static const struct vt_mode mode = {
×
1864
                .mode = VT_AUTO,
1865
        };
1866

UNCOV
1867
        int r, ret = 0;
×
1868

UNCOV
1869
        assert(fd >= 0);
×
1870

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

1874
        if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
×
UNCOV
1875
                RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT to text mode, ignoring: %m"));
×
1876

1877
        r = vt_reset_keyboard(fd);
×
1878
        if (r < 0)
×
UNCOV
1879
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1880

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

1884
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1885
        if (r < 0)
×
UNCOV
1886
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1887

1888
        return ret;
1889
}
1890

1891
int vt_release(int fd, bool restore) {
×
UNCOV
1892
        assert(fd >= 0);
×
1893

1894
        /* This function releases the VT by acknowledging the VT-switch signal
1895
         * sent by the kernel and optionally reset the VT in text and auto
1896
         * VT-switching modes. */
1897

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

1901
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
UNCOV
1902
                return -errno;
×
1903

1904
        if (restore)
×
UNCOV
1905
                return vt_restore(fd);
×
1906

1907
        return 0;
1908
}
1909

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

1914
        if (priority <= LOG_ERR) {
176,716✔
1915
                if (on)
6,354✔
1916
                        *on = ansi_highlight_red();
12,708✔
1917
                if (off)
6,354✔
1918
                        *off = ansi_normal();
12,708✔
1919
                if (highlight)
6,354✔
UNCOV
1920
                        *highlight = ansi_highlight();
×
1921

1922
        } else if (priority <= LOG_WARNING) {
170,362✔
1923
                if (on)
957✔
1924
                        *on = ansi_highlight_yellow();
957✔
1925
                if (off)
957✔
1926
                        *off = ansi_normal();
1,914✔
1927
                if (highlight)
957✔
UNCOV
1928
                        *highlight = ansi_highlight();
×
1929

1930
        } else if (priority <= LOG_NOTICE) {
169,405✔
1931
                if (on)
869✔
1932
                        *on = ansi_highlight();
1,738✔
1933
                if (off)
869✔
1934
                        *off = ansi_normal();
1,738✔
1935
                if (highlight)
869✔
UNCOV
1936
                        *highlight = ansi_highlight_red();
×
1937

1938
        } else if (priority >= LOG_DEBUG) {
168,536✔
1939
                if (on)
127,111✔
1940
                        *on = ansi_grey();
127,111✔
1941
                if (off)
127,111✔
1942
                        *off = ansi_normal();
254,222✔
1943
                if (highlight)
127,111✔
UNCOV
1944
                        *highlight = ansi_highlight_red();
×
1945
        }
1946
}
176,716✔
1947

1948
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
UNCOV
1949
        assert(fd >= 0);
×
1950

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

UNCOV
1954
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1955
}
1956

1957
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
317✔
1958
        int r = 0;
317✔
1959

1960
        assert(fd >= 0);
317✔
1961
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
317✔
1962

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

1966
        if (!isatty_safe(fd))
317✔
1967
                return -ENOTTY;
317✔
1968

1969
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
310✔
1970

1971
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
310✔
1972
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
304✔
1973
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
304✔
1974

1975
        return r;
1976
}
1977

1978
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
6✔
1979
        assert(fd >= 0);
6✔
1980

1981
        _cleanup_close_ int lock_fd = lock_dev_console();
6✔
1982
        if (lock_fd < 0)
6✔
UNCOV
1983
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
1984

1985
        return terminal_reset_defensive(fd, flags);
6✔
1986
}
1987

1988
void termios_disable_echo(struct termios *termios) {
×
UNCOV
1989
        assert(termios);
×
1990

1991
        termios->c_lflag &= ~(ICANON|ECHO);
×
1992
        termios->c_cc[VMIN] = 1;
×
1993
        termios->c_cc[VTIME] = 0;
×
UNCOV
1994
}
×
1995

1996
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1997
        assert(input_fd >= 0);
1✔
1998
        assert(output_fd >= 0);
1✔
1999

2000
        /* Validates that the specified fds reference the same TTY */
2001

2002
        if (input_fd != output_fd) {
1✔
2003
                struct stat sti;
1✔
2004
                if (fstat(input_fd, &sti) < 0)
1✔
2005
                        return -errno;
1✔
2006

2007
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
2008
                        return -ENOTTY;
2009

2010
                struct stat sto;
1✔
2011
                if (fstat(output_fd, &sto) < 0)
1✔
UNCOV
2012
                        return -errno;
×
2013

2014
                if (!S_ISCHR(sto.st_mode))
1✔
2015
                        return -ENOTTY;
2016

UNCOV
2017
                if (sti.st_rdev != sto.st_rdev)
×
2018
                        return -ENOLINK;
2019
        }
2020

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

2024
        return 0;
2025
}
2026

2027
typedef enum BackgroundColorState {
2028
        BACKGROUND_TEXT,
2029
        BACKGROUND_ESCAPE,
2030
        BACKGROUND_BRACKET,
2031
        BACKGROUND_FIRST_ONE,
2032
        BACKGROUND_SECOND_ONE,
2033
        BACKGROUND_SEMICOLON,
2034
        BACKGROUND_R,
2035
        BACKGROUND_G,
2036
        BACKGROUND_B,
2037
        BACKGROUND_RED,
2038
        BACKGROUND_GREEN,
2039
        BACKGROUND_BLUE,
2040
        BACKGROUND_STRING_TERMINATOR,
2041
} BackgroundColorState;
2042

2043
typedef struct BackgroundColorContext {
2044
        BackgroundColorState state;
2045
        uint32_t red, green, blue;
2046
        unsigned red_bits, green_bits, blue_bits;
2047
} BackgroundColorContext;
2048

UNCOV
2049
static int scan_background_color_response(
×
2050
                BackgroundColorContext *context,
2051
                const char *buf,
2052
                size_t size,
2053
                size_t *ret_processed) {
2054

2055
        assert(context);
×
UNCOV
2056
        assert(buf || size == 0);
×
2057

2058
        for (size_t i = 0; i < size; i++) {
×
UNCOV
2059
                char c = buf[i];
×
2060

UNCOV
2061
                switch (context->state) {
×
2062

2063
                case BACKGROUND_TEXT:
×
2064
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
UNCOV
2065
                        break;
×
2066

2067
                case BACKGROUND_ESCAPE:
×
2068
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
UNCOV
2069
                        break;
×
2070

2071
                case BACKGROUND_BRACKET:
×
2072
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
UNCOV
2073
                        break;
×
2074

2075
                case BACKGROUND_FIRST_ONE:
×
2076
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
UNCOV
2077
                        break;
×
2078

2079
                case BACKGROUND_SECOND_ONE:
×
2080
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
UNCOV
2081
                        break;
×
2082

2083
                case BACKGROUND_SEMICOLON:
×
2084
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
UNCOV
2085
                        break;
×
2086

2087
                case BACKGROUND_R:
×
2088
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
UNCOV
2089
                        break;
×
2090

2091
                case BACKGROUND_G:
×
2092
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
UNCOV
2093
                        break;
×
2094

2095
                case BACKGROUND_B:
×
2096
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
UNCOV
2097
                        break;
×
2098

2099
                case BACKGROUND_RED:
×
2100
                        if (c == '/')
×
UNCOV
2101
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2102
                        else {
2103
                                int d = unhexchar(c);
×
2104
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
UNCOV
2105
                                        context->state = BACKGROUND_TEXT;
×
2106
                                else {
2107
                                        context->red = (context->red << 4) | d;
×
UNCOV
2108
                                        context->red_bits += 4;
×
2109
                                }
2110
                        }
2111
                        break;
2112

2113
                case BACKGROUND_GREEN:
×
2114
                        if (c == '/')
×
UNCOV
2115
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2116
                        else {
2117
                                int d = unhexchar(c);
×
2118
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
UNCOV
2119
                                        context->state = BACKGROUND_TEXT;
×
2120
                                else {
2121
                                        context->green = (context->green << 4) | d;
×
UNCOV
2122
                                        context->green_bits += 4;
×
2123
                                }
2124
                        }
2125
                        break;
2126

2127
                case BACKGROUND_BLUE:
×
2128
                        if (c == '\x07') {
×
2129
                                if (context->blue_bits > 0) {
×
2130
                                        if (ret_processed)
×
UNCOV
2131
                                                *ret_processed = i + 1;
×
2132

UNCOV
2133
                                        return 1; /* success! */
×
2134
                                }
2135

2136
                                context->state = BACKGROUND_TEXT;
×
2137
                        } else if (c == '\x1b')
×
UNCOV
2138
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2139
                        else {
2140
                                int d = unhexchar(c);
×
2141
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
UNCOV
2142
                                        context->state = BACKGROUND_TEXT;
×
2143
                                else {
2144
                                        context->blue = (context->blue << 4) | d;
×
UNCOV
2145
                                        context->blue_bits += 4;
×
2146
                                }
2147
                        }
2148
                        break;
2149

2150
                case BACKGROUND_STRING_TERMINATOR:
×
2151
                        if (c == '\\') {
×
2152
                                if (ret_processed)
×
UNCOV
2153
                                        *ret_processed = i + 1;
×
2154

UNCOV
2155
                                return 1; /* success! */
×
2156
                        }
2157

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

2161
                }
2162

2163
                /* Reset any colors we might have picked up */
UNCOV
2164
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2165
                        /* reset color */
2166
                        context->red = context->green = context->blue = 0;
×
UNCOV
2167
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2168
                }
2169
        }
2170

2171
        if (ret_processed)
×
UNCOV
2172
                *ret_processed = size;
×
2173

2174
        return 0; /* all good, but not enough data yet */
2175
}
2176

2177
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
124✔
2178
        _cleanup_close_ int nonblock_input_fd = -EBADF;
124✔
2179
        int r;
124✔
2180

2181
        assert(ret_red);
124✔
2182
        assert(ret_green);
124✔
2183
        assert(ret_blue);
124✔
2184

2185
        if (!colors_enabled())
124✔
2186
                return -EOPNOTSUPP;
2187

2188
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
UNCOV
2189
        if (r < 0)
×
2190
                return r;
2191

UNCOV
2192
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2193
                /* Linux console is black */
2194
                *ret_red = *ret_green = *ret_blue = 0.0;
×
UNCOV
2195
                return 0;
×
2196
        }
2197

2198
        struct termios old_termios;
×
2199
        if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
×
UNCOV
2200
                return -errno;
×
2201

2202
        struct termios new_termios = old_termios;
×
UNCOV
2203
        termios_disable_echo(&new_termios);
×
2204

2205
        if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) < 0)
×
UNCOV
2206
                return -errno;
×
2207

2208
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
2209
        if (r < 0)
×
UNCOV
2210
                goto finish;
×
2211

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

2215
        nonblock_input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
UNCOV
2216
        if (nonblock_input_fd < 0)
×
2217
                return nonblock_input_fd;
2218

2219
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2220
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
2221
        size_t buf_full = 0;
×
UNCOV
2222
        BackgroundColorContext context = {};
×
2223

2224
        for (bool first = true;; first = false) {
×
2225
                if (buf_full == 0) {
×
2226
                        usec_t n = now(CLOCK_MONOTONIC);
×
2227
                        if (n >= end) {
×
2228
                                r = -EOPNOTSUPP;
×
UNCOV
2229
                                goto finish;
×
2230
                        }
2231

2232
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2233
                        if (r < 0)
×
2234
                                goto finish;
×
2235
                        if (r == 0) {
×
2236
                                r = -EOPNOTSUPP;
×
UNCOV
2237
                                goto finish;
×
2238
                        }
2239

2240
                        /* On the first try, read multiple characters, i.e. the shortest valid
2241
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2242
                         * unnecessarily drop too many characters from the input queue. */
2243
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2244
                        if (l < 0) {
×
2245
                                if (errno == EAGAIN)
×
2246
                                        continue;
×
2247
                                r = -errno;
×
UNCOV
2248
                                goto finish;
×
2249
                        }
2250

UNCOV
2251
                        assert((size_t) l <= sizeof(buf));
×
2252
                        buf_full = l;
2253
                }
2254

2255
                size_t processed;
×
2256
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
2257
                if (r < 0)
×
UNCOV
2258
                        goto finish;
×
2259

2260
                assert(processed <= buf_full);
×
2261
                buf_full -= processed;
×
UNCOV
2262
                memmove(buf, buf + processed, buf_full);
×
2263

2264
                if (r > 0) {
×
2265
                        assert(context.red_bits > 0);
×
2266
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
2267
                        assert(context.green_bits > 0);
×
2268
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
2269
                        assert(context.blue_bits > 0);
×
2270
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
2271
                        r = 0;
×
UNCOV
2272
                        goto finish;
×
2273
                }
2274
        }
2275

2276
finish:
×
UNCOV
2277
        RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios)));
×
2278
        return r;
2279
}
2280

2281
typedef enum CursorPositionState {
2282
        CURSOR_TEXT,
2283
        CURSOR_ESCAPE,
2284
        CURSOR_ROW,
2285
        CURSOR_COLUMN,
2286
} CursorPositionState;
2287

2288
typedef struct CursorPositionContext {
2289
        CursorPositionState state;
2290
        unsigned row, column;
2291
} CursorPositionContext;
2292

UNCOV
2293
static int scan_cursor_position_response(
×
2294
                CursorPositionContext *context,
2295
                const char *buf,
2296
                size_t size,
2297
                size_t *ret_processed) {
2298

2299
        assert(context);
×
UNCOV
2300
        assert(buf || size == 0);
×
2301

2302
        for (size_t i = 0; i < size; i++) {
×
UNCOV
2303
                char c = buf[i];
×
2304

UNCOV
2305
                switch (context->state) {
×
2306

2307
                case CURSOR_TEXT:
×
2308
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
UNCOV
2309
                        break;
×
2310

2311
                case CURSOR_ESCAPE:
×
2312
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
UNCOV
2313
                        break;
×
2314

2315
                case CURSOR_ROW:
×
2316
                        if (c == ';')
×
UNCOV
2317
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
2318
                        else {
UNCOV
2319
                                int d = undecchar(c);
×
2320

2321
                                /* We read a decimal character, let's suffix it to the number we so far read,
2322
                                 * but let's do an overflow check first. */
2323
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
UNCOV
2324
                                        context->state = CURSOR_TEXT;
×
2325
                                else
UNCOV
2326
                                        context->row = context->row * 10 + d;
×
2327
                        }
2328
                        break;
2329

2330
                case CURSOR_COLUMN:
×
2331
                        if (c == 'R') {
×
2332
                                if (context->column > 0) {
×
2333
                                        if (ret_processed)
×
UNCOV
2334
                                                *ret_processed = i + 1;
×
2335

UNCOV
2336
                                        return 1; /* success! */
×
2337
                                }
2338

UNCOV
2339
                                context->state = CURSOR_TEXT;
×
2340
                        } else {
UNCOV
2341
                                int d = undecchar(c);
×
2342

2343
                                /* As above, add the decimal character to our column number */
2344
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
UNCOV
2345
                                        context->state = CURSOR_TEXT;
×
2346
                                else
UNCOV
2347
                                        context->column = context->column * 10 + d;
×
2348
                        }
2349

2350
                        break;
2351
                }
2352

2353
                /* Reset any positions we might have picked up */
2354
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
UNCOV
2355
                        context->row = context->column = 0;
×
2356
        }
2357

2358
        if (ret_processed)
×
UNCOV
2359
                *ret_processed = size;
×
2360

2361
        return 0; /* all good, but not enough data yet */
2362
}
2363

2364
int terminal_get_size_by_dsr(
172✔
2365
                int input_fd,
2366
                int output_fd,
2367
                unsigned *ret_rows,
2368
                unsigned *ret_columns) {
2369

2370
        _cleanup_close_ int nonblock_input_fd = -EBADF;
172✔
2371

2372
        assert(input_fd >= 0);
172✔
2373
        assert(output_fd >= 0);
172✔
2374

2375
        int r;
172✔
2376

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

2392
        if (terminal_is_dumb())
172✔
2393
                return -EOPNOTSUPP;
2394

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

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

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

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

UNCOV
2409
        unsigned saved_row = 0, saved_column = 0;
×
2410

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

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

2422
        nonblock_input_fd = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
UNCOV
2423
        if (nonblock_input_fd < 0)
×
2424
                return nonblock_input_fd;
2425

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

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

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

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

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

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

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

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

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

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

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

2486
                                saved_row = context.row;
×
UNCOV
2487
                                saved_column = context.column;
×
2488

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

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

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

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

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

UNCOV
2518
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSADRAIN, &old_termios)));
×
2519
        return r;
2520
}
2521

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

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

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

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

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

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

2545
        ws.ws_col = columns;
×
UNCOV
2546
        ws.ws_row = rows;
×
2547

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

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

2555
int terminal_is_pty_fd(int fd) {
3✔
2556
        int r;
3✔
2557

2558
        assert(fd >= 0);
3✔
2559

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

2562
        if (!isatty_safe(fd))
3✔
2563
                return false;
3✔
2564

2565
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2✔
2566
        if (r != 0)
2✔
2567
                return r;
2568

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

2572
        int v;
×
2573
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
×
UNCOV
2574
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
2575
                        return false;
2576

UNCOV
2577
                return -errno;
×
2578
        }
2579

2580
        return true;
2581
}
2582

2583
int pty_open_peer(int fd, int mode) {
20✔
2584
        assert(fd >= 0);
20✔
2585

2586
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2587
         *
2588
         * This is safe to be called on TTYs from other namespaces. */
2589

2590
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
20✔
2591

2592
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
UNCOV
2593
        for (unsigned c = 0;; c++) {
×
2594
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
20✔
2595
                if (peer_fd >= 0)
20✔
2596
                        return peer_fd;
2597

2598
                if (errno != EIO)
×
UNCOV
2599
                        return -errno;
×
2600

2601
                /* Max 1s in total */
UNCOV
2602
                if (c >= 20)
×
2603
                        return -EIO;
2604

UNCOV
2605
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2606
        }
2607
}
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