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

systemd / systemd / 13210122091

07 Feb 2025 10:56PM UTC coverage: 71.748% (-0.07%) from 71.813%
13210122091

push

github

web-flow
network: allow to configure routing policy rule even if requesting interface is not activated yet (#36257)

Fixes a regression caused by 4f8b153d9
(v257).
Fixes #36244.

16 of 16 new or added lines in 2 files covered. (100.0%)

3079 existing lines in 54 files now uncovered.

292917 of 408258 relevant lines covered (71.75%)

714241.77 hits per line

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

48.13
/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 "fd-util.h"
30
#include "fileio.h"
31
#include "fs-util.h"
32
#include "glyph-util.h"
33
#include "hexdecoct.h"
34
#include "inotify-util.h"
35
#include "io-util.h"
36
#include "log.h"
37
#include "macro.h"
38
#include "missing_magic.h"
39
#include "namespace-util.h"
40
#include "parse-util.h"
41
#include "path-util.h"
42
#include "proc-cmdline.h"
43
#include "process-util.h"
44
#include "signal-util.h"
45
#include "socket-util.h"
46
#include "stat-util.h"
47
#include "stdio-util.h"
48
#include "string-table.h"
49
#include "string-util.h"
50
#include "strv.h"
51
#include "terminal-util.h"
52
#include "time-util.h"
53
#include "user-util.h"
54

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

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

63
bool isatty_safe(int fd) {
6,645,153✔
64
        assert(fd >= 0);
6,645,153✔
65

66
        if (isatty(fd))
6,645,153✔
67
                return true;
68

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

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

78
        return false;
79
}
80

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

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

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

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

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

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

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

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

111
        assert(f);
10✔
112
        assert(ret);
10✔
113

114
        /* If this is a terminal, then switch canonical mode off, so that we can read a single
115
         * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
116
         * nicely.) */
117
        fd = fileno(f);
10✔
118
        if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
10✔
119
                struct termios new_termios = old_termios;
×
120

121
                new_termios.c_lflag &= ~ICANON;
×
122
                new_termios.c_cc[VMIN] = 1;
×
123
                new_termios.c_cc[VTIME] = 0;
×
124

125
                if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
×
126
                        char c;
×
127

128
                        if (t != USEC_INFINITY) {
×
129
                                if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
×
130
                                        (void) tcsetattr(fd, TCSADRAIN, &old_termios);
×
131
                                        return -ETIMEDOUT;
×
132
                                }
133
                        }
134

135
                        r = safe_fgetc(f, &c);
×
136
                        (void) tcsetattr(fd, TCSADRAIN, &old_termios);
×
137
                        if (r < 0)
×
138
                                return r;
139
                        if (r == 0)
×
140
                                return -EIO;
141

142
                        if (need_nl)
×
143
                                *need_nl = c != '\n';
×
144

145
                        *ret = c;
×
146
                        return 0;
×
147
                }
148
        }
149

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

156
                if (fd_wait_for_event(fd, POLLIN, t) <= 0)
4✔
157
                        return -ETIMEDOUT;
158
        }
159

160
        /* If this is not a terminal, then read a full line instead */
161

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

168
        if (strlen(line) != 1)
8✔
169
                return -EBADMSG;
170

171
        if (need_nl)
1✔
172
                *need_nl = false;
1✔
173

174
        *ret = line[0];
1✔
175
        return 0;
1✔
176
}
177

178
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
179

180
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
×
181
        int r;
×
182

183
        assert(ret);
×
184
        assert(replies);
×
185
        assert(fmt);
×
186

187
        for (;;) {
×
188
                va_list ap;
×
189
                char c;
×
190
                bool need_nl = true;
×
191

192
                fputs(ansi_highlight(), stdout);
×
193

194
                putchar('\r');
×
195

196
                va_start(ap, fmt);
×
197
                vprintf(fmt, ap);
×
198
                va_end(ap);
×
199

200
                fputs(ansi_normal(), stdout);
×
201

202
                fflush(stdout);
×
203

204
                r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
×
205
                if (r < 0) {
×
206

207
                        if (r == -ETIMEDOUT)
×
208
                                continue;
×
209

210
                        if (r == -EBADMSG) {
×
211
                                puts("Bad input, please try again.");
×
212
                                continue;
×
213
                        }
214

215
                        putchar('\n');
×
216
                        return r;
×
217
                }
218

219
                if (need_nl)
×
220
                        putchar('\n');
×
221

222
                if (strchr(replies, c)) {
×
223
                        *ret = c;
×
224
                        return 0;
×
225
                }
226

227
                puts("Read unexpected character, please try again.");
×
228
        }
229
}
230

231
int ask_string(char **ret, const char *text, ...) {
7✔
232
        _cleanup_free_ char *line = NULL;
7✔
233
        va_list ap;
7✔
234
        int r;
7✔
235

236
        assert(ret);
7✔
237
        assert(text);
7✔
238

239
        fputs(ansi_highlight(), stdout);
14✔
240

241
        va_start(ap, text);
7✔
242
        vprintf(text, ap);
7✔
243
        va_end(ap);
7✔
244

245
        fputs(ansi_normal(), stdout);
14✔
246

247
        fflush(stdout);
7✔
248

249
        r = read_line(stdin, LONG_LINE_MAX, &line);
7✔
250
        if (r < 0)
7✔
251
                return r;
252
        if (r == 0)
7✔
253
                return -EIO;
254

255
        *ret = TAKE_PTR(line);
7✔
256
        return 0;
7✔
257
}
258

259
bool any_key_to_proceed(void) {
6✔
260
        char key = 0;
6✔
261
        bool need_nl = true;
6✔
262

263
        /*
264
         * Insert a new line here as well as to when the user inputs, as this is also used during the
265
         * boot up sequence when status messages may be interleaved with the current program output.
266
         * This ensures that the status messages aren't appended on the same line as this message.
267
         */
268
        puts("-- Press any key to proceed --");
6✔
269

270
        (void) read_one_char(stdin, &key, USEC_INFINITY, &need_nl);
6✔
271

272
        if (need_nl)
6✔
273
                putchar('\n');
6✔
274

275
        return key != 'q';
6✔
276
}
277

278
int show_menu(char **x, unsigned n_columns, unsigned width, unsigned percentage) {
×
279
        unsigned break_lines, break_modulo;
×
280
        size_t n, per_column, i, j;
×
281

282
        assert(n_columns > 0);
×
283

284
        n = strv_length(x);
×
285
        per_column = DIV_ROUND_UP(n, n_columns);
×
286

287
        break_lines = lines();
×
288
        if (break_lines > 2)
×
289
                break_lines--;
×
290

291
        /* The first page gets two extra lines, since we want to show
292
         * a title */
293
        break_modulo = break_lines;
×
294
        if (break_modulo > 3)
×
295
                break_modulo -= 3;
×
296

297
        for (i = 0; i < per_column; i++) {
×
298

299
                for (j = 0; j < n_columns; j++) {
×
300
                        _cleanup_free_ char *e = NULL;
×
301

302
                        if (j * per_column + i >= n)
×
303
                                break;
304

305
                        e = ellipsize(x[j * per_column + i], width, percentage);
×
306
                        if (!e)
×
307
                                return log_oom();
×
308

309
                        printf("%4zu) %-*s", j * per_column + i + 1, (int) width, e);
×
310
                }
311

312
                putchar('\n');
×
313

314
                /* on the first screen we reserve 2 extra lines for the title */
315
                if (i % break_lines == break_modulo) {
×
316
                        if (!any_key_to_proceed())
×
317
                                return 0;
318
                }
319
        }
320

321
        return 0;
322
}
323

324
int open_terminal(const char *name, int mode) {
49,777✔
325
        _cleanup_close_ int fd = -EBADF;
49,777✔
326

327
        /*
328
         * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
329
         * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
330
         * times.
331
         *
332
         * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
333
         */
334

335
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
49,777✔
336

337
        for (unsigned c = 0;; c++) {
×
338
                fd = open(name, mode, 0);
49,777✔
339
                if (fd >= 0)
49,777✔
340
                        break;
341

342
                if (errno != EIO)
13,191✔
343
                        return -errno;
13,191✔
344

345
                /* Max 1s in total */
346
                if (c >= 20)
×
347
                        return -EIO;
348

349
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
350
        }
351

352
        if (!isatty_safe(fd))
36,586✔
353
                return -ENOTTY;
×
354

355
        return TAKE_FD(fd);
356
}
357

