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

systemd / systemd / 13380515387

17 Feb 2025 09:20PM UTC coverage: 71.822% (+0.1%) from 71.714%
13380515387

push

github

DaanDeMeyer
ukify: print all remaining log-like output to stderr

We want to be able to capture stdout for json and such, so convert
all remaining logging to stderr.

293883 of 409184 relevant lines covered (71.82%)

716959.33 hits per line

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

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

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

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

56
static volatile unsigned cached_columns = 0;
57
static volatile unsigned cached_lines = 0;
58

59
static volatile int cached_on_tty = -1;
60
static volatile int cached_on_dev_null = -1;
61
static volatile int cached_color_mode = _COLOR_MODE_INVALID;
62
static volatile int cached_underline_enabled = -1;
63

64
bool isatty_safe(int fd) {
6,699,543✔
65
        assert(fd >= 0);
6,699,543✔
66

67
        if (isatty(fd))
6,699,543✔
68
                return true;
69

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

76
        /* Be resilient if we're working on stdio, since they're set up by parent process. */
77
        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
6,660,526✔
78

79
        return false;
80
}
81

82
int chvt(int vt) {
×
83
        _cleanup_close_ int fd = -EBADF;
×
84

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

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

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

98
                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
×
99
                        return -errno;
×
100

101
                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
×
102
        }
103

104
        return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
×
105
}
106

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

112
        assert(ret);
10✔
113

114
        if (!f)
10✔
115
                f = stdin;
×
116

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

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

129
                if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
×
130
                        char c;
×
131

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

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

146
                        if (need_nl)
×
147
                                *need_nl = c != '\n';
×
148

149
                        *ret = c;
×
150
                        return 0;
×
151
                }
152
        }
153

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

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

164
        /* If this is not a terminal, then read a full line instead */
165

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

172
        if (strlen(line) != 1)
8✔
173
                return -EBADMSG;
174

175
        if (need_nl)
1✔
176
                *need_nl = false;
1✔
177

178
        *ret = line[0];
1✔
179
        return 0;
1✔
180
}
181

182
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
183

184
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
×
185
        int r;
×
186

187
        assert(ret);
×
188
        assert(replies);
×
189
        assert(fmt);
×
190

191
        for (;;) {
×
192
                va_list ap;
×
193
                char c;
×
194
                bool need_nl = true;
×
195

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

198
                putchar('\r');
×
199

200
                va_start(ap, fmt);
×
201
                vprintf(fmt, ap);
×
202
                va_end(ap);
×
203

204
                fputs(ansi_normal(), stdout);
×
205

206
                fflush(stdout);
×
207

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

211
                        if (r == -ETIMEDOUT)
×
212
                                continue;
×
213

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

219
                        putchar('\n');
×
220
                        return r;
×
221
                }
222

223
                if (need_nl)
×
224
                        putchar('\n');
×
225

226
                if (strchr(replies, c)) {
×
227
                        *ret = c;
×
228
                        return 0;
×
229
                }
230

231
                puts("Read unexpected character, please try again.");
×
232
        }
233
}
234

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

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

249
        string = strempty(string);
×
250

251
        STRV_FOREACH(c, completions) {
×
252

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

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

263
                        continue;
×
264
                }
265

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

272
                found[n] = 0;
×
273
                partial = true;
×
274
        }
275

276
        *ret = TAKE_PTR(found);
×
277

278
        if (!*ret)
×
279
                return COMPLETION_NONE;
280
        if (partial)
×
281
                return COMPLETION_PARTIAL;
282

283
        return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
×
284
}
285

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

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

298
        va_list ap;
7✔
299
        int r;
7✔
300

301
        assert(ret);
7✔
302
        assert(text);
7✔
303

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

312
        _cleanup_free_ char *string = NULL;
7✔
313
        size_t n = 0;
7✔
314

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

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

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

333
        for (;;) {
×
334
                int c = fgetc(stdin);
×
335

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

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

346
                if (c == '\t') {
×
347
                        /* Tab */
348

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

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

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

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

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

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

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

403
                } else if (IN_SET(c, '\b', 127)) {
×
404
                        /* Backspace */
405

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

411
                                char *e = string + n - m;
×
412
                                clear_by_backspace(utf8_console_width(e));
×
413

414
                                *e = 0;
×
415
                                n -= m;
×
416
                        }
417

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

421
                        clear_by_backspace(utf8_console_width(string));
×
422
                        string[n = 0] = 0;
×
423

424
                } else if (c == 4) {
×
425
                        /* Ctrl-d → cancel this field input */
426

427
                        r = -ECANCELED;
×
428
                        goto fail;
×
429

430
                } else if (char_is_cc(c) || n >= LINE_MAX)
×
431
                        /* refuse control characters and too long strings */
432
                        fputc('\a', stdout); /* BEL */
×
433
                else {
434
                        /* Regular char */
435

436
                        if (!GREEDY_REALLOC(string, n+2)) {
×
437
                                r = -ENOMEM;
×
438
                                goto fail;
×
439
                        }
440

441
                        string[n++] = (char) c;
×
442
                        string[n] = 0;
×
443

444
                        fputc(c, stdout);
×
445
                }
446

447
                fflush(stdout);
×
448
        }
449

450
        if (tcsetattr(fd_input, TCSADRAIN, &old_termios) < 0)
×
451
                return -errno;
×
452

453
        if (!string) {
×
454
                string = strdup("");
×
455
                if (!string)
×
456
                        return -ENOMEM;
457
        }
458

459
        *ret = TAKE_PTR(string);
×
460
        return 0;
×
461

462
fail:
×
463
        (void) tcsetattr(fd_input, TCSADRAIN, &old_termios);
×
464
        return r;
×
465

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

474
        *ret = TAKE_PTR(string);
7✔
475
        return 0;
7✔
476
}
477

478
bool any_key_to_proceed(void) {
6✔
479

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

484
        fputc('\n', stdout);
6✔
485
        fputs(ansi_highlight_magenta(), stdout);
12✔
486
        fputs("-- Press any key to proceed --", stdout);
6✔
487
        fputs(ansi_normal(), stdout);
12✔
488
        fflush(stdout);
6✔
489

490
        char key = 0;
6✔
491
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
6✔
492

493
        fputc('\n', stdout);
6✔
494
        fputc('\n', stdout);
6✔
495
        fflush(stdout);
6✔
496

497
        return key != 'q';
6✔
498
}
499

500
static size_t widest_list_element(char *const*l) {
×
501
        size_t w = 0;
×
502

503
        /* Returns the largest console width of all elements in 'l' */
504

505
        STRV_FOREACH(i, l)
×
506
                w = MAX(w, utf8_console_width(*i));
×
507

508
        return w;
×
509
}
510

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

518
        assert(n_columns > 0);
×
519

520
        if (n_columns == SIZE_MAX)
×
521
                n_columns = 3;
×
522

523
        if (column_width == SIZE_MAX) {
×
524
                size_t widest = widest_list_element(x);
×
525

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

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

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

538
                        if (with_numbers && column_max > 6)
×
539
                                column_max -= 6;
×
540
                }
541

542
                column_width = CLAMP(widest+1, 10U, column_max);
×
543
        }
544

545
        size_t n = strv_length(x);
×
546
        size_t per_column = DIV_ROUND_UP(n, n_columns);
×
547

548
        size_t break_lines = lines();
×
549
        if (break_lines > 2)
×
550
                break_lines--;
×
551

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

558
        for (size_t i = 0; i < per_column; i++) {
×
559

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

563
                        if (j * per_column + i >= n)
×
564
                                break;
565

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

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

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

588
                putchar('\n');
×
589

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

596
        return 0;
597
}
598

599
int open_terminal(const char *name, int mode) {
49,890✔
600
        _cleanup_close_ int fd = -EBADF;
49,890✔
601

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

610
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
49,890✔
611

612
        for (unsigned c = 0;; c++) {
×
613
                fd = open(name, mode, 0);
49,890✔
614
                if (fd >= 0)
49,890✔
615
                        break;
616

617
                if (errno != EIO)
13,108✔
618
                        return -errno;
13,108✔
619

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

624
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
625
        }
626

627
        if (!isatty_safe(fd))
36,782✔
628
                return -ENOTTY;
×
629

630
        return TAKE_FD(fd);
631
}
632

