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

systemd / systemd / 22601885815

02 Mar 2026 11:59PM UTC coverage: 72.342% (-0.2%) from 72.572%
22601885815

push

github

yuwata
network: fix error aggregation in wwan_check_and_set_configuration()

When removing marked routes, the condition `if (ret)` incorrectly
overwrites any previously accumulated error in `ret` with the latest
return value `r`, even if `r >= 0` (success). This means an earlier
real error can be silently cleared by a subsequent successful
route_remove() call.

The parallel address_remove() block just above uses the correct
`if (r < 0)` pattern. Apply the same fix to the route_remove() block.

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

1949 existing lines in 60 files now uncovered.

314857 of 435233 relevant lines covered (72.34%)

1137439.04 hits per line

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

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

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

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

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

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

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

56
bool isatty_safe(int fd) {
5,421,645✔
57
        assert(fd >= 0);
5,421,645✔
58

59
        if (isatty(fd))
5,421,645✔
60
                return true;
61

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

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

71
        return false;
72
}
73

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

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

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

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

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

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

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

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

104
        assert(ret);
4✔
105

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

174
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
175

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

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

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

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

190
                putchar('\r');
×
191

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

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

198
                fflush(stdout);
×
199

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

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

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

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

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

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

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

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

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

241
        string = strempty(string);
×
242

243
        STRV_FOREACH(c, completions) {
×
244

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

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

255
                        continue;
×
256
                }
257

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

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

268
        *ret = TAKE_PTR(found);
×
269

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

442
                fflush(stdout);
×
443
        }
444

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

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

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

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

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

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

473
bool any_key_to_proceed(void) {
×
474

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

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

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

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

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

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

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

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

503
        return w;
×
504
}
505

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

513
        assert(n_columns > 0);
×
514

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

583
                putchar('\n');
×
584

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

591
        return 0;
592
}
593

594
int open_terminal(const char *name, int mode) {
50,578✔
595
        _cleanup_close_ int fd = -EBADF;
50,578✔
596

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

605
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
50,578✔
606

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

612
                if (errno != EIO)
1,126✔
613
                        return -errno;
1,126✔
614

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

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

622
        if (!isatty_safe(fd))
49,452✔
623
                return -ENOTTY;
1✔
624

625
        return TAKE_FD(fd);
626
}
627

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

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

637
        assert(name);
187✔
638

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

726
                                left = timeout - n;
×
727
                        }
728

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

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

749
                                return -errno;
×
750
                        }
751

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

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

760
                        break;
×
761
                }
762

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

768
        return TAKE_FD(fd);
187✔
769
}
770

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

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

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

784
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
21✔
785

786
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
21✔
787

788
        return r;
789
}
790

791
int terminal_new_session(void) {
5✔
792

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

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

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

807
void terminal_detach_session(void) {
55✔
808
        (void) setsid();
55✔
809
        (void) release_terminal();
55✔
810
}
55✔
811

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

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

820
        assert(tty);
×
821

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

826
        return terminal_vhangup_fd(fd);
×
827
}
828

829
int vt_disallocate(const char *tty_path) {
49✔
830
        assert(tty_path);
49✔
831

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

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

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

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

851
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
98✔
852
        if (fd2 < 0)
49✔
853
                return fd2;
854

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

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

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

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

874
        return parse_boolean(b);
488✔
875
}
876

877
static int vt_reset_keyboard(int fd) {
441✔
878
        int r, kb;
441✔
879

880
        assert(fd >= 0);
441✔
881

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

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

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

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

897
        assert(fd >= 0);
441✔
898

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

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

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

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

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

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

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

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

945
        termios.c_cc[VTIME]  = 0;
439✔
946
        termios.c_cc[VMIN]   = 1;
439✔
947

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

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

956
        return r;
441✔
957
}
958

959
int terminal_reset_ansi_seq(int fd) {
435✔
960
        int r, k;
435✔
961

962
        assert(fd >= 0);
435✔
963

964
        if (getenv_terminal_is_dumb())
435✔
965
                return 0;
966

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

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

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

989
        return k < 0 ? k : r;
×
990
}
991

992
void reset_dev_console_fd(int fd, bool switch_to_text) {
36✔
993
        int r;
36✔
994

995
        assert(fd >= 0);
36✔
996

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

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

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

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

1021
int lock_dev_console(void) {
576✔
1022
        _cleanup_close_ int fd = -EBADF;
576✔
1023
        int r;
576✔
1024

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

1031
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
576✔
1032
        if (r < 0)
576✔
1033
                return r;
×
1034

1035
        return TAKE_FD(fd);
1036
}
1037

1038
int make_console_stdio(void) {
×
1039
        int fd, r;
×
1040

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

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

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

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

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

1061
        reset_terminal_feature_caches();
×
1062
        return 0;
×
1063
}
1064

1065
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
302✔
1066
        assert(tty);
302✔
1067

1068
        tty = skip_dev_prefix(tty);
302✔
1069

1070
        const char *e = startswith(tty, "tty");
302✔
1071
        if (!e)
302✔
1072
                return -EINVAL;
1073

1074
        return safe_atou(e, ret);
260✔
1075
}
1076

1077
int vtnr_from_tty(const char *tty) {
176✔
1078
        unsigned u;
176✔
1079
        int r;
176✔
1080

1081
        assert(tty);
176✔
1082

1083
        r = vtnr_from_tty_raw(tty, &u);
176✔
1084
        if (r < 0)
176✔
1085
                return r;
176✔
1086
        if (!vtnr_is_valid(u))
176✔
1087
                return -ERANGE;
1088

1089
        return (int) u;
176✔
1090
}
1091

1092
bool tty_is_vc(const char *tty) {
126✔
1093
        assert(tty);
126✔
1094

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

1100
        return vtnr_from_tty_raw(tty, /* ret= */ NULL) >= 0;
126✔
1101
}
1102

1103
bool tty_is_console(const char *tty) {
445✔
1104
        assert(tty);
445✔
1105

1106
        return streq(skip_dev_prefix(tty), "console");
445✔
1107
}
1108