358
int acquire_terminal(
346✔
359
                const char *name,
360
                AcquireTerminalFlags flags,
361
                usec_t timeout) {
362

363
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
346✔
364
        usec_t ts = USEC_INFINITY;
346✔
365
        int r, wd = -1;
346✔
366

367
        assert(name);
346✔
368
        assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
346✔
369

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

379
        if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
346✔
380
                notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
692✔
381
                if (notify < 0)
346✔
382
                        return -errno;
×
383

384
                wd = inotify_add_watch(notify, name, IN_CLOSE);
346✔
385
                if (wd < 0)
346✔
386
                        return -errno;
×
387

388
                if (timeout != USEC_INFINITY)
346✔
389
                        ts = now(CLOCK_MONOTONIC);
346✔
390
        }
391

392
        for (;;) {
346✔
393
                if (notify >= 0) {
346✔
394
                        r = flush_fd(notify);
346✔
395
                        if (r < 0)
346✔
396
                                return r;
×
397
                }
398

399
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
400
                 * to figure out if we successfully became the controlling process of the tty */
401
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
346✔
402
                if (fd < 0)
346✔
403
                        return fd;
404

405
                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
406
                struct sigaction sa_old;
346✔
407
                assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
346✔
408

409
                /* First, try to get the tty */
410
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE));
346✔
411

412
                /* Reset signal handler to old value */
413
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
346✔
414

415
                /* Success? Exit the loop now! */
416
                if (r >= 0)
346✔
417
                        break;
418

419
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
420
                if (r != -EPERM)
×
421
                        return r;
422

423
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
×
424
                                                          * into a success. Note that EPERM is also returned if we
425
                                                          * already are the owner of the TTY. */
426
                        break;
427

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

431
                assert(notify >= 0);
×
432
                assert(wd >= 0);
×
433

434
                for (;;) {
×
435
                        union inotify_event_buffer buffer;
×
436
                        ssize_t l;
×
437

438
                        if (timeout != USEC_INFINITY) {
×
439
                                usec_t n;
×
440

441
                                assert(ts != USEC_INFINITY);
×
442

443
                                n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
×
444
                                if (n >= timeout)
×
445
                                        return -ETIMEDOUT;
×
446

447
                                r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
×
448
                                if (r < 0)
×
449
                                        return r;
450
                                if (r == 0)
×
451
                                        return -ETIMEDOUT;
452
                        }
453

454
                        l = read(notify, &buffer, sizeof(buffer));
×
455
                        if (l < 0) {
×
456
                                if (ERRNO_IS_TRANSIENT(errno))
×
457
                                        continue;
×
458

459
                                return -errno;
×
460
                        }
461

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

466
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
×
467
                                        return -EIO;
×
468
                        }
469

470
                        break;
×
471
                }
472

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

478
        return TAKE_FD(fd);
346✔
479
}
480

481
int release_terminal(void) {
115✔
482
        _cleanup_close_ int fd = -EBADF;
115✔
483
        int r;
115✔
484

485
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
115✔
486
        if (fd < 0)
115✔
487
                return -errno;
95✔
488

489
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
490
         * by our own TIOCNOTTY */
491
        struct sigaction sa_old;
20✔
492
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
20✔
493

494
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
20✔
495

496
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
20✔
497

498
        return r;
499
}
500

501
int terminal_new_session(void) {
4✔
502

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

510
        if (!isatty_safe(STDIN_FILENO))
4✔
511
                return -ENXIO;
512

513
        (void) setsid();
3✔
514
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
3✔
515
}
516

517
int terminal_vhangup_fd(int fd) {
158✔
518
        assert(fd >= 0);
158✔
519
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
158✔
520
}
521

522
int terminal_vhangup(const char *tty) {
×
523
        _cleanup_close_ int fd = -EBADF;
×
524

525
        assert(tty);
×
526

527
        fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
×
528
        if (fd < 0)
×
529
                return fd;
530

531
        return terminal_vhangup_fd(fd);
×
532
}
533

534
int vt_disallocate(const char *tty_path) {
87✔
535
        assert(tty_path);
87✔
536

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

540
        int ttynr = vtnr_from_tty(tty_path);
87✔
541
        if (ttynr > 0) {
87✔
542
                _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
87✔
543
                if (fd < 0)
87✔
544
                        return fd;
545

546
                /* Try to deallocate */
547
                if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
87✔
548
                        return 0;
549
                if (errno != EBUSY)
87✔
550
                        return -errno;
×
551
        }
552

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

556
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
174✔
557
        if (fd2 < 0)
87✔
558
                return fd2;
559

560
        return loop_write_full(fd2,
87✔
561
                               "\033[r"   /* clear scrolling region */
562
                               "\033[H"   /* move home */
563
                               "\033[3J"  /* clear screen including scrollback, requires Linux 2.6.40 */
564
                               "\033c",   /* reset to initial state */
565
                               SIZE_MAX,
566
                               100 * USEC_PER_MSEC);
567
}
568

569
static int vt_default_utf8(void) {
790✔
570
        _cleanup_free_ char *b = NULL;
790✔
571
        int r;
790✔
572

573
        /* Read the default VT UTF8 setting from the kernel */
574

575
        r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
790✔
576
        if (r < 0)
790✔
577
                return r;
578

579
        return parse_boolean(b);
492✔
580
}
581

582
static int vt_reset_keyboard(int fd) {
395✔
583
        int r, kb;
395✔
584

585
        assert(fd >= 0);
395✔
586

587
        /* If we can't read the default, then default to Unicode. It's 2024 after all. */
588
        r = vt_default_utf8();
395✔
589
        if (r < 0)
395✔
590
                log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
149✔
591

592
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
395✔
593
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
395✔
594
}
595

596
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
395✔
597
        struct termios termios;
395✔
598
        int r;
395✔
599

600
        /* Set terminal to some sane defaults */
601

602
        assert(fd >= 0);
395✔
603

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

607
        /* Disable exclusive mode, just in case */
608
        if (ioctl(fd, TIOCNXCL) < 0)
395✔
609
                log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
4✔
610

611
        /* Switch to text mode */
612
        if (switch_to_text)
395✔
613
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
162✔
614
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
75✔
615

616
        /* Set default keyboard mode */
617
        r = vt_reset_keyboard(fd);
395✔
618
        if (r < 0)
395✔
619
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
224✔
620

621
        if (tcgetattr(fd, &termios) < 0) {
395✔
622
                r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
4✔
623
                goto finish;
4✔
624
        }
625

626
        /* We only reset the stuff that matters to the software. How
627
         * hardware is set up we don't touch assuming that somebody
628
         * else will do that for us */
629

630
        termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
391✔
631
        termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
391✔
632
        termios.c_oflag |= ONLCR | OPOST;
391✔
633
        termios.c_cflag |= CREAD;
391✔
634
        termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
391✔
635

636
        termios.c_cc[VINTR]    =   03;  /* ^C */
391✔
637
        termios.c_cc[VQUIT]    =  034;  /* ^\ */
391✔
638
        termios.c_cc[VERASE]   = 0177;
391✔
639
        termios.c_cc[VKILL]    =  025;  /* ^X */
391✔
640
        termios.c_cc[VEOF]     =   04;  /* ^D */
391✔
641
        termios.c_cc[VSTART]   =  021;  /* ^Q */
391✔
642
        termios.c_cc[VSTOP]    =  023;  /* ^S */
391✔
643
        termios.c_cc[VSUSP]    =  032;  /* ^Z */
391✔
644
        termios.c_cc[VLNEXT]   =  026;  /* ^V */
391✔
645
        termios.c_cc[VWERASE]  =  027;  /* ^W */
391✔
646
        termios.c_cc[VREPRINT] =  022;  /* ^R */
391✔
647
        termios.c_cc[VEOL]     =    0;
391✔
648
        termios.c_cc[VEOL2]    =    0;
391✔
649

650
        termios.c_cc[VTIME]  = 0;
391✔
651
        termios.c_cc[VMIN]   = 1;
391✔
652

653
        r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
391✔
654
        if (r < 0)
×
655
                log_debug_errno(r, "Failed to set terminal parameters: %m");
×
656

657
finish:
×
658
        /* Just in case, flush all crap out */
659
        (void) tcflush(fd, TCIOFLUSH);
395✔
660

661
        return r;
395✔
662
}
663