633
int acquire_terminal(
354✔
634
                const char *name,
635
                AcquireTerminalFlags flags,
636
                usec_t timeout) {
637

638
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
354✔
639
        usec_t ts = USEC_INFINITY;
354✔
640
        int r, wd = -1;
354✔
641

642
        assert(name);
354✔
643
        assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
354✔
644

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

654
        if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
354✔
655
                notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
708✔
656
                if (notify < 0)
354✔
657
                        return -errno;
×
658

659
                wd = inotify_add_watch(notify, name, IN_CLOSE);
354✔
660
                if (wd < 0)
354✔
661
                        return -errno;
×
662

663
                if (timeout != USEC_INFINITY)
354✔
664
                        ts = now(CLOCK_MONOTONIC);
354✔
665
        }
666

667
        for (;;) {
354✔
668
                if (notify >= 0) {
354✔
669
                        r = flush_fd(notify);
354✔
670
                        if (r < 0)
354✔
671
                                return r;
×
672
                }
673

674
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
675
                 * to figure out if we successfully became the controlling process of the tty */
676
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
354✔
677
                if (fd < 0)
354✔
678
                        return fd;
679

680
                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
681
                struct sigaction sa_old;
354✔
682
                assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
354✔
683

684
                /* First, try to get the tty */
685
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE));
354✔
686

687
                /* Reset signal handler to old value */
688
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
354✔
689

690
                /* Success? Exit the loop now! */
691
                if (r >= 0)
354✔
692
                        break;
693

694
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
695
                if (r != -EPERM)
×
696
                        return r;
697

698
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
×
699
                                                          * into a success. Note that EPERM is also returned if we
700
                                                          * already are the owner of the TTY. */
701
                        break;
702

703
                if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
×
704
                        return r;
705

706
                assert(notify >= 0);
×
707
                assert(wd >= 0);
×
708

709
                for (;;) {
×
710
                        union inotify_event_buffer buffer;
×
711
                        ssize_t l;
×
712

713
                        if (timeout != USEC_INFINITY) {
×
714
                                usec_t n;
×
715

716
                                assert(ts != USEC_INFINITY);
×
717

718
                                n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
719
                                if (n >= timeout)
×
720
                                        return -ETIMEDOUT;
×
721

722
                                r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
×
723
                                if (r < 0)
×
724
                                        return r;
725
                                if (r == 0)
×
726
                                        return -ETIMEDOUT;
727
                        }
728

729
                        l = read(notify, &buffer, sizeof(buffer));
×
730
                        if (l < 0) {
×
731
                                if (ERRNO_IS_TRANSIENT(errno))
×
732
                                        continue;
×
733

734
                                return -errno;
×
735
                        }
736

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

741
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
×
742
                                        return -EIO;
×
743
                        }
744

745
                        break;
×
746
                }
747

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

753
        return TAKE_FD(fd);
354✔
754
}
755

756
int release_terminal(void) {
117✔
757
        _cleanup_close_ int fd = -EBADF;
117✔
758
        int r;
117✔
759

760
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
117✔
761
        if (fd < 0)
117✔
762
                return -errno;
96✔
763

764
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
765
         * by our own TIOCNOTTY */
766
        struct sigaction sa_old;
21✔
767
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
21✔
768

769
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
21✔
770

771
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
21✔
772

773
        return r;
774
}
775

776
int terminal_new_session(void) {
5✔
777

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

785
        if (!isatty_safe(STDIN_FILENO))
5✔
786
                return -ENXIO;
787

788
        (void) setsid();
4✔
789
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
4✔
790
}
791

792
int terminal_vhangup_fd(int fd) {
165✔
793
        assert(fd >= 0);
165✔
794
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
165✔
795
}
796

797
int terminal_vhangup(const char *tty) {
×
798
        _cleanup_close_ int fd = -EBADF;
×
799

800
        assert(tty);
×
801

802
        fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
×
803
        if (fd < 0)
×
804
                return fd;
805

806
        return terminal_vhangup_fd(fd);
×
807
}
808

809
int vt_disallocate(const char *tty_path) {
89✔
810
        assert(tty_path);
89✔
811

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

815
        int ttynr = vtnr_from_tty(tty_path);
89✔
816
        if (ttynr > 0) {
89✔
817
                _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
89✔
818
                if (fd < 0)
89✔
819
                        return fd;
820

821
                /* Try to deallocate */
822
                if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
89✔
823
                        return 0;
824
                if (errno != EBUSY)
89✔
825
                        return -errno;
×
826
        }
827

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

831
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
178✔
832
        if (fd2 < 0)
89✔
833
                return fd2;
834

835
        return loop_write_full(fd2,
89✔
836
                               "\033[r"   /* clear scrolling region */
837
                               "\033[H"   /* move home */
838
                               "\033[3J"  /* clear screen including scrollback, requires Linux 2.6.40 */
839
                               "\033c",   /* reset to initial state */
840
                               SIZE_MAX,
841
                               100 * USEC_PER_MSEC);
842
}
843

844
static int vt_default_utf8(void) {
820✔
845
        _cleanup_free_ char *b = NULL;
820✔
846
        int r;
820✔
847

848
        /* Read the default VT UTF8 setting from the kernel */
849

850
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
820✔
851
        if (r < 0)
820✔
852
                return r;
853

854
        return parse_boolean(b);
500✔
855
}
856

857
static int vt_reset_keyboard(int fd) {
410✔
858
        int r, kb;
410✔
859

860
        assert(fd >= 0);
410✔
861

862
        /* If we can't read the default, then default to Unicode. It's 2024 after all. */
863
        r = vt_default_utf8();
410✔
864
        if (r < 0)
410✔
865
                log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
160✔
866

867
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
410✔
868
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
410✔
869
}
870

871
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
410✔
872
        struct termios termios;
410✔
873
        int r;
410✔
874

875
        /* Set terminal to some sane defaults */
876

877
        assert(fd >= 0);
410✔
878

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

882
        /* Disable exclusive mode, just in case */
883
        if (ioctl(fd, TIOCNXCL) < 0)
410✔
884
                log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
4✔
885

886
        /* Switch to text mode */
887
        if (switch_to_text)
410✔
888
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
170✔
889
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
81✔
890

891
        /* Set default keyboard mode */
892
        r = vt_reset_keyboard(fd);
410✔
893
        if (r < 0)
410✔
894
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
235✔
895

896
        if (tcgetattr(fd, &termios) < 0) {
410✔
897
                r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
4✔
898
                goto finish;
4✔
899
        }
900

901
        /* We only reset the stuff that matters to the software. How
902
         * hardware is set up we don't touch assuming that somebody
903
         * else will do that for us */
904

905
        termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
406✔
906
        termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
406✔
907
        termios.c_oflag |= ONLCR | OPOST;
406✔
908
        termios.c_cflag |= CREAD;
406✔
909
        termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
406✔
910

911
        termios.c_cc[VINTR]    =   03;  /* ^C */
406✔
912
        termios.c_cc[VQUIT]    =  034;  /* ^\ */
406✔
913
        termios.c_cc[VERASE]   = 0177;
406✔
914
        termios.c_cc[VKILL]    =  025;  /* ^X */
406✔
915
        termios.c_cc[VEOF]     =   04;  /* ^D */
406✔
916
        termios.c_cc[VSTART]   =  021;  /* ^Q */
406✔
917
        termios.c_cc[VSTOP]    =  023;  /* ^S */
406✔
918
        termios.c_cc[VSUSP]    =  032;  /* ^Z */
406✔
919
        termios.c_cc[VLNEXT]   =  026;  /* ^V */
406✔
920
        termios.c_cc[VWERASE]  =  027;  /* ^W */
406✔
921
        termios.c_cc[VREPRINT] =  022;  /* ^R */
406✔
922
        termios.c_cc[VEOL]     =    0;
406✔
923
        termios.c_cc[VEOL2]    =    0;
406✔
924

925
        termios.c_cc[VTIME]  = 0;
406✔
926
        termios.c_cc[VMIN]   = 1;
406✔
927

928
        r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
406✔
929
        if (r < 0)
×
930
                log_debug_errno(r, "Failed to set terminal parameters: %m");
×
931

932
finish:
×
933
        /* Just in case, flush all crap out */
934
        (void) tcflush(fd, TCIOFLUSH);
410✔
935

936
        return r;
410✔
937
}
938