1109
int resolve_dev_console(char **ret) {
180✔
1110
        int r;
180✔
1111

1112
        assert(ret);
180✔
1113

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

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

1128
        r = path_is_read_only_fs("/sys");
98✔
1129
        if (r < 0)
98✔
1130
                return r;
1131
        if (r > 0)
98✔
1132
                return -ENOMEDIUM;
1133

1134
        _cleanup_free_ char *active = NULL;
98✔
1135
        r = read_one_line_file("/sys/class/tty/console/active", &active);
98✔
1136
        if (r < 0)
98✔
1137
                return r;
1138
        if (r == 0)
98✔
1139
                return -ENXIO;
1140

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

1148
        if (streq(tty, "tty0")) {
98✔
1149
                active = mfree(active);
×
1150

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

1158
                tty = active;
×
1159
        }
1160

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

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

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

UNCOV
1175
        assert(ret);
×
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. */
UNCOV
1179
        if (path_is_read_only_fs("/sys") > 0)
×
UNCOV
1180
                goto fallback;
×
1181

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

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

1189
                r = extract_first_word(&p, &tty, NULL, 0);
×
1190
                if (r < 0)
×
1191
                        return r;
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);
×
1198
                        if (r < 0)
×
1199
                                return r;
1200
                        if (r == 0) {
×
1201
                                log_debug("No VT active, skipping /dev/tty0.");
×
1202
                                continue;
×
1203
                        }
1204
                }
1205

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

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

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

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

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

UNCOV
1228
fallback:
×
UNCOV
1229
        r = strv_extend(&l, "/dev/console");
×
UNCOV
1230
        if (r < 0)
×
1231
                return r;
1232

UNCOV
1233
        *ret = TAKE_PTR(l);
×
UNCOV
1234
        return 0;
×
1235
}
1236

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

1240
        assert(tty);
49✔
1241

1242
        if (streq(skip_dev_prefix(tty), "console")) {
49✔
1243
                if (resolve_dev_console(&resolved) < 0)
1✔
1244
                        return false;
1245

1246
                tty = resolved;
1✔
1247
        }
1248

1249
        return tty_is_vc(tty);
49✔
1250
}
1251

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

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

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

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

1264
        return ws.ws_col;
×
1265
}
1266

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

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

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

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

1282
unsigned columns(void) {
267,605✔
1283

1284
        if (cached_columns > 0)
267,605✔
1285
                return cached_columns;
266,216✔
1286

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

1294
        assert(c > 0);
2✔
1295

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

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

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

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

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

1312
        return ws.ws_row;
×
1313
}
1314

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

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

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

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

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

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

1340
        assert(fd >= 0);
558✔
1341

1342
        if (!ident)
558✔
1343
                ident = "TTY";
86✔
1344

1345
        if (rows == UINT_MAX && cols == UINT_MAX)
558✔
1346
                return 0;
558✔
1347

1348
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
413✔
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)
413✔
1354
                rows = ws.ws_row;
×
1355
        else if (rows > USHRT_MAX)
413✔
1356
                rows = USHRT_MAX;
×
1357

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

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

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

1369
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
136✔
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) {
508✔
1376
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
508✔
1377
        unsigned rows = UINT_MAX, cols = UINT_MAX;
508✔
1378
        int r;
508✔
1379

1380
        assert(tty);
508✔
1381

1382
        if (!ret_rows && !ret_cols)
508✔
1383
                return 0;
1384

1385
        tty = skip_dev_prefix(tty);
508✔
1386
        if (path_startswith(tty, "pts/"))
508✔
1387
                return -EMEDIUMTYPE;
1388
        if (!in_charset(tty, ALPHANUMERICAL))
508✔
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);
508✔
1393
        if (!rowskey)
508✔
1394
                return -ENOMEM;
1395

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

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

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

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

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

1423
        return rows != UINT_MAX || cols != UINT_MAX;
508✔
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;
×
1430
}
×
1431

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

1436
        cached_on_tty = -1;
24✔
1437
        cached_on_dev_null = -1;
24✔
1438

1439
        reset_ansi_feature_caches();
24✔
1440
}
24✔
1441

1442
bool on_tty(void) {
7,474,900✔
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,474,900✔
1451
                cached_on_tty =
33,008✔
1452
                        isatty_safe(STDOUT_FILENO) &&
33,045✔
1453
                        isatty_safe(STDERR_FILENO);
37✔
1454

1455
        return cached_on_tty;
7,474,900✔
1456
}
1457

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

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

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

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

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

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

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

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

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

1496
        assert(pid >= 0);
4,964✔
1497

1498
        p = procfs_file_alloca(pid, "stat");
24,480✔
1499
        r = read_one_line_file(p, &line);
4,964✔
1500
        if (r < 0)
4,964✔
1501
                return r;
1502

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

1507
        p++;
4,964✔
1508

1509
        if (sscanf(p, " "
4,964✔
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))
4,964✔
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) {
31✔
1528
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
31✔
1529
        _cleanup_free_ char *buf = NULL;
31✔
1530
        const char *fn = NULL, *w;
31✔
1531
        dev_t devnr;
31✔
1532
        int r;
31✔
1533

1534
        r = get_ctty_devnr(pid, &devnr);
31✔
1535
        if (r < 0)
31✔
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✔
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)
×
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);
×
1564
                        if (r < 0)
×
1565
                                return r;
1566

1567
                        fn = buf;
×
1568
                }
1569
        } else
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✔
1583
                *ret_devnr = devnr;
×
1584

1585
        return 0;
1586
}
1587

1588
int ptsname_malloc(int fd, char **ret) {
136✔
1589
        assert(fd >= 0);
136✔
1590
        assert(ret);
136✔
1591

1592
        for (size_t l = 50;;) {
×
1593
                _cleanup_free_ char *c = NULL;
×
1594

1595
                c = new(char, l);
136✔
1596
                if (!c)
136✔
1597
                        return -ENOMEM;
1598

1599
                if (ptsname_r(fd, c, l) >= 0) {
136✔
1600
                        *ret = TAKE_PTR(c);
136✔
1601
                        return 0;
136✔
1602
                }
1603
                if (errno != ERANGE)
×
1604
                        return -errno;
×
1605

1606
                if (!MUL_ASSIGN_SAFE(&l, 2))
×
1607
                        return -ENOMEM;
1608
        }
1609
}
1610