664
static int terminal_reset_ansi_seq(int fd) {
256✔
665
        int r, k;
256✔
666

667
        assert(fd >= 0);
256✔
668

669
        if (getenv_terminal_is_dumb())
256✔
670
                return 0;
671

672
        r = fd_nonblock(fd, true);
×
673
        if (r < 0)
×
674
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
×
675

676
        k = loop_write_full(fd,
×
677
                            "\033[!p"      /* soft terminal reset */
678
                            "\033]104\007" /* reset colors */
679
                            "\033[?7h",    /* enable line-wrapping */
680
                            SIZE_MAX,
681
                            100 * USEC_PER_MSEC);
682
        if (k < 0)
×
683
                log_debug_errno(k, "Failed to reset terminal through ANSI sequences: %m");
×
684

685
        if (r > 0) {
×
686
                r = fd_nonblock(fd, false);
×
687
                if (r < 0)
×
688
                        log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
×
689
        }
690

691
        return k < 0 ? k : r;
×
692
}
693

694
void reset_dev_console_fd(int fd, bool switch_to_text) {
85✔
695
        int r;
85✔
696

697
        assert(fd >= 0);
85✔
698

699
        _cleanup_close_ int lock_fd = lock_dev_console();
85✔
700
        if (lock_fd < 0)
85✔
701
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
702

703
        r = terminal_reset_ioctl(fd, switch_to_text);
85✔
704
        if (r < 0)
85✔
705
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
×
706

707
        unsigned rows, cols;
85✔
708
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
85✔
709
        if (r < 0)
85✔
710
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
×
711
        else if (r > 0) {
85✔
712
                r = terminal_set_size_fd(fd, NULL, rows, cols);
85✔
713
                if (r < 0)
85✔
714
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
×
715
        } else
716
                (void) terminal_fix_size(fd, fd);
×
717

718
        r = terminal_reset_ansi_seq(fd);
85✔
719
        if (r < 0)
85✔
720
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
85✔
721
}
85✔
722

723
int lock_dev_console(void) {
1,030✔
724
        _cleanup_close_ int fd = -EBADF;
1,030✔
725
        int r;
1,030✔
726

727
        /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
728
         * pty in /dev/console, in which case it should be fine to lock the target TTY. */
729
        fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1,030✔
730
        if (fd < 0)
1,030✔
731
                return fd;
732

733
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
1,030✔
734
        if (r < 0)
1,030✔
735
                return r;
×
736

737
        return TAKE_FD(fd);
738
}
739

740
int make_console_stdio(void) {
×
741
        int fd, r;
×
742

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

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

751
                r = make_null_stdio();
×
752
                if (r < 0)
×
753
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
×
754

755
        } else {
756
                reset_dev_console_fd(fd, /* switch_to_text= */ true);
×
757

758
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
×
759
                if (r < 0)
×
760
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
×
761
        }
762

763
        reset_terminal_feature_caches();
×
764
        return 0;
×
765
}
766

767
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
220✔
768
        assert(tty);
220✔
769

770
        tty = skip_dev_prefix(tty);
220✔
771

772
        const char *e = startswith(tty, "tty");
220✔
773
        if (!e)
220✔
774
                return -EINVAL;
775

776
        return safe_atou(e, ret);
179✔
777
}
778

779
int vtnr_from_tty(const char *tty) {
136✔
780
        unsigned u;
136✔
781
        int r;
136✔
782

783
        assert(tty);
136✔
784

785
        r = vtnr_from_tty_raw(tty, &u);
136✔
786
        if (r < 0)
136✔
787
                return r;
136✔
788
        if (!vtnr_is_valid(u))
136✔
789
                return -ERANGE;
790

791
        return (int) u;
136✔
792
}
793

794
bool tty_is_vc(const char *tty) {
84✔
795
        assert(tty);
84✔
796

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

802
        return vtnr_from_tty_raw(tty, /* ret = */ NULL) >= 0;
84✔
803
}
804

805
bool tty_is_console(const char *tty) {
35✔
806
        assert(tty);
35✔
807

808
        return streq(skip_dev_prefix(tty), "console");
35✔
809
}
810

811
int resolve_dev_console(char **ret) {
26✔
812
        int r;
26✔
813

814
        assert(ret);
26✔
815

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

821
        _cleanup_free_ char *chased = NULL;
26✔
822
        r = chase("/dev/console", /* root= */ NULL, /* chase_flags= */ 0,  &chased, /* ret_fd= */ NULL);
26✔
823
        if (r < 0)
26✔
824
                return r;
825
        if (!path_equal(chased, "/dev/console")) {
26✔
826
                *ret = TAKE_PTR(chased);
2✔
827
                return 0;
2✔
828
        }
829

830
        r = path_is_read_only_fs("/sys");
24✔
831
        if (r < 0)
24✔
832
                return r;
833
        if (r > 0)
24✔
834
                return -ENOMEDIUM;
835

836
        _cleanup_free_ char *active = NULL;
24✔
837
        r = read_one_line_file("/sys/class/tty/console/active", &active);
24✔
838
        if (r < 0)
24✔
839
                return r;
840

841
        /* If multiple log outputs are configured the last one is what /dev/console points to */
842
        const char *tty = strrchr(active, ' ');
24✔
843
        if (tty)
24✔
844
                tty++;
×
845
        else
846
                tty = active;
847

848
        if (streq(tty, "tty0")) {
24✔
849
                active = mfree(active);
×
850

851
                /* Get the active VC (e.g. tty1) */
852
                r = read_one_line_file("/sys/class/tty/tty0/active", &active);
×
853
                if (r < 0)
×
854
                        return r;
855

856
                tty = active;
×
857
        }
858

859
        if (tty != active)
24✔
860
                return strdup_to(ret, tty);
×
861

862
        *ret = TAKE_PTR(active);
24✔
863
        return 0;
24✔
864
}
865

UNCOV
866
int get_kernel_consoles(char ***ret) {
×
867
        _cleanup_strv_free_ char **l = NULL;
×
UNCOV
868
        _cleanup_free_ char *line = NULL;
×
UNCOV
869
        int r;
×
870

UNCOV
871
        assert(ret);
×
872

873
        /* If /sys/ is mounted read-only this means we are running in some kind of container environment.
874
         * In that case /sys/ would reflect the host system, not us, hence ignore the data we can read from it. */
UNCOV
875
        if (path_is_read_only_fs("/sys") > 0)
×
UNCOV
876
                goto fallback;
×
877

878
        r = read_one_line_file("/sys/class/tty/console/active", &line);
×
879
        if (r < 0)
×
880
                return r;
881

882
        for (const char *p = line;;) {
×
883
                _cleanup_free_ char *tty = NULL, *path = NULL;
×
884

885
                r = extract_first_word(&p, &tty, NULL, 0);
×
886
                if (r < 0)
×
887
                        return r;
888
                if (r == 0)
×
889
                        break;
890

891
                if (streq(tty, "tty0")) {
×
892
                        tty = mfree(tty);
×
893
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
×
894
                        if (r < 0)
×
895
                                return r;
896
                }
897

898
                path = path_join("/dev", tty);
×
899
                if (!path)
×
900
                        return -ENOMEM;
901

902
                if (access(path, F_OK) < 0) {
×
903
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
×
904
                        continue;
×
905
                }
906

907
                r = strv_consume(&l, TAKE_PTR(path));
×
908
                if (r < 0)
×
909
                        return r;
910
        }
911

912
        if (strv_isempty(l)) {
×
913
                log_debug("No devices found for system console");
×
914
                goto fallback;
×
915
        }
916

917
        *ret = TAKE_PTR(l);
×
918
        return strv_length(*ret);
×
919

UNCOV
920
fallback:
×
UNCOV
921
        r = strv_extend(&l, "/dev/console");
×
UNCOV
922
        if (r < 0)
×
923
                return r;
924

UNCOV
925
        *ret = TAKE_PTR(l);
×
UNCOV
926
        return 0;
×
927
}
928

929
bool tty_is_vc_resolve(const char *tty) {
49✔
930
        _cleanup_free_ char *resolved = NULL;
49✔
931

932
        assert(tty);
49✔
933

934
        tty = skip_dev_prefix(tty);
49✔
935

936
        if (streq(tty, "console")) {
49✔
937
                if (resolve_dev_console(&resolved) < 0)
2✔
938
                        return false;
939

940
                tty = resolved;
2✔
941
        }
942

943
        return tty_is_vc(tty);
49✔
944
}
945