939
static int terminal_reset_ansi_seq(int fd) {
260✔
940
        int r, k;
260✔
941

942
        assert(fd >= 0);
260✔
943

944
        if (getenv_terminal_is_dumb())
260✔
945
                return 0;
946

947
        r = fd_nonblock(fd, true);
×
948
        if (r < 0)
×
949
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
950

951
        k = loop_write_full(fd,
×
952
                            "\033[!p"      /* soft terminal reset */
953
                            "\033]104\007" /* reset colors */
954
                            "\033[?7h",    /* enable line-wrapping */
955
                            SIZE_MAX,
956
                            100 * USEC_PER_MSEC);
957
        if (k < 0)
×
958
                log_debug_errno(k, "Failed to reset terminal through ANSI sequences: %m");
×
959

960
        if (r > 0) {
×
961
                r = fd_nonblock(fd, false);
×
962
                if (r < 0)
×
963
                        log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
×
964
        }
965

966
        return k < 0 ? k : r;
×
967
}
968

969
void reset_dev_console_fd(int fd, bool switch_to_text) {
85✔
970
        int r;
85✔
971

972
        assert(fd >= 0);
85✔
973

974
        _cleanup_close_ int lock_fd = lock_dev_console();
85✔
975
        if (lock_fd < 0)
85✔
976
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
977

978
        r = terminal_reset_ioctl(fd, switch_to_text);
85✔
979
        if (r < 0)
85✔
980
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
×
981

982
        unsigned rows, cols;
85✔
983
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
85✔
984
        if (r < 0)
85✔
985
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
×
986
        else if (r > 0) {
85✔
987
                r = terminal_set_size_fd(fd, NULL, rows, cols);
85✔
988
                if (r < 0)
85✔
989
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
×
990
        } else
991
                (void) terminal_fix_size(fd, fd);
×
992

993
        r = terminal_reset_ansi_seq(fd);
85✔
994
        if (r < 0)
85✔
995
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
85✔
996
}
85✔
997

998
int lock_dev_console(void) {
1,045✔
999
        _cleanup_close_ int fd = -EBADF;
1,045✔
1000
        int r;
1,045✔
1001

1002
        /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
1003
         * pty in /dev/console, in which case it should be fine to lock the target TTY. */
1004
        fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1,045✔
1005
        if (fd < 0)
1,045✔
1006
                return fd;
1007

1008
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
1,045✔
1009
        if (r < 0)
1,045✔
1010
                return r;
×
1011

1012
        return TAKE_FD(fd);
1013
}
1014

1015
int make_console_stdio(void) {
×
1016
        int fd, r;
×
1017

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

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

1026
                r = make_null_stdio();
×
1027
                if (r < 0)
×
1028
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
×
1029

1030
        } else {
1031
                reset_dev_console_fd(fd, /* switch_to_text= */ true);
×
1032

1033
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
×
1034
                if (r < 0)
×
1035
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
×
1036
        }
1037

1038
        reset_terminal_feature_caches();
×
1039
        return 0;
×
1040
}
1041

1042
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
225✔
1043
        assert(tty);
225✔
1044

1045
        tty = skip_dev_prefix(tty);
225✔
1046

1047
        const char *e = startswith(tty, "tty");
225✔
1048
        if (!e)
225✔
1049
                return -EINVAL;
1050

1051
        return safe_atou(e, ret);
184✔
1052
}
1053

1054
int vtnr_from_tty(const char *tty) {
138✔
1055
        unsigned u;
138✔
1056
        int r;
138✔
1057

1058
        assert(tty);
138✔
1059

1060
        r = vtnr_from_tty_raw(tty, &u);
138✔
1061
        if (r < 0)
138✔
1062
                return r;
138✔
1063
        if (!vtnr_is_valid(u))
138✔
1064
                return -ERANGE;
1065

1066
        return (int) u;
138✔
1067
}
1068

1069
bool tty_is_vc(const char *tty) {
87✔
1070
        assert(tty);
87✔
1071

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

1077
        return vtnr_from_tty_raw(tty, /* ret = */ NULL) >= 0;
87✔
1078
}
1079

1080
bool tty_is_console(const char *tty) {
35✔
1081
        assert(tty);
35✔
1082

1083
        return streq(skip_dev_prefix(tty), "console");
35✔
1084
}
1085

1086
int resolve_dev_console(char **ret) {
26✔
1087
        int r;
26✔
1088

1089
        assert(ret);
26✔
1090

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

1096
        _cleanup_free_ char *chased = NULL;
26✔
1097
        r = chase("/dev/console", /* root= */ NULL, /* chase_flags= */ 0,  &chased, /* ret_fd= */ NULL);
26✔
1098
        if (r < 0)
26✔
1099
                return r;
1100
        if (!path_equal(chased, "/dev/console")) {
26✔
1101
                *ret = TAKE_PTR(chased);
2✔
1102
                return 0;
2✔
1103
        }
1104

1105
        r = path_is_read_only_fs("/sys");
24✔
1106
        if (r < 0)
24✔
1107
                return r;
1108
        if (r > 0)
24✔
1109
                return -ENOMEDIUM;
1110

1111
        _cleanup_free_ char *active = NULL;
24✔
1112
        r = read_one_line_file("/sys/class/tty/console/active", &active);
24✔
1113
        if (r < 0)
24✔
1114
                return r;
1115

1116
        /* If multiple log outputs are configured the last one is what /dev/console points to */
1117
        const char *tty = strrchr(active, ' ');
24✔
1118
        if (tty)
24✔
1119
                tty++;
×
1120
        else
1121
                tty = active;
1122

1123
        if (streq(tty, "tty0")) {
24✔
1124
                active = mfree(active);
×
1125

1126
                /* Get the active VC (e.g. tty1) */
1127
                r = read_one_line_file("/sys/class/tty/tty0/active", &active);
×
1128
                if (r < 0)
×
1129
                        return r;
1130

1131
                tty = active;
×
1132
        }
1133

1134
        if (tty != active)
24✔
1135
                return strdup_to(ret, tty);
×
1136

1137
        *ret = TAKE_PTR(active);
24✔
1138
        return 0;
24✔
1139
}
1140

1141
int get_kernel_consoles(char ***ret) {
1✔
1142
        _cleanup_strv_free_ char **l = NULL;
×
1143
        _cleanup_free_ char *line = NULL;
1✔
1144
        int r;
1✔
1145

1146
        assert(ret);
1✔
1147

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

1153
        r = read_one_line_file("/sys/class/tty/console/active", &line);
×
1154
        if (r < 0)
×
1155
                return r;
1156

1157
        for (const char *p = line;;) {
×
1158
                _cleanup_free_ char *tty = NULL, *path = NULL;
×
1159

1160
                r = extract_first_word(&p, &tty, NULL, 0);
×
1161
                if (r < 0)
×
1162
                        return r;
1163
                if (r == 0)
×
1164
                        break;
1165

1166
                if (streq(tty, "tty0")) {
×
1167
                        tty = mfree(tty);
×
1168
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
1169
                        if (r < 0)
×
1170
                                return r;
1171
                }
1172

1173
                path = path_join("/dev", tty);
×
1174
                if (!path)
×
1175
                        return -ENOMEM;
1176

1177
                if (access(path, F_OK) < 0) {
×
1178
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
×
1179
                        continue;
×
1180
                }
1181

1182
                r = strv_consume(&l, TAKE_PTR(path));
×
1183
                if (r < 0)
×
1184
                        return r;
1185
        }
1186

1187
        if (strv_isempty(l)) {
×
1188
                log_debug("No devices found for system console");
×
1189
                goto fallback;
×
1190
        }
1191

1192
        *ret = TAKE_PTR(l);
×
1193
        return strv_length(*ret);
×
1194

1195
fallback:
1✔
1196
        r = strv_extend(&l, "/dev/console");
1✔
1197
        if (r < 0)
1✔
1198
                return r;
1199

1200
        *ret = TAKE_PTR(l);
1✔
1201
        return 0;
1✔
1202
}
1203

1204
bool tty_is_vc_resolve(const char *tty) {
52✔
1205
        _cleanup_free_ char *resolved = NULL;
52✔
1206

1207
        assert(tty);
52✔
1208

1209
        tty = skip_dev_prefix(tty);
52✔
1210

1211
        if (streq(tty, "console")) {
52✔
1212
                if (resolve_dev_console(&resolved) < 0)
2✔
1213
                        return false;
1214

1215
                tty = resolved;
2✔
1216
        }
1217

1218
        return tty_is_vc(tty);
52✔
1219
}
1220