1611
int openpt_allocate(int flags, char **ret_peer_path) {
140✔
1612
        _cleanup_close_ int fd = -EBADF;
140✔
1613
        int r;
140✔
1614

1615
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
140✔
1616
        if (fd < 0)
140✔
1617
                return -errno;
×
1618

1619
        _cleanup_free_ char *p = NULL;
140✔
1620
        if (ret_peer_path) {
140✔
1621
                r = ptsname_malloc(fd, &p);
136✔
1622
                if (r < 0)
136✔
1623
                        return r;
1624

1625
                if (!path_startswith(p, "/dev/pts/"))
136✔
1626
                        return -EINVAL;
1627
        }
1628

1629
        if (unlockpt(fd) < 0)
140✔
1630
                return -errno;
×
1631

1632
        if (ret_peer_path)
140✔
1633
                *ret_peer_path = TAKE_PTR(p);
136✔
1634

1635
        return TAKE_FD(fd);
1636
}
1637

1638
static int ptsname_namespace(int pty, char **ret) {
×
1639
        int no = -1;
×
1640

1641
        assert(pty >= 0);
×
1642
        assert(ret);
×
1643

1644
        /* Like ptsname(), but doesn't assume that the path is
1645
         * accessible in the local namespace. */
1646

1647
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
1648
                return -errno;
×
1649

1650
        if (no < 0)
×
1651
                return -EIO;
1652

1653
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
1654
                return -ENOMEM;
×
1655

1656
        return 0;
1657
}
1658

1659
int openpt_allocate_in_namespace(
×
1660
                const PidRef *pidref,
1661
                int flags,
1662
                char **ret_peer_path) {
1663

1664
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
1665
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
1666
        int r;
×
1667

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

1672
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
1673
                return -errno;
×
1674

1675
        r = namespace_fork(
×
1676
                        "(sd-openptns)",
1677
                        "(sd-openpt)",
1678
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1679
                        pidnsfd,
1680
                        mntnsfd,
1681
                        /* netns_fd= */ -EBADF,
1682
                        usernsfd,
1683
                        rootfd,
1684
                        /* ret= */ NULL);
1685
        if (r < 0)
×
1686
                return r;
1687
        if (r == 0) {
×
1688
                pair[0] = safe_close(pair[0]);
×
1689

1690
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1691
                if (fd < 0)
×
1692
                        _exit(EXIT_FAILURE);
×
1693

1694
                if (send_one_fd(pair[1], fd, 0) < 0)
×
1695
                        _exit(EXIT_FAILURE);
×
1696

1697
                _exit(EXIT_SUCCESS);
×
1698
        }
1699

1700
        pair[1] = safe_close(pair[1]);
×
1701

1702
        fd = receive_one_fd(pair[0], 0);
×
1703
        if (fd < 0)
×
1704
                return fd;
1705

1706
        if (ret_peer_path) {
×
1707
                r = ptsname_namespace(fd, ret_peer_path);
×
1708
                if (r < 0)
×
1709
                        return r;
×
1710
        }
1711

1712
        return TAKE_FD(fd);
1713
}
1714

1715
static bool on_dev_null(void) {
40,363✔
1716
        struct stat dst, ost, est;
40,363✔
1717

1718
        if (cached_on_dev_null >= 0)
40,363✔
1719
                return cached_on_dev_null;
7,483✔
1720

1721
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
32,880✔
1722
                cached_on_dev_null = false;
1✔
1723
        else
1724
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
36,714✔
1725

1726
        return cached_on_dev_null;
32,880✔
1727
}
1728

1729
bool getenv_terminal_is_dumb(void) {
13,433✔
1730
        const char *e;
13,433✔
1731

1732
        e = getenv("TERM");
13,433✔
1733
        if (!e)
13,433✔
1734
                return true;
1735

1736
        return streq(e, "dumb");
1,306✔
1737
}
1738

1739
bool terminal_is_dumb(void) {
40,400✔
1740
        if (!on_tty() && !on_dev_null())
40,400✔
1741
                return true;
1742

1743
        return getenv_terminal_is_dumb();
158✔
1744
}
1745

1746
bool dev_console_colors_enabled(void) {
×
1747
        _cleanup_free_ char *s = NULL;
×
1748
        ColorMode m;
×
1749

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

1757
        m = parse_systemd_colors();
×
1758
        if (m >= 0)
×
1759
                return m;
×
1760

1761
        if (getenv("NO_COLOR"))
×
1762
                return false;
1763

1764
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
1765
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1766

1767
        return !streq_ptr(s, "dumb");
×
1768
}
1769

1770
int vt_restore(int fd) {
×
1771

1772
        static const struct vt_mode mode = {
×
1773
                .mode = VT_AUTO,
1774
        };
1775

1776
        int r, ret = 0;
×
1777

1778
        assert(fd >= 0);
×
1779

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

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

1786
        r = vt_reset_keyboard(fd);
×
1787
        if (r < 0)
×
1788
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1789

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

1793
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1794
        if (r < 0)
×
1795
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1796

1797
        return ret;
1798
}
1799

1800
int vt_release(int fd, bool restore) {
×
1801
        assert(fd >= 0);
×
1802

1803
        /* This function releases the VT by acknowledging the VT-switch signal
1804
         * sent by the kernel and optionally reset the VT in text and auto
1805
         * VT-switching modes. */
1806

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

1810
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
1811
                return -errno;
×
1812

1813
        if (restore)
×
1814
                return vt_restore(fd);
×
1815

1816
        return 0;
1817
}
1818

1819
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
227,485✔
1820
        /* Note that this will initialize output variables only when there's something to output.
1821
         * The caller must pre-initialize to "" or NULL as appropriate. */
1822

1823
        if (priority <= LOG_ERR) {
227,485✔
1824
                if (on)
6,455✔
1825
                        *on = ansi_highlight_red();
12,910✔
1826
                if (off)
6,455✔
1827
                        *off = ansi_normal();
12,910✔
1828
                if (highlight)
6,455✔
1829
                        *highlight = ansi_highlight();
×
1830

1831
        } else if (priority <= LOG_WARNING) {
221,030✔
1832
                if (on)
948✔
1833
                        *on = ansi_highlight_yellow();
948✔
1834
                if (off)
948✔
1835
                        *off = ansi_normal();
1,896✔
1836
                if (highlight)
948✔
1837
                        *highlight = ansi_highlight();
×
1838

1839
        } else if (priority <= LOG_NOTICE) {
220,082✔
1840
                if (on)
912✔
1841
                        *on = ansi_highlight();
1,824✔
1842
                if (off)
912✔
1843
                        *off = ansi_normal();
1,824✔
1844
                if (highlight)
912✔
1845
                        *highlight = ansi_highlight_red();
×
1846

1847
        } else if (priority >= LOG_DEBUG) {
219,170✔
1848
                if (on)
171,673✔
1849
                        *on = ansi_grey();
171,673✔
1850
                if (off)
171,673✔
1851
                        *off = ansi_normal();
343,346✔
1852
                if (highlight)
171,673✔
1853
                        *highlight = ansi_highlight_red();
×
1854
        }
