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