1221
const char* default_term_for_tty(const char *tty) {
67✔
1222
        return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
67✔
1223
}
1224

1225
int fd_columns(int fd) {
1,189✔
1226
        struct winsize ws = {};
1,189✔
1227

1228
        if (fd < 0)
1,189✔
1229
                return -EBADF;
1230

1231
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1,189✔
1232
                return -errno;
1,189✔
1233

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

1237
        return ws.ws_col;
×
1238
}
1239

1240
int getenv_columns(void) {
1,358✔
1241
        int r;
1,358✔
1242

1243
        const char *e = getenv("COLUMNS");
1,358✔
1244
        if (!e)
1,358✔
1245
                return -ENXIO;
1,358✔
1246

1247
        unsigned c;
1✔
1248
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
1✔
1249
        if (r < 0)
1✔
1250
                return r;
1251

1252
        return (int) c;
1✔
1253
}
1254

1255
unsigned columns(void) {
178,625✔
1256

1257
        if (cached_columns > 0)
178,625✔
1258
                return cached_columns;
177,435✔
1259

1260
        int c = getenv_columns();
1,190✔
1261
        if (c < 0) {
1,190✔
1262
                c = fd_columns(STDOUT_FILENO);
1,189✔
1263
                if (c < 0)
1,189✔
1264
                        c = 80;
1265
        }
1266

1267
        assert(c > 0);
1✔
1268

1269
        cached_columns = c;
1,190✔
1270
        return cached_columns;
1,190✔
1271
}
1272

1273
int fd_lines(int fd) {
184✔
1274
        struct winsize ws = {};
184✔
1275

1276
        if (fd < 0)
184✔
1277
                return -EBADF;
1278

1279
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
184✔
1280
                return -errno;
184✔
1281

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

1285
        return ws.ws_row;
×
1286
}
1287

1288
unsigned lines(void) {
184✔
1289
        const char *e;
184✔
1290
        int l;
184✔
1291

1292
        if (cached_lines > 0)
184✔
1293
                return cached_lines;
×
1294

1295
        l = 0;
184✔
1296
        e = getenv("LINES");
184✔
1297
        if (e)
184✔
1298
                (void) safe_atoi(e, &l);
×
1299

1300
        if (l <= 0 || l > USHRT_MAX) {
184✔
1301
                l = fd_lines(STDOUT_FILENO);
184✔
1302
                if (l <= 0)
184✔
1303
                        l = 24;
184✔
1304
        }
1305

1306
        cached_lines = l;
184✔
1307
        return cached_lines;
184✔
1308
}
1309

1310
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
1,162✔
1311
        struct winsize ws;
1,162✔
1312

1313
        assert(fd >= 0);
1,162✔
1314

1315
        if (!ident)
1,162✔
1316
                ident = "TTY";
115✔
1317

1318
        if (rows == UINT_MAX && cols == UINT_MAX)
1,162✔
1319
                return 0;
1,162✔
1320

1321
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
957✔
1322
                return log_debug_errno(errno,
×
1323
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1324
                                       ident);
1325

1326
        if (rows == UINT_MAX)
957✔
1327
                rows = ws.ws_row;
×
1328
        else if (rows > USHRT_MAX)
957✔
1329
                rows = USHRT_MAX;
×
1330

1331
        if (cols == UINT_MAX)
957✔
1332
                cols = ws.ws_col;
×
1333
        else if (cols > USHRT_MAX)
957✔
1334
                cols = USHRT_MAX;
×
1335

1336
        if (rows == ws.ws_row && cols == ws.ws_col)
957✔
1337
                return 0;
1338

1339
        ws.ws_row = rows;
424✔
1340
        ws.ws_col = cols;
424✔
1341

1342
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
424✔
1343
                return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
×
1344

1345
        return 0;
1346
}
1347

1348
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
1,132✔
1349
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
1,132✔
1350
        unsigned rows = UINT_MAX, cols = UINT_MAX;
1,132✔
1351
        int r;
1,132✔
1352

1353
        assert(tty);
1,132✔
1354

1355
        if (!ret_rows && !ret_cols)
1,132✔
1356
                return 0;
1357

1358
        tty = skip_dev_prefix(tty);
1,132✔
1359
        if (path_startswith(tty, "pts/"))
1,132✔
1360
                return -EMEDIUMTYPE;
1361
        if (!in_charset(tty, ALPHANUMERICAL))
1,132✔
1362
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
×
1363
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1364

1365
        rowskey = strjoin("systemd.tty.rows.", tty);
1,132✔
1366
        if (!rowskey)
1,132✔
1367
                return -ENOMEM;
1368

1369
        colskey = strjoin("systemd.tty.columns.", tty);
1,132✔
1370
        if (!colskey)
1,132✔
1371
                return -ENOMEM;
1372

1373
        r = proc_cmdline_get_key_many(/* flags = */ 0,
1,132✔
1374
                                      rowskey, &rowsvalue,
1375
                                      colskey, &colsvalue);
1376
        if (r < 0)
1,132✔
1377
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
×
1378

1379
        if (rowsvalue) {
1,132✔
1380
                r = safe_atou(rowsvalue, &rows);
957✔
1381
                if (r < 0)
957✔
1382
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
×
1383
        }
1384

1385
        if (colsvalue) {
1,132✔
1386
                r = safe_atou(colsvalue, &cols);
957✔
1387
                if (r < 0)
957✔
1388
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
×
1389
        }
1390

1391
        if (ret_rows)
1,132✔
1392
                *ret_rows = rows;
1,132✔
1393
        if (ret_cols)
1,132✔
1394
                *ret_cols = cols;
1,132✔
1395

1396
        return rows != UINT_MAX || cols != UINT_MAX;
1,132✔
1397
}
1398

1399
/* intended to be used as a SIGWINCH sighandler */
1400
void columns_lines_cache_reset(int signum) {
×
1401
        cached_columns = 0;
×
1402
        cached_lines = 0;
×
1403
}
×
1404

1405
void reset_terminal_feature_caches(void) {
14✔
1406
        cached_columns = 0;
14✔
1407
        cached_lines = 0;
14✔
1408

1409
        cached_color_mode = _COLOR_MODE_INVALID;
14✔
1410
        cached_underline_enabled = -1;
14✔
1411
        cached_on_tty = -1;
14✔
1412
        cached_on_dev_null = -1;
14✔
1413
}
14✔
1414

1415
bool on_tty(void) {
7,318,473✔
1416

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

1423
        if (cached_on_tty < 0)
7,318,473✔
1424
                cached_on_tty =
39,219✔
1425
                        isatty_safe(STDOUT_FILENO) &&
39,234✔
1426
                        isatty_safe(STDERR_FILENO);
15✔
1427

1428
        return cached_on_tty;
7,318,473✔
1429
}
1430

1431
int getttyname_malloc(int fd, char **ret) {
325✔
1432
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
325✔
1433
        int r;
325✔
1434

1435
        assert(fd >= 0);
325✔
1436
        assert(ret);
325✔
1437

1438
        r = ttyname_r(fd, path, sizeof path); /* positive error */
325✔
1439
        assert(r >= 0);
325✔
1440
        if (r == ERANGE)
325✔
1441
                return -ENAMETOOLONG;
325✔
1442
        if (r > 0)
325✔
1443
                return -r;
324✔
1444

1445
        return strdup_to(ret, skip_dev_prefix(path));
1✔
1446
}
1447

1448
int getttyname_harder(int fd, char **ret) {
22✔
1449
        _cleanup_free_ char *s = NULL;
22✔
1450
        int r;
22✔
1451

1452
        r = getttyname_malloc(fd, &s);
22✔
1453
        if (r < 0)
22✔
1454
                return r;
1455

1456
        if (streq(s, "tty"))
×
1457
                return get_ctty(0, NULL, ret);
×
1458

1459
        *ret = TAKE_PTR(s);
×
1460
        return 0;
×
1461
}
1462