1855
}
227,485✔
1856

1857
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
1858
        assert(fd >= 0);
×
1859

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

1863
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1864
}
1865

1866
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1867
        assert(input_fd >= 0);
1✔
1868
        assert(output_fd >= 0);
1✔
1869

1870
        /* Validates that the specified fds reference the same TTY */
1871

1872
        if (input_fd != output_fd) {
1✔
1873
                struct stat sti;
1✔
1874
                if (fstat(input_fd, &sti) < 0)
1✔
1875
                        return -errno;
1✔
1876

1877
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
1878
                        return -ENOTTY;
1879

1880
                struct stat sto;
1✔
1881
                if (fstat(output_fd, &sto) < 0)
1✔
1882
                        return -errno;
×
1883

1884
                if (!S_ISCHR(sto.st_mode))
1✔
1885
                        return -ENOTTY;
1886

1887
                if (sti.st_rdev != sto.st_rdev)
×
1888
                        return -ENOLINK;
1889
        }
1890

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

1894
        return 0;
1895
}
1896

1897
typedef enum CursorPositionState {
1898
        CURSOR_TEXT,
1899
        CURSOR_ESCAPE,
1900
        CURSOR_ROW,
1901
        CURSOR_COLUMN,
1902
} CursorPositionState;
1903

1904
typedef struct CursorPositionContext {
1905
        CursorPositionState state;
1906
        unsigned row, column;
1907
} CursorPositionContext;
1908

1909
static int scan_cursor_position_response(
×
1910
                CursorPositionContext *context,
1911
                const char *buf,
1912
                size_t size,
1913
                size_t *ret_processed) {
1914

1915
        assert(context);
×
1916
        assert(buf);
×
1917
        assert(ret_processed);
×
1918

1919
        for (size_t i = 0; i < size; i++) {
×
1920
                char c = buf[i];
×
1921

1922
                switch (context->state) {
×
1923

1924
                case CURSOR_TEXT:
×
1925
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
1926
                        break;
×
1927

1928
                case CURSOR_ESCAPE:
×
1929
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
1930
                        break;
×
1931

1932
                case CURSOR_ROW:
×
1933
                        if (c == ';')
×
1934
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
1935
                        else {
1936
                                int d = undecchar(c);
×
1937

1938
                                /* We read a decimal character, let's suffix it to the number we so far read,
1939
                                 * but let's do an overflow check first. */
1940
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
1941
                                        context->state = CURSOR_TEXT;
×
1942
                                else
1943
                                        context->row = context->row * 10 + d;
×
1944
                        }
1945
                        break;
1946

1947
                case CURSOR_COLUMN:
×
1948
                        if (c == 'R') {
×
1949
                                if (context->column > 0) {
×
1950
                                        *ret_processed = i + 1;
×
1951
                                        return 1; /* success! */
×
1952
                                }
1953

1954
                                context->state = CURSOR_TEXT;
×
1955
                        } else {
1956
                                int d = undecchar(c);
×
1957

1958
                                /* As above, add the decimal character to our column number */
1959
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
1960
                                        context->state = CURSOR_TEXT;
×
1961
                                else
1962
                                        context->column = context->column * 10 + d;
×
1963
                        }
1964

1965
                        break;
1966
                }
1967

1968
                /* Reset any positions we might have picked up */
1969
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
1970
                        context->row = context->column = 0;
×
1971
        }
1972

1973
        *ret_processed = size;
×
1974
        return 0; /* all good, but not enough data yet */
×
1975
}
1976

1977
int terminal_get_cursor_position(
×
1978
                int input_fd,
1979
                int output_fd,
1980
                unsigned *ret_row,
1981
                unsigned *ret_column) {
1982

1983
        _cleanup_close_ int nonblock_input_fd = -EBADF;
×
1984
        int r;
×
1985

1986
        assert(input_fd >= 0);
×
1987
        assert(output_fd >= 0);
×
1988

1989
        if (terminal_is_dumb())
×
1990
                return -EOPNOTSUPP;
1991

1992
        r = terminal_verify_same(input_fd, output_fd);
×
1993
        if (r < 0)
×
1994
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
1995

1996
        struct termios old_termios;
×
1997
        if (tcgetattr(input_fd, &old_termios) < 0)
×
1998
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
1999

2000
        struct termios new_termios = old_termios;
×
2001
        termios_disable_echo(&new_termios);
×
2002

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

2006
        /* Request cursor position (DSR/CPR) */
2007
        r = loop_write(output_fd, "\x1B[6n", SIZE_MAX);
×
2008
        if (r < 0)
×
2009
                goto finish;
×
2010

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

2014
        nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2015
        if (r < 0)
×
2016
                goto finish;
×
2017

2018
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2019
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2020
        size_t buf_full = 0;
×
2021
        CursorPositionContext context = {};
×
2022

2023
        for (bool first = true;; first = false) {
×
2024
                if (buf_full == 0) {
×
2025
                        usec_t n = now(CLOCK_MONOTONIC);
×
2026
                        if (n >= end) {
×
2027
                                r = -EOPNOTSUPP;
×
2028
                                goto finish;
×
2029
                        }
2030

2031
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2032
                        if (r < 0)
×
2033
                                goto finish;
×
2034
                        if (r == 0) {
×
2035
                                r = -EOPNOTSUPP;
×
2036
                                goto finish;
×
2037
                        }
2038

2039
                        /* On the first try, read multiple characters, i.e. the shortest valid
2040
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2041
                         * unnecessarily drop too many characters from the input queue. */
2042
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2043
                        if (l < 0) {
×
2044
                                if (errno == EAGAIN)
×
2045
                                        continue;
×
2046

2047
                                r = -errno;
×
2048
                                goto finish;
×
2049
                        }
2050

2051
                        assert((size_t) l <= sizeof(buf));
×
2052
                        buf_full = l;
2053
                }
2054

2055
                size_t processed;
×
2056
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2057
                if (r < 0)
×
2058
                        goto finish;
×
2059

2060
                assert(processed <= buf_full);
×
2061
                buf_full -= processed;
×
2062
                memmove(buf, buf + processed, buf_full);
×
2063

2064
                if (r > 0) {
×
2065
                        /* Superficial validity check */
2066
                        if (context.row >= 32766 || context.column >= 32766) {
×
2067
                                r = -ENODATA;
×
2068
                                goto finish;
×
2069
                        }
2070

2071
                        if (ret_row)
×
2072
                                *ret_row = context.row;
×
2073
                        if (ret_column)
×
2074
                                *ret_column = context.column;
×
2075

2076
                        r = 0;
×
2077
                        goto finish;
×
2078
                }
2079
        }
2080

2081
finish:
×
2082
        /* We ignore failure here and in similar cases below. We already got a reply and if cleanup fails,
2083
         * this doesn't change the validity of the result. */
2084
        (void) tcsetattr(input_fd, TCSANOW, &old_termios);
×
2085
        return r;
×
2086
}
2087