946
const char* default_term_for_tty(const char *tty) {
64✔
947
        return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
64✔
948
}
949

950
int fd_columns(int fd) {
1,178✔
951
        struct winsize ws = {};
1,178✔
952

953
        if (fd < 0)
1,178✔
954
                return -EBADF;
955

956
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1,178✔
957
                return -errno;
1,178✔
958

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

962
        return ws.ws_col;
×
963
}
964

965
int getenv_columns(void) {
1,347✔
966
        int r;
1,347✔
967

968
        const char *e = getenv("COLUMNS");
1,347✔
969
        if (!e)
1,347✔
970
                return -ENXIO;
1,347✔
971

972
        unsigned c;
1✔
973
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
1✔
974
        if (r < 0)
1✔
975
                return r;
976

977
        return (int) c;
1✔
978
}
979

980
unsigned columns(void) {
181,932✔
981

982
        if (cached_columns > 0)
181,932✔
983
                return cached_columns;
180,753✔
984

985
        int c = getenv_columns();
1,179✔
986
        if (c < 0) {
1,179✔
987
                c = fd_columns(STDOUT_FILENO);
1,178✔
988
                if (c < 0)
1,178✔
989
                        c = 80;
990
        }
991

992
        assert(c > 0);
1✔
993

994
        cached_columns = c;
1,179✔
995
        return cached_columns;
1,179✔
996
}
997

998
int fd_lines(int fd) {
183✔
999
        struct winsize ws = {};
183✔
1000

1001
        if (fd < 0)
183✔
1002
                return -EBADF;
1003

1004
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
183✔
1005
                return -errno;
183✔
1006

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

1010
        return ws.ws_row;
×
1011
}
1012

1013
unsigned lines(void) {
183✔
1014
        const char *e;
183✔
1015
        int l;
183✔
1016

1017
        if (cached_lines > 0)
183✔
1018
                return cached_lines;
×
1019

1020
        l = 0;
183✔
1021
        e = getenv("LINES");
183✔
1022
        if (e)
183✔
1023
                (void) safe_atoi(e, &l);
×
1024

1025
        if (l <= 0 || l > USHRT_MAX) {
183✔
1026
                l = fd_lines(STDOUT_FILENO);
183✔
1027
                if (l <= 0)
183✔
1028
                        l = 24;
183✔
1029
        }
1030

1031
        cached_lines = l;
183✔
1032
        return cached_lines;
183✔
1033
}
1034

1035
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
1,148✔
1036
        struct winsize ws;
1,148✔
1037

1038
        assert(fd >= 0);
1,148✔
1039

1040
        if (!ident)
1,148✔
1041
                ident = "TTY";
115✔
1042

1043
        if (rows == UINT_MAX && cols == UINT_MAX)
1,148✔
1044
                return 0;
1,148✔
1045

1046
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
945✔
1047
                return log_debug_errno(errno,
×
1048
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1049
                                       ident);
1050

1051
        if (rows == UINT_MAX)
945✔
1052
                rows = ws.ws_row;
×
1053
        else if (rows > USHRT_MAX)
945✔
1054
                rows = USHRT_MAX;
×
1055

1056
        if (cols == UINT_MAX)
945✔
1057
                cols = ws.ws_col;
×
1058
        else if (cols > USHRT_MAX)
945✔
1059
                cols = USHRT_MAX;
×
1060

1061
        if (rows == ws.ws_row && cols == ws.ws_col)
945✔
1062
                return 0;
1063

1064
        ws.ws_row = rows;
426✔
1065
        ws.ws_col = cols;
426✔
1066

1067
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
426✔
1068
                return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
×
1069

1070
        return 0;
1071
}
1072

1073
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
1,118✔
1074
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
1,118✔
1075
        unsigned rows = UINT_MAX, cols = UINT_MAX;
1,118✔
1076
        int r;
1,118✔
1077

1078
        assert(tty);
1,118✔
1079

1080
        if (!ret_rows && !ret_cols)
1,118✔
1081
                return 0;
1082

1083
        tty = skip_dev_prefix(tty);
1,118✔
1084
        if (path_startswith(tty, "pts/"))
1,118✔
1085
                return -EMEDIUMTYPE;
1086
        if (!in_charset(tty, ALPHANUMERICAL))
1,118✔
1087
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
×
1088
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1089

1090
        rowskey = strjoin("systemd.tty.rows.", tty);
1,118✔
1091
        if (!rowskey)
1,118✔
1092
                return -ENOMEM;
1093

1094
        colskey = strjoin("systemd.tty.columns.", tty);
1,118✔
1095
        if (!colskey)
1,118✔
1096
                return -ENOMEM;
1097

1098
        r = proc_cmdline_get_key_many(/* flags = */ 0,
1,118✔
1099
                                      rowskey, &rowsvalue,
1100
                                      colskey, &colsvalue);
1101
        if (r < 0)
1,118✔
1102
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
2✔
1103

1104
        if (rowsvalue) {
1,116✔
1105
                r = safe_atou(rowsvalue, &rows);
945✔
1106
                if (r < 0)
945✔
1107
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
×
1108
        }
1109

1110
        if (colsvalue) {
1,116✔
1111
                r = safe_atou(colsvalue, &cols);
945✔
1112
                if (r < 0)
945✔
1113
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
×
1114
        }
1115

1116
        if (ret_rows)
1,116✔
1117
                *ret_rows = rows;
1,116✔
1118
        if (ret_cols)
1,116✔
1119
                *ret_cols = cols;
1,116✔
1120

1121
        return rows != UINT_MAX || cols != UINT_MAX;
1,116✔
1122
}
1123

1124
/* intended to be used as a SIGWINCH sighandler */
1125
void columns_lines_cache_reset(int signum) {
×
1126
        cached_columns = 0;
×
1127
        cached_lines = 0;
×
1128
}
×
1129

1130
void reset_terminal_feature_caches(void) {
14✔
1131
        cached_columns = 0;
14✔
1132
        cached_lines = 0;
14✔
1133

1134
        cached_color_mode = _COLOR_MODE_INVALID;
14✔
1135
        cached_underline_enabled = -1;
14✔
1136
        cached_on_tty = -1;
14✔
1137
        cached_on_dev_null = -1;
14✔
1138
}
14✔
1139

1140
bool on_tty(void) {
7,315,464✔
1141

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

1148
        if (cached_on_tty < 0)
7,315,464✔
1149
                cached_on_tty =
39,320✔
1150
                        isatty_safe(STDOUT_FILENO) &&
39,335✔
1151
                        isatty_safe(STDERR_FILENO);
15✔
1152

1153
        return cached_on_tty;
7,315,464✔
1154
}
1155

1156
int getttyname_malloc(int fd, char **ret) {
325✔
1157
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
325✔
1158
        int r;
325✔
1159

1160
        assert(fd >= 0);
325✔
1161
        assert(ret);
325✔
1162

1163
        r = ttyname_r(fd, path, sizeof path); /* positive error */
325✔
1164
        assert(r >= 0);
325✔
1165
        if (r == ERANGE)
325✔
1166
                return -ENAMETOOLONG;
325✔
1167
        if (r > 0)
325✔
1168
                return -r;
324✔
1169

1170
        return strdup_to(ret, skip_dev_prefix(path));
1✔
1171
}
1172

1173
int getttyname_harder(int fd, char **ret) {
22✔
1174
        _cleanup_free_ char *s = NULL;
22✔
1175
        int r;
22✔
1176

1177
        r = getttyname_malloc(fd, &s);
22✔
1178
        if (r < 0)
22✔
1179
                return r;
1180

1181
        if (streq(s, "tty"))
×
1182
                return get_ctty(0, NULL, ret);
×
1183

1184
        *ret = TAKE_PTR(s);
×
1185
        return 0;
×
1186
}
1187