1463
int get_ctty_devnr(pid_t pid, dev_t *ret) {
2,466✔
1464
        _cleanup_free_ char *line = NULL;
2,466✔
1465
        unsigned long ttynr;
2,466✔
1466
        const char *p;
2,466✔
1467
        int r;
2,466✔
1468

1469
        assert(pid >= 0);
2,466✔
1470

1471
        p = procfs_file_alloca(pid, "stat");
2,466✔
1472
        r = read_one_line_file(p, &line);
2,466✔
1473
        if (r < 0)
2,466✔
1474
                return r;
1475

1476
        p = strrchr(line, ')');
2,466✔
1477
        if (!p)
2,466✔
1478
                return -EIO;
1479

1480
        p++;
2,466✔
1481

1482
        if (sscanf(p, " "
2,466✔
1483
                   "%*c "  /* state */
1484
                   "%*d "  /* ppid */
1485
                   "%*d "  /* pgrp */
1486
                   "%*d "  /* session */
1487
                   "%lu ", /* ttynr */
1488
                   &ttynr) != 1)
1489
                return -EIO;
1490

1491
        if (devnum_is_zero(ttynr))
2,466✔
1492
                return -ENXIO;
1493

1494
        if (ret)
4✔
1495
                *ret = (dev_t) ttynr;
2✔
1496

1497
        return 0;
1498
}
1499

1500
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
30✔
1501
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
30✔
1502
        _cleanup_free_ char *buf = NULL;
30✔
1503
        const char *fn = NULL, *w;
30✔
1504
        dev_t devnr;
30✔
1505
        int r;
30✔
1506

1507
        r = get_ctty_devnr(pid, &devnr);
30✔
1508
        if (r < 0)
30✔
1509
                return r;
1510

1511
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
2✔
1512
        if (r < 0) {
2✔
1513
                struct stat st;
2✔
1514

1515
                if (r != -ENOENT) /* No symlink for this in /dev/char/? */
2✔
1516
                        return r;
×
1517

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

1526
                if (stat(pty, &st) < 0) {
2✔
1527
                        if (errno != ENOENT)
×
1528
                                return -errno;
×
1529

1530
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
2✔
1531
                        fn = pty;
1532

1533
                if (!fn) {
1534
                        /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1535
                         * symlink in /dev/char/. Let's return something vaguely useful. */
1536
                        r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
×
1537
                        if (r < 0)
×
1538
                                return r;
1539

1540
                        fn = buf;
×
1541
                }
1542
        } else
1543
                fn = buf;
×
1544

1545
        w = path_startswith(fn, "/dev/");
2✔
1546
        if (!w)
2✔
1547
                return -EINVAL;
1548

1549
        if (ret) {
2✔
1550
                r = strdup_to(ret, w);
2✔
1551
                if (r < 0)
2✔
1552
                        return r;
1553
        }
1554

1555
        if (ret_devnr)
2✔
1556
                *ret_devnr = devnr;
×
1557

1558
        return 0;
1559
}
1560

1561
int ptsname_malloc(int fd, char **ret) {
143✔
1562
        size_t l = 100;
143✔
1563

1564
        assert(fd >= 0);
143✔
1565
        assert(ret);
143✔
1566

1567
        for (;;) {
143✔
1568
                char *c;
143✔
1569

1570
                c = new(char, l);
143✔
1571
                if (!c)
143✔
1572
                        return -ENOMEM;
1573

1574
                if (ptsname_r(fd, c, l) == 0) {
143✔
1575
                        *ret = c;
143✔
1576
                        return 0;
143✔
1577
                }
1578
                if (errno != ERANGE) {
×
1579
                        free(c);
×
1580
                        return -errno;
×
1581
                }
1582

1583
                free(c);
×
1584

1585
                if (l > SIZE_MAX / 2)
×
1586
                        return -ENOMEM;
1587

1588
                l *= 2;
×
1589
        }
1590
}
1591

1592
int openpt_allocate(int flags, char **ret_peer_path) {
147✔
1593
        _cleanup_close_ int fd = -EBADF;
147✔
1594
        int r;
147✔
1595

1596
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
147✔
1597
        if (fd < 0)
147✔
1598
                return -errno;
×
1599

1600
        _cleanup_free_ char *p = NULL;
147✔
1601
        if (ret_peer_path) {
147✔
1602
                r = ptsname_malloc(fd, &p);
143✔
1603
                if (r < 0)
143✔
1604
                        return r;
1605

1606
                if (!path_startswith(p, "/dev/pts/"))
143✔
1607
                        return -EINVAL;
1608
        }
1609

1610
        if (unlockpt(fd) < 0)
147✔
1611
                return -errno;
×
1612

1613
        if (ret_peer_path)
147✔
1614
                *ret_peer_path = TAKE_PTR(p);
143✔
1615

1616
        return TAKE_FD(fd);
1617
}
1618

1619
static int ptsname_namespace(int pty, char **ret) {
×
1620
        int no = -1;
×
1621

1622
        assert(pty >= 0);
×
1623
        assert(ret);
×
1624

1625
        /* Like ptsname(), but doesn't assume that the path is
1626
         * accessible in the local namespace. */
1627

1628
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
1629
                return -errno;
×
1630

1631
        if (no < 0)
×
1632
                return -EIO;
1633

1634
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
1635
                return -ENOMEM;
×
1636

1637
        return 0;
1638
}
1639

1640
int openpt_allocate_in_namespace(
×
1641
                const PidRef *pidref,
1642
                int flags,
1643
                char **ret_peer_path) {
1644

1645
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
1646
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
1647
        int r;
×
1648

1649
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
×
1650
        if (r < 0)
×
1651
                return r;
1652

1653
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
1654
                return -errno;
×
1655

1656
        r = namespace_fork(
×
1657
                        "(sd-openptns)",
1658
                        "(sd-openpt)",
1659
                        /* except_fds= */ NULL,
1660
                        /* n_except_fds= */ 0,
1661
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1662
                        pidnsfd,
1663
                        mntnsfd,
1664
                        /* netns_fd= */ -EBADF,
1665
                        usernsfd,
1666
                        rootfd,
1667
                        /* ret_pid= */ NULL);
1668
        if (r < 0)
×
1669
                return r;
1670
        if (r == 0) {
×
1671
                pair[0] = safe_close(pair[0]);
×
1672

1673
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1674
                if (fd < 0)
×
1675
                        _exit(EXIT_FAILURE);
×
1676

1677
                if (send_one_fd(pair[1], fd, 0) < 0)
×
1678
                        _exit(EXIT_FAILURE);
×
1679

1680
                _exit(EXIT_SUCCESS);
×
1681
        }
1682

1683
        pair[1] = safe_close(pair[1]);
×
1684

1685
        fd = receive_one_fd(pair[0], 0);
×
1686
        if (fd < 0)
×
1687
                return fd;
1688

1689
        if (ret_peer_path) {
×
1690
                r = ptsname_namespace(fd, ret_peer_path);
×
1691
                if (r < 0)
×
1692
                        return r;
×
1693
        }
1694

1695
        return TAKE_FD(fd);
1696
}
1697

1698
static bool on_dev_null(void) {
47,494✔
1699
        struct stat dst, ost, est;
47,494✔
1700

1701
        if (cached_on_dev_null >= 0)
47,494✔
1702
                return cached_on_dev_null;
8,355✔
1703

1704
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
39,139✔
1705
                cached_on_dev_null = false;
1✔
1706
        else
1707
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
39,824✔
1708

1709
        return cached_on_dev_null;
39,139✔
1710
}
1711

1712
bool getenv_terminal_is_dumb(void) {
2,868✔
1713
        const char *e;
2,868✔
1714

1715
        e = getenv("TERM");
2,868✔
1716
        if (!e)
2,868✔
1717
                return true;
1718

1719
        return streq(e, "dumb");
1,821✔
1720
}
1721

1722
bool terminal_is_dumb(void) {
47,501✔
1723
        if (!on_tty() && !on_dev_null())
47,501✔
1724
                return true;
1725

1726
        return getenv_terminal_is_dumb();
202✔
1727
}
1728

1729
static const char* const color_mode_table[_COLOR_MODE_MAX] = {
1730
        [COLOR_OFF]   = "off",
1731
        [COLOR_16]    = "16",
1732
        [COLOR_256]   = "256",
1733
        [COLOR_24BIT] = "24bit",
1734
};
1735

1736
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_24BIT);
27✔
1737