2088
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
412✔
2089
        int r = 0;
412✔
2090

2091
        assert(fd >= 0);
412✔
2092
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
412✔
2093

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

2097
        if (!isatty_safe(fd))
412✔
2098
                return -ENOTTY;
412✔
2099

2100
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
405✔
2101

2102
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
405✔
2103
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
399✔
2104
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
399✔
2105

2106
        return r;
2107
}
2108

2109
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
6✔
2110
        assert(fd >= 0);
6✔
2111

2112
        _cleanup_close_ int lock_fd = lock_dev_console();
6✔
2113
        if (lock_fd < 0)
6✔
2114
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
2115

2116
        return terminal_reset_defensive(fd, flags);
6✔
2117
}
2118

2119
void termios_disable_echo(struct termios *termios) {
1✔
2120
        assert(termios);
1✔
2121

2122
        termios->c_lflag &= ~(ICANON|ECHO);
1✔
2123
        termios->c_cc[VMIN] = 1;
1✔
2124
        termios->c_cc[VTIME] = 0;
1✔
2125
}
1✔
2126

2127
typedef enum BackgroundColorState {
2128
        BACKGROUND_TEXT,
2129
        BACKGROUND_ESCAPE,
2130
        BACKGROUND_BRACKET,
2131
        BACKGROUND_FIRST_ONE,
2132
        BACKGROUND_SECOND_ONE,
2133
        BACKGROUND_SEMICOLON,
2134
        BACKGROUND_R,
2135
        BACKGROUND_G,
2136
        BACKGROUND_B,
2137
        BACKGROUND_RED,
2138
        BACKGROUND_GREEN,
2139
        BACKGROUND_BLUE,
2140
        BACKGROUND_STRING_TERMINATOR,
2141
} BackgroundColorState;
2142

2143
typedef struct BackgroundColorContext {
2144
        BackgroundColorState state;
2145
        uint32_t red, green, blue;
2146
        unsigned red_bits, green_bits, blue_bits;
2147
} BackgroundColorContext;
2148

2149
static int scan_background_color_response(
×
2150
                BackgroundColorContext *context,
2151
                const char *buf,
2152
                size_t size,
2153
                size_t *ret_processed) {
2154

2155
        assert(context);
×
2156
        assert(buf);
×
2157
        assert(ret_processed);
×
2158

2159
        for (size_t i = 0; i < size; i++) {
×
2160
                char c = buf[i];
×
2161

2162
                switch (context->state) {
×
2163

2164
                case BACKGROUND_TEXT:
×
2165
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2166
                        break;
×
2167

2168
                case BACKGROUND_ESCAPE:
×
2169
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
2170
                        break;
×
2171

2172
                case BACKGROUND_BRACKET:
×
2173
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
2174
                        break;
×
2175

2176
                case BACKGROUND_FIRST_ONE:
×
2177
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
2178
                        break;
×
2179

2180
                case BACKGROUND_SECOND_ONE:
×
2181
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
2182
                        break;
×
2183

2184
                case BACKGROUND_SEMICOLON:
×
2185
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
2186
                        break;
×
2187

2188
                case BACKGROUND_R:
×
2189
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
2190
                        break;
×
2191

2192
                case BACKGROUND_G:
×
2193
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
2194
                        break;
×
2195

2196
                case BACKGROUND_B:
×
2197
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
2198
                        break;
×
2199

2200
                case BACKGROUND_RED:
×
2201
                        if (c == '/')
×
2202
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2203
                        else {
2204
                                int d = unhexchar(c);
×
2205
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
2206
                                        context->state = BACKGROUND_TEXT;
×
2207
                                else {
2208
                                        context->red = (context->red << 4) | d;
×
2209
                                        context->red_bits += 4;
×
2210
                                }
2211
                        }
2212
                        break;
2213

2214
                case BACKGROUND_GREEN:
×
2215
                        if (c == '/')
×
2216
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2217
                        else {
2218
                                int d = unhexchar(c);
×
2219
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
2220
                                        context->state = BACKGROUND_TEXT;
×
2221
                                else {
2222
                                        context->green = (context->green << 4) | d;
×
2223
                                        context->green_bits += 4;
×
2224
                                }
2225
                        }
2226
                        break;
2227

2228
                case BACKGROUND_BLUE:
×
2229
                        if (c == '\x07') {
×
2230
                                if (context->blue_bits > 0) {
×
2231
                                        *ret_processed = i + 1;
×
2232
                                        return 1; /* success! */
×
2233
                                }
2234

2235
                                context->state = BACKGROUND_TEXT;
×
2236
                        } else if (c == '\x1b')
×
2237
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2238
                        else {
2239
                                int d = unhexchar(c);
×
2240
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
2241
                                        context->state = BACKGROUND_TEXT;
×
2242
                                else {
2243
                                        context->blue = (context->blue << 4) | d;
×
2244
                                        context->blue_bits += 4;
×
2245
                                }
2246
                        }
2247
                        break;
2248

2249
                case BACKGROUND_STRING_TERMINATOR:
×
2250
                        if (c == '\\') {
×
2251
                                *ret_processed = i + 1;
×
2252
                                return 1; /* success! */
×
2253
                        }
2254

2255
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2256
                        break;
×
2257

2258
                }
2259

2260
                /* Reset any colors we might have picked up */
2261
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2262
                        /* reset color */
2263
                        context->red = context->green = context->blue = 0;
×
2264
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2265
                }
2266
        }