1188
int get_ctty_devnr(pid_t pid, dev_t *ret) {
2,443✔
1189
        _cleanup_free_ char *line = NULL;
2,443✔
1190
        unsigned long ttynr;
2,443✔
1191
        const char *p;
2,443✔
1192
        int r;
2,443✔
1193

1194
        assert(pid >= 0);
2,443✔
1195

1196
        p = procfs_file_alloca(pid, "stat");
2,443✔
1197
        r = read_one_line_file(p, &line);
2,443✔
1198
        if (r < 0)
2,443✔
1199
                return r;
1200

1201
        p = strrchr(line, ')');
2,443✔
1202
        if (!p)
2,443✔
1203
                return -EIO;
1204

1205
        p++;
2,443✔
1206

1207
        if (sscanf(p, " "
2,443✔
1208
                   "%*c "  /* state */
1209
                   "%*d "  /* ppid */
1210
                   "%*d "  /* pgrp */
1211
                   "%*d "  /* session */
1212
                   "%lu ", /* ttynr */
1213
                   &ttynr) != 1)
1214
                return -EIO;
1215

1216
        if (devnum_is_zero(ttynr))
2,443✔
1217
                return -ENXIO;
1218

1219
        if (ret)
4✔
1220
                *ret = (dev_t) ttynr;
2✔
1221

1222
        return 0;
1223
}
1224

1225
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
30✔
1226
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
30✔
1227
        _cleanup_free_ char *buf = NULL;
30✔
1228
        const char *fn = NULL, *w;
30✔
1229
        dev_t devnr;
30✔
1230
        int r;
30✔
1231

1232
        r = get_ctty_devnr(pid, &devnr);
30✔
1233
        if (r < 0)
30✔
1234
                return r;
1235

1236
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
2✔
1237
        if (r < 0) {
2✔
1238
                struct stat st;
2✔
1239

1240
                if (r != -ENOENT) /* No symlink for this in /dev/char/? */
2✔
1241
                        return r;
×
1242

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

1251
                if (stat(pty, &st) < 0) {
2✔
1252
                        if (errno != ENOENT)
×
1253
                                return -errno;
×
1254

1255
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
2✔
1256
                        fn = pty;
1257

1258
                if (!fn) {
1259
                        /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1260
                         * symlink in /dev/char/. Let's return something vaguely useful. */
1261
                        r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
×
1262
                        if (r < 0)
×
1263
                                return r;
1264

1265
                        fn = buf;
×
1266
                }
1267
        } else
1268
                fn = buf;
×
1269

1270
        w = path_startswith(fn, "/dev/");
2✔
1271
        if (!w)
2✔
1272
                return -EINVAL;
1273

1274
        if (ret) {
2✔
1275
                r = strdup_to(ret, w);
2✔
1276
                if (r < 0)
2✔
1277
                        return r;
1278
        }
1279

1280
        if (ret_devnr)
2✔
1281
                *ret_devnr = devnr;
×
1282

1283
        return 0;
1284
}
1285

1286
int ptsname_malloc(int fd, char **ret) {
143✔
1287
        size_t l = 100;
143✔
1288

1289
        assert(fd >= 0);
143✔
1290
        assert(ret);
143✔
1291

1292
        for (;;) {
143✔
1293
                char *c;
143✔
1294

1295
                c = new(char, l);
143✔
1296
                if (!c)
143✔
1297
                        return -ENOMEM;
1298

1299
                if (ptsname_r(fd, c, l) == 0) {
143✔
1300
                        *ret = c;
143✔
1301
                        return 0;
143✔
1302
                }
1303
                if (errno != ERANGE) {
×
1304
                        free(c);
×
1305
                        return -errno;
×
1306
                }
1307

1308
                free(c);
×
1309

1310
                if (l > SIZE_MAX / 2)
×
1311
                        return -ENOMEM;
1312

1313
                l *= 2;
×
1314
        }
1315
}
1316

1317
int openpt_allocate(int flags, char **ret_peer_path) {
146✔
1318
        _cleanup_close_ int fd = -EBADF;
146✔
1319
        int r;
146✔
1320

1321
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
146✔
1322
        if (fd < 0)
146✔
1323
                return -errno;
×
1324

1325
        _cleanup_free_ char *p = NULL;
146✔
1326
        if (ret_peer_path) {
146✔
1327
                r = ptsname_malloc(fd, &p);
143✔
1328
                if (r < 0)
143✔
1329
                        return r;
1330

1331
                if (!path_startswith(p, "/dev/pts/"))
143✔
1332
                        return -EINVAL;
1333
        }
1334

1335
        if (unlockpt(fd) < 0)
146✔
1336
                return -errno;
×
1337

1338
        if (ret_peer_path)
146✔
1339
                *ret_peer_path = TAKE_PTR(p);
143✔
1340

1341
        return TAKE_FD(fd);
1342
}
1343

1344
static int ptsname_namespace(int pty, char **ret) {
×
1345
        int no = -1;
×
1346

1347
        assert(pty >= 0);
×
1348
        assert(ret);
×
1349

1350
        /* Like ptsname(), but doesn't assume that the path is
1351
         * accessible in the local namespace. */
1352

1353
        if (ioctl(pty, TIOCGPTN, &no) < 0)
×
1354
                return -errno;
×
1355

1356
        if (no < 0)
×
1357
                return -EIO;
1358

1359
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
×
1360
                return -ENOMEM;
×
1361

1362
        return 0;
1363
}
1364

1365
int openpt_allocate_in_namespace(
×
1366
                const PidRef *pidref,
1367
                int flags,
1368
                char **ret_peer_path) {
1369

1370
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
×
1371
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
×
1372
        int r;
×
1373

1374
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
×
1375
        if (r < 0)
×
1376
                return r;
1377

1378
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
×
1379
                return -errno;
×
1380

1381
        r = namespace_fork(
×
1382
                        "(sd-openptns)",
1383
                        "(sd-openpt)",
1384
                        /* except_fds= */ NULL,
1385
                        /* n_except_fds= */ 0,
1386
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1387
                        pidnsfd,
1388
                        mntnsfd,
1389
                        /* netns_fd= */ -EBADF,
1390
                        usernsfd,
1391
                        rootfd,
1392
                        /* ret_pid= */ NULL);
1393
        if (r < 0)
×
1394
                return r;
1395
        if (r == 0) {
×
1396
                pair[0] = safe_close(pair[0]);
×
1397

1398
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
×
1399
                if (fd < 0)
×
1400
                        _exit(EXIT_FAILURE);
×
1401

1402
                if (send_one_fd(pair[1], fd, 0) < 0)
×
1403
                        _exit(EXIT_FAILURE);
×
1404

1405
                _exit(EXIT_SUCCESS);
×
1406
        }
1407

1408
        pair[1] = safe_close(pair[1]);
×
1409

1410
        fd = receive_one_fd(pair[0], 0);
×
1411
        if (fd < 0)
×
1412
                return fd;
1413

1414
        if (ret_peer_path) {
×
1415
                r = ptsname_namespace(fd, ret_peer_path);
×
1416
                if (r < 0)
×
1417
                        return r;
×
1418
        }
1419

1420
        return TAKE_FD(fd);
1421
}
1422

1423
static bool on_dev_null(void) {
47,650✔
1424
        struct stat dst, ost, est;
47,650✔
1425

1426
        if (cached_on_dev_null >= 0)
47,650✔
1427
                return cached_on_dev_null;
8,415✔
1428

1429
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
39,235✔
1430
                cached_on_dev_null = false;
1✔
1431
        else
1432
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
39,920✔
1433

1434
        return cached_on_dev_null;
39,235✔
1435
}
1436

1437
bool getenv_terminal_is_dumb(void) {
2,851✔
1438
        const char *e;
2,851✔
1439

1440
        e = getenv("TERM");
2,851✔
1441
        if (!e)
2,851✔
1442
                return true;
1443

1444
        return streq(e, "dumb");
1,808✔
1445
}
1446

1447
bool terminal_is_dumb(void) {
47,657✔
1448
        if (!on_tty() && !on_dev_null())
47,657✔
1449
                return true;
1450

1451
        return getenv_terminal_is_dumb();
198✔
1452
}
1453

1454
static const char* const color_mode_table[_COLOR_MODE_MAX] = {
1455
        [COLOR_OFF]   = "off",
1456
        [COLOR_16]    = "16",
1457
        [COLOR_256]   = "256",
1458
        [COLOR_24BIT] = "24bit",
1459
};
1460

1461
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_24BIT);
27✔
1462

1463
static ColorMode parse_systemd_colors(void) {
6,886✔
1464
        const char *e;
6,886✔
1465

1466
        e = getenv("SYSTEMD_COLORS");
6,886✔
1467
        if (!e)
6,886✔
1468
                return _COLOR_MODE_INVALID;
1469

1470
        ColorMode m = color_mode_from_string(e);
13✔
1471
        if (m < 0)
13✔
1472
                return log_debug_errno(m, "Failed to parse $SYSTEMD_COLORS value '%s', ignoring: %m", e);
2✔
1473

1474
        return m;
1475
}
1476