1738
static ColorMode parse_systemd_colors(void) {
6,926✔
1739
        const char *e;
6,926✔
1740

1741
        e = getenv("SYSTEMD_COLORS");
6,926✔
1742
        if (!e)
6,926✔
1743
                return _COLOR_MODE_INVALID;
1744

1745
        ColorMode m = color_mode_from_string(e);
13✔
1746
        if (m < 0)
13✔
1747
                return log_debug_errno(m, "Failed to parse $SYSTEMD_COLORS value '%s', ignoring: %m", e);
2✔
1748

1749
        return m;
1750
}
1751

1752
static ColorMode get_color_mode_impl(void) {
6,926✔
1753
        /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1754
         * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors, and COLOR_24BIT for
1755
         * unrestricted color output. */
1756

1757
        /* First, we check $SYSTEMD_COLORS, which is the explicit way to change the mode. */
1758
        ColorMode m = parse_systemd_colors();
6,926✔
1759
        if (m >= 0)
6,926✔
1760
                return m;
1761

1762
        /* Next, check for the presence of $NO_COLOR; value is ignored. */
1763
        if (getenv("NO_COLOR"))
6,915✔
1764
                return COLOR_OFF;
1765

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

1773
        /* We failed to figure out any reason to *disable* colors. Let's see how many colors we shall use. */
1774
        if (STRPTR_IN_SET(getenv("COLORTERM"),
×
1775
                          "truecolor",
1776
                          "24bit"))
1777
                return COLOR_24BIT;
×
1778

1779
        /* Note that the Linux console can only display 16 colors. We still enable 256 color mode
1780
         * even for PID1 output though (which typically goes to the Linux console), since the Linux
1781
         * console is able to parse the 256 color sequences and automatically map them to the closest
1782
         * color in the 16 color palette (since kernel 3.16). Doing 256 colors is nice for people who
1783
         * invoke systemd in a container or via a serial link or such, and use a true 256 color
1784
         * terminal to do so. */
1785
        return COLOR_256;
1786
}
1787

1788
ColorMode get_color_mode(void) {
890,729✔
1789
        if (cached_color_mode < 0)
890,729✔
1790
                cached_color_mode = get_color_mode_impl();
6,926✔
1791

1792
        return cached_color_mode;
890,729✔
1793
}
1794

1795
bool dev_console_colors_enabled(void) {
×
1796
        _cleanup_free_ char *s = NULL;
×
1797
        ColorMode m;
×
1798

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

1806
        m = parse_systemd_colors();
×
1807
        if (m >= 0)
×
1808
                return m;
×
1809

1810
        if (getenv("NO_COLOR"))
×
1811
                return false;
1812

1813
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
1814
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1815

1816
        return !streq_ptr(s, "dumb");
×
1817
}
1818

1819
bool underline_enabled(void) {
420,945✔
1820

1821
        if (cached_underline_enabled < 0) {
420,945✔
1822

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

1825
                if (colors_enabled())
2,623✔
1826
                        cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1✔
1827
                else
1828
                        cached_underline_enabled = false;
2,622✔
1829
        }
1830

1831
        return cached_underline_enabled;
420,945✔
1832
}
1833

1834
int vt_restore(int fd) {
×
1835

1836
        static const struct vt_mode mode = {
×
1837
                .mode = VT_AUTO,
1838
        };
1839

1840
        int r, ret = 0;
×
1841

1842
        assert(fd >= 0);
×
1843

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

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

1850
        r = vt_reset_keyboard(fd);
×
1851
        if (r < 0)
×
1852
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1853

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

1857
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1858
        if (r < 0)
×
1859
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1860

1861
        return ret;
1862
}
1863

1864
int vt_release(int fd, bool restore) {
×
1865
        assert(fd >= 0);
×
1866

1867
        /* This function releases the VT by acknowledging the VT-switch signal
1868
         * sent by the kernel and optionally reset the VT in text and auto
1869
         * VT-switching modes. */
1870

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

1874
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
1875
                return -errno;
×
1876

1877
        if (restore)
×
1878
                return vt_restore(fd);
×
1879

1880
        return 0;
1881
}
1882

1883
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
27,173✔
1884
        /* Note that this will initialize output variables only when there's something to output.
1885
         * The caller must pre-initialize to "" or NULL as appropriate. */
1886

1887
        if (priority <= LOG_ERR) {
27,173✔
1888
                if (on)
839✔
1889
                        *on = ansi_highlight_red();
1,678✔
1890
                if (off)
839✔
1891
                        *off = ansi_normal();
1,678✔
1892
                if (highlight)
839✔
1893
                        *highlight = ansi_highlight();
×
1894

1895
        } else if (priority <= LOG_WARNING) {
26,334✔
1896
                if (on)
654✔
1897
                        *on = ansi_highlight_yellow();
654✔
1898
                if (off)
654✔
1899
                        *off = ansi_normal();
1,308✔
1900
                if (highlight)
654✔
1901
                        *highlight = ansi_highlight();
×
1902

1903
        } else if (priority <= LOG_NOTICE) {
25,680✔
1904
                if (on)
226✔
1905
                        *on = ansi_highlight();
452✔
1906
                if (off)
226✔
1907
                        *off = ansi_normal();
452✔
1908
                if (highlight)
226✔
1909
                        *highlight = ansi_highlight_red();
×
1910

1911
        } else if (priority >= LOG_DEBUG) {
25,454✔
1912
                if (on)
8,793✔
1913
                        *on = ansi_grey();
8,793✔
1914
                if (off)
8,793✔
1915
                        *off = ansi_normal();
17,586✔
1916
                if (highlight)
8,793✔
1917
                        *highlight = ansi_highlight_red();
×
1918
        }
1919
}
27,173✔
1920

1921
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
1922
        assert(fd >= 0);
×
1923

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

1927
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1928
}
1929

1930
int terminal_reset_defensive(int fd, bool switch_to_text) {
332✔
1931
        int r = 0;
332✔
1932

1933
        assert(fd >= 0);
332✔
1934

1935
        /* Resets the terminal comprehensively, but defensively. i.e. both resets the tty via ioctl()s and
1936
         * via ANSI sequences, but avoids the latter in case we are talking to a pty. That's a safety measure
1937
         * because ptys might be connected to shell pipelines where we cannot expect such ansi sequences to
1938
         * work. Given that ptys are generally short-lived (and not recycled) this restriction shouldn't hurt
1939
         * much.
1940
         *
1941
         * The specified fd should be open for *writing*! */
1942

1943
        if (!isatty_safe(fd))
332✔
1944
                return -ENOTTY;
332✔
1945

1946
        RET_GATHER(r, terminal_reset_ioctl(fd, switch_to_text));
325✔
1947

1948
        if (terminal_is_pty_fd(fd) == 0)
325✔
1949
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
175✔
1950

1951
        return r;
1952
}
1953

1954
int terminal_reset_defensive_locked(int fd, bool switch_to_text) {
7✔
1955
        assert(fd >= 0);
7✔
1956

1957
        _cleanup_close_ int lock_fd = lock_dev_console();
7✔
1958
        if (lock_fd < 0)
7✔
1959
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
1960

1961
        return terminal_reset_defensive(fd, switch_to_text);
7✔
1962
}
1963

1964
void termios_disable_echo(struct termios *termios) {
×
1965
        assert(termios);
×
1966

1967
        termios->c_lflag &= ~(ICANON|ECHO);
×
1968
        termios->c_cc[VMIN] = 1;
×
1969
        termios->c_cc[VTIME] = 0;
×
1970
}
×
1971

1972
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1973
        assert(input_fd >= 0);
1✔
1974
        assert(output_fd >= 0);
1✔
1975

1976
        /* Validates that the specified fds reference the same TTY */
1977

1978
        if (input_fd != output_fd) {
1✔
1979
                struct stat sti;
1✔
1980
                if (fstat(input_fd, &sti) < 0)
1✔
1981
                        return -errno;
1✔
1982

1983
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
1984
                        return -ENOTTY;
1985

1986
                struct stat sto;
1✔
1987
                if (fstat(output_fd, &sto) < 0)
1✔
1988
                        return -errno;
×
1989

1990
                if (!S_ISCHR(sto.st_mode))
1✔
1991
                        return -ENOTTY;
1992

1993
                if (sti.st_rdev != sto.st_rdev)
×
1994
                        return -ENOLINK;
1995
        }
1996

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

2000
        return 0;
2001
}
2002

