chiark / gitweb /
Fix typo
[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 "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         if (cached_on_tty < 0)
899                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
900
901         return cached_on_tty;
902 }
903
904 int getttyname_malloc(int fd, char **ret) {
905         size_t l = 100;
906         int r;
907
908         assert(fd >= 0);
909         assert(ret);
910
911         for (;;) {
912                 char path[l];
913
914                 r = ttyname_r(fd, path, sizeof(path));
915                 if (r == 0) {
916                         char *c;
917
918                         c = strdup(skip_dev_prefix(path));
919                         if (!c)
920                                 return -ENOMEM;
921
922                         *ret = c;
923                         return 0;
924                 }
925
926                 if (r != ERANGE)
927                         return -r;
928
929                 l *= 2;
930         }
931
932         return 0;
933 }
934
935 int getttyname_harder(int fd, char **r) {
936         int k;
937         char *s = NULL;
938
939         k = getttyname_malloc(fd, &s);
940         if (k < 0)
941                 return k;
942
943         if (streq(s, "tty")) {
944                 free(s);
945                 return get_ctty(0, NULL, r);
946         }
947
948         *r = s;
949         return 0;
950 }
951
952 int get_ctty_devnr(pid_t pid, dev_t *d) {
953         int r;
954         _cleanup_free_ char *line = NULL;
955         const char *p;
956         unsigned long ttynr;
957
958         assert(pid >= 0);
959
960         p = procfs_file_alloca(pid, "stat");
961         r = read_one_line_file(p, &line);
962         if (r < 0)
963                 return r;
964
965         p = strrchr(line, ')');
966         if (!p)
967                 return -EIO;
968
969         p++;
970
971         if (sscanf(p, " "
972                    "%*c "  /* state */
973                    "%*d "  /* ppid */
974                    "%*d "  /* pgrp */
975                    "%*d "  /* session */
976                    "%lu ", /* ttynr */
977                    &ttynr) != 1)
978                 return -EIO;
979
980         if (major(ttynr) == 0 && minor(ttynr) == 0)
981                 return -ENXIO;
982
983         if (d)
984                 *d = (dev_t) ttynr;
985
986         return 0;
987 }
988
989 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
990         char fn[STRLEN("/dev/char/") + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
991         _cleanup_free_ char *s = NULL;
992         const char *p;
993         dev_t devnr;
994         int k;
995
996         assert(r);
997
998         k = get_ctty_devnr(pid, &devnr);
999         if (k < 0)
1000                 return k;
1001
1002         sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
1003
1004         k = readlink_malloc(fn, &s);
1005         if (k < 0) {
1006
1007                 if (k != -ENOENT)
1008                         return k;
1009
1010                 /* This is an ugly hack */
1011                 if (major(devnr) == 136) {
1012                         if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
1013                                 return -ENOMEM;
1014                 } else {
1015                         /* Probably something like the ptys which have no
1016                          * symlink in /dev/char. Let's return something
1017                          * vaguely useful. */
1018
1019                         b = strdup(fn + 5);
1020                         if (!b)
1021                                 return -ENOMEM;
1022                 }
1023         } else {
1024                 if (startswith(s, "/dev/"))
1025                         p = s + 5;
1026                 else if (startswith(s, "../"))
1027                         p = s + 3;
1028                 else
1029                         p = s;
1030
1031                 b = strdup(p);
1032                 if (!b)
1033                         return -ENOMEM;
1034         }
1035
1036         *r = b;
1037         if (_devnr)
1038                 *_devnr = devnr;
1039
1040         return 0;
1041 }
1042
1043 #if 0 /// UNNEEDED by elogind
1044 int ptsname_malloc(int fd, char **ret) {
1045         size_t l = 100;
1046
1047         assert(fd >= 0);
1048         assert(ret);
1049
1050         for (;;) {
1051                 char *c;
1052
1053                 c = new(char, l);
1054                 if (!c)
1055                         return -ENOMEM;
1056
1057                 if (ptsname_r(fd, c, l) == 0) {
1058                         *ret = c;
1059                         return 0;
1060                 }
1061                 if (errno != ERANGE) {
1062                         free(c);
1063                         return -errno;
1064                 }
1065
1066                 free(c);
1067                 l *= 2;
1068         }
1069 }
1070
1071 int ptsname_namespace(int pty, char **ret) {
1072         int no = -1, r;
1073
1074         /* Like ptsname(), but doesn't assume that the path is
1075          * accessible in the local namespace. */
1076
1077         r = ioctl(pty, TIOCGPTN, &no);
1078         if (r < 0)
1079                 return -errno;
1080
1081         if (no < 0)
1082                 return -EIO;
1083
1084         if (asprintf(ret, "/dev/pts/%i", no) < 0)
1085                 return -ENOMEM;
1086
1087         return 0;
1088 }
1089
1090 int openpt_in_namespace(pid_t pid, int flags) {
1091         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1092         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1093         pid_t child;
1094         int r;
1095
1096         assert(pid > 0);
1097
1098         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1099         if (r < 0)
1100                 return r;
1101
1102         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1103                 return -errno;
1104
1105         r = safe_fork("(sd-openpt)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1106         if (r < 0)
1107                 return r;
1108         if (r == 0) {
1109                 int master;
1110
1111                 pair[0] = safe_close(pair[0]);
1112
1113                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1114                 if (r < 0)
1115                         _exit(EXIT_FAILURE);
1116
1117                 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1118                 if (master < 0)
1119                         _exit(EXIT_FAILURE);
1120
1121                 if (unlockpt(master) < 0)
1122                         _exit(EXIT_FAILURE);
1123
1124                 if (send_one_fd(pair[1], master, 0) < 0)
1125                         _exit(EXIT_FAILURE);
1126
1127                 _exit(EXIT_SUCCESS);
1128         }
1129
1130         pair[1] = safe_close(pair[1]);
1131
1132         r = wait_for_terminate_and_check("(sd-openpt)", child, 0);
1133         if (r < 0)
1134                 return r;
1135         if (r != EXIT_SUCCESS)
1136                 return -EIO;
1137
1138         return receive_one_fd(pair[0], 0);
1139 }
1140
1141 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1142         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1143         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1144         pid_t child;
1145         int r;
1146
1147         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1148         if (r < 0)
1149                 return r;
1150
1151         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1152                 return -errno;
1153
1154         r = safe_fork("(sd-terminal)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1155         if (r < 0)
1156                 return r;
1157         if (r == 0) {
1158                 int master;
1159
1160                 pair[0] = safe_close(pair[0]);
1161
1162                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1163                 if (r < 0)
1164                         _exit(EXIT_FAILURE);
1165
1166                 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1167                 if (master < 0)
1168                         _exit(EXIT_FAILURE);
1169
1170                 if (send_one_fd(pair[1], master, 0) < 0)
1171                         _exit(EXIT_FAILURE);
1172
1173                 _exit(EXIT_SUCCESS);
1174         }
1175
1176         pair[1] = safe_close(pair[1]);
1177
1178         r = wait_for_terminate_and_check("(sd-terminal)", child, 0);
1179         if (r < 0)
1180                 return r;
1181         if (r != EXIT_SUCCESS)
1182                 return -EIO;
1183
1184         return receive_one_fd(pair[0], 0);
1185 }
1186 #endif // 0
1187
1188 static bool getenv_terminal_is_dumb(void) {
1189         const char *e;
1190
1191         e = getenv("TERM");
1192         if (!e)
1193                 return true;
1194
1195         return streq(e, "dumb");
1196 }
1197
1198 bool terminal_is_dumb(void) {
1199         if (!on_tty())
1200                 return true;
1201
1202         return getenv_terminal_is_dumb();
1203 }
1204
1205 bool colors_enabled(void) {
1206
1207         /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1208          * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1209          * 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
1210          * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1211          * continously due to fear of SAK, and hence things are a bit weird. */
1212
1213         if (cached_colors_enabled < 0) {
1214 #if 0 /// elogind does not allow such forcing, and we are never init!
1215                 int val;
1216
1217                 val = getenv_bool("SYSTEMD_COLORS");
1218                 if (val >= 0)
1219                         cached_colors_enabled = val;
1220                 else if (getpid_cached() == 1)
1221                         /* PID1 outputs to the console without holding it open all the time */
1222                         cached_colors_enabled = !getenv_terminal_is_dumb();
1223                 else
1224 #endif // 0
1225                         cached_colors_enabled = !terminal_is_dumb();
1226         }
1227
1228         return cached_colors_enabled;
1229 }
1230
1231 #if 0 /// UNNEEDED by elogind
1232 bool dev_console_colors_enabled(void) {
1233         _cleanup_free_ char *s = NULL;
1234         int b;
1235
1236         /* Returns true if we assume that color is supported on /dev/console.
1237          *
1238          * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1239          * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1240          * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1241          * colors_enabled() operates. */
1242
1243         b = getenv_bool("SYSTEMD_COLORS");
1244         if (b >= 0)
1245                 return b;
1246
1247         if (getenv_for_pid(1, "TERM", &s) <= 0)
1248                 (void) proc_cmdline_get_key("TERM", 0, &s);
1249
1250         return !streq_ptr(s, "dumb");
1251 }
1252 #endif // 0
1253
1254 bool underline_enabled(void) {
1255
1256         if (cached_underline_enabled < 0) {
1257
1258                 /* The Linux console doesn't support underlining, turn it off, but only there. */
1259
1260                 if (colors_enabled())
1261                         cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1262                 else
1263                         cached_underline_enabled = false;
1264         }
1265
1266         return cached_underline_enabled;
1267 }
1268
1269 int vt_default_utf8(void) {
1270         _cleanup_free_ char *b = NULL;
1271         int r;
1272
1273         /* Read the default VT UTF8 setting from the kernel */
1274
1275         r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1276         if (r < 0)
1277                 return r;
1278
1279         return parse_boolean(b);
1280 }
1281
1282 int vt_reset_keyboard(int fd) {
1283         int kb;
1284
1285         /* If we can't read the default, then default to unicode. It's 2017 after all. */
1286         kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1287
1288         if (ioctl(fd, KDSKBMODE, kb) < 0)
1289                 return -errno;
1290
1291         return 0;
1292 }
1293
1294 static bool urlify_enabled(void) {
1295         static int cached_urlify_enabled = -1;
1296
1297         /* Unfortunately 'less' doesn't support links like this yet ðŸ˜­, hence let's disable this as long as there's a
1298          * pager in effect. Let's drop this check as soon as less got fixed a and enough time passed so that it's safe
1299          * to assume that a link-enabled 'less' version has hit most installations. */
1300
1301         if (cached_urlify_enabled < 0) {
1302                 int val;
1303
1304                 val = getenv_bool("SYSTEMD_URLIFY");
1305                 if (val >= 0)
1306                         cached_urlify_enabled = val;
1307                 else
1308                         cached_urlify_enabled = colors_enabled() && !pager_have();
1309         }
1310
1311         return cached_urlify_enabled;
1312 }
1313
1314 int terminal_urlify(const char *url, const char *text, char **ret) {
1315         char *n;
1316
1317         assert(url);
1318
1319         /* Takes an URL and a pretty string and formats it as clickable link for the terminal. See
1320          * https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda for details. */
1321
1322         if (isempty(text))
1323                 text = url;
1324
1325         if (urlify_enabled())
1326                 n = strjoin("\x1B]8;;", url, "\a", text, "\x1B]8;;\a");
1327         else
1328                 n = strdup(text);
1329         if (!n)
1330                 return -ENOMEM;
1331
1332         *ret = n;
1333         return 0;
1334 }
1335
1336 int terminal_urlify_path(const char *path, const char *text, char **ret) {
1337         _cleanup_free_ char *absolute = NULL;
1338         struct utsname u;
1339         const char *url;
1340         int r;
1341
1342         assert(path);
1343
1344         /* Much like terminal_urlify() above, but takes a file system path as input
1345          * and turns it into a proper file:// URL first. */
1346
1347         if (isempty(path))
1348                 return -EINVAL;
1349
1350         if (isempty(text))
1351                 text = path;
1352
1353         if (!urlify_enabled()) {
1354                 char *n;
1355
1356                 n = strdup(text);
1357                 if (!n)
1358                         return -ENOMEM;
1359
1360                 *ret = n;
1361                 return 0;
1362         }
1363
1364         if (uname(&u) < 0)
1365                 return -errno;
1366
1367         if (!path_is_absolute(path)) {
1368                 r = path_make_absolute_cwd(path, &absolute);
1369                 if (r < 0)
1370                         return r;
1371
1372                 path = absolute;
1373         }
1374
1375         /* As suggested by https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda, let's include the local
1376          * hostname here. Note that we don't use gethostname_malloc() or gethostname_strict() since we are interested
1377          * in the raw string the kernel has set, whatever it may be, under the assumption that terminals are not overly
1378          * careful with validating the strings either. */
1379
1380         url = strjoina("file://", u.nodename, path);
1381
1382         return terminal_urlify(url, text, ret);
1383 }