1477
static ColorMode get_color_mode_impl(void) {
6,886✔
1478
        /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1479
         * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors, and COLOR_24BIT for
1480
         * unrestricted color output. */
1481

1482
        /* First, we check $SYSTEMD_COLORS, which is the explicit way to change the mode. */
1483
        ColorMode m = parse_systemd_colors();
6,886✔
1484
        if (m >= 0)
6,886✔
1485
                return m;
1486

1487
        /* Next, check for the presence of $NO_COLOR; value is ignored. */
1488
        if (getenv("NO_COLOR"))
6,875✔
1489
                return COLOR_OFF;
1490

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

1498
        /* We failed to figure out any reason to *disable* colors. Let's see how many colors we shall use. */
1499
        if (STRPTR_IN_SET(getenv("COLORTERM"),
×
1500
                          "truecolor",
1501
                          "24bit"))
1502
                return COLOR_24BIT;
×
1503

1504
        /* Note that the Linux console can only display 16 colors. We still enable 256 color mode
1505
         * even for PID1 output though (which typically goes to the Linux console), since the Linux
1506
         * console is able to parse the 256 color sequences and automatically map them to the closest
1507
         * color in the 16 color palette (since kernel 3.16). Doing 256 colors is nice for people who
1508
         * invoke systemd in a container or via a serial link or such, and use a true 256 color
1509
         * terminal to do so. */
1510
        return COLOR_256;
1511
}
1512

1513
ColorMode get_color_mode(void) {
890,008✔
1514
        if (cached_color_mode < 0)
890,008✔
1515
                cached_color_mode = get_color_mode_impl();
6,886✔
1516

1517
        return cached_color_mode;
890,008✔
1518
}
1519

1520
bool dev_console_colors_enabled(void) {
×
1521
        _cleanup_free_ char *s = NULL;
×
1522
        ColorMode m;
×
1523

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

1531
        m = parse_systemd_colors();
×
1532
        if (m >= 0)
×
1533
                return m;
×
1534

1535
        if (getenv("NO_COLOR"))
×
1536
                return false;
1537

1538
        if (getenv_for_pid(1, "TERM", &s) <= 0)
×
1539
                (void) proc_cmdline_get_key("TERM", 0, &s);
×
1540

1541
        return !streq_ptr(s, "dumb");
×
1542
}
1543

1544
bool underline_enabled(void) {
421,181✔
1545

1546
        if (cached_underline_enabled < 0) {
421,181✔
1547

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

1550
                if (colors_enabled())
2,620✔
1551
                        cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1✔
1552
                else
1553
                        cached_underline_enabled = false;
2,619✔
1554
        }
1555

1556
        return cached_underline_enabled;
421,181✔
1557
}
1558

1559
int vt_restore(int fd) {
×
1560

1561
        static const struct vt_mode mode = {
×
1562
                .mode = VT_AUTO,
1563
        };
1564

1565
        int r, ret = 0;
×
1566

1567
        assert(fd >= 0);
×
1568

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

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

1575
        r = vt_reset_keyboard(fd);
×
1576
        if (r < 0)
×
1577
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
×
1578

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

1582
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
×
1583
        if (r < 0)
×
1584
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
×
1585

1586
        return ret;
1587
}
1588

1589
int vt_release(int fd, bool restore) {
×
1590
        assert(fd >= 0);
×
1591

1592
        /* This function releases the VT by acknowledging the VT-switch signal
1593
         * sent by the kernel and optionally reset the VT in text and auto
1594
         * VT-switching modes. */
1595

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

1599
        if (ioctl(fd, VT_RELDISP, 1) < 0)
×
1600
                return -errno;
×
1601

1602
        if (restore)
×
1603
                return vt_restore(fd);
×
1604

1605
        return 0;
1606
}
1607

1608
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
26,589✔
1609
        /* Note that this will initialize output variables only when there's something to output.
1610
         * The caller must pre-initialize to "" or NULL as appropriate. */
1611

1612
        if (priority <= LOG_ERR) {
26,589✔
1613
                if (on)
832✔
1614
                        *on = ansi_highlight_red();
1,664✔
1615
                if (off)
832✔
1616
                        *off = ansi_normal();
1,664✔
1617
                if (highlight)
832✔
1618
                        *highlight = ansi_highlight();
×
1619

1620
        } else if (priority <= LOG_WARNING) {
25,757✔
1621
                if (on)
642✔
1622
                        *on = ansi_highlight_yellow();
642✔
1623
                if (off)
642✔
1624
                        *off = ansi_normal();
1,284✔
1625
                if (highlight)
642✔
1626
                        *highlight = ansi_highlight();
×
1627

1628
        } else if (priority <= LOG_NOTICE) {
25,115✔
1629
                if (on)
219✔
1630
                        *on = ansi_highlight();
438✔
1631
                if (off)
219✔
1632
                        *off = ansi_normal();
438✔
1633
                if (highlight)
219✔
1634
                        *highlight = ansi_highlight_red();
×
1635

1636
        } else if (priority >= LOG_DEBUG) {
24,896✔
1637
                if (on)
8,817✔
1638
                        *on = ansi_grey();
8,817✔
1639
                if (off)
8,817✔
1640
                        *off = ansi_normal();
17,634✔
1641
                if (highlight)
8,817✔
1642
                        *highlight = ansi_highlight_red();
×
1643
        }
1644
}
26,589✔
1645

1646
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
×
1647
        assert(fd >= 0);
×
1648

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

1652
        return loop_write(fd, cursor_position, SIZE_MAX);
×
1653
}
1654

1655
int terminal_reset_defensive(int fd, bool switch_to_text) {
317✔
1656
        int r = 0;
317✔
1657

1658
        assert(fd >= 0);
317✔
1659

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

1668
        if (!isatty_safe(fd))
317✔
1669
                return -ENOTTY;
317✔
1670

1671
        RET_GATHER(r, terminal_reset_ioctl(fd, switch_to_text));
310✔
1672

1673
        if (terminal_is_pty_fd(fd) == 0)
310✔
1674
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
171✔
1675

1676
        return r;
1677
}
1678

1679
int terminal_reset_defensive_locked(int fd, bool switch_to_text) {
6✔
1680
        assert(fd >= 0);
6✔
1681

1682
        _cleanup_close_ int lock_fd = lock_dev_console();
6✔
1683
        if (lock_fd < 0)
6✔
1684
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
×
1685

1686
        return terminal_reset_defensive(fd, switch_to_text);
6✔
1687
}
1688

1689
void termios_disable_echo(struct termios *termios) {
×
1690
        assert(termios);
×
1691

1692
        termios->c_lflag &= ~(ICANON|ECHO);
×
1693
        termios->c_cc[VMIN] = 1;
×
1694
        termios->c_cc[VTIME] = 0;
×
1695
}
×
1696

1697
static int terminal_verify_same(int input_fd, int output_fd) {
1✔
1698
        assert(input_fd >= 0);
1✔
1699
        assert(output_fd >= 0);
1✔
1700

1701
        /* Validates that the specified fds reference the same TTY */
1702

1703
        if (input_fd != output_fd) {
1✔
1704
                struct stat sti;
1✔
1705
                if (fstat(input_fd, &sti) < 0)
1✔
1706
                        return -errno;
1✔
1707

1708
                if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
1✔
1709
                        return -ENOTTY;
1710

1711
                struct stat sto;
1✔
1712
                if (fstat(output_fd, &sto) < 0)
1✔
1713
                        return -errno;
×
1714

1715
                if (!S_ISCHR(sto.st_mode))
1✔
1716
                        return -ENOTTY;
1717

1718
                if (sti.st_rdev != sto.st_rdev)
×
1719
                        return -ENOLINK;
1720
        }
1721

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

1725
        return 0;
1726
}
1727

1728
typedef enum BackgroundColorState {
1729
        BACKGROUND_TEXT,
1730
        BACKGROUND_ESCAPE,
1731
        BACKGROUND_BRACKET,
1732
        BACKGROUND_FIRST_ONE,
1733
        BACKGROUND_SECOND_ONE,
1734
        BACKGROUND_SEMICOLON,
1735
        BACKGROUND_R,
1736
        BACKGROUND_G,
1737
        BACKGROUND_B,
1738
        BACKGROUND_RED,
1739
        BACKGROUND_GREEN,
1740
        BACKGROUND_BLUE,
1741
        BACKGROUND_STRING_TERMINATOR,
1742
} BackgroundColorState;
1743