2003
typedef enum BackgroundColorState {
2004
        BACKGROUND_TEXT,
2005
        BACKGROUND_ESCAPE,
2006
        BACKGROUND_BRACKET,
2007
        BACKGROUND_FIRST_ONE,
2008
        BACKGROUND_SECOND_ONE,
2009
        BACKGROUND_SEMICOLON,
2010
        BACKGROUND_R,
2011
        BACKGROUND_G,
2012
        BACKGROUND_B,
2013
        BACKGROUND_RED,
2014
        BACKGROUND_GREEN,
2015
        BACKGROUND_BLUE,
2016
        BACKGROUND_STRING_TERMINATOR,
2017
} BackgroundColorState;
2018

2019
typedef struct BackgroundColorContext {
2020
        BackgroundColorState state;
2021
        uint32_t red, green, blue;
2022
        unsigned red_bits, green_bits, blue_bits;
2023
} BackgroundColorContext;
2024

2025
static int scan_background_color_response(
×
2026
                BackgroundColorContext *context,
2027
                const char *buf,
2028
                size_t size,
2029
                size_t *ret_processed) {
2030

2031
        assert(context);
×
2032
        assert(buf || size == 0);
×
2033

2034
        for (size_t i = 0; i < size; i++) {
×
2035
                char c = buf[i];
×
2036

2037
                switch (context->state) {
×
2038

2039
                case BACKGROUND_TEXT:
×
2040
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2041
                        break;
×
2042

2043
                case BACKGROUND_ESCAPE:
×
2044
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
2045
                        break;
×
2046

2047
                case BACKGROUND_BRACKET:
×
2048
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
2049
                        break;
×
2050

2051
                case BACKGROUND_FIRST_ONE:
×
2052
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
2053
                        break;
×
2054

2055
                case BACKGROUND_SECOND_ONE:
×
2056
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
2057
                        break;
×
2058

2059
                case BACKGROUND_SEMICOLON:
×
2060
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
2061
                        break;
×
2062

2063
                case BACKGROUND_R:
×
2064
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
2065
                        break;
×
2066

2067
                case BACKGROUND_G:
×
2068
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
2069
                        break;
×
2070

2071
                case BACKGROUND_B:
×
2072
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
2073
                        break;
×
2074

2075
                case BACKGROUND_RED:
×
2076
                        if (c == '/')
×
2077
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
2078
                        else {
2079
                                int d = unhexchar(c);
×
2080
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
2081
                                        context->state = BACKGROUND_TEXT;
×
2082
                                else {
2083
                                        context->red = (context->red << 4) | d;
×
2084
                                        context->red_bits += 4;
×
2085
                                }
2086
                        }
2087
                        break;
2088

2089
                case BACKGROUND_GREEN:
×
2090
                        if (c == '/')
×
2091
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
2092
                        else {
2093
                                int d = unhexchar(c);
×
2094
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
2095
                                        context->state = BACKGROUND_TEXT;
×
2096
                                else {
2097
                                        context->green = (context->green << 4) | d;
×
2098
                                        context->green_bits += 4;
×
2099
                                }
2100
                        }
2101
                        break;
2102

2103
                case BACKGROUND_BLUE:
×
2104
                        if (c == '\x07') {
×
2105
                                if (context->blue_bits > 0) {
×
2106
                                        if (ret_processed)
×
2107
                                                *ret_processed = i + 1;
×
2108

2109
                                        return 1; /* success! */
×
2110
                                }
2111

2112
                                context->state = BACKGROUND_TEXT;
×
2113
                        } else if (c == '\x1b')
×
2114
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
2115
                        else {
2116
                                int d = unhexchar(c);
×
2117
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
2118
                                        context->state = BACKGROUND_TEXT;
×
2119
                                else {
2120
                                        context->blue = (context->blue << 4) | d;
×
2121
                                        context->blue_bits += 4;
×
2122
                                }
2123
                        }
2124
                        break;
2125

2126
                case BACKGROUND_STRING_TERMINATOR:
×
2127
                        if (c == '\\') {
×
2128
                                if (ret_processed)
×
2129
                                        *ret_processed = i + 1;
×
2130

2131
                                return 1; /* success! */
×
2132
                        }
2133

2134
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
2135
                        break;
×
2136

2137
                }
2138

2139
                /* Reset any colors we might have picked up */
2140
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
2141
                        /* reset color */
2142
                        context->red = context->green = context->blue = 0;
×
2143
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
2144
                }
2145
        }
2146

2147
        if (ret_processed)
×
2148
                *ret_processed = size;
×
2149

2150
        return 0; /* all good, but not enough data yet */
2151
}
2152

2153
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
153✔
2154
        _cleanup_close_ int nonblock_input_fd = -EBADF;
153✔
2155
        int r;
153✔
2156

2157
        assert(ret_red);
153✔
2158
        assert(ret_green);
153✔
2159
        assert(ret_blue);
153✔
2160

2161
        if (!colors_enabled())
153✔
2162
                return -EOPNOTSUPP;
2163

2164
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
2165
        if (r < 0)
×
2166
                return r;
2167

2168
        if (streq_ptr(getenv("TERM"), "linux")) {
×
2169
                /* Linux console is black */
2170
                *ret_red = *ret_green = *ret_blue = 0.0;
×
2171
                return 0;
×
2172
        }
2173

2174
        struct termios old_termios;
×
2175
        if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
×
2176
                return -errno;
×
2177

2178
        struct termios new_termios = old_termios;
×
2179
        termios_disable_echo(&new_termios);
×
2180

2181
        if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) < 0)
×
2182
                return -errno;
×
2183

2184
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
2185
        if (r < 0)
×
2186
                goto finish;
×
2187

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

2191
        nonblock_input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2192
        if (nonblock_input_fd < 0)
×
2193
                return nonblock_input_fd;
2194

2195
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2196
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
2197
        size_t buf_full = 0;
×
2198
        BackgroundColorContext context = {};
×
2199

2200
        for (bool first = true;; first = false) {
×
2201
                if (buf_full == 0) {
×
2202
                        usec_t n = now(CLOCK_MONOTONIC);
×
2203
                        if (n >= end) {
×
2204
                                r = -EOPNOTSUPP;
×
2205
                                goto finish;
×
2206
                        }
2207

2208
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2209
                        if (r < 0)
×
2210
                                goto finish;
×
2211
                        if (r == 0) {
×
2212
                                r = -EOPNOTSUPP;
×
2213
                                goto finish;
×
2214
                        }
2215

2216
                        /* On the first try, read multiple characters, i.e. the shortest valid
2217
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2218
                         * unnecessarily drop too many characters from the input queue. */
2219
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2220
                        if (l < 0) {
×
2221
                                if (errno == EAGAIN)
×
2222
                                        continue;
×
2223
                                r = -errno;
×
2224
                                goto finish;
×
2225
                        }
2226

2227
                        assert((size_t) l <= sizeof(buf));
×
2228
                        buf_full = l;
2229
                }
2230

2231
                size_t processed;
×
2232
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
2233
                if (r < 0)
×
2234
                        goto finish;
×
2235

2236
                assert(processed <= buf_full);
×
2237
                buf_full -= processed;
×
2238
                memmove(buf, buf + processed, buf_full);
×
2239

2240
                if (r > 0) {
×
2241
                        assert(context.red_bits > 0);
×
2242
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
2243
                        assert(context.green_bits > 0);
×
2244
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
2245
                        assert(context.blue_bits > 0);
×
2246
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
2247
                        r = 0;
×
2248
                        goto finish;
×
2249
                }
2250
        }
2251

2252
finish:
×
2253
        RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios)));
×
2254
        return r;
2255
}
2256

2257
typedef enum CursorPositionState {
2258
        CURSOR_TEXT,
2259
        CURSOR_ESCAPE,
2260
        CURSOR_ROW,
2261
        CURSOR_COLUMN,
2262
} CursorPositionState;
2263

2264
typedef struct CursorPositionContext {
2265
        CursorPositionState state;
2266
        unsigned row, column;
2267
} CursorPositionContext;
2268

