chiark / gitweb /
core: introduce parse_ip_port (#4825)
[elogind.git] / src / basic / terminal-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <stdarg.h>
24 #include <stddef.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/inotify.h>
28 #include <sys/socket.h>
29 #include <sys/sysmacros.h>
30 #include <sys/time.h>
31 #include <linux/kd.h>
32 #include <linux/tiocl.h>
33 #include <linux/vt.h>
34 #include <poll.h>
35 #include <signal.h>
36 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <termios.h>
39 #include <unistd.h>
40
41 #include "alloc-util.h"
42 #include "fd-util.h"
43 #include "fileio.h"
44 #include "fs-util.h"
45 #include "io-util.h"
46 #include "log.h"
47 #include "macro.h"
48 #include "parse-util.h"
49 #include "process-util.h"
50 #include "socket-util.h"
51 #include "stat-util.h"
52 #include "string-util.h"
53 #include "strv.h"
54 #include "terminal-util.h"
55 #include "time-util.h"
56 #include "util.h"
57
58 static volatile unsigned cached_columns = 0;
59 static volatile unsigned cached_lines = 0;
60
61 int chvt(int vt) {
62         _cleanup_close_ int fd;
63
64         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
65         if (fd < 0)
66                 return -errno;
67
68         if (vt <= 0) {
69                 int tiocl[2] = {
70                         TIOCL_GETKMSGREDIRECT,
71                         0
72                 };
73
74                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
75                         return -errno;
76
77                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
78         }
79
80         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
81                 return -errno;
82
83         return 0;
84 }
85
86 #if 0 /// UNNEEDED by elogind
87 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
88         struct termios old_termios, new_termios;
89         char c, line[LINE_MAX];
90
91         assert(f);
92         assert(ret);
93
94         if (tcgetattr(fileno(f), &old_termios) >= 0) {
95                 new_termios = old_termios;
96
97                 new_termios.c_lflag &= ~ICANON;
98                 new_termios.c_cc[VMIN] = 1;
99                 new_termios.c_cc[VTIME] = 0;
100
101                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
102                         size_t k;
103
104                         if (t != USEC_INFINITY) {
105                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
106                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
107                                         return -ETIMEDOUT;
108                                 }
109                         }
110
111                         k = fread(&c, 1, 1, f);
112
113                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
114
115                         if (k <= 0)
116                                 return -EIO;
117
118                         if (need_nl)
119                                 *need_nl = c != '\n';
120
121                         *ret = c;
122                         return 0;
123                 }
124         }
125
126         if (t != USEC_INFINITY) {
127                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
128                         return -ETIMEDOUT;
129         }
130
131         errno = 0;
132         if (!fgets(line, sizeof(line), f))
133                 return errno > 0 ? -errno : -EIO;
134
135         truncate_nl(line);
136
137         if (strlen(line) != 1)
138                 return -EBADMSG;
139
140         if (need_nl)
141                 *need_nl = false;
142
143         *ret = line[0];
144         return 0;
145 }
146
147 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
148
149 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
150         int r;
151
152         assert(ret);
153         assert(replies);
154         assert(fmt);
155
156         for (;;) {
157                 va_list ap;
158                 char c;
159                 bool need_nl = true;
160
161                 if (colors_enabled())
162                         fputs(ANSI_HIGHLIGHT, stdout);
163
164                 putchar('\r');
165
166                 va_start(ap, fmt);
167                 vprintf(fmt, ap);
168                 va_end(ap);
169
170                 if (colors_enabled())
171                         fputs(ANSI_NORMAL, stdout);
172
173                 fflush(stdout);
174
175                 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
176                 if (r < 0) {
177
178                         if (r == -ETIMEDOUT)
179                                 continue;
180
181                         if (r == -EBADMSG) {
182                                 puts("Bad input, please try again.");
183                                 continue;
184                         }
185
186                         putchar('\n');
187                         return r;
188                 }
189
190                 if (need_nl)
191                         putchar('\n');
192
193                 if (strchr(replies, c)) {
194                         *ret = c;
195                         return 0;
196                 }
197
198                 puts("Read unexpected character, please try again.");
199         }
200 }
201
202 int ask_string(char **ret, const char *text, ...) {
203         assert(ret);
204         assert(text);
205
206         for (;;) {
207                 char line[LINE_MAX];
208                 va_list ap;
209
210                 if (colors_enabled())
211                         fputs(ANSI_HIGHLIGHT, stdout);
212
213                 va_start(ap, text);
214                 vprintf(text, ap);
215                 va_end(ap);
216
217                 if (colors_enabled())
218                         fputs(ANSI_NORMAL, stdout);
219
220                 fflush(stdout);
221
222                 errno = 0;
223                 if (!fgets(line, sizeof(line), stdin))
224                         return errno > 0 ? -errno : -EIO;
225
226                 if (!endswith(line, "\n"))
227                         putchar('\n');
228                 else {
229                         char *s;
230
231                         if (isempty(line))
232                                 continue;
233
234                         truncate_nl(line);
235                         s = strdup(line);
236                         if (!s)
237                                 return -ENOMEM;
238
239                         *ret = s;
240                         return 0;
241                 }
242         }
243 }
244
245 int reset_terminal_fd(int fd, bool switch_to_text) {
246         struct termios termios;
247         int r = 0;
248
249         /* Set terminal to some sane defaults */
250
251         assert(fd >= 0);
252
253         /* We leave locked terminal attributes untouched, so that
254          * Plymouth may set whatever it wants to set, and we don't
255          * interfere with that. */
256
257         /* Disable exclusive mode, just in case */
258         (void) ioctl(fd, TIOCNXCL);
259
260         /* Switch to text mode */
261         if (switch_to_text)
262                 (void) ioctl(fd, KDSETMODE, KD_TEXT);
263
264         /* Enable console unicode mode */
265         (void) ioctl(fd, KDSKBMODE, K_UNICODE);
266
267         if (tcgetattr(fd, &termios) < 0) {
268                 r = -errno;
269                 goto finish;
270         }
271
272         /* We only reset the stuff that matters to the software. How
273          * hardware is set up we don't touch assuming that somebody
274          * else will do that for us */
275
276         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
277         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
278         termios.c_oflag |= ONLCR;
279         termios.c_cflag |= CREAD;
280         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
281
282         termios.c_cc[VINTR]    =   03;  /* ^C */
283         termios.c_cc[VQUIT]    =  034;  /* ^\ */
284         termios.c_cc[VERASE]   = 0177;
285         termios.c_cc[VKILL]    =  025;  /* ^X */
286         termios.c_cc[VEOF]     =   04;  /* ^D */
287         termios.c_cc[VSTART]   =  021;  /* ^Q */
288         termios.c_cc[VSTOP]    =  023;  /* ^S */
289         termios.c_cc[VSUSP]    =  032;  /* ^Z */
290         termios.c_cc[VLNEXT]   =  026;  /* ^V */
291         termios.c_cc[VWERASE]  =  027;  /* ^W */
292         termios.c_cc[VREPRINT] =  022;  /* ^R */
293         termios.c_cc[VEOL]     =    0;
294         termios.c_cc[VEOL2]    =    0;
295
296         termios.c_cc[VTIME]  = 0;
297         termios.c_cc[VMIN]   = 1;
298
299         if (tcsetattr(fd, TCSANOW, &termios) < 0)
300                 r = -errno;
301
302 finish:
303         /* Just in case, flush all crap out */
304         (void) tcflush(fd, TCIOFLUSH);
305
306         return r;
307 }
308
309 int reset_terminal(const char *name) {
310         _cleanup_close_ int fd = -1;
311
312         /* We open the terminal with O_NONBLOCK here, to ensure we
313          * don't block on carrier if this is a terminal with carrier
314          * configured. */
315
316         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
317         if (fd < 0)
318                 return fd;
319
320         return reset_terminal_fd(fd, true);
321 }
322 #endif // 0
323
324 int open_terminal(const char *name, int mode) {
325         int fd, r;
326         unsigned c = 0;
327
328         /*
329          * If a TTY is in the process of being closed opening it might
330          * cause EIO. This is horribly awful, but unlikely to be
331          * changed in the kernel. Hence we work around this problem by
332          * retrying a couple of times.
333          *
334          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
335          */
336
337         if (mode & O_CREAT)
338                 return -EINVAL;
339
340         for (;;) {
341                 fd = open(name, mode, 0);
342                 if (fd >= 0)
343                         break;
344
345                 if (errno != EIO)
346                         return -errno;
347
348                 /* Max 1s in total */
349                 if (c >= 20)
350                         return -errno;
351
352                 usleep(50 * USEC_PER_MSEC);
353                 c++;
354         }
355
356         r = isatty(fd);
357         if (r == 0) {
358                 safe_close(fd);
359                 return -ENOTTY;
360         }
361
362         return fd;
363 }
364
365 #if 0 /// UNNEEDED by elogind
366 int acquire_terminal(
367                 const char *name,
368                 bool fail,
369                 bool force,
370                 bool ignore_tiocstty_eperm,
371                 usec_t timeout) {
372
373         int fd = -1, notify = -1, r = 0, wd = -1;
374         usec_t ts = 0;
375
376         assert(name);
377
378         /* We use inotify to be notified when the tty is closed. We
379          * create the watch before checking if we can actually acquire
380          * it, so that we don't lose any event.
381          *
382          * Note: strictly speaking this actually watches for the
383          * device being closed, it does *not* really watch whether a
384          * tty loses its controlling process. However, unless some
385          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
386          * its tty otherwise this will not become a problem. As long
387          * as the administrator makes sure not configure any service
388          * on the same tty as an untrusted user this should not be a
389          * problem. (Which he probably should not do anyway.) */
390
391         if (timeout != USEC_INFINITY)
392                 ts = now(CLOCK_MONOTONIC);
393
394         if (!fail && !force) {
395                 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
396                 if (notify < 0) {
397                         r = -errno;
398                         goto fail;
399                 }
400
401                 wd = inotify_add_watch(notify, name, IN_CLOSE);
402                 if (wd < 0) {
403                         r = -errno;
404                         goto fail;
405                 }
406         }
407
408         for (;;) {
409                 struct sigaction sa_old, sa_new = {
410                         .sa_handler = SIG_IGN,
411                         .sa_flags = SA_RESTART,
412                 };
413
414                 if (notify >= 0) {
415                         r = flush_fd(notify);
416                         if (r < 0)
417                                 goto fail;
418                 }
419
420                 /* We pass here O_NOCTTY only so that we can check the return
421                  * value TIOCSCTTY and have a reliable way to figure out if we
422                  * successfully became the controlling process of the tty */
423                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
424                 if (fd < 0)
425                         return fd;
426
427                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
428                  * if we already own the tty. */
429                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
430
431                 /* First, try to get the tty */
432                 if (ioctl(fd, TIOCSCTTY, force) < 0)
433                         r = -errno;
434
435                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
436
437                 /* Sometimes, it makes sense to ignore TIOCSCTTY
438                  * returning EPERM, i.e. when very likely we already
439                  * are have this controlling terminal. */
440                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
441                         r = 0;
442
443                 if (r < 0 && (force || fail || r != -EPERM))
444                         goto fail;
445
446                 if (r >= 0)
447                         break;
448
449                 assert(!fail);
450                 assert(!force);
451                 assert(notify >= 0);
452
453                 for (;;) {
454                         union inotify_event_buffer buffer;
455                         struct inotify_event *e;
456                         ssize_t l;
457
458                         if (timeout != USEC_INFINITY) {
459                                 usec_t n;
460
461                                 n = now(CLOCK_MONOTONIC);
462                                 if (ts + timeout < n) {
463                                         r = -ETIMEDOUT;
464                                         goto fail;
465                                 }
466
467                                 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
468                                 if (r < 0)
469                                         goto fail;
470
471                                 if (r == 0) {
472                                         r = -ETIMEDOUT;
473                                         goto fail;
474                                 }
475                         }
476
477                         l = read(notify, &buffer, sizeof(buffer));
478                         if (l < 0) {
479                                 if (errno == EINTR || errno == EAGAIN)
480                                         continue;
481
482                                 r = -errno;
483                                 goto fail;
484                         }
485
486                         FOREACH_INOTIFY_EVENT(e, buffer, l) {
487                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
488                                         r = -EIO;
489                                         goto fail;
490                                 }
491                         }
492
493                         break;
494                 }
495
496                 /* We close the tty fd here since if the old session
497                  * ended our handle will be dead. It's important that
498                  * we do this after sleeping, so that we don't enter
499                  * an endless loop. */
500                 fd = safe_close(fd);
501         }
502
503         safe_close(notify);
504
505         return fd;
506
507 fail:
508         safe_close(fd);
509         safe_close(notify);
510
511         return r;
512 }
513 #endif // 0
514
515 #if 0 /// UNNEEDED by elogind
516 int release_terminal(void) {
517         static const struct sigaction sa_new = {
518                 .sa_handler = SIG_IGN,
519                 .sa_flags = SA_RESTART,
520         };
521
522         _cleanup_close_ int fd = -1;
523         struct sigaction sa_old;
524         int r = 0;
525
526         fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
527         if (fd < 0)
528                 return -errno;
529
530         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
531          * by our own TIOCNOTTY */
532         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
533
534         if (ioctl(fd, TIOCNOTTY) < 0)
535                 r = -errno;
536
537         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
538
539         return r;
540 }
541
542 int terminal_vhangup_fd(int fd) {
543         assert(fd >= 0);
544
545         if (ioctl(fd, TIOCVHANGUP) < 0)
546                 return -errno;
547
548         return 0;
549 }
550
551 int terminal_vhangup(const char *name) {
552         _cleanup_close_ int fd;
553
554         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
555         if (fd < 0)
556                 return fd;
557
558         return terminal_vhangup_fd(fd);
559 }
560
561 int vt_disallocate(const char *name) {
562         _cleanup_close_ int fd = -1;
563         unsigned u;
564         int r;
565
566         /* Deallocate the VT if possible. If not possible
567          * (i.e. because it is the active one), at least clear it
568          * entirely (including the scrollback buffer) */
569
570         if (!startswith(name, "/dev/"))
571                 return -EINVAL;
572
573         if (!tty_is_vc(name)) {
574                 /* So this is not a VT. I guess we cannot deallocate
575                  * it then. But let's at least clear the screen */
576
577                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
578                 if (fd < 0)
579                         return fd;
580
581                 loop_write(fd,
582                            "\033[r"    /* clear scrolling region */
583                            "\033[H"    /* move home */
584                            "\033[2J",  /* clear screen */
585                            10, false);
586                 return 0;
587         }
588
589         if (!startswith(name, "/dev/tty"))
590                 return -EINVAL;
591
592         r = safe_atou(name+8, &u);
593         if (r < 0)
594                 return r;
595
596         if (u <= 0)
597                 return -EINVAL;
598
599         /* Try to deallocate */
600         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
601         if (fd < 0)
602                 return fd;
603
604         r = ioctl(fd, VT_DISALLOCATE, u);
605         fd = safe_close(fd);
606
607         if (r >= 0)
608                 return 0;
609
610         if (errno != EBUSY)
611                 return -errno;
612
613         /* Couldn't deallocate, so let's clear it fully with
614          * scrollback */
615         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
616         if (fd < 0)
617                 return fd;
618
619         loop_write(fd,
620                    "\033[r"   /* clear scrolling region */
621                    "\033[H"   /* move home */
622                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
623                    10, false);
624         return 0;
625 }
626
627 int make_console_stdio(void) {
628         int fd, r;
629
630         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
631
632         fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
633         if (fd < 0)
634                 return log_error_errno(fd, "Failed to acquire terminal: %m");
635
636         r = reset_terminal_fd(fd, true);
637         if (r < 0)
638                 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
639
640         r = make_stdio(fd);
641         if (r < 0)
642                 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
643
644         return 0;
645 }
646 #endif // 0
647
648 bool tty_is_vc(const char *tty) {
649         assert(tty);
650
651         return vtnr_from_tty(tty) >= 0;
652 }
653
654 bool tty_is_console(const char *tty) {
655         assert(tty);
656
657         if (startswith(tty, "/dev/"))
658                 tty += 5;
659
660         return streq(tty, "console");
661 }
662
663 int vtnr_from_tty(const char *tty) {
664         int i, r;
665
666         assert(tty);
667
668         if (startswith(tty, "/dev/"))
669                 tty += 5;
670
671         if (!startswith(tty, "tty") )
672                 return -EINVAL;
673
674         if (tty[3] < '0' || tty[3] > '9')
675                 return -EINVAL;
676
677         r = safe_atoi(tty+3, &i);
678         if (r < 0)
679                 return r;
680
681         if (i < 0 || i > 63)
682                 return -EINVAL;
683
684         return i;
685 }
686
687 #if 0 /// UNNEEDED by elogind
688 char *resolve_dev_console(char **active) {
689         char *tty;
690
691         /* Resolve where /dev/console is pointing to, if /sys is actually ours
692          * (i.e. not read-only-mounted which is a sign for container setups) */
693
694         if (path_is_read_only_fs("/sys") > 0)
695                 return NULL;
696
697         if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
698                 return NULL;
699
700         /* If multiple log outputs are configured the last one is what
701          * /dev/console points to */
702         tty = strrchr(*active, ' ');
703         if (tty)
704                 tty++;
705         else
706                 tty = *active;
707
708         if (streq(tty, "tty0")) {
709                 char *tmp;
710
711                 /* Get the active VC (e.g. tty1) */
712                 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
713                         free(*active);
714                         tty = *active = tmp;
715                 }
716         }
717
718         return tty;
719 }
720
721 int get_kernel_consoles(char ***consoles) {
722         _cleanup_strv_free_ char **con = NULL;
723         _cleanup_free_ char *line = NULL;
724         const char *active;
725         int r;
726
727         assert(consoles);
728
729         r = read_one_line_file("/sys/class/tty/console/active", &line);
730         if (r < 0)
731                 return r;
732
733         active = line;
734         for (;;) {
735                 _cleanup_free_ char *tty = NULL;
736                 char *path;
737
738                 r = extract_first_word(&active, &tty, NULL, 0);
739                 if (r < 0)
740                         return r;
741                 if (r == 0)
742                         break;
743
744                 if (streq(tty, "tty0")) {
745                         tty = mfree(tty);
746                         r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
747                         if (r < 0)
748                                 return r;
749                 }
750
751                 path = strappend("/dev/", tty);
752                 if (!path)
753                         return -ENOMEM;
754
755                 if (access(path, F_OK) < 0) {
756                         log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
757                         free(path);
758                         continue;
759                 }
760
761                 r = strv_consume(&con, path);
762                 if (r < 0)
763                         return r;
764         }
765
766         if (strv_isempty(con)) {
767                 log_debug("No devices found for system console");
768
769                 r = strv_extend(&con, "/dev/console");
770                 if (r < 0)
771                         return r;
772         }
773
774         *consoles = con;
775         con = NULL;
776         return 0;
777 }
778
779 bool tty_is_vc_resolve(const char *tty) {
780         _cleanup_free_ char *active = NULL;
781
782         assert(tty);
783
784         if (startswith(tty, "/dev/"))
785                 tty += 5;
786
787         if (streq(tty, "console")) {
788                 tty = resolve_dev_console(&active);
789                 if (!tty)
790                         return false;
791         }
792
793         return tty_is_vc(tty);
794 }
795
796 const char *default_term_for_tty(const char *tty) {
797         return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
798 }
799 #endif // 0
800
801 int fd_columns(int fd) {
802         struct winsize ws = {};
803
804         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
805                 return -errno;
806
807         if (ws.ws_col <= 0)
808                 return -EIO;
809
810         return ws.ws_col;
811 }
812
813 unsigned columns(void) {
814         const char *e;
815         int c;
816
817         if (_likely_(cached_columns > 0))
818                 return cached_columns;
819
820         c = 0;
821         e = getenv("COLUMNS");
822         if (e)
823                 (void) safe_atoi(e, &c);
824
825         if (c <= 0)
826                 c = fd_columns(STDOUT_FILENO);
827
828         if (c <= 0)
829                 c = 80;
830
831         cached_columns = c;
832         return cached_columns;
833 }
834
835 int fd_lines(int fd) {
836         struct winsize ws = {};
837
838         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
839                 return -errno;
840
841         if (ws.ws_row <= 0)
842                 return -EIO;
843
844         return ws.ws_row;
845 }
846
847 unsigned lines(void) {
848         const char *e;
849         int l;
850
851         if (_likely_(cached_lines > 0))
852                 return cached_lines;
853
854         l = 0;
855         e = getenv("LINES");
856         if (e)
857                 (void) safe_atoi(e, &l);
858
859         if (l <= 0)
860                 l = fd_lines(STDOUT_FILENO);
861
862         if (l <= 0)
863                 l = 24;
864
865         cached_lines = l;
866         return cached_lines;
867 }
868
869 /* intended to be used as a SIGWINCH sighandler */
870 #if 0 /// UNNEEDED by elogind
871 void columns_lines_cache_reset(int signum) {
872         cached_columns = 0;
873         cached_lines = 0;
874 }
875 #endif // 0
876
877 bool on_tty(void) {
878         static int cached_on_tty = -1;
879
880         if (_unlikely_(cached_on_tty < 0))
881                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
882
883         return cached_on_tty;
884 }
885
886 int make_stdio(int fd) {
887         int r, s, t;
888
889         assert(fd >= 0);
890
891         r = dup2(fd, STDIN_FILENO);
892         s = dup2(fd, STDOUT_FILENO);
893         t = dup2(fd, STDERR_FILENO);
894
895         if (fd >= 3)
896                 safe_close(fd);
897
898         if (r < 0 || s < 0 || t < 0)
899                 return -errno;
900
901         /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
902          * dup2() was a NOP and the bit hence possibly set. */
903         stdio_unset_cloexec();
904
905         return 0;
906 }
907
908 int make_null_stdio(void) {
909         int null_fd;
910
911         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
912         if (null_fd < 0)
913                 return -errno;
914
915         return make_stdio(null_fd);
916 }
917
918 int getttyname_malloc(int fd, char **ret) {
919         size_t l = 100;
920         int r;
921
922         assert(fd >= 0);
923         assert(ret);
924
925         for (;;) {
926                 char path[l];
927
928                 r = ttyname_r(fd, path, sizeof(path));
929                 if (r == 0) {
930                         const char *p;
931                         char *c;
932
933                         p = startswith(path, "/dev/");
934                         c = strdup(p ?: path);
935                         if (!c)
936                                 return -ENOMEM;
937
938                         *ret = c;
939                         return 0;
940                 }
941
942                 if (r != ERANGE)
943                         return -r;
944
945                 l *= 2;
946         }
947
948         return 0;
949 }
950
951 int getttyname_harder(int fd, char **r) {
952         int k;
953         char *s = NULL;
954
955         k = getttyname_malloc(fd, &s);
956         if (k < 0)
957                 return k;
958
959         if (streq(s, "tty")) {
960                 free(s);
961                 return get_ctty(0, NULL, r);
962         }
963
964         *r = s;
965         return 0;
966 }
967
968 int get_ctty_devnr(pid_t pid, dev_t *d) {
969         int r;
970         _cleanup_free_ char *line = NULL;
971         const char *p;
972         unsigned long ttynr;
973
974         assert(pid >= 0);
975
976         p = procfs_file_alloca(pid, "stat");
977         r = read_one_line_file(p, &line);
978         if (r < 0)
979                 return r;
980
981         p = strrchr(line, ')');
982         if (!p)
983                 return -EIO;
984
985         p++;
986
987         if (sscanf(p, " "
988                    "%*c "  /* state */
989                    "%*d "  /* ppid */
990                    "%*d "  /* pgrp */
991                    "%*d "  /* session */
992                    "%lu ", /* ttynr */
993                    &ttynr) != 1)
994                 return -EIO;
995
996         if (major(ttynr) == 0 && minor(ttynr) == 0)
997                 return -ENXIO;
998
999         if (d)
1000                 *d = (dev_t) ttynr;
1001
1002         return 0;
1003 }
1004
1005 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
1006         char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
1007         _cleanup_free_ char *s = NULL;
1008         const char *p;
1009         dev_t devnr;
1010         int k;
1011
1012         assert(r);
1013
1014         k = get_ctty_devnr(pid, &devnr);
1015         if (k < 0)
1016                 return k;
1017
1018         sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
1019
1020         k = readlink_malloc(fn, &s);
1021         if (k < 0) {
1022
1023                 if (k != -ENOENT)
1024                         return k;
1025
1026                 /* This is an ugly hack */
1027                 if (major(devnr) == 136) {
1028                         if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
1029                                 return -ENOMEM;
1030                 } else {
1031                         /* Probably something like the ptys which have no
1032                          * symlink in /dev/char. Let's return something
1033                          * vaguely useful. */
1034
1035                         b = strdup(fn + 5);
1036                         if (!b)
1037                                 return -ENOMEM;
1038                 }
1039         } else {
1040                 if (startswith(s, "/dev/"))
1041                         p = s + 5;
1042                 else if (startswith(s, "../"))
1043                         p = s + 3;
1044                 else
1045                         p = s;
1046
1047                 b = strdup(p);
1048                 if (!b)
1049                         return -ENOMEM;
1050         }
1051
1052         *r = b;
1053         if (_devnr)
1054                 *_devnr = devnr;
1055
1056         return 0;
1057 }
1058
1059 #if 0 /// UNNEEDED by elogind
1060 int ptsname_malloc(int fd, char **ret) {
1061         size_t l = 100;
1062
1063         assert(fd >= 0);
1064         assert(ret);
1065
1066         for (;;) {
1067                 char *c;
1068
1069                 c = new(char, l);
1070                 if (!c)
1071                         return -ENOMEM;
1072
1073                 if (ptsname_r(fd, c, l) == 0) {
1074                         *ret = c;
1075                         return 0;
1076                 }
1077                 if (errno != ERANGE) {
1078                         free(c);
1079                         return -errno;
1080                 }
1081
1082                 free(c);
1083                 l *= 2;
1084         }
1085 }
1086
1087 int ptsname_namespace(int pty, char **ret) {
1088         int no = -1, r;
1089
1090         /* Like ptsname(), but doesn't assume that the path is
1091          * accessible in the local namespace. */
1092
1093         r = ioctl(pty, TIOCGPTN, &no);
1094         if (r < 0)
1095                 return -errno;
1096
1097         if (no < 0)
1098                 return -EIO;
1099
1100         if (asprintf(ret, "/dev/pts/%i", no) < 0)
1101                 return -ENOMEM;
1102
1103         return 0;
1104 }
1105
1106 int openpt_in_namespace(pid_t pid, int flags) {
1107         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1108         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1109         siginfo_t si;
1110         pid_t child;
1111         int r;
1112
1113         assert(pid > 0);
1114
1115         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1116         if (r < 0)
1117                 return r;
1118
1119         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1120                 return -errno;
1121
1122         child = fork();
1123         if (child < 0)
1124                 return -errno;
1125
1126         if (child == 0) {
1127                 int master;
1128
1129                 pair[0] = safe_close(pair[0]);
1130
1131                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1132                 if (r < 0)
1133                         _exit(EXIT_FAILURE);
1134
1135                 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1136                 if (master < 0)
1137                         _exit(EXIT_FAILURE);
1138
1139                 if (unlockpt(master) < 0)
1140                         _exit(EXIT_FAILURE);
1141
1142                 if (send_one_fd(pair[1], master, 0) < 0)
1143                         _exit(EXIT_FAILURE);
1144
1145                 _exit(EXIT_SUCCESS);
1146         }
1147
1148         pair[1] = safe_close(pair[1]);
1149
1150         r = wait_for_terminate(child, &si);
1151         if (r < 0)
1152                 return r;
1153         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
1154                 return -EIO;
1155
1156         return receive_one_fd(pair[0], 0);
1157 }
1158
1159 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1160         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1161         _cleanup_close_pair_ int pair[2] = { -1, -1 };
1162         siginfo_t si;
1163         pid_t child;
1164         int r;
1165
1166         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1167         if (r < 0)
1168                 return r;
1169
1170         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1171                 return -errno;
1172
1173         child = fork();
1174         if (child < 0)
1175                 return -errno;
1176
1177         if (child == 0) {
1178                 int master;
1179
1180                 pair[0] = safe_close(pair[0]);
1181
1182                 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1183                 if (r < 0)
1184                         _exit(EXIT_FAILURE);
1185
1186                 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1187                 if (master < 0)
1188                         _exit(EXIT_FAILURE);
1189
1190                 if (send_one_fd(pair[1], master, 0) < 0)
1191                         _exit(EXIT_FAILURE);
1192
1193                 _exit(EXIT_SUCCESS);
1194         }
1195
1196         pair[1] = safe_close(pair[1]);
1197
1198         r = wait_for_terminate(child, &si);
1199         if (r < 0)
1200                 return r;
1201         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
1202                 return -EIO;
1203
1204         return receive_one_fd(pair[0], 0);
1205 }
1206 #endif // 0
1207
1208 static bool getenv_terminal_is_dumb(void) {
1209         const char *e;
1210
1211         e = getenv("TERM");
1212         if (!e)
1213                 return true;
1214
1215         return streq(e, "dumb");
1216 }
1217
1218 bool terminal_is_dumb(void) {
1219         if (!on_tty())
1220                 return true;
1221
1222         return getenv_terminal_is_dumb();
1223 }
1224
1225 bool colors_enabled(void) {
1226         static int enabled = -1;
1227
1228         if (_unlikely_(enabled < 0)) {
1229 #if 0 /// elogind does not allow such forcing, and we are never init!
1230                 int val;
1231
1232                 val = getenv_bool("SYSTEMD_COLORS");
1233                 if (val >= 0)
1234                         enabled = val;
1235                 else if (getpid() == 1)
1236                         /* PID1 outputs to the console without holding it open all the time */
1237                         enabled = !getenv_terminal_is_dumb();
1238                 else
1239 #endif // 0
1240                         enabled = !terminal_is_dumb();
1241         }
1242
1243         return enabled;
1244 }