1744
typedef struct BackgroundColorContext {
1745
        BackgroundColorState state;
1746
        uint32_t red, green, blue;
1747
        unsigned red_bits, green_bits, blue_bits;
1748
} BackgroundColorContext;
1749

1750
static int scan_background_color_response(
×
1751
                BackgroundColorContext *context,
1752
                const char *buf,
1753
                size_t size,
1754
                size_t *ret_processed) {
1755

1756
        assert(context);
×
1757
        assert(buf || size == 0);
×
1758

1759
        for (size_t i = 0; i < size; i++) {
×
1760
                char c = buf[i];
×
1761

1762
                switch (context->state) {
×
1763

1764
                case BACKGROUND_TEXT:
×
1765
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
1766
                        break;
×
1767

1768
                case BACKGROUND_ESCAPE:
×
1769
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
×
1770
                        break;
×
1771

1772
                case BACKGROUND_BRACKET:
×
1773
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
×
1774
                        break;
×
1775

1776
                case BACKGROUND_FIRST_ONE:
×
1777
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
×
1778
                        break;
×
1779

1780
                case BACKGROUND_SECOND_ONE:
×
1781
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
×
1782
                        break;
×
1783

1784
                case BACKGROUND_SEMICOLON:
×
1785
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
×
1786
                        break;
×
1787

1788
                case BACKGROUND_R:
×
1789
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
×
1790
                        break;
×
1791

1792
                case BACKGROUND_G:
×
1793
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
×
1794
                        break;
×
1795

1796
                case BACKGROUND_B:
×
1797
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
×
1798
                        break;
×
1799

1800
                case BACKGROUND_RED:
×
1801
                        if (c == '/')
×
1802
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
×
1803
                        else {
1804
                                int d = unhexchar(c);
×
1805
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
×
1806
                                        context->state = BACKGROUND_TEXT;
×
1807
                                else {
1808
                                        context->red = (context->red << 4) | d;
×
1809
                                        context->red_bits += 4;
×
1810
                                }
1811
                        }
1812
                        break;
1813

1814
                case BACKGROUND_GREEN:
×
1815
                        if (c == '/')
×
1816
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
×
1817
                        else {
1818
                                int d = unhexchar(c);
×
1819
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
×
1820
                                        context->state = BACKGROUND_TEXT;
×
1821
                                else {
1822
                                        context->green = (context->green << 4) | d;
×
1823
                                        context->green_bits += 4;
×
1824
                                }
1825
                        }
1826
                        break;
1827

1828
                case BACKGROUND_BLUE:
×
1829
                        if (c == '\x07') {
×
1830
                                if (context->blue_bits > 0) {
×
1831
                                        if (ret_processed)
×
1832
                                                *ret_processed = i + 1;
×
1833

1834
                                        return 1; /* success! */
×
1835
                                }
1836

1837
                                context->state = BACKGROUND_TEXT;
×
1838
                        } else if (c == '\x1b')
×
1839
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
×
1840
                        else {
1841
                                int d = unhexchar(c);
×
1842
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
×
1843
                                        context->state = BACKGROUND_TEXT;
×
1844
                                else {
1845
                                        context->blue = (context->blue << 4) | d;
×
1846
                                        context->blue_bits += 4;
×
1847
                                }
1848
                        }
1849
                        break;
1850

1851
                case BACKGROUND_STRING_TERMINATOR:
×
1852
                        if (c == '\\') {
×
1853
                                if (ret_processed)
×
1854
                                        *ret_processed = i + 1;
×
1855

1856
                                return 1; /* success! */
×
1857
                        }
1858

1859
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
×
1860
                        break;
×
1861

1862
                }
1863

1864
                /* Reset any colors we might have picked up */
1865
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
×
1866
                        /* reset color */
1867
                        context->red = context->green = context->blue = 0;
×
1868
                        context->red_bits = context->green_bits = context->blue_bits = 0;
×
1869
                }
1870
        }
1871

1872
        if (ret_processed)
×
1873
                *ret_processed = size;
×
1874

1875
        return 0; /* all good, but not enough data yet */
1876
}
1877

1878
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
153✔
1879
        _cleanup_close_ int nonblock_input_fd = -EBADF;
153✔
1880
        int r;
153✔
1881

1882
        assert(ret_red);
153✔
1883
        assert(ret_green);
153✔
1884
        assert(ret_blue);
153✔
1885

1886
        if (!colors_enabled())
153✔
1887
                return -EOPNOTSUPP;
1888

1889
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
×
1890
        if (r < 0)
×
1891
                return r;
1892

1893
        if (streq_ptr(getenv("TERM"), "linux")) {
×
1894
                /* Linux console is black */
1895
                *ret_red = *ret_green = *ret_blue = 0.0;
×
1896
                return 0;
×
1897
        }
1898

1899
        struct termios old_termios;
×
1900
        if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
×
1901
                return -errno;
×
1902

1903
        struct termios new_termios = old_termios;
×
1904
        termios_disable_echo(&new_termios);
×
1905

1906
        if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) < 0)
×
1907
                return -errno;
×
1908

1909
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
×
1910
        if (r < 0)
×
1911
                goto finish;
×
1912

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

1916
        nonblock_input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
1917
        if (nonblock_input_fd < 0)
×
1918
                return nonblock_input_fd;
1919

1920
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
1921
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
×
1922
        size_t buf_full = 0;
×
1923
        BackgroundColorContext context = {};
×
1924

1925
        for (bool first = true;; first = false) {
×
1926
                if (buf_full == 0) {
×
1927
                        usec_t n = now(CLOCK_MONOTONIC);
×
1928
                        if (n >= end) {
×
1929
                                r = -EOPNOTSUPP;
×
1930
                                goto finish;
×
1931
                        }
1932

1933
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
1934
                        if (r < 0)
×
1935
                                goto finish;
×
1936
                        if (r == 0) {
×
1937
                                r = -EOPNOTSUPP;
×
1938
                                goto finish;
×
1939
                        }
1940

1941
                        /* On the first try, read multiple characters, i.e. the shortest valid
1942
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
1943
                         * unnecessarily drop too many characters from the input queue. */
1944
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
1945
                        if (l < 0) {
×
1946
                                if (errno == EAGAIN)
×
1947
                                        continue;
×
1948
                                r = -errno;
×
1949
                                goto finish;
×
1950
                        }
1951

1952
                        assert((size_t) l <= sizeof(buf));
×
1953
                        buf_full = l;
1954
                }
1955

1956
                size_t processed;
×
1957
                r = scan_background_color_response(&context, buf, buf_full, &processed);
×
1958
                if (r < 0)
×
1959
                        goto finish;
×
1960

1961
                assert(processed <= buf_full);
×
1962
                buf_full -= processed;
×
1963
                memmove(buf, buf + processed, buf_full);
×
1964

1965
                if (r > 0) {
×
1966
                        assert(context.red_bits > 0);
×
1967
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
×
1968
                        assert(context.green_bits > 0);
×
1969
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
×
1970
                        assert(context.blue_bits > 0);
×
1971
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
×
1972
                        r = 0;
×
1973
                        goto finish;
×
1974
                }
1975
        }
1976

1977
finish:
×
1978
        RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios)));
×
1979
        return r;
1980
}
1981

1982
typedef enum CursorPositionState {
1983
        CURSOR_TEXT,
1984
        CURSOR_ESCAPE,
1985
        CURSOR_ROW,
1986
        CURSOR_COLUMN,
1987
} CursorPositionState;
1988

1989
typedef struct CursorPositionContext {
1990
        CursorPositionState state;
1991
        unsigned row, column;
1992
} CursorPositionContext;
1993

