chiark / gitweb /
dab4f10b06700ffebdd179cda3ba11ca2d108810
[elogind.git] / src / basic / terminal-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2010 Lennart Poettering
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <limits.h>
9 //#include <linux/kd.h>
10 //#include <linux/tiocl.h>
11 //#include <linux/vt.h>
12 //#include <poll.h>
13 //#include <signal.h>
14 #include <stdarg.h>
15 #include <stddef.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/inotify.h>
19 //#include <sys/ioctl.h>
20 #include <sys/socket.h>
21 #include <sys/sysmacros.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 //#include <sys/utsname.h>
25 #include <termios.h>
26 #include <unistd.h>
27
28 #include "alloc-util.h"
29 //#include "copy.h"
30 //#include "def.h"
31 #include "env-util.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 #include "io-util.h"
36 #include "log.h"
37 #include "macro.h"
38 //#include "pager.h"
39 #include "parse-util.h"
40 //#include "path-util.h"
41 //#include "proc-cmdline.h"
42 #include "process-util.h"
43 #include "socket-util.h"
44 #include "stat-util.h"
45 #include "string-util.h"
46 #include "strv.h"
47 #include "terminal-util.h"
48 #include "time-util.h"
49 #include "util.h"
50
51 /// Additional includes needed by elogind
52 #include "path-util.h"
53
54 static volatile unsigned cached_columns = 0;
55 static volatile unsigned cached_lines = 0;
56
57 static volatile int cached_on_tty = -1;
58 static volatile int cached_colors_enabled = -1;
59 static volatile int cached_underline_enabled = -1;
60
61 int chvt(int vt) {
62         _cleanup_close_ int fd;
63
64         /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
65          * if that's configured. */
66
67         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
68         if (fd < 0)
69                 return -errno;
70
71         if (vt <= 0) {
72                 int tiocl[2] = {
73                         TIOCL_GETKMSGREDIRECT,
74                         0
75                 };
76
77                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
78                         return -errno;
79
80                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
81         }
82
83         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
84                 return -errno;
85
86         return 0;
87 }
88
89 #if 0 /// UNNEEDED by elogind
90 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
91         struct termios old_termios, new_termios;
92         char c, line[LINE_MAX];
93
94         assert(f);
95         assert(ret);
96
97         if (tcgetattr(fileno(f), &old_termios) >= 0) {
98                 new_termios = old_termios;
99
100                 new_termios.c_lflag &= ~ICANON;
101                 new_termios.c_cc[VMIN] = 1;
102                 new_termios.c_cc[VTIME] = 0;
103
104                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
105                         size_t k;
106
107                         if (t != USEC_INFINITY) {
108                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
109                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
110                                         return -ETIMEDOUT;
111                                 }
112                         }
113
114                         k = fread(&c, 1, 1, f);
115
116                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
117
118                         if (k <= 0)
119                                 return -EIO;
120
121                         if (need_nl)
122                                 *need_nl = c != '\n';
123
124                         *ret = c;
125                         return 0;
126                 }
127         }
128
129         if (t != USEC_INFINITY) {
130                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
131                         return -ETIMEDOUT;
132         }
133
134         errno = 0;
135         if (!fgets(line, sizeof(line), f))
136                 return errno > 0 ? -errno : -EIO;
137
138         truncate_nl(line);
139
140         if (strlen(line) != 1)
141                 return -EBADMSG;
142
143         if (need_nl)
144                 *need_nl = false;
145
146         *ret = line[0];
147         return 0;
148 }
149
150 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
151
152 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
153         int r;
154
155         assert(ret);
156         assert(replies);
157         assert(fmt);
158
159         for (;;) {
160                 va_list ap;
161                 char c;
162                 bool need_nl = true;
163
164                 if (colors_enabled())
165                         fputs(ANSI_HIGHLIGHT, stdout);
166
167                 putchar('\r');
168
169                 va_start(ap, fmt);
170                 vprintf(fmt, ap);
171                 va_end(ap);
172
173                 if (colors_enabled())
174                         fputs(ANSI_NORMAL, stdout);
175
176                 fflush(stdout);
177
178                 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
179                 if (r < 0) {
180
181                         if (r == -ETIMEDOUT)
182                                 continue;
183
184                         if (r == -EBADMSG) {
185                                 puts("Bad input, please try again.");
186                                 continue;
187                         }
188
189                         putchar('\n');
190                         return r;
191                 }
192
193                 if (need_nl)
194                         putchar('\n');
195
196                 if (strchr(replies, c)) {
197                         *ret = c;
198                         return 0;
199                 }
200
201                 puts("Read unexpected character, please try again.");
202         }
203 }
204
205 int ask_string(char **ret, const char *text, ...) {
206         assert(ret);
207         assert(text);
208
209         for (;;) {
210                 char line[LINE_MAX];
211                 va_list ap;
212
213                 if (colors_enabled())
214                         fputs(ANSI_HIGHLIGHT, stdout);
215
216                 va_start(ap, text);
217                 vprintf(text, ap);
218                 va_end(ap);
219
220                 if (colors_enabled())
221                         fputs(ANSI_NORMAL, stdout);
222
223                 fflush(stdout);
224
225                 errno = 0;
226                 if (!fgets(line, sizeof(line), stdin))
227                         return errno > 0 ? -errno : -EIO;
228
229                 if (!endswith(line, "\n"))
230                         putchar('\n');
231                 else {
232                         char *s;
233
234                         if (isempty(line))
235                                 continue;
236
237                         truncate_nl(line);
238                         s = strdup(line);
239                         if (!s)
240                                 return -ENOMEM;
241
242                         *ret = s;
243                         return 0;
244                 }
245         }
246 }
247
248 int reset_terminal_fd(int fd, bool switch_to_text) {
249         struct termios termios;
250         int r = 0;
251
252         /* Set terminal to some sane defaults */
253
254         assert(fd >= 0);
255
256         /* We leave locked terminal attributes untouched, so that
257          * Plymouth may set whatever it wants to set, and we don't
258          * interfere with that. */
259
260         /* Disable exclusive mode, just in case */
261         (void) ioctl(fd, TIOCNXCL);
262
263         /* Switch to text mode */
264         if (switch_to_text)
265                 (void) ioctl(fd, KDSETMODE, KD_TEXT);
266
267         /* Set default keyboard mode */
268         (void) vt_reset_keyboard(fd);
269
270         if (tcgetattr(fd, &termios) < 0) {
271                 r = -errno;
272                 goto finish;
273         }
274
275         /* We only reset the stuff that matters to the software. How
276          * hardware is set up we don't touch assuming that somebody
277          * else will do that for us */
278
279         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
280         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
281         termios.c_oflag |= ONLCR;
282         termios.c_cflag |= CREAD;
283         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
284
285         termios.c_cc[VINTR]    =   03;  /* ^C */
286         termios.c_cc[VQUIT]    =  034;  /* ^\ */
287         termios.c_cc[VERASE]   = 0177;
288         termios.c_cc[VKILL]    =  025;  /* ^X */
289         termios.c_cc[VEOF]     =   04;  /* ^D */
290         termios.c_cc[VSTART]   =  021;  /* ^Q */
291         termios.c_cc[VSTOP]    =  023;  /* ^S */
292         termios.c_cc[VSUSP]    =  032;  /* ^Z */
293         termios.c_cc[VLNEXT]   =  026;  /* ^V */
294         termios.c_cc[VWERASE]  =  027;  /* ^W */
295         termios.c_cc[VREPRINT] =  022;  /* ^R */
296         termios.c_cc[VEOL]     =    0;
297         termios.c_cc[VEOL2]    =    0;
298
299         termios.c_cc[VTIME]  = 0;
300         termios.c_cc[VMIN]   = 1;
301
302         if (tcsetattr(fd, TCSANOW, &termios) < 0)
303                 r = -errno;
304
305 finish:
306         /* Just in case, flush all crap out */
307         (void) tcflush(fd, TCIOFLUSH);
308
309         return r;
310 }
311
312 int reset_terminal(const char *name) {
313         _cleanup_close_ int fd = -1;
314
315         /* We open the terminal with O_NONBLOCK here, to ensure we
316          * don't block on carrier if this is a terminal with carrier
317          * configured. */
318
319         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
320         if (fd < 0)
321                 return fd;
322
323         return reset_terminal_fd(fd, true);
324 }
325 #endif // 0
326
327 int open_terminal(const char *name, int mode) {
328         unsigned c = 0;
329         int fd;
330
331         /*
332          * If a TTY is in the process of being closed opening it might
333          * cause EIO. This is horribly awful, but unlikely to be
334          * changed in the kernel. Hence we work around this problem by
335          * retrying a couple of times.
336          *
337          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
338          */
339
340         if (mode & O_CREAT)
341                 return -EINVAL;
342
343         for (;;) {
344                 fd = open(name, mode, 0);
345                 if (fd >= 0)
346                         break;
347
348                 if (errno != EIO)
349                         return -errno;
350
351                 /* Max 1s in total */
352                 if (c >= 20)
353                         return -errno;
354
355                 usleep(50 * USEC_PER_MSEC);
356                 c++;
357         }
358
359         if (isatty(fd) <= 0) {
360                 safe_close(fd);
361                 return -ENOTTY;
362         }
363
364         return fd;
365 }
366
367 #if 0 /// UNNEEDED by elogind
368 int acquire_terminal(
369                 const char *name,
370                 AcquireTerminalFlags flags,
371                 usec_t timeout) {
372
373         _cleanup_close_ int notify = -1, fd = -1;
374         usec_t ts = USEC_INFINITY;
375         int r, wd = -1;
376
377         assert(name);
378         assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
379
380         /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
381          * acquire it, so that we don't lose any event.
382          *
383          * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
384          * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
385          * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
386          * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
387          * probably should not do anyway.) */
388
389         if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
390                 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
391                 if (notify < 0)
392                         return -errno;
393
394                 wd = inotify_add_watch(notify, name, IN_CLOSE);
395                 if (wd < 0)
396                         return -errno;
397
398                 if (timeout != USEC_INFINITY)
399                         ts = now(CLOCK_MONOTONIC);
400         }
401
402         for (;;) {
403                 struct sigaction sa_old, sa_new = {
404                         .sa_handler = SIG_IGN,
405                         .sa_flags = SA_RESTART,
406                 };
407
408                 if (notify >= 0) {
409                         r = flush_fd(notify);
410                         if (r < 0)
411                                 return r;
412                 }
413
414                 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
415                  * to figure out if we successfully became the controlling process of the tty */
416                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
417                 if (fd < 0)
418                         return fd;
419
420                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
421                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
422
423                 /* First, try to get the tty */
424                 r = ioctl(fd, TIOCSCTTY,
425                           (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
426
427                 /* Reset signal handler to old value */
428                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
429
430                 /* Success? Exit the loop now! */
431                 if (r >= 0)
432                         break;
433
434                 /* Any failure besides -EPERM? Fail, regardless of the mode. */
435                 if (r != -EPERM)
436                         return r;
437
438                 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
439                                                           * into a success. Note that EPERM is also returned if we
440                                                           * already are the owner of the TTY. */
441                         break;
442
443                 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
444                         return r;
445
446                 assert(notify >= 0);
447                 assert(wd >= 0);
448
449                 for (;;) {
450                         union inotify_event_buffer buffer;
451                         struct inotify_event *e;
452                         ssize_t l;
453
454                         if (timeout != USEC_INFINITY) {
455                                 usec_t n;
456
457                                 assert(ts != USEC_INFINITY);
458
459                                 n = now(CLOCK_MONOTONIC);
460                                 if (ts + timeout < n)
461                                         return -ETIMEDOUT;
462
463                                 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
464                                 if (r < 0)
465                                         return r;
466                                 if (r == 0)
467                                         return -ETIMEDOUT;
468                         }
469
470                         l = read(notify, &buffer, sizeof(buffer));
471                         if (l < 0) {
472                                 if (IN_SET(errno, EINTR, EAGAIN))
473                                         continue;
474
475                                 return -errno;
476                         }
477
478                         FOREACH_INOTIFY_EVENT(e, buffer, l) {
479                                 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
480                                         break;
481
482                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
483                                         return -EIO;
484                         }
485
486                         break;
487                 }
488
489                 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
490                  * we do this after sleeping, so that we don't enter an endless loop. */
491                 fd = safe_close(fd);
492         }
493
494         return TAKE_FD(fd);
495 }
496 #endif // 0
497
498 #if 0 /// UNNEEDED by elogind
499 int release_terminal(void) {
500         static const struct sigaction sa_new = {
501                 .sa_handler = SIG_IGN,
502                 .sa_flags = SA_RESTART,
503         };
504
505         _cleanup_close_ int fd = -1;
506         struct sigaction sa_old;
507         int r;
508
509         fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
510         if (fd < 0)
511                 return -errno;
512
513         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
514          * by our own TIOCNOTTY */
515         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
516
517         r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
518
519         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
520
521         return r;
522 }
523
524 int terminal_vhangup_fd(int fd) {
525         assert(fd >= 0);
526
527         if (ioctl(fd, TIOCVHANGUP) < 0)
528                 return -errno;
529
530         return 0;
531 }
532
533 int terminal_vhangup(const char *name) {
534         _cleanup_close_ int fd;
535
536         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
537         if (fd < 0)
538                 return fd;
539
540         return terminal_vhangup_fd(fd);
541 }
542
543 int vt_disallocate(const char *name) {
544         _cleanup_close_ int fd = -1;
545         const char *e, *n;
546         unsigned u;
547         int r;
548
549         /* Deallocate the VT if possible. If not possible
550          * (i.e. because it is the active one), at least clear it
551          * entirely (including the scrollback buffer) */
552
553         e = path_startswith(name, "/dev/");
554         if (!e)
555                 return -EINVAL;
556
557         if (!tty_is_vc(name)) {
558                 /* So this is not a VT. I guess we cannot deallocate
559                  * it then. But let's at least clear the screen */
560
561                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
562                 if (fd < 0)
563                         return fd;
564
565                 loop_write(fd,
566                            "\033[r"    /* clear scrolling region */
567                            "\033[H"    /* move home */
568                            "\033[2J",  /* clear screen */
569                            10, false);
570                 return 0;
571         }
572
573         n = startswith(e, "tty");
574         if (!n)
575                 return -EINVAL;
576
577         r = safe_atou(n, &u);
578         if (r < 0)
579                 return r;
580
581         if (u <= 0)
582                 return -EINVAL;
583
584         /* Try to deallocate */
585         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
586         if (fd < 0)
587                 return fd;
588
589         r = ioctl(fd, VT_DISALLOCATE, u);
590         fd = safe_close(fd);
591
592         if (r >= 0)
593                 return 0;
594
595         if (errno != EBUSY)
596                 return -errno;
597
598         /* Couldn't deallocate, so let's clear it fully with
599          * scrollback */
600         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
601         if (fd < 0)
602                 return fd;
603
604         loop_write(fd,
605                    "\033[r"   /* clear scrolling region */
606                    "\033[H"   /* move home */
607                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
608                    10, false);
609         return 0;
610 }
611
612 int make_console_stdio(void) {
613         int fd, r;
614
615         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
616
617         fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
618         if (fd < 0)
619                 return log_error_errno(fd, "Failed to acquire terminal: %m");
620
621         r = reset_terminal_fd(fd, true);
622         if (r < 0)
623                 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
624
625         r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
626         if (r < 0)
627                 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
628
629         reset_terminal_feature_caches();
630
631         return 0;
632 }
633 #endif // 0
634
635 bool tty_is_vc(const char *tty) {
636         assert(tty);
637
638         return vtnr_from_tty(tty) >= 0;
639 }
640
641 bool tty_is_console(const char *tty) {
642         assert(tty);
643
644         return streq(skip_dev_prefix(tty), "console");
645 }
646
647 int vtnr_from_tty(const char *tty) {
648         int i, r;
649
650         assert(tty);
651
652         tty = skip_dev_prefix(tty);
653
654         if (!startswith(tty, "tty") )
655                 return -EINVAL;
656
657         if (tty[3] < '0' || tty[3] > '9')
658                 return -EINVAL;
659
660         r = safe_atoi(tty+3, &i);
661         if (r < 0)
662                 return r;
663
664         if (i < 0 || i > 63)
665                 return -EINVAL;
666
667         return i;
668 }
669
670 #if 0 /// UNNEEDED by elogind
671  int resolve_dev_console(char **ret) {
672         _cleanup_free_ char *active = NULL;
673         char *tty;
674         int r;
675
676         assert(ret);
677
678         /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
679          * sign for container setups) */
680
681         if (path_is_read_only_fs("/sys") > 0)
682                 return -ENOMEDIUM;
683
684         r = read_one_line_file("/sys/class/tty/console/active", &active);
685         if (r < 0)
686                 return r;
687
688         /* If multiple log outputs are configured the last one is what /dev/console points to */
689         tty = strrchr(active, ' ');
690         if (tty)
691                 tty++;
692         else
693                 tty = active;
694
695         if (streq(tty, "tty0")) {
696                 active = mfree(active);
697
698                 /* Get the active VC (e.g. tty1) */
699                 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
700                 if (r < 0)
701                         return r;
702
703                 tty = active;
704         }
705
706         if (tty == active)
707                 *ret = TAKE_PTR(active);
708         else {
709                 char *tmp;
710
711                 tmp = strdup(tty);
712                 if (!tmp)
713                         return -ENOMEM;
714
715                 *ret = tmp;
716         }
717
718         return 0;
719 }
720
721 int get_kernel_consoles(char ***ret) {
722         _cleanup_strv_free_ char **l = NULL;
723         _cleanup_free_ char *line = NULL;
724         const char *p;
725         int r;
726
727         assert(ret);
728
729         /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
730          * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
731         if (path_is_read_only_fs("/sys") > 0)
732                 goto fallback;
733
734         r = read_one_line_file("/sys/class/tty/console/active", &line);
735         if (r < 0)
736                 return r;
737
738         p = line;
739         for (;;) {
740                 _cleanup_free_ char *tty = NULL;
741                 char *path;
742
743                 r = extract_first_word(&p, &tty, NULL, 0);
744                 if (r < 0)
745                         return r;
746                 if (r == 0)
747                         break;
748
749                 if (streq(tty, "tty0")) {
750                         tty = mfree(tty);
751                         r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
752                         if (r < 0)
753                                 return r;
754                 }
755
756                 path = strappend("/dev/", tty);
757                 if (!path)
758                         return -ENOMEM;
759
760                 if (access(path, F_OK) < 0) {
761                         log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
762                         free(path);
763                         continue;
764                 }
765
766                 r = strv_consume(&l, path);
767                 if (r < 0)
768                         return r;
769         }
770
771         if (strv_isempty(l)) {
772                 log_debug("No devices found for system console");
773                 goto fallback;
774         }
775
776         *ret = TAKE_PTR(l);
777
778         return 0;
779
780 fallback:
781         r = strv_extend(&l, "/dev/console");
782         if (r < 0)
783                 return r;
784
785         *ret = TAKE_PTR(l);
786
787         return 0;
788 }
789
790 bool tty_is_vc_resolve(const char *tty) {
791         _cleanup_free_ char *resolved = NULL;
792
793         assert(tty);
794
795         tty = skip_dev_prefix(tty);
796
797         if (streq(tty, "console")) {
798                 if (resolve_dev_console(&resolved) < 0)
799                         return false;
800
801                 tty = resolved;
802         }
803
804         return tty_is_vc(tty);
805 }
806
807 const char *default_term_for_tty(const char *tty) {
808         return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
809 }
810 #endif // 0
811
812 int fd_columns(int fd) {
813         struct winsize ws = {};
814
815         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
816                 return -errno;
817
818         if (ws.ws_col <= 0)
819                 return -EIO;
820
821         return ws.ws_col;
822 }
823
824 unsigned columns(void) {
825         const char *e;
826         int c;
827
828         if (cached_columns > 0)
829                 return cached_columns;
830
831         c = 0;
832         e = getenv("COLUMNS");
833         if (e)
834                 (void) safe_atoi(e, &c);
835
836         if (c <= 0)
837                 c = fd_columns(STDOUT_FILENO);
838
839         if (c <= 0)
840                 c = 80;
841
842         cached_columns = c;
843         return cached_columns;
844 }
845
846 int fd_lines(int fd) {
847         struct winsize ws = {};
848
849         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
850                 return -errno;
851
852         if (ws.ws_row <= 0)
853                 return -EIO;
854
855         return ws.ws_row;
856 }
857
858 unsigned lines(void) {
859         const char *e;
860         int l;
861
862         if (cached_lines > 0)
863                 return cached_lines;
864
865         l = 0;
866         e = getenv("LINES");
867         if (e)
868                 (void) safe_atoi(e, &l);
869
870         if (l <= 0)
871                 l = fd_lines(STDOUT_FILENO);
872
873         if (l <= 0)
874                 l = 24;
875
876         cached_lines = l;
877         return cached_lines;
878 }
879
880 /* intended to be used as a SIGWINCH sighandler */
881 #if 0 /// UNNEEDED by elogind
882 void columns_lines_cache_reset(int signum) {
883         cached_columns = 0;
884         cached_lines = 0;
885 }
886 #endif // 0
887
888 void reset_terminal_feature_caches(void) {
889         cached_columns = 0;
890         cached_lines = 0;
891
892         cached_colors_enabled = -1;
893         cached_underline_enabled = -1;
894         cached_on_tty = -1;
895 }
896
897 bool on_tty(void) {
898
899         /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
900          * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
901          * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
902          * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
903          * terminal functionality when outputting stuff, even if the input is piped to us. */
904
905         if (cached_on_tty < 0)
906                 cached_on_tty =
907                         isatty(STDOUT_FILENO) > 0 &&
908                         isatty(STDERR_FILENO) > 0;
909
910         return cached_on_tty;
911 }
912
913 int getttyname_malloc(int fd, char **ret) {
914         size_t l = 100;
915         int r;
916
917         assert(fd >= 0);
918         assert(ret);
919
920         for (;;) {
921                 char path[l];
922
923                 r = ttyname_r(fd, path, sizeof(path));
924                 if (r == 0) {
925                         char *c;
926
927                         c = strdup(skip_dev_prefix(path));
928                         if (!c)
929                                 return -ENOMEM;
930
931                         *ret = c;
932                         return 0;
933                 }
934
935                 if (r != ERANGE)
936                         return -r;
937
938                 l *= 2;
939         }
940
941         return 0;
942 }
943
944 int getttyname_harder(int fd, char **r) {
945         int k;
946         char *s = NULL;
947
948         k = getttyname_malloc(fd, &s);
949         if (k < 0)
950                 return k;
951
952         if (streq(s, "tty")) {
953                 free(s);
954                 return get_ctty(0, NULL, r);
955         }
956
957         *r = s;
958         return 0;
959 }
960
961 int get_ctty_devnr(pid_t pid, dev_t *d) {
962         int r;
963         _cleanup_free_ char *line = NULL;
964         const char *p;
965         unsigned long ttynr;
966
967         assert(pid >= 0);
968
969         p = procfs_file_alloca(pid, "stat");
970         r = read_one_line_file(p, &line);
971         if (r < 0)
972                 return r;
973
974         p = strrchr(line, ')');
975         if (!p)
976                 return -EIO;
977
978         p++;
979
980         if (sscanf(p, " "
981                    "%*c "  /* state */
982                    "%*d "  /* ppid */
983                    "%*d "  /* pgrp */
984                    "%*d "  /* session */
985                    "%lu ", /* ttynr */
986                    &ttynr) != 1)
987                 return -EIO;
988
989         if (major(ttynr) == 0 && minor(ttynr) == 0)
990                 return -ENXIO;
991
992         if (d)
993                 *d = (dev_t) ttynr;
994
995         return 0;
996 }
997
998 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
999         char fn[STRLEN("/dev/char/") + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
1000         _cleanup_free_ char *s = NULL;
1001         const char *p;
1002         dev_t devnr;
1003         int k;
1004
1005         assert(r);
1006
1007         k = get_ctty_devnr(pid, &devnr);
1008         if (k < 0)
1009                 return k;
1010
1011         sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
1012
1013         k = readlink_malloc(fn, &s);
1014         if (k < 0) {
1015
1016                 if (k != -ENOENT)
1017                         return k;
1018
1019                 /* This is an ugly hack */
1020                 if (major(devnr) == 136) {
1021                         if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
1022                                 return -ENOMEM;
1023                 } else {
1024                         /* Probably something like the ptys which have no
1025                          * symlink in /dev/char. Let's return something
1026                          * vaguely useful. */
1027
1028                         b = strdup(fn + 5);
1029                         if (!b)
1030                                 return -ENOMEM;
1031                 }
1032         } else {
1033                 if (startswith(s, "/dev/"))
1034                         p = s + 5;
1035                 else if (startswith(s, "../"))
1036                         p = s + 3;
1037                 else
1038                         p = s;
1039
1040                 b = strdup(p);
1041                 if (!b)
1042                         return -ENOMEM;
1043         }
1044
1045         *r = b;
1046         if (_devnr)
1047                 *_devnr = devnr;
1048
1049         return 0;
1050 }
1051
1052 #if 0 /// UNNEEDED by elogind
1053 int ptsname_malloc(int fd, char **ret) {
1054         size_t l = 100;
1055
1056         assert(fd >= 0);
1057         assert(ret);
1058
1059         for (;;) {
1060                 char *c;
1061
1062                 c = new(char, l);
1063                 if (!c)
1064                         return -ENOMEM;
1065
1066                 if (ptsname_r(fd, c, l) == 0) {
1067                         *ret = c;
1068                         return 0;
1069                 }
1070                 if (errno != ERANGE) {
1071                         free(c);
1072                         return -errno;
1073                 }
1074
1075                 free(c);
1076                 l *= 2;
1077         }
1078 }
1079
1080 int ptsname_namespace(int pty, char **ret) {
1081         int no = -1, r;
1082
1083         /* Like ptsname(), but doesn't assume that the path is
1084          * accessible in the local namespace. */
1085
1086         r = ioctl(pty, TIOCGPTN, &no);
1087         if (r < 0)
1088                 return -errno;
1089
1090         if (no < 0)
1091                 return -EIO;
1092
1093         if (asprintf(ret, "/dev/pts/%i", no) < 0)
1094                 return -ENOMEM;
1095
1096         return 0;
1097 }
1098
1099 int openpt_in_namespace(pid_t pid, int flags) {
1100         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1101         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1102         pid_t child;
1103         int r;
1104
1105         assert(pid > 0);
1106
1107         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1108         if (r < 0)
1109                 return r;
1110
1111         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1112                 return -errno;
1113
1114         r = safe_fork("(sd-openpt)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1115         if (r < 0)
1116                 return r;
1117         if (r == 0) {
1118                 int master;
1119
1120                 pair[0] = safe_close(pair[0]);
1121
1122                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1123                 if (r < 0)
1124                         _exit(EXIT_FAILURE);
1125
1126                 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1127                 if (master < 0)
1128                         _exit(EXIT_FAILURE);
1129
1130                 if (unlockpt(master) < 0)
1131                         _exit(EXIT_FAILURE);
1132
1133                 if (send_one_fd(pair[1], master, 0) < 0)
1134                         _exit(EXIT_FAILURE);
1135
1136                 _exit(EXIT_SUCCESS);
1137         }
1138
1139         pair[1] = safe_close(pair[1]);
1140
1141         r = wait_for_terminate_and_check("(sd-openpt)", child, 0);
1142         if (r < 0)
1143                 return r;
1144         if (r != EXIT_SUCCESS)
1145                 return -EIO;
1146
1147         return receive_one_fd(pair[0], 0);
1148 }
1149
1150 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1151         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1152         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1153         pid_t child;
1154         int r;
1155
1156         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1157         if (r < 0)
1158                 return r;
1159
1160         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1161                 return -errno;
1162
1163         r = safe_fork("(sd-terminal)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1164         if (r < 0)
1165                 return r;
1166         if (r == 0) {
1167                 int master;
1168
1169                 pair[0] = safe_close(pair[0]);
1170
1171                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1172                 if (r < 0)
1173                         _exit(EXIT_FAILURE);
1174
1175                 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1176                 if (master < 0)
1177                         _exit(EXIT_FAILURE);
1178
1179                 if (send_one_fd(pair[1], master, 0) < 0)
1180                         _exit(EXIT_FAILURE);
1181
1182                 _exit(EXIT_SUCCESS);
1183         }
1184
1185         pair[1] = safe_close(pair[1]);
1186
1187         r = wait_for_terminate_and_check("(sd-terminal)", child, 0);
1188         if (r < 0)
1189                 return r;
1190         if (r != EXIT_SUCCESS)
1191                 return -EIO;
1192
1193         return receive_one_fd(pair[0], 0);
1194 }
1195 #endif // 0
1196
1197 static bool getenv_terminal_is_dumb(void) {
1198         const char *e;
1199
1200         e = getenv("TERM");
1201         if (!e)
1202                 return true;
1203
1204         return streq(e, "dumb");
1205 }
1206
1207 bool terminal_is_dumb(void) {
1208         if (!on_tty())
1209                 return true;
1210
1211         return getenv_terminal_is_dumb();
1212 }
1213
1214 bool colors_enabled(void) {
1215
1216         /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1217          * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1218          * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if
1219          * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1220          * continously due to fear of SAK, and hence things are a bit weird. */
1221
1222         if (cached_colors_enabled < 0) {
1223 #if 0 /// elogind does not allow such forcing, and we are never init!
1224                 int val;
1225
1226                 val = getenv_bool("SYSTEMD_COLORS");
1227                 if (val >= 0)
1228                         cached_colors_enabled = val;
1229                 else if (getpid_cached() == 1)
1230                         /* PID1 outputs to the console without holding it open all the time */
1231                         cached_colors_enabled = !getenv_terminal_is_dumb();
1232                 else
1233 #endif // 0
1234                         cached_colors_enabled = !terminal_is_dumb();
1235         }
1236
1237         return cached_colors_enabled;
1238 }
1239
1240 #if 0 /// UNNEEDED by elogind
1241 bool dev_console_colors_enabled(void) {
1242         _cleanup_free_ char *s = NULL;
1243         int b;
1244
1245         /* Returns true if we assume that color is supported on /dev/console.
1246          *
1247          * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1248          * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1249          * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1250          * colors_enabled() operates. */
1251
1252         b = getenv_bool("SYSTEMD_COLORS");
1253         if (b >= 0)
1254                 return b;
1255
1256         if (getenv_for_pid(1, "TERM", &s) <= 0)
1257                 (void) proc_cmdline_get_key("TERM", 0, &s);
1258
1259         return !streq_ptr(s, "dumb");
1260 }
1261 #endif // 0
1262
1263 bool underline_enabled(void) {
1264
1265         if (cached_underline_enabled < 0) {
1266
1267                 /* The Linux console doesn't support underlining, turn it off, but only there. */
1268
1269                 if (colors_enabled())
1270                         cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1271                 else
1272                         cached_underline_enabled = false;
1273         }
1274
1275         return cached_underline_enabled;
1276 }
1277
1278 int vt_default_utf8(void) {
1279         _cleanup_free_ char *b = NULL;
1280         int r;
1281
1282         /* Read the default VT UTF8 setting from the kernel */
1283
1284         r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1285         if (r < 0)
1286                 return r;
1287
1288         return parse_boolean(b);
1289 }
1290
1291 int vt_reset_keyboard(int fd) {
1292         int kb;
1293
1294         /* If we can't read the default, then default to unicode. It's 2017 after all. */
1295         kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1296
1297         if (ioctl(fd, KDSKBMODE, kb) < 0)
1298                 return -errno;
1299
1300         return 0;
1301 }
1302
1303 static bool urlify_enabled(void) {
1304         static int cached_urlify_enabled = -1;
1305
1306         /* Unfortunately 'less' doesn't support links like this yet ðŸ˜­, hence let's disable this as long as there's a
1307          * pager in effect. Let's drop this check as soon as less got fixed a and enough time passed so that it's safe
1308          * to assume that a link-enabled 'less' version has hit most installations. */
1309
1310         if (cached_urlify_enabled < 0) {
1311                 int val;
1312
1313                 val = getenv_bool("SYSTEMD_URLIFY");
1314                 if (val >= 0)
1315                         cached_urlify_enabled = val;
1316                 else
1317                         cached_urlify_enabled = colors_enabled() && !pager_have();
1318         }
1319
1320         return cached_urlify_enabled;
1321 }
1322
1323 int terminal_urlify(const char *url, const char *text, char **ret) {
1324         char *n;
1325
1326         assert(url);
1327
1328         /* Takes an URL and a pretty string and formats it as clickable link for the terminal. See
1329          * https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda for details. */
1330
1331         if (isempty(text))
1332                 text = url;
1333
1334         if (urlify_enabled())
1335                 n = strjoin("\x1B]8;;", url, "\a", text, "\x1B]8;;\a");
1336         else
1337                 n = strdup(text);
1338         if (!n)
1339                 return -ENOMEM;
1340
1341         *ret = n;
1342         return 0;
1343 }
1344
1345 int terminal_urlify_path(const char *path, const char *text, char **ret) {
1346         _cleanup_free_ char *absolute = NULL;
1347         struct utsname u;
1348         const char *url;
1349         int r;
1350
1351         assert(path);
1352
1353         /* Much like terminal_urlify() above, but takes a file system path as input
1354          * and turns it into a proper file:// URL first. */
1355
1356         if (isempty(path))
1357                 return -EINVAL;
1358
1359         if (isempty(text))
1360                 text = path;
1361
1362         if (!urlify_enabled()) {
1363                 char *n;
1364
1365                 n = strdup(text);
1366                 if (!n)
1367                         return -ENOMEM;
1368
1369                 *ret = n;
1370                 return 0;
1371         }
1372
1373         if (uname(&u) < 0)
1374                 return -errno;
1375
1376         if (!path_is_absolute(path)) {
1377                 r = path_make_absolute_cwd(path, &absolute);
1378                 if (r < 0)
1379                         return r;
1380
1381                 path = absolute;
1382         }
1383
1384         /* As suggested by https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda, let's include the local
1385          * hostname here. Note that we don't use gethostname_malloc() or gethostname_strict() since we are interested
1386          * in the raw string the kernel has set, whatever it may be, under the assumption that terminals are not overly
1387          * careful with validating the strings either. */
1388
1389         url = strjoina("file://", u.nodename, path);
1390
1391         return terminal_urlify(url, text, ret);
1392 }
1393
1394 static int cat_file(const char *filename, bool newline) {
1395         _cleanup_fclose_ FILE *f = NULL;
1396         _cleanup_free_ char *urlified = NULL;
1397         int r;
1398
1399         f = fopen(filename, "re");
1400         if (!f)
1401                 return -errno;
1402
1403         r = terminal_urlify_path(filename, NULL, &urlified);
1404         if (r < 0)
1405                 return r;
1406
1407         printf("%s%s# %s%s\n",
1408                newline ? "\n" : "",
1409                ansi_highlight_blue(),
1410                urlified,
1411                ansi_normal());
1412         fflush(stdout);
1413
1414         for (;;) {
1415                 _cleanup_free_ char *line = NULL;
1416
1417                 r = read_line(f, LONG_LINE_MAX, &line);
1418                 if (r < 0)
1419                         return log_error_errno(r, "Failed to read \"%s\": %m", filename);
1420                 if (r == 0)
1421                         break;
1422
1423                 puts(line);
1424         }
1425
1426         return 0;
1427 }
1428
1429 int cat_files(const char *file, char **dropins, CatFlags flags) {
1430         char **path;
1431         int r;
1432
1433         if (file) {
1434                 r = cat_file(file, false);
1435                 if (r == -ENOENT && (flags & CAT_FLAGS_MAIN_FILE_OPTIONAL))
1436                         printf("%s# config file %s not found%s\n",
1437                                ansi_highlight_magenta(),
1438                                file,
1439                                ansi_normal());
1440                 else if (r < 0)
1441                         return log_warning_errno(r, "Failed to cat %s: %m", file);
1442         }
1443
1444         STRV_FOREACH(path, dropins) {
1445                 r = cat_file(*path, file || path != dropins);
1446                 if (r < 0)
1447                         return log_warning_errno(r, "Failed to cat %s: %m", *path);
1448         }
1449
1450         return 0;
1451 }
1452
1453 void print_separator(void) {
1454
1455         /* Outputs a separator line that resolves to whitespace when copied from the terminal. We do that by outputting
1456          * one line filled with spaces with ANSI underline set, followed by a second (empty) line. */
1457
1458         if (underline_enabled()) {
1459                 size_t i, c;
1460
1461                 c = columns();
1462
1463                 flockfile(stdout);
1464                 fputs_unlocked(ANSI_UNDERLINE, stdout);
1465
1466                 for (i = 0; i < c; i++)
1467                         fputc_unlocked(' ', stdout);
1468
1469                 fputs_unlocked(ANSI_NORMAL "\n\n", stdout);
1470                 funlockfile(stdout);
1471         } else
1472                 fputs("\n\n", stdout);
1473 }