2267

2268
        *ret_processed = size;
×
2269
        return 0; /* all good, but not enough data yet */
×
2270
}
2271

2272
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
170✔
2273
        int r;
170✔
2274

2275
        assert(ret_red);
170✔
2276
        assert(ret_green);
170✔
2277
        assert(ret_blue);
170✔
2278

2279
        if (!colors_enabled())
170✔
2280
                return -EOPNOTSUPP;
170✔
2281

2282
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
2283
        if (r < 0)
×
2284
                return r;
2285

2286
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2287
                /* Linux console is black */
2288
                *ret_red = *ret_green = *ret_blue = 0.0;
×
2289
                return 0;
×
2290
        }
2291

2292
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2293
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2294
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
170✔
2295
        if (r < 0)
×
2296
                return r;
2297

2298
        struct termios old_termios;
×
2299
        if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
×
2300
                return -errno;
×
2301

2302
        struct termios new_termios = old_termios;
×
2303
        termios_disable_echo(&new_termios);
×
2304

2305
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
×
2306
                return -errno;
×
2307

2308
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
2309
        if (r < 0)
×
2310
                goto finish;
×
2311

2312
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2313
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
2314
        size_t buf_full = 0;
×
2315
        BackgroundColorContext context = {};
×
2316

2317
        for (bool first = true;; first = false) {
×
2318
                if (buf_full == 0) {
×
2319
                        usec_t n = now(CLOCK_MONOTONIC);
×
2320
                        if (n >= end) {
×
2321
                                r = -EOPNOTSUPP;
×
2322
                                goto finish;
×
2323
                        }
2324

2325
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2326
                        if (r < 0)
×
2327
                                goto finish;
×
2328
                        if (r == 0) {
×
2329
                                r = -EOPNOTSUPP;
×
2330
                                goto finish;
×
2331
                        }
2332

2333
                        /* On the first try, read multiple characters, i.e. the shortest valid
2334
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2335
                         * unnecessarily drop too many characters from the input queue. */
2336
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2337
                        if (l < 0) {
×
2338
                                if (errno == EAGAIN)
×
2339
                                        continue;
×
2340
                                r = -errno;
×
2341
                                goto finish;
×
2342
                        }
2343

2344
                        assert((size_t) l <= sizeof(buf));
×
2345
                        buf_full = l;
2346
                }
2347

2348
                size_t processed;
×
2349
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
2350
                if (r < 0)
×
2351
                        goto finish;
×
2352

2353
                assert(processed <= buf_full);
×
2354
                buf_full -= processed;
×
2355
                memmove(buf, buf + processed, buf_full);
×
2356

2357
                if (r > 0) {
×
2358
                        assert(context.red_bits > 0);
×
2359
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
2360
                        assert(context.green_bits > 0);
×
2361
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
2362
                        assert(context.blue_bits > 0);
×
2363
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
2364
                        r = 0;
×
2365
                        goto finish;
×
2366
                }
2367
        }
2368

2369
finish:
×
2370
        (void) tcsetattr(nonblock_input_fd, TCSANOW, &old_termios);
×
2371
        return r;
×
2372
}
2373

2374
int terminal_get_size_by_dsr(
100✔
2375
                int input_fd,
2376
                int output_fd,
2377
                unsigned *ret_rows,
2378
                unsigned *ret_columns) {
2379

2380
        int r;
100✔
2381

2382
        assert(input_fd >= 0);
100✔
2383
        assert(output_fd >= 0);
100✔
2384

2385
        /* Tries to determine the terminal dimension by means of ANSI sequences.
2386
         *
2387
         * We position the cursor briefly at an absolute location very far down and very far to the right,
2388
         * and then read back where we actually ended up. Because cursor locations are capped at the terminal
2389
         * width/height we should then see the right values. In order to not risk integer overflows in
2390
         * terminal applications we'll use INT16_MAX-1 as location to jump to — hopefully a value that is
2391
         * large enough for any real-life terminals, but small enough to not overflow anything or be
2392
         * recognized as a "niche" value. (Note that the dimension fields in "struct winsize" are 16bit only,
2393
         * too). */
2394

2395
        if (terminal_is_dumb())
100✔
2396
                return -EOPNOTSUPP;
100✔
2397

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

2402
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2403
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2404
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
100✔
2405
        if (r < 0)
×
2406
                return r;
2407

2408
        struct termios old_termios;
×
2409
        if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
×
2410
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
2411

2412
        struct termios new_termios = old_termios;
×
2413
        termios_disable_echo(&new_termios);
×
2414

2415
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
×
2416
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
×
2417

2418
        unsigned saved_row = 0, saved_column = 0;
×
2419

2420
        r = loop_write(output_fd,
×
2421
                       "\x1B[6n"           /* Request cursor position (DSR/CPR) */
2422
                       "\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
2423
                       "\x1B[6n",          /* Request cursor position again */
2424
                       SIZE_MAX);
2425
        if (r < 0)
×
2426
                goto finish;
×
2427

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2515
finish:
×
2516
        /* Restore cursor position */
2517
        if (saved_row > 0 && saved_column > 0)
×
2518
                (void) terminal_set_cursor_position(output_fd, saved_row, saved_column);
×
2519
        (void) tcsetattr(nonblock_input_fd, TCSANOW, &old_termios);
×
2520

2521
        return r;
×
2522
}
2523

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

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

2539
        assert(buf);
×
2540
        assert(ret_rows);
×
2541
        assert(ret_columns);
×
2542

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

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

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

2555
        *ret_rows = rows;
×
2556
        *ret_columns = columns;
×
2557
        return 0;
×
2558
}
2559