1994
static int scan_cursor_position_response(
×
1995
                CursorPositionContext *context,
1996
                const char *buf,
1997
                size_t size,
1998
                size_t *ret_processed) {
1999

2000
        assert(context);
×
2001
        assert(buf || size == 0);
×
2002

2003
        for (size_t i = 0; i < size; i++) {
×
2004
                char c = buf[i];
×
2005

2006
                switch (context->state) {
×
2007

2008
                case CURSOR_TEXT:
×
2009
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
×
2010
                        break;
×
2011

2012
                case CURSOR_ESCAPE:
×
2013
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
×
2014
                        break;
×
2015

2016
                case CURSOR_ROW:
×
2017
                        if (c == ';')
×
2018
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
×
2019
                        else {
2020
                                int d = undecchar(c);
×
2021

2022
                                /* We read a decimal character, let's suffix it to the number we so far read,
2023
                                 * but let's do an overflow check first. */
2024
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
×
2025
                                        context->state = CURSOR_TEXT;
×
2026
                                else
2027
                                        context->row = context->row * 10 + d;
×
2028
                        }
2029
                        break;
2030

2031
                case CURSOR_COLUMN:
×
2032
                        if (c == 'R') {
×
2033
                                if (context->column > 0) {
×
2034
                                        if (ret_processed)
×
2035
                                                *ret_processed = i + 1;
×
2036

2037
                                        return 1; /* success! */
×
2038
                                }
2039

2040
                                context->state = CURSOR_TEXT;
×
2041
                        } else {
2042
                                int d = undecchar(c);
×
2043

2044
                                /* As above, add the decimal charatcer to our column number */
2045
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
×
2046
                                        context->state = CURSOR_TEXT;
×
2047
                                else
2048
                                        context->column = context->column * 10 + d;
×
2049
                        }
2050

2051
                        break;
2052
                }
2053

2054
                /* Reset any positions we might have picked up */
2055
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
×
2056
                        context->row = context->column = 0;
×
2057
        }
2058

2059
        if (ret_processed)
×
2060
                *ret_processed = size;
×
2061

2062
        return 0; /* all good, but not enough data yet */
2063
}
2064

2065
int terminal_get_size_by_dsr(
172✔
2066
                int input_fd,
2067
                int output_fd,
2068
                unsigned *ret_rows,
2069
                unsigned *ret_columns) {
2070

2071
        _cleanup_close_ int nonblock_input_fd = -EBADF;
172✔
2072

2073
        assert(input_fd >= 0);
172✔
2074
        assert(output_fd >= 0);
172✔
2075

2076
        int r;
172✔
2077

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

2093
        if (terminal_is_dumb())
172✔
2094
                return -EOPNOTSUPP;
2095

2096
        r = terminal_verify_same(input_fd, output_fd);
×
2097
        if (r < 0)
×
2098
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
×
2099

2100
        struct termios old_termios;
×
2101
        if (tcgetattr(input_fd, &old_termios) < 0)
×
2102
                return log_debug_errno(errno, "Failed to to get terminal settings: %m");
×
2103

2104
        struct termios new_termios = old_termios;
×
2105
        termios_disable_echo(&new_termios);
×
2106

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

2110
        unsigned saved_row = 0, saved_column = 0;
×
2111

2112
        r = loop_write(output_fd,
×
2113
                       "\x1B[6n"           /* Request cursor position (DSR/CPR) */
2114
                       "\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
2115
                       "\x1B[6n",          /* Request cursor position again */
2116
                       SIZE_MAX);
2117
        if (r < 0)
×
2118
                goto finish;
×
2119

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

2123
        nonblock_input_fd = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
×
2124
        if (nonblock_input_fd < 0)
×
2125
                return nonblock_input_fd;
2126

2127
        usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
×
2128
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
×
2129
        size_t buf_full = 0;
×
2130
        CursorPositionContext context = {};
×
2131

2132
        for (bool first = true;; first = false) {
×
2133
                if (buf_full == 0) {
×
2134
                        usec_t n = now(CLOCK_MONOTONIC);
×
2135
                        if (n >= end) {
×
2136
                                r = -EOPNOTSUPP;
×
2137
                                goto finish;
×
2138
                        }
2139

2140
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
×
2141
                        if (r < 0)
×
2142
                                goto finish;
×
2143
                        if (r == 0) {
×
2144
                                r = -EOPNOTSUPP;
×
2145
                                goto finish;
×
2146
                        }
2147

2148
                        /* On the first try, read multiple characters, i.e. the shortest valid
2149
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
2150
                         * unnecessarily drop too many characters from the input queue. */
2151
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
×
2152
                        if (l < 0) {
×
2153
                                if (errno == EAGAIN)
×
2154
                                        continue;
×
2155

2156
                                r = -errno;
×
2157
                                goto finish;
×
2158
                        }
2159

2160
                        assert((size_t) l <= sizeof(buf));
×
2161
                        buf_full = l;
2162
                }
2163

2164
                size_t processed;
×
2165
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
×
2166
                if (r < 0)
×
2167
                        goto finish;
×
2168

2169
                assert(processed <= buf_full);
×
2170
                buf_full -= processed;
×
2171
                memmove(buf, buf + processed, buf_full);
×
2172

2173
                if (r > 0) {
×
2174
                        if (saved_row == 0) {
×
2175
                                assert(saved_column == 0);
×
2176

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

2181
                                /* Superficial validity checks */
2182
                                if (context.row <= 0 || context.column <= 0 || context.row >= 32766 || context.column >= 32766) {
×
2183
                                        r = -ENODATA;
×
2184
                                        goto finish;
×
2185
                                }
2186

2187
                                saved_row = context.row;
×
2188
                                saved_column = context.column;
×
2189

2190
                                /* Reset state */
2191
                                context = (CursorPositionContext) {};
×
2192
                        } else {
2193
                                /* Second sequence, this is the cursor position after we set it somewhere
2194
                                 * into the void at the bottom right. */
2195

2196
                                /* Superficial validity checks (no particular reason to check for < 4, it's
2197
                                 * just a way to look for unreasonably small values) */
2198
                                if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766) {
×
2199
                                        r = -ENODATA;
×
2200
                                        goto finish;
×
2201
                                }
2202

2203
                                if (ret_rows)
×
2204
                                        *ret_rows = context.row;
×
2205
                                if (ret_columns)
×
2206
                                        *ret_columns = context.column;
×
2207

2208
                                r = 0;
×
2209
                                goto finish;
×
2210
                        }
2211
                }
2212
        }
2213

2214
finish:
×
2215
        /* Restore cursor position */
2216
        if (saved_row > 0 && saved_column > 0)
×
2217
                RET_GATHER(r, terminal_set_cursor_position(output_fd, saved_row, saved_column));
×
2218

2219
        RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSADRAIN, &old_termios)));
×
2220
        return r;
2221
}
2222

2223
int terminal_fix_size(int input_fd, int output_fd) {
1✔
2224
        unsigned rows, columns;
1✔
2225
        int r;
1✔
2226

2227
        /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences */
2228

2229
        r = terminal_verify_same(input_fd, output_fd);
1✔
2230
        if (r < 0)
1✔
2231
                return r;
1✔
2232

2233
        struct winsize ws = {};
×
2234
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
×
2235
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
×
2236

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

2241
        if (ws.ws_row == rows && ws.ws_col == columns) {
×
2242
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
×
2243
                return 0;
×
2244
        }
2245

2246
        ws.ws_col = columns;
×
2247
        ws.ws_row = rows;
×
2248

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

2252
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
×
2253
        return 1;
2254
}
2255

2256
int terminal_is_pty_fd(int fd) {
494✔
2257
        int r;
494✔
2258

2259
        assert(fd >= 0);
494✔
2260

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

2263
        if (!isatty_safe(fd))
494✔
2264
                return false;
494✔
2265

2266
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
493✔
2267
        if (r != 0)
493✔
2268
                return r;
2269

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

2273
        int v;
342✔
2274
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
342✔
2275
                if (ERRNO_IS_NOT_SUPPORTED(errno))
342✔
2276
                        return false;
2277

2278
                return -errno;
×
2279
        }
2280

2281
        return true;
2282
}
2283

2284
int pty_open_peer(int fd, int mode) {
18✔
2285
        assert(fd >= 0);
18✔
2286

2287
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2288
         *
2289
         * This is safe to be called on TTYs from other namespaces. */
2290

2291
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
18✔
2292

2293
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
2294
        for (unsigned c = 0;; c++) {
×
2295
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
18✔
2296
                if (peer_fd >= 0)
18✔
2297
                        return peer_fd;
2298

2299
                if (errno != EIO)
×
2300
                        return -errno;
×
2301

2302
                /* Max 1s in total */
2303
                if (c >= 20)
×
2304
                        return -EIO;
2305

2306
                (void) usleep_safe(50 * USEC_PER_MSEC);
×
2307
        }
2308
}
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