2269
static int scan_cursor_position_response(
×
2270
                CursorPositionContext *context,
2271
                const char *buf,
2272
                size_t size,
2273
                size_t *ret_processed) {
2274

2275
        assert(context);
×
2276
        assert(buf || size == 0);
×
2277

2278
        for (size_t i = 0; i < size; i++) {
×
2279
                char c = buf[i];
×
2280

2281
                switch (context->state) {
×
2282

2283
                case CURSOR_TEXT:
×
2284
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
2285
                        break;
×
2286

2287
                case CURSOR_ESCAPE:
×
2288
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
2289
                        break;
×
2290

2291
                case CURSOR_ROW:
×
2292
                        if (c == ';')
×
2293
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
2294
                        else {
2295
                                int d = undecchar(c);
×
2296

2297
                                /* We read a decimal character, let's suffix it to the number we so far read,
2298
                                 * but let's do an overflow check first. */
2299
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
2300
                                        context->state = CURSOR_TEXT;
×
2301
                                else
2302
                                        context->row = context->row * 10 + d;
×
2303
                        }
2304
                        break;
2305

2306
                case CURSOR_COLUMN:
×
2307
                        if (c == 'R') {
×
2308
                                if (context->column > 0) {
×
2309
                                        if (ret_processed)
×
2310
                                                *ret_processed = i + 1;
×
2311

2312
                                        return 1; /* success! */
×
2313
                                }
2314

2315
                                context->state = CURSOR_TEXT;
×
2316
                        } else {
2317
                                int d = undecchar(c);
×
2318

2319
                                /* As above, add the decimal charatcer to our column number */
2320
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
2321
                                        context->state = CURSOR_TEXT;
×
2322
                                else
2323
                                        context->column = context->column * 10 + d;
×
2324
                        }
2325

2326
                        break;
2327
                }
2328

2329
                /* Reset any positions we might have picked up */
2330
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
2331
                        context->row = context->column = 0;
×
2332
        }
2333

2334
        if (ret_processed)
×
2335
                *ret_processed = size;
×
2336

2337
        return 0; /* all good, but not enough data yet */
2338
}
2339

2340
int terminal_get_size_by_dsr(
176✔
2341
                int input_fd,
2342
                int output_fd,
2343
                unsigned *ret_rows,
2344
                unsigned *ret_columns) {
2345

2346
        _cleanup_close_ int nonblock_input_fd = -EBADF;
176✔
2347

2348
        assert(input_fd >= 0);
176✔
2349
        assert(output_fd >= 0);
176✔
2350

2351
        int r;
176✔
2352

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

2368
        if (terminal_is_dumb())
176✔
2369
                return -EOPNOTSUPP;
2370

2371
        r = terminal_verify_same(input_fd, output_fd);
×
2372
        if (r < 0)
×
2373
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2374

2375
        struct termios old_termios;
×
2376
        if (tcgetattr(input_fd, &old_termios) < 0)
×
2377
                return log_debug_errno(errno, "Failed to to get terminal settings: %m");
×
2378

2379
        struct termios new_termios = old_termios;
×
2380
        termios_disable_echo(&new_termios);
×
2381

2382
        if (tcsetattr(input_fd, TCSADRAIN, &new_termios) < 0)
×
2383
                return log_debug_errno(errno, "Failed to to set new terminal settings: %m");
×
2384

2385
        unsigned saved_row = 0, saved_column = 0;
×
2386

2387
        r = loop_write(output_fd,
×
2388
                       "\x1B[6n"           /* Request cursor position (DSR/CPR) */
2389
                       "\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
2390
                       "\x1B[6n",          /* Request cursor position again */
2391
                       SIZE_MAX);
2392
        if (r < 0)
×
2393
                goto finish;
×
2394

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

2398
        nonblock_input_fd = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2399
        if (nonblock_input_fd < 0)
×
2400
                return nonblock_input_fd;
2401

2402
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2403
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2404
        size_t buf_full = 0;
×
2405
        CursorPositionContext context = {};
×
2406

2407
        for (bool first = true;; first = false) {
×
2408
                if (buf_full == 0) {
×
2409
                        usec_t n = now(CLOCK_MONOTONIC);
×
2410
                        if (n >= end) {
×
2411
                                r = -EOPNOTSUPP;
×
2412
                                goto finish;
×
2413
                        }
2414

2415
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2416
                        if (r < 0)
×
2417
                                goto finish;
×
2418
                        if (r == 0) {
×
2419
                                r = -EOPNOTSUPP;
×
2420
                                goto finish;
×
2421
                        }
2422

2423
                        /* On the first try, read multiple characters, i.e. the shortest valid
2424
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2425
                         * unnecessarily drop too many characters from the input queue. */
2426
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2427
                        if (l < 0) {
×
2428
                                if (errno == EAGAIN)
×
2429
                                        continue;
×
2430

2431
                                r = -errno;
×
2432
                                goto finish;
×
2433
                        }
2434

2435
                        assert((size_t) l <= sizeof(buf));
×
2436
                        buf_full = l;
2437
                }
2438

2439
                size_t processed;
×
2440
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2441
                if (r < 0)
×
2442
                        goto finish;
×
2443

2444
                assert(processed <= buf_full);
×
2445
                buf_full -= processed;
×
2446
                memmove(buf, buf + processed, buf_full);
×
2447

2448
                if (r > 0) {
×
2449
                        if (saved_row == 0) {
×
2450
                                assert(saved_column == 0);
×
2451

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

2456
                                /* Superficial validity checks */
2457
                                if (context.row <= 0 || context.column <= 0 || context.row >= 32766 || context.column >= 32766) {
×
2458
                                        r = -ENODATA;
×
2459
                                        goto finish;
×
2460
                                }
2461

2462
                                saved_row = context.row;
×
2463
                                saved_column = context.column;
×
2464

2465
                                /* Reset state */
2466
                                context = (CursorPositionContext) {};
×
2467
                        } else {
2468
                                /* Second sequence, this is the cursor position after we set it somewhere
2469
                                 * into the void at the bottom right. */
2470

2471
                                /* Superficial validity checks (no particular reason to check for < 4, it's
2472
                                 * just a way to look for unreasonably small values) */
2473
                                if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766) {
×
2474
                                        r = -ENODATA;
×
2475
                                        goto finish;
×
2476
                                }
2477

2478
                                if (ret_rows)
×
2479
                                        *ret_rows = context.row;
×
2480
                                if (ret_columns)
×
2481
                                        *ret_columns = context.column;
×
2482

2483
                                r = 0;
×
2484
                                goto finish;
×
2485
                        }
2486
                }
2487
        }
2488

2489
finish:
×
2490
        /* Restore cursor position */
2491
        if (saved_row > 0 && saved_column > 0)
×
2492
                RET_GATHER(r, terminal_set_cursor_position(output_fd, saved_row, saved_column));
×
2493

2494
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSADRAIN, &old_termios)));
×
2495
        return r;
2496
}
2497

2498
int terminal_fix_size(int input_fd, int output_fd) {
1✔
2499
        unsigned rows, columns;
1✔
2500
        int r;
1✔
2501

2502
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences */
2503

2504
        r = terminal_verify_same(input_fd, output_fd);
1✔
2505
        if (r < 0)
1✔
2506
                return r;
1✔
2507

2508
        struct winsize ws = {};
×
2509
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
×
2510
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
×
2511

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

2516
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
2517
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2518
                return 0;
×
2519
        }
2520

2521
        ws.ws_col = columns;
×
2522
        ws.ws_row = rows;
×
2523

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

2527
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2528
        return 1;
2529
}
2530

2531
int terminal_is_pty_fd(int fd) {
511✔
2532
        int r;
511✔
2533

2534
        assert(fd >= 0);
511✔
2535

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

2538
        if (!isatty_safe(fd))
511✔
2539
                return false;
511✔
2540

2541
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
510✔
2542
        if (r != 0)
510✔
2543
                return r;
2544

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

2548
        int v;
350✔
2549
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
350✔
2550
                if (ERRNO_IS_NOT_SUPPORTED(errno))
350✔
2551
                        return false;
2552

2553
                return -errno;
×
2554
        }
2555

2556
        return true;
2557
}
2558

2559
int pty_open_peer(int fd, int mode) {
19✔
2560
        assert(fd >= 0);
19✔
2561

2562
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2563
         *
2564
         * This is safe to be called on TTYs from other namespaces. */
2565

2566
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
19✔
2567

2568
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
2569
        for (unsigned c = 0;; c++) {
×
2570
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
19✔
2571
                if (peer_fd >= 0)
19✔
2572
                        return peer_fd;
2573

2574
                if (errno != EIO)
×
2575
                        return -errno;
×
2576

2577
                /* Max 1s in total */
2578
                if (c >= 20)
×
2579
                        return -EIO;
2580

2581
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2582
        }
2583
}
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