2560
int terminal_get_size_by_csi18(
1✔
2561
                int input_fd,
2562
                int output_fd,
2563
                unsigned *ret_rows,
2564
                unsigned *ret_columns) {
2565
        int r;
1✔
2566

2567
        assert(input_fd >= 0);
1✔
2568
        assert(output_fd >= 0);
1✔
2569

2570
        /* Tries to determine the terminal dimension by means of an ANSI sequence CSI 18. */
2571

2572
        if (terminal_is_dumb())
1✔
2573
                return -EOPNOTSUPP;
1✔
2574

2575
        r = terminal_verify_same(input_fd, output_fd);
×
2576
        if (r < 0)
×
2577
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2578

2579
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2580
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2581
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1✔
2582
        if (r < 0)
×
2583
                return r;
2584

2585
        struct termios old_termios;
×
2586
        if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
×
2587
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
×
2588

2589
        struct termios new_termios = old_termios;
×
2590
        termios_disable_echo(&new_termios);
×
2591

2592
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
×
2593
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
×
2594

2595
        r = loop_write(output_fd, CSI18_Q, SIZE_MAX);
×
2596
        if (r < 0)
×
2597
                goto finish;
×
2598

2599
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
×
2600
        char buf[STRLEN(CSI18_R1)];
×
2601
        size_t bytes = 0;
×
2602

2603
        for (;;) {
×
2604
                usec_t n = now(CLOCK_MONOTONIC);
×
2605
                if (n >= end) {
×
2606
                        r = -EOPNOTSUPP;
2607
                        break;
2608
                }
2609

2610
                r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2611
                if (r < 0)
×
2612
                        break;
2613
                if (r == 0) {
×
2614
                        r = -EOPNOTSUPP;
2615
                        break;
2616
                }
2617

2618
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2619
                 * read byte by byte, since we don't want to read too much and drop characters from the input
2620
                 * queue. */
2621
                ssize_t l = read(nonblock_input_fd, buf + bytes, bytes == 0 ? STRLEN(CSI18_R0) : 1);
×
2622
                if (l < 0) {
×
2623
                        if (errno == EAGAIN)
×
2624
                                continue;
×
2625
                        r = -errno;
×
2626
                        break;
×
2627
                }
2628

2629
                assert((size_t) l <= sizeof(buf) - bytes);
×
2630
                bytes += l;
×
2631

2632
                r = scan_text_area_size_response(buf, bytes, ret_rows, ret_columns);
×
2633
                if (r != -EAGAIN)
×
2634
                        break;
2635

2636
                if (bytes == sizeof(buf)) {
×
2637
                        r = -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2638
                                          * answer with a terminator in the allotted space. Something is
2639
                                          * wrong, possibly some unrelated bytes got injected into the
2640
                                          * answer. */
2641
                        break;
2642
                }
2643
        }
2644

2645
finish:
×
2646
        (void) tcsetattr(nonblock_input_fd, TCSANOW, &old_termios);
×
2647
        return r;
×
2648
}
2649

2650
int terminal_fix_size(int input_fd, int output_fd) {
1✔
2651
        unsigned rows, columns;
1✔
2652
        int r;
1✔
2653

2654
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences.
2655
         *
2656
         * Why bother with this? The ioctl() information is often incorrect on serial terminals (since
2657
         * there's no handshake or protocol to determine the right dimensions in RS232), but since the ANSI
2658
         * sequences are interpreted by the final terminal instead of an intermediary tty driver they should
2659
         * be more accurate.
2660
         */
2661
        r = terminal_verify_same(input_fd, output_fd);
1✔
2662
        if (r < 0)
1✔
2663
                return r;
1✔
2664

2665
        struct winsize ws = {};
×
2666
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
×
2667
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
×
2668

2669
        r = terminal_get_size_by_csi18(input_fd, output_fd, &rows, &columns);
×
2670
        if (IN_SET(r, -EOPNOTSUPP, -EINVAL))
×
2671
                /* We get -EOPNOTSUPP if the query fails and -EINVAL when the received answer is invalid.
2672
                 * Try the fallback method. It is more involved and moves the cursor, but seems to have wider
2673
                 * support. */
2674
                r = terminal_get_size_by_dsr(input_fd, output_fd, &rows, &columns);
×
2675
        if (r < 0)
×
2676
                return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
×
2677

2678
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
2679
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2680
                return 0;
×
2681
        }
2682

2683
        ws.ws_col = columns;
×
2684
        ws.ws_row = rows;
×
2685

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

2689
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2690
        return 1;
2691
}
2692

2693
#define MAX_TERMINFO_LENGTH 64
2694
/* python -c 'print("".join(hex(ord(i))[2:] for i in "name").upper())' */
2695
#define DCS_TERMINFO_Q ANSI_DCS "+q" "6E616D65" ANSI_ST
2696
/* The answer is either 0+r… (invalid) or 1+r… (OK). */
2697
#define DCS_TERMINFO_R0 ANSI_DCS "0+r" ANSI_ST
2698
#define DCS_TERMINFO_R1 ANSI_DCS "1+r" "6E616D65" "=" /* This is followed by Pt ST. */
2699
assert_cc(STRLEN(DCS_TERMINFO_R0) <= STRLEN(DCS_TERMINFO_R1 ANSI_ST));
2700

2701
static int scan_terminfo_response(
×
2702
                const char *buf,
2703
                size_t size,
2704
                char **ret_name) {
2705
        int r;
×
2706

2707
        assert(buf);
×
2708
        assert(ret_name);
×
2709

2710
        /* Check if we have enough space for the shortest possible answer. */
2711
        if (size < STRLEN(DCS_TERMINFO_R0))
×
2712
                return -EAGAIN;
×
2713

2714
        /* Check if the terminating sequence is present */
2715
        if (memcmp(buf + size - STRLEN(ANSI_ST), ANSI_ST, STRLEN(ANSI_ST)) != 0)
×
2716
                return -EAGAIN;
2717

2718
        if (size <= STRLEN(DCS_TERMINFO_R1 ANSI_ST))
×
2719
                return -EINVAL;  /* The answer is invalid or empty */
2720

2721
        if (memcmp(buf, DCS_TERMINFO_R1, STRLEN(DCS_TERMINFO_R1)) != 0)
×
2722
                return -EINVAL;  /* The answer is not valid */
2723

2724
        _cleanup_free_ void *dec = NULL;
×
2725
        size_t dec_size;
×
2726
        r = unhexmem_full(buf + STRLEN(DCS_TERMINFO_R1), size - STRLEN(DCS_TERMINFO_R1 ANSI_ST),
×
2727
                          /* secure= */ false,
2728
                          &dec, &dec_size);
2729
        if (r < 0)
×
2730
                return r;
2731

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

2736
        *ret_name = TAKE_PTR(dec);
×
2737
        return 0;
×
2738
}
2739

2740
int terminal_get_terminfo_by_dcs(int fd, char **ret_name) {
2✔
2741
        int r;
2✔
2742

2743
        assert(fd >= 0);
2✔
2744
        assert(ret_name);
2✔
2745

2746
        /* Note: fd must be in non-blocking read-write mode! */
2747

2748
        struct termios old_termios;
2✔
2749
        if (tcgetattr(fd, &old_termios) < 0)
2✔
2750
                return -errno;
1✔
2751

2752
        struct termios new_termios = old_termios;
1✔
2753
        termios_disable_echo(&new_termios);
1✔
2754

2755
        if (tcsetattr(fd, TCSANOW, &new_termios) < 0)
1✔
2756
                return -errno;
×
2757

2758
        r = loop_write(fd, DCS_TERMINFO_Q, SIZE_MAX);
1✔
2759
        if (r < 0)
1✔
2760
                goto finish;
×
2761

2762
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_REPLY_WAIT_USEC);
1✔
2763
        char buf[STRLEN(DCS_TERMINFO_R1) + MAX_TERMINFO_LENGTH + STRLEN(ANSI_ST)];
1✔
2764
        size_t bytes = 0;
1✔
2765

2766
        for (;;) {
1✔
2767
                usec_t n = now(CLOCK_MONOTONIC);
1✔
2768
                if (n >= end) {
1✔
2769
                        r = -EOPNOTSUPP;
2770
                        break;
2771
                }
2772

2773
                r = fd_wait_for_event(fd, POLLIN, usec_sub_unsigned(end, n));
2✔
2774
                if (r < 0)
1✔
2775
                        break;
2776
                if (r == 0) {
1✔
2777
                        r = -EOPNOTSUPP;
2778
                        break;
2779
                }
2780

2781
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2782
                 * read byte by byte, since we don't want to read too much and drop characters from the input
2783
                 * queue. */
2784
                ssize_t l = read(fd, buf + bytes, bytes == 0 ? STRLEN(DCS_TERMINFO_R0) : 1);
×
2785
                if (l < 0) {
×
2786
                        if (errno == EAGAIN)
×
2787
                                continue;
×
2788
                        r = -errno;
×
2789
                        break;
×
2790
                }
2791

2792
                assert((size_t) l <= sizeof(buf) - bytes);
×
2793
                bytes += l;
×
2794

2795
                r = scan_terminfo_response(buf, bytes, ret_name);
×
2796
                if (r != -EAGAIN)
×
2797
                        break;
2798

2799
                if (bytes == sizeof(buf)) {
×
2800
                        r = -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2801
                                          * answer with a terminator in the allotted space. Something is
2802
                                          * wrong, possibly some unrelated bytes got injected into the
2803
                                          * answer. */
2804
                        break;
2805
                }
2806
        }
2807

2808
finish:
×
2809
        (void) tcsetattr(fd, TCSANOW, &old_termios);
1✔
2810
        return r;
1✔
2811
}
2812

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

2818
        assert(filename_is_valid(name));
5✔
2819

2820
        _cleanup_free_ char *p = path_join("/usr/share/terminfo", CHAR_TO_STR(name[0]), name);
10✔
2821
        if (!p)
5✔
2822
                return log_oom_debug();
×
2823

2824
        r = RET_NERRNO(access(p, F_OK));
5✔
2825
        if (r == -ENOENT)
1✔
2826
                return false;
2827
        if (r < 0)
4✔
2828
                return r;
×
2829
        return true;
2830
}
2831

2832
int query_term_for_tty(const char *tty, char **ret_term) {
49✔
2833
        _cleanup_free_ char *dcs_term = NULL;
49✔
2834
        int r;
49✔
2835

2836
        assert(tty);
49✔
2837
        assert(ret_term);
49✔
2838

2839
        if (tty_is_vc_resolve(tty))
49✔
2840
                return strdup_to(ret_term, "linux");
46✔
2841

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

2845
        _cleanup_close_ int tty_fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
52✔
2846
        if (tty_fd < 0)
3✔
2847
                return log_debug_errno(tty_fd, "Failed to open %s to query terminfo: %m", tty);
2✔
2848

2849
        r = terminal_get_terminfo_by_dcs(tty_fd, &dcs_term);
1✔
2850
        if (r < 0)
1✔
2851
                return log_debug_errno(r, "Failed to query %s for terminfo: %m", tty);
1✔
2852

2853
        r = have_terminfo_file(dcs_term);
×
2854
        if (r < 0)
×
2855
                return log_debug_errno(r, "Failed to look for terminfo %s: %m", dcs_term);
×
2856
        if (r == 0)
×
2857
                return log_info_errno(SYNTHETIC_ERRNO(ENODATA),
×
2858
                                      "Terminfo %s not found for %s.", dcs_term, tty);
2859

2860
        *ret_term = TAKE_PTR(dcs_term);
×
2861
        return 0;
×
2862
}
2863

2864
int terminal_is_pty_fd(int fd) {
3✔
2865
        int r;
3✔
2866

2867
        assert(fd >= 0);
3✔
2868

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

2871
        if (!isatty_safe(fd))
3✔
2872
                return false;
3✔
2873

2874
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2✔
2875
        if (r != 0)
2✔
2876
                return r;
2877

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

2881
        int v;
×
2882
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
×
2883
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
2884
                        return false;
2885

2886
                return -errno;
×
2887
        }
2888

2889
        return true;
2890
}
2891

2892
int pty_open_peer(int fd, int mode) {
27✔
2893
        assert(fd >= 0);
27✔
2894

2895
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2896
         *
2897
         * This is safe to be called on TTYs from other namespaces. */
2898

2899
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
27✔
2900

2901
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
2902
        for (unsigned c = 0;; c++) {
×
2903
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
27✔
2904
                if (peer_fd >= 0)
27✔
2905
                        return peer_fd;
2906

2907
                if (errno != EIO)
×
2908
                        return -errno;
×
2909

2910
                /* Max 1s in total */
2911
                if (c >= 20)
×
2912
                        return -EIO;
2913

2914
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2915
        }
2916
}
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