1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/kd.h>
#include <linux/tiocl.h>
#include <linux/vt.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <termios.h>
#include <unistd.h>
#include "alloc-util.h"
#include "constants.h"
#include "devnum-util.h"
#include "env-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "hexdecoct.h"
#include "inotify-util.h"
#include "io-util.h"
#include "log.h"
#include "macro.h"
#include "missing_magic.h"
#include "namespace-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "time-util.h"
#include "user-util.h"
static volatile unsigned cached_columns = 0;
static volatile unsigned cached_lines = 0;
static volatile int cached_on_tty = -1;
static volatile int cached_on_dev_null = -1;
static volatile int cached_color_mode = _COLOR_MODE_INVALID;
static volatile int cached_underline_enabled = -1;
bool isatty_safe(int fd) {
assert(fd >= 0);
if (isatty(fd))
return true;
/* Be resilient if we're working on stdio, since they're set up by parent process. */
assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
return false;
}
int chvt(int vt) {
_cleanup_close_ int fd = -EBADF;
/* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
* if that's configured. */
fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
if (fd < 0)
return fd;
if (vt <= 0) {
int tiocl[2] = {
TIOCL_GETKMSGREDIRECT,
0
};
if (ioctl(fd, TIOCLINUX, tiocl) < 0)
return -errno;
vt = tiocl[0] <= 0 ? 1 : tiocl[0];
}
return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
}
int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
_cleanup_free_ char *line = NULL;
struct termios old_termios;
int r, fd;
assert(f);
assert(ret);
/* If this is a terminal, then switch canonical mode off, so that we can read a single
* character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
* nicely.) */
fd = fileno(f);
if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
struct termios new_termios = old_termios;
new_termios.c_lflag &= ~ICANON;
new_termios.c_cc[VMIN] = 1;
new_termios.c_cc[VTIME] = 0;
if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
char c;
if (t != USEC_INFINITY) {
if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
(void) tcsetattr(fd, TCSADRAIN, &old_termios);
return -ETIMEDOUT;
}
}
r = safe_fgetc(f, &c);
(void) tcsetattr(fd, TCSADRAIN, &old_termios);
if (r < 0)
return r;
if (r == 0)
return -EIO;
if (need_nl)
*need_nl = c != '\n';
*ret = c;
return 0;
}
}
if (t != USEC_INFINITY && fd > 0) {
/* Let's wait the specified amount of time for input. When we have no fd we skip this, under
* the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
* anyway, as the data is either already in the stream or cannot possible be placed there
* while we access the stream */
if (fd_wait_for_event(fd, POLLIN, t) <= 0)
return -ETIMEDOUT;
}
/* If this is not a terminal, then read a full line instead */
r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
if (r < 0)
return r;
if (r == 0)
return -EIO;
if (strlen(line) != 1)
return -EBADMSG;
if (need_nl)
*need_nl = false;
*ret = line[0];
return 0;
}
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
int r;
assert(ret);
assert(replies);
assert(fmt);
for (;;) {
va_list ap;
char c;
bool need_nl = true;
fputs(ansi_highlight(), stdout);
putchar('\r');
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
fputs(ansi_normal(), stdout);
fflush(stdout);
r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
if (r < 0) {
if (r == -ETIMEDOUT)
continue;
if (r == -EBADMSG) {
puts("Bad input, please try again.");
continue;
}
putchar('\n');
return r;
}
if (need_nl)
putchar('\n');
if (strchr(replies, c)) {
*ret = c;
return 0;
}
puts("Read unexpected character, please try again.");
}
}
int ask_string(char **ret, const char *text, ...) {
_cleanup_free_ char *line = NULL;
va_list ap;
int r;
assert(ret);
assert(text);
fputs(ansi_highlight(), stdout);
va_start(ap, text);
vprintf(text, ap);
va_end(ap);
fputs(ansi_normal(), stdout);
fflush(stdout);
r = read_line(stdin, LONG_LINE_MAX, &line);
if (r < 0)
return r;
if (r == 0)
return -EIO;
*ret = TAKE_PTR(line);
return 0;
}
int reset_terminal_fd(int fd, bool switch_to_text) {
struct termios termios;
int r;
/* Set terminal to some sane defaults */
assert(fd >= 0);
if (!isatty_safe(fd))
return log_debug_errno(errno, "Asked to reset a terminal that actually isn't a terminal: %m");
/* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
* and we don't interfere with that. */
/* Disable exclusive mode, just in case */
if (ioctl(fd, TIOCNXCL) < 0)
log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
/* Switch to text mode */
if (switch_to_text)
if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
/* Set default keyboard mode */
r = vt_reset_keyboard(fd);
if (r < 0)
log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
if (tcgetattr(fd, &termios) < 0) {
r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
goto finish;
}
/* We only reset the stuff that matters to the software. How
* hardware is set up we don't touch assuming that somebody
* else will do that for us */
termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
termios.c_oflag |= ONLCR | OPOST;
termios.c_cflag |= CREAD;
termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
termios.c_cc[VINTR] = 03; /* ^C */
termios.c_cc[VQUIT] = 034; /* ^\ */
termios.c_cc[VERASE] = 0177;
termios.c_cc[VKILL] = 025; /* ^X */
termios.c_cc[VEOF] = 04; /* ^D */
termios.c_cc[VSTART] = 021; /* ^Q */
termios.c_cc[VSTOP] = 023; /* ^S */
termios.c_cc[VSUSP] = 032; /* ^Z */
termios.c_cc[VLNEXT] = 026; /* ^V */
termios.c_cc[VWERASE] = 027; /* ^W */
termios.c_cc[VREPRINT] = 022; /* ^R */
termios.c_cc[VEOL] = 0;
termios.c_cc[VEOL2] = 0;
termios.c_cc[VTIME] = 0;
termios.c_cc[VMIN] = 1;
r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
if (r < 0)
log_debug_errno(r, "Failed to set terminal parameters: %m");
finish:
/* Just in case, flush all crap out */
(void) tcflush(fd, TCIOFLUSH);
return r;
}
int reset_terminal(const char *name) {
_cleanup_close_ int fd = -EBADF;
/* We open the terminal with O_NONBLOCK here, to ensure we
* don't block on carrier if this is a terminal with carrier
* configured. */
fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
if (fd < 0)
return fd;
return reset_terminal_fd(fd, true);
}
int open_terminal(const char *name, int mode) {
_cleanup_close_ int fd = -EBADF;
unsigned c = 0;
/*
* If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
* unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
* times.
*
* https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
*/
if ((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) != 0)
return -EINVAL;
for (;;) {
fd = open(name, mode, 0);
if (fd >= 0)
break;
if (errno != EIO)
return -errno;
/* Max 1s in total */
if (c >= 20)
return -errno;
(void) usleep_safe(50 * USEC_PER_MSEC);
c++;
}
if (!isatty_safe(fd))
return negative_errno();
return TAKE_FD(fd);
}
int acquire_terminal(
const char *name,
AcquireTerminalFlags flags,
usec_t timeout) {
_cleanup_close_ int notify = -EBADF, fd = -EBADF;
usec_t ts = USEC_INFINITY;
int r, wd = -1;
assert(name);
assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
/* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
* acquire it, so that we don't lose any event.
*
* Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
* whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
* *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
* not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
* probably should not do anyway.) */
if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
if (notify < 0)
return -errno;
wd = inotify_add_watch(notify, name, IN_CLOSE);
if (wd < 0)
return -errno;
if (timeout != USEC_INFINITY)
ts = now(CLOCK_MONOTONIC);
}
for (;;) {
if (notify >= 0) {
r = flush_fd(notify);
if (r < 0)
return r;
}
/* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
* to figure out if we successfully became the controlling process of the tty */
fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
if (fd < 0)
return fd;
/* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
struct sigaction sa_old;
assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
/* First, try to get the tty */
r = RET_NERRNO(ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE));
/* Reset signal handler to old value */
assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
/* Success? Exit the loop now! */
if (r >= 0)
break;
/* Any failure besides -EPERM? Fail, regardless of the mode. */
if (r != -EPERM)
return r;
if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
* into a success. Note that EPERM is also returned if we
* already are the owner of the TTY. */
break;
if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
return r;
assert(notify >= 0);
assert(wd >= 0);
for (;;) {
union inotify_event_buffer buffer;
ssize_t l;
if (timeout != USEC_INFINITY) {
usec_t n;
assert(ts != USEC_INFINITY);
n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
if (n >= timeout)
return -ETIMEDOUT;
r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
if (r < 0)
return r;
if (r == 0)
return -ETIMEDOUT;
}
l = read(notify, &buffer, sizeof(buffer));
if (l < 0) {
if (ERRNO_IS_TRANSIENT(errno))
continue;
return -errno;
}
FOREACH_INOTIFY_EVENT(e, buffer, l) {
if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
break;
if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
return -EIO;
}
break;
}
/* We close the tty fd here since if the old session ended our handle will be dead. It's important that
* we do this after sleeping, so that we don't enter an endless loop. */
fd = safe_close(fd);
}
return TAKE_FD(fd);
}
int release_terminal(void) {
_cleanup_close_ int fd = -EBADF;
int r;
fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
if (fd < 0)
return -errno;
/* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
* by our own TIOCNOTTY */
struct sigaction sa_old;
assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
return r;
}
int terminal_vhangup_fd(int fd) {
assert(fd >= 0);
return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
}
int terminal_vhangup(const char *name) {
_cleanup_close_ int fd = -EBADF;
fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
if (fd < 0)
return fd;
return terminal_vhangup_fd(fd);
}
int vt_disallocate(const char *name) {
const char *e;
int r;
/* Deallocate the VT if possible. If not possible
* (i.e. because it is the active one), at least clear it
* entirely (including the scrollback buffer). */
e = path_startswith(name, "/dev/");
if (!e)
return -EINVAL;
if (tty_is_vc(name)) {
_cleanup_close_ int fd = -EBADF;
unsigned u;
const char *n;
n = startswith(e, "tty");
if (!n)
return -EINVAL;
r = safe_atou(n, &u);
if (r < 0)
return r;
if (u <= 0)
return -EINVAL;
/* Try to deallocate */
fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
if (fd < 0)
return fd;
r = ioctl(fd, VT_DISALLOCATE, u);
if (r >= 0)
return 0;
if (errno != EBUSY)
return -errno;
}
/* So this is not a VT (in which case we cannot deallocate it),
* or we failed to deallocate. Let's at least clear the screen. */
_cleanup_close_ int fd2 = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
if (fd2 < 0)
return fd2;
(void) loop_write(fd2,
"\033[r" /* clear scrolling region */
"\033[H" /* move home */
"\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
10);
return 0;
}
void reset_dev_console_fd(int fd, bool switch_to_text) {
int r;
assert(fd >= 0);
r = reset_terminal_fd(fd, switch_to_text);
if (r < 0)
log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
unsigned rows, cols;
r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
if (r < 0)
log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
else if (r > 0) {
r = terminal_set_size_fd(fd, NULL, rows, cols);
if (r < 0)
log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
} else
(void) terminal_fix_size(fd, fd);
r = terminal_reset_ansi_seq(fd);
if (r < 0)
log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
}
int make_console_stdio(void) {
int fd, r;
/* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
* /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
* is specified on the kernel command line. */
fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
if (fd < 0) {
log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
r = make_null_stdio();
if (r < 0)
return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
} else {
reset_dev_console_fd(fd, /* switch_to_text= */ true);
r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
if (r < 0)
return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
}
reset_terminal_feature_caches();
return 0;
}
bool tty_is_vc(const char *tty) {
assert(tty);
return vtnr_from_tty(tty) >= 0;
}
bool tty_is_console(const char *tty) {
assert(tty);
return streq(skip_dev_prefix(tty), "console");
}
int vtnr_from_tty(const char *tty) {
int i, r;
assert(tty);
tty = skip_dev_prefix(tty);
if (!startswith(tty, "tty") )
return -EINVAL;
if (!ascii_isdigit(tty[3]))
return -EINVAL;
r = safe_atoi(tty+3, &i);
if (r < 0)
return r;
if (i < 0 || i > 63)
return -EINVAL;
return i;
}
int resolve_dev_console(char **ret) {
_cleanup_free_ char *active = NULL;
char *tty;
int r;
assert(ret);
/* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
* sign for container setups) */
if (path_is_read_only_fs("/sys") > 0)
return -ENOMEDIUM;
r = read_one_line_file("/sys/class/tty/console/active", &active);
if (r < 0)
return r;
/* If multiple log outputs are configured the last one is what /dev/console points to */
tty = strrchr(active, ' ');
if (tty)
tty++;
else
tty = active;
if (streq(tty, "tty0")) {
active = mfree(active);
/* Get the active VC (e.g. tty1) */
r = read_one_line_file("/sys/class/tty/tty0/active", &active);
if (r < 0)
return r;
tty = active;
}
if (tty != active)
return strdup_to(ret, tty);
*ret = TAKE_PTR(active);
return 0;
}
int get_kernel_consoles(char ***ret) {
_cleanup_strv_free_ char **l = NULL;
_cleanup_free_ char *line = NULL;
const char *p;
int r;
assert(ret);
/* If /sys is mounted read-only this means we are running in some kind of container environment. In that
* case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
if (path_is_read_only_fs("/sys") > 0)
goto fallback;
r = read_one_line_file("/sys/class/tty/console/active", &line);
if (r < 0)
return r;
p = line;
for (;;) {
_cleanup_free_ char *tty = NULL, *path = NULL;
r = extract_first_word(&p, &tty, NULL, 0);
if (r < 0)
return r;
if (r == 0)
break;
if (streq(tty, "tty0")) {
tty = mfree(tty);
r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
if (r < 0)
return r;
}
path = path_join("/dev", tty);
if (!path)
return -ENOMEM;
if (access(path, F_OK) < 0) {
log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
continue;
}
r = strv_consume(&l, TAKE_PTR(path));
if (r < 0)
return r;
}
if (strv_isempty(l)) {
log_debug("No devices found for system console");
goto fallback;
}
*ret = TAKE_PTR(l);
return 0;
fallback:
r = strv_extend(&l, "/dev/console");
if (r < 0)
return r;
*ret = TAKE_PTR(l);
return 0;
}
bool tty_is_vc_resolve(const char *tty) {
_cleanup_free_ char *resolved = NULL;
assert(tty);
tty = skip_dev_prefix(tty);
if (streq(tty, "console")) {
if (resolve_dev_console(&resolved) < 0)
return false;
tty = resolved;
}
return tty_is_vc(tty);
}
const char* default_term_for_tty(const char *tty) {
return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
}
int fd_columns(int fd) {
struct winsize ws = {};
if (fd < 0)
return -EBADF;
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
return -errno;
if (ws.ws_col <= 0)
return -EIO;
return ws.ws_col;
}
unsigned columns(void) {
const char *e;
int c;
if (cached_columns > 0)
return cached_columns;
c = 0;
e = getenv("COLUMNS");
if (e)
(void) safe_atoi(e, &c);
if (c <= 0 || c > USHRT_MAX) {
c = fd_columns(STDOUT_FILENO);
if (c <= 0)
c = 80;
}
cached_columns = c;
return cached_columns;
}
int fd_lines(int fd) {
struct winsize ws = {};
if (fd < 0)
return -EBADF;
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
return -errno;
if (ws.ws_row <= 0)
return -EIO;
return ws.ws_row;
}
unsigned lines(void) {
const char *e;
int l;
if (cached_lines > 0)
return cached_lines;
l = 0;
e = getenv("LINES");
if (e)
(void) safe_atoi(e, &l);
if (l <= 0 || l > USHRT_MAX) {
l = fd_lines(STDOUT_FILENO);
if (l <= 0)
l = 24;
}
cached_lines = l;
return cached_lines;
}
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
struct winsize ws;
if (rows == UINT_MAX && cols == UINT_MAX)
return 0;
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
return log_debug_errno(errno,
"TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
ident ?: "TTY");
if (rows == UINT_MAX)
rows = ws.ws_row;
else if (rows > USHRT_MAX)
rows = USHRT_MAX;
if (cols == UINT_MAX)
cols = ws.ws_col;
else if (cols > USHRT_MAX)
cols = USHRT_MAX;
if (rows == ws.ws_row && cols == ws.ws_col)
return 0;
ws.ws_row = rows;
ws.ws_col = cols;
if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident ?: "TTY");
return 0;
}
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
_cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
unsigned rows = UINT_MAX, cols = UINT_MAX;
int r;
assert(tty);
if (!ret_rows && !ret_cols)
return 0;
tty = skip_dev_prefix(tty);
if (!in_charset(tty, ALPHANUMERICAL))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "%s contains non-alphanumeric characters", tty);
rowskey = strjoin("systemd.tty.rows.", tty);
if (!rowskey)
return -ENOMEM;
colskey = strjoin("systemd.tty.columns.", tty);
if (!colskey)
return -ENOMEM;
r = proc_cmdline_get_key_many(/* flags = */ 0,
rowskey, &rowsvalue,
colskey, &colsvalue);
if (r < 0)
return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
if (rowsvalue) {
r = safe_atou(rowsvalue, &rows);
if (r < 0)
return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
}
if (colsvalue) {
r = safe_atou(colsvalue, &cols);
if (r < 0)
return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
}
if (ret_rows)
*ret_rows = rows;
if (ret_cols)
*ret_cols = cols;
return rows != UINT_MAX || cols != UINT_MAX;
}
/* intended to be used as a SIGWINCH sighandler */
void columns_lines_cache_reset(int signum) {
cached_columns = 0;
cached_lines = 0;
}
void reset_terminal_feature_caches(void) {
cached_columns = 0;
cached_lines = 0;
cached_color_mode = _COLOR_MODE_INVALID;
cached_underline_enabled = -1;
cached_on_tty = -1;
cached_on_dev_null = -1;
}
bool on_tty(void) {
/* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
* recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
* used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
* here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
* terminal functionality when outputting stuff, even if the input is piped to us. */
if (cached_on_tty < 0)
cached_on_tty =
isatty(STDOUT_FILENO) > 0 &&
isatty(STDERR_FILENO) > 0;
return cached_on_tty;
}
int getttyname_malloc(int fd, char **ret) {
char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
int r;
assert(fd >= 0);
assert(ret);
r = ttyname_r(fd, path, sizeof path); /* positive error */
assert(r >= 0);
if (r == ERANGE)
return -ENAMETOOLONG;
if (r > 0)
return -r;
return strdup_to(ret, skip_dev_prefix(path));
}
int getttyname_harder(int fd, char **ret) {
_cleanup_free_ char *s = NULL;
int r;
r = getttyname_malloc(fd, &s);
if (r < 0)
return r;
if (streq(s, "tty"))
return get_ctty(0, NULL, ret);
*ret = TAKE_PTR(s);
return 0;
}
int get_ctty_devnr(pid_t pid, dev_t *d) {
int r;
_cleanup_free_ char *line = NULL;
const char *p;
unsigned long ttynr;
assert(pid >= 0);
p = procfs_file_alloca(pid, "stat");
r = read_one_line_file(p, &line);
if (r < 0)
return r;
p = strrchr(line, ')');
if (!p)
return -EIO;
p++;
if (sscanf(p, " "
"%*c " /* state */
"%*d " /* ppid */
"%*d " /* pgrp */
"%*d " /* session */
"%lu ", /* ttynr */
&ttynr) != 1)
return -EIO;
if (devnum_is_zero(ttynr))
return -ENXIO;
if (d)
*d = (dev_t) ttynr;
return 0;
}
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
_cleanup_free_ char *buf = NULL;
const char *fn = NULL, *w;
dev_t devnr;
int r;
r = get_ctty_devnr(pid, &devnr);
if (r < 0)
return r;
r = device_path_make_canonical(S_IFCHR, devnr, &buf);
if (r < 0) {
struct stat st;
if (r != -ENOENT) /* No symlink for this in /dev/char/? */
return r;
/* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
* Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
* assume this is a PTY for a moment, and check if the device node this would then map to in
* /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
* number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
* the minor number of the pty. */
xsprintf(pty, "/dev/pts/%u", minor(devnr));
if (stat(pty, &st) < 0) {
if (errno != ENOENT)
return -errno;
} else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
fn = pty;
if (!fn) {
/* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
* symlink in /dev/char/. Let's return something vaguely useful. */
r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
if (r < 0)
return r;
fn = buf;
}
} else
fn = buf;
w = path_startswith(fn, "/dev/");
if (!w)
return -EINVAL;
if (ret) {
r = strdup_to(ret, w);
if (r < 0)
return r;
}
if (ret_devnr)
*ret_devnr = devnr;
return 0;
}
int ptsname_malloc(int fd, char **ret) {
size_t l = 100;
assert(fd >= 0);
assert(ret);
for (;;) {
char *c;
c = new(char, l);
if (!c)
return -ENOMEM;
if (ptsname_r(fd, c, l) == 0) {
*ret = c;
return 0;
}
if (errno != ERANGE) {
free(c);
return -errno;
}
free(c);
if (l > SIZE_MAX / 2)
return -ENOMEM;
l *= 2;
}
}
int openpt_allocate(int flags, char **ret_slave) {
_cleanup_close_ int fd = -EBADF;
_cleanup_free_ char *p = NULL;
int r;
fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
if (fd < 0)
return -errno;
if (ret_slave) {
r = ptsname_malloc(fd, &p);
if (r < 0)
return r;
if (!path_startswith(p, "/dev/pts/"))
return -EINVAL;
}
if (unlockpt(fd) < 0)
return -errno;
if (ret_slave)
*ret_slave = TAKE_PTR(p);
return TAKE_FD(fd);
}
static int ptsname_namespace(int pty, char **ret) {
int no = -1, r;
/* Like ptsname(), but doesn't assume that the path is
* accessible in the local namespace. */
r = ioctl(pty, TIOCGPTN, &no);
if (r < 0)
return -errno;
if (no < 0)
return -EIO;
if (asprintf(ret, "/dev/pts/%i", no) < 0)
return -ENOMEM;
return 0;
}
int openpt_allocate_in_namespace(pid_t pid, int flags, char **ret_slave) {
_cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
_cleanup_close_pair_ int pair[2] = EBADF_PAIR;
pid_t child;
int r;
assert(pid > 0);
r = namespace_open(pid, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
if (r < 0)
return r;
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
return -errno;
r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL,
pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
if (r < 0)
return r;
if (r == 0) {
pair[0] = safe_close(pair[0]);
fd = openpt_allocate(flags, NULL);
if (fd < 0)
_exit(EXIT_FAILURE);
if (send_one_fd(pair[1], fd, 0) < 0)
_exit(EXIT_FAILURE);
_exit(EXIT_SUCCESS);
}
pair[1] = safe_close(pair[1]);
r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
if (r < 0)
return r;
if (r != EXIT_SUCCESS)
return -EIO;
fd = receive_one_fd(pair[0], 0);
if (fd < 0)
return fd;
if (ret_slave) {
r = ptsname_namespace(fd, ret_slave);
if (r < 0)
return r;
}
return TAKE_FD(fd);
}
int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
_cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF;
_cleanup_close_pair_ int pair[2] = EBADF_PAIR;
pid_t child;
int r;
r = namespace_open(pid, &pidnsfd, &mntnsfd, /* ret_netns_fd = */ NULL, &usernsfd, &rootfd);
if (r < 0)
return r;
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
return -errno;
r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL,
pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
if (r < 0)
return r;
if (r == 0) {
int master;
pair[0] = safe_close(pair[0]);
master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
if (master < 0)
_exit(EXIT_FAILURE);
if (send_one_fd(pair[1], master, 0) < 0)
_exit(EXIT_FAILURE);
_exit(EXIT_SUCCESS);
}
pair[1] = safe_close(pair[1]);
r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
if (r < 0)
return r;
if (r != EXIT_SUCCESS)
return -EIO;
return receive_one_fd(pair[0], 0);
}
static bool on_dev_null(void) {
struct stat dst, ost, est;
if (cached_on_dev_null >= 0)
return cached_on_dev_null;
if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
cached_on_dev_null = false;
else
cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
return cached_on_dev_null;
}
bool getenv_terminal_is_dumb(void) {
const char *e;
e = getenv("TERM");
if (!e)
return true;
return streq(e, "dumb");
}
bool terminal_is_dumb(void) {
if (!on_tty() && !on_dev_null())
return true;
return getenv_terminal_is_dumb();
}
static const char* const color_mode_table[_COLOR_MODE_MAX] = {
[COLOR_OFF] = "off",
[COLOR_16] = "16",
[COLOR_256] = "256",
[COLOR_24BIT] = "24bit",
};
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_24BIT);
static ColorMode parse_systemd_colors(void) {
const char *e;
e = getenv("SYSTEMD_COLORS");
if (!e)
return _COLOR_MODE_INVALID;
ColorMode m = color_mode_from_string(e);
if (m < 0)
return log_debug_errno(m, "Failed to parse $SYSTEMD_COLORS value '%s', ignoring: %m", e);
return m;
}
static ColorMode get_color_mode_impl(void) {
/* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
* COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors, and COLOR_24BIT for
* unrestricted color output. */
/* First, we check $SYSTEMD_COLORS, which is the explicit way to change the mode. */
ColorMode m = parse_systemd_colors();
if (m >= 0)
return m;
/* Next, check for the presence of $NO_COLOR; value is ignored. */
if (getenv("NO_COLOR"))
return COLOR_OFF;
/* If the above didn't work, we turn colors off unless we are on a 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 we are PID 1 then we
* do not check whether we are connected to a TTY, because we don't keep /dev/console open
* continuously due to fear of SAK, and hence things are a bit weird. */
if (getpid_cached() == 1 ? getenv_terminal_is_dumb() : terminal_is_dumb())
return COLOR_OFF;
/* We failed to figure out any reason to *disable* colors. Let's see how many colors we shall use. */
if (STRPTR_IN_SET(getenv("COLORTERM"),
"truecolor",
"24bit"))
return COLOR_24BIT;
/* Note that the Linux console can only display 16 colors. We still enable 256 color mode
* even for PID1 output though (which typically goes to the Linux console), since the Linux
* console is able to parse the 256 color sequences and automatically map them to the closest
* color in the 16 color palette (since kernel 3.16). Doing 256 colors is nice for people who
* invoke systemd in a container or via a serial link or such, and use a true 256 color
* terminal to do so. */
return COLOR_256;
}
ColorMode get_color_mode(void) {
if (cached_color_mode < 0)
cached_color_mode = get_color_mode_impl();
return cached_color_mode;
}
bool dev_console_colors_enabled(void) {
_cleanup_free_ char *s = NULL;
ColorMode m;
/* Returns true if we assume that color is supported on /dev/console.
*
* For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
* isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
* line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
* colors_enabled() operates. */
m = parse_systemd_colors();
if (m >= 0)
return m;
if (getenv("NO_COLOR"))
return false;
if (getenv_for_pid(1, "TERM", &s) <= 0)
(void) proc_cmdline_get_key("TERM", 0, &s);
return !streq_ptr(s, "dumb");
}
bool underline_enabled(void) {
if (cached_underline_enabled < 0) {
/* The Linux console doesn't support underlining, turn it off, but only there. */
if (colors_enabled())
cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
else
cached_underline_enabled = false;
}
return cached_underline_enabled;
}
int vt_default_utf8(void) {
_cleanup_free_ char *b = NULL;
int r;
/* Read the default VT UTF8 setting from the kernel */
r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
if (r < 0)
return r;
return parse_boolean(b);
}
int vt_reset_keyboard(int fd) {
int kb;
/* If we can't read the default, then default to unicode. It's 2017 after all. */
kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
}
int vt_restore(int fd) {
static const struct vt_mode mode = {
.mode = VT_AUTO,
};
int r, ret = 0;
assert(fd >= 0);
if (!isatty_safe(fd))
return log_debug_errno(errno, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT to text mode, ignoring: %m"));
r = vt_reset_keyboard(fd);
if (r < 0)
RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
if (ioctl(fd, VT_SETMODE, &mode) < 0)
RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"));
r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
if (r < 0)
RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
return ret;
}
int vt_release(int fd, bool restore) {
assert(fd >= 0);
/* This function releases the VT by acknowledging the VT-switch signal
* sent by the kernel and optionally reset the VT in text and auto
* VT-switching modes. */
if (!isatty_safe(fd))
return log_debug_errno(errno, "Asked to release the VT for an fd that does not refer to a terminal: %m");
if (ioctl(fd, VT_RELDISP, 1) < 0)
return -errno;
if (restore)
return vt_restore(fd);
return 0;
}
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
/* Note that this will initialize output variables only when there's something to output.
* The caller must pre-initialize to "" or NULL as appropriate. */
if (priority <= LOG_ERR) {
if (on)
*on = ansi_highlight_red();
if (off)
*off = ansi_normal();
if (highlight)
*highlight = ansi_highlight();
} else if (priority <= LOG_WARNING) {
if (on)
*on = ansi_highlight_yellow();
if (off)
*off = ansi_normal();
if (highlight)
*highlight = ansi_highlight();
} else if (priority <= LOG_NOTICE) {
if (on)
*on = ansi_highlight();
if (off)
*off = ansi_normal();
if (highlight)
*highlight = ansi_highlight_red();
} else if (priority >= LOG_DEBUG) {
if (on)
*on = ansi_grey();
if (off)
*off = ansi_normal();
if (highlight)
*highlight = ansi_highlight_red();
}
}
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
assert(fd >= 0);
char cursor_position[STRLEN("\x1B[" ";" "H") + DECIMAL_STR_MAX(unsigned) * 2 + 1];
xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
return loop_write(fd, cursor_position, SIZE_MAX);
}
int terminal_reset_ansi_seq(int fd) {
int r, k;
assert(fd >= 0);
if (getenv_terminal_is_dumb())
return 0;
r = fd_nonblock(fd, true);
if (r < 0)
return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
k = loop_write_full(fd,
"\033c" /* reset to initial state */
"\033[!p" /* soft terminal reset */
"\033]104\007" /* reset colors */
"\033[?7h", /* enable line-wrapping */
SIZE_MAX,
50 * USEC_PER_MSEC);
if (k < 0)
log_debug_errno(k, "Failed to write to terminal: %m");
if (r > 0) {
r = fd_nonblock(fd, false);
if (r < 0)
log_debug_errno(r, "Failed to set terminal back to blocking mode: %m");
}
return k < 0 ? k : r;
}
void termios_disable_echo(struct termios *termios) {
assert(termios);
termios->c_lflag &= ~(ICANON|ECHO);
termios->c_cc[VMIN] = 1;
termios->c_cc[VTIME] = 0;
}
static int terminal_verify_same(int input_fd, int output_fd) {
assert(input_fd >= 0);
assert(output_fd >= 0);
/* Validates that the specified fds reference the same TTY */
if (input_fd != output_fd) {
struct stat sti;
if (fstat(input_fd, &sti) < 0)
return -errno;
if (!S_ISCHR(sti.st_mode)) /* TTYs are character devices */
return -ENOTTY;
struct stat sto;
if (fstat(output_fd, &sto) < 0)
return -errno;
if (!S_ISCHR(sto.st_mode))
return -ENOTTY;
if (sti.st_rdev != sto.st_rdev)
return -ENOLINK;
}
if (!isatty_safe(input_fd)) /* The check above was just for char device, but now let's ensure it's actually a tty */
return -ENOTTY;
return 0;
}
typedef enum BackgroundColorState {
BACKGROUND_TEXT,
BACKGROUND_ESCAPE,
BACKGROUND_BRACKET,
BACKGROUND_FIRST_ONE,
BACKGROUND_SECOND_ONE,
BACKGROUND_SEMICOLON,
BACKGROUND_R,
BACKGROUND_G,
BACKGROUND_B,
BACKGROUND_RED,
BACKGROUND_GREEN,
BACKGROUND_BLUE,
BACKGROUND_STRING_TERMINATOR,
} BackgroundColorState;
typedef struct BackgroundColorContext {
BackgroundColorState state;
uint32_t red, green, blue;
unsigned red_bits, green_bits, blue_bits;
} BackgroundColorContext;
static int scan_background_color_response(
BackgroundColorContext *context,
const char *buf,
size_t size,
size_t *ret_processed) {
assert(context);
assert(buf || size == 0);
for (size_t i = 0; i < size; i++) {
char c = buf[i];
switch (context->state) {
case BACKGROUND_TEXT:
context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
break;
case BACKGROUND_ESCAPE:
context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
break;
case BACKGROUND_BRACKET:
context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
break;
case BACKGROUND_FIRST_ONE:
context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
break;
case BACKGROUND_SECOND_ONE:
context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
break;
case BACKGROUND_SEMICOLON:
context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
break;
case BACKGROUND_R:
context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
break;
case BACKGROUND_G:
context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
break;
case BACKGROUND_B:
context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
break;
case BACKGROUND_RED:
if (c == '/')
context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
else {
int d = unhexchar(c);
if (d < 0 || context->red_bits >= sizeof(context->red)*8)
context->state = BACKGROUND_TEXT;
else {
context->red = (context->red << 4) | d;
context->red_bits += 4;
}
}
break;
case BACKGROUND_GREEN:
if (c == '/')
context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
else {
int d = unhexchar(c);
if (d < 0 || context->green_bits >= sizeof(context->green)*8)
context->state = BACKGROUND_TEXT;
else {
context->green = (context->green << 4) | d;
context->green_bits += 4;
}
}
break;
case BACKGROUND_BLUE:
if (c == '\x07') {
if (context->blue_bits > 0) {
if (ret_processed)
*ret_processed = i + 1;
return 1; /* success! */
}
context->state = BACKGROUND_TEXT;
} else if (c == '\x1b')
context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
else {
int d = unhexchar(c);
if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
context->state = BACKGROUND_TEXT;
else {
context->blue = (context->blue << 4) | d;
context->blue_bits += 4;
}
}
break;
case BACKGROUND_STRING_TERMINATOR:
if (c == '\\') {
if (ret_processed)
*ret_processed = i + 1;
return 1; /* success! */
}
context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
break;
}
/* Reset any colors we might have picked up */
if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
/* reset color */
context->red = context->green = context->blue = 0;
context->red_bits = context->green_bits = context->blue_bits = 0;
}
}
if (ret_processed)
*ret_processed = size;
return 0; /* all good, but not enough data yet */
}
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
int r;
assert(ret_red);
assert(ret_green);
assert(ret_blue);
if (!colors_enabled())
return -EOPNOTSUPP;
r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
if (r < 0)
return r;
if (streq_ptr(getenv("TERM"), "linux")) {
/* Linux console is black */
*ret_red = *ret_green = *ret_blue = 0.0;
return 0;
}
struct termios old_termios;
if (tcgetattr(STDIN_FILENO, &old_termios) < 0)
return -errno;
struct termios new_termios = old_termios;
termios_disable_echo(&new_termios);
if (tcsetattr(STDIN_FILENO, TCSADRAIN, &new_termios) < 0)
return -errno;
r = loop_write(STDOUT_FILENO, "\x1B]11;?\x07", SIZE_MAX);
if (r < 0)
goto finish;
usec_t end = usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC);
char buf[256];
size_t buf_full = 0;
BackgroundColorContext context = {};
for (;;) {
if (buf_full == 0) {
usec_t n = now(CLOCK_MONOTONIC);
if (n >= end) {
r = -EOPNOTSUPP;
goto finish;
}
r = fd_wait_for_event(STDIN_FILENO, POLLIN, usec_sub_unsigned(end, n));
if (r < 0)
goto finish;
if (r == 0) {
r = -EOPNOTSUPP;
goto finish;
}
ssize_t l = read(STDIN_FILENO, buf, sizeof(buf));
if (l < 0) {
r = -errno;
goto finish;
}
assert((size_t) l <= sizeof(buf));
buf_full = l;
}
size_t processed;
r = scan_background_color_response(&context, buf, buf_full, &processed);
if (r < 0)
goto finish;
assert(processed <= buf_full);
buf_full -= processed;
memmove(buf, buf + processed, buf_full);
if (r > 0) {
assert(context.red_bits > 0);
*ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
assert(context.green_bits > 0);
*ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
assert(context.blue_bits > 0);
*ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
r = 0;
goto finish;
}
}
finish:
RET_GATHER(r, RET_NERRNO(tcsetattr(STDIN_FILENO, TCSADRAIN, &old_termios)));
return r;
}
typedef enum CursorPositionState {
CURSOR_TEXT,
CURSOR_ESCAPE,
CURSOR_ROW,
CURSOR_COLUMN,
} CursorPositionState;
typedef struct CursorPositionContext {
CursorPositionState state;
unsigned row, column;
} CursorPositionContext;
static int scan_cursor_position_response(
CursorPositionContext *context,
const char *buf,
size_t size,
size_t *ret_processed) {
assert(context);
assert(buf || size == 0);
for (size_t i = 0; i < size; i++) {
char c = buf[i];
switch (context->state) {
case CURSOR_TEXT:
context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
break;
case CURSOR_ESCAPE:
context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
break;
case CURSOR_ROW:
if (c == ';')
context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
else {
int d = undecchar(c);
/* We read a decimal character, let's suffix it to the number we so far read,
* but let's do an overflow check first. */
if (d < 0 || context->row > (UINT_MAX-d)/10)
context->state = CURSOR_TEXT;
else
context->row = context->row * 10 + d;
}
break;
case CURSOR_COLUMN:
if (c == 'R') {
if (context->column > 0) {
if (ret_processed)
*ret_processed = i + 1;
return 1; /* success! */
}
context->state = CURSOR_TEXT;
} else {
int d = undecchar(c);
/* As above, add the decimal charatcer to our column number */
if (d < 0 || context->column > (UINT_MAX-d)/10)
context->state = CURSOR_TEXT;
else
context->column = context->column * 10 + d;
}
break;
}
/* Reset any positions we might have picked up */
if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
context->row = context->column = 0;
}
if (ret_processed)
*ret_processed = size;
return 0; /* all good, but not enough data yet */
}
int terminal_get_size_by_dsr(
int input_fd,
int output_fd,
unsigned *ret_rows,
unsigned *ret_columns) {
assert(input_fd >= 0);
assert(output_fd >= 0);
int r;
/* Tries to determine the terminal dimension by means of ANSI sequences rather than TIOCGWINSZ
* ioctl(). Why bother with this? The ioctl() information is often incorrect on serial terminals
* (since there's no handshake or protocol to determine the right dimensions in RS232), but since the
* ANSI sequences are interpreted by the final terminal instead of an intermediary tty driver they
* should be more accurate.
*
* Unfortunately there's no direct ANSI sequence to query terminal dimensions. But we can hack around
* it: we position the cursor briefly at an absolute location very far down and very far to the
* right, and then read back where we actually ended up. Because cursor locations are capped at the
* terminal width/height we should then see the right values. In order to not risk integer overflows
* in terminal applications we'll use INT16_MAX-1 as location to jump to — hopefully a value that is
* large enough for any real-life terminals, but small enough to not overflow anything or be
* recognized as a "niche" value. (Note that the dimension fields in "struct winsize" are 16bit only,
* too). */
if (terminal_is_dumb())
return -EOPNOTSUPP;
r = terminal_verify_same(input_fd, output_fd);
if (r < 0)
return log_debug_errno(r, "Called with distinct input/output fds: %m");
struct termios old_termios;
if (tcgetattr(input_fd, &old_termios) < 0)
return log_debug_errno(errno, "Failed to to get terminal settings: %m");
struct termios new_termios = old_termios;
termios_disable_echo(&new_termios);
if (tcsetattr(input_fd, TCSADRAIN, &new_termios) < 0)
return log_debug_errno(errno, "Failed to to set new terminal settings: %m");
unsigned saved_row = 0, saved_column = 0;
r = loop_write(output_fd,
"\x1B[6n" /* Request cursor position (DSR/CPR) */
"\x1B[32766;32766H" /* Position cursor really far to the right and to the bottom, but let's stay within the 16bit signed range */
"\x1B[6n", /* Request cursor position again */
SIZE_MAX);
if (r < 0)
goto finish;
usec_t end = usec_add(now(CLOCK_MONOTONIC), 333 * USEC_PER_MSEC);
char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
size_t buf_full = 0;
CursorPositionContext context = {};
for (bool first = true;; first = false) {
if (buf_full == 0) {
usec_t n = now(CLOCK_MONOTONIC);
if (n >= end) {
r = -EOPNOTSUPP;
goto finish;
}
r = fd_wait_for_event(input_fd, POLLIN, usec_sub_unsigned(end, n));
if (r < 0)
goto finish;
if (r == 0) {
r = -EOPNOTSUPP;
goto finish;
}
/* On the first try, read multiple characters, i.e. the shortest valid
* reply. Afterwards read byte-wise, since we don't want to read too much, and
* unnecessarily drop too many characters from the input queue. */
ssize_t l = read(input_fd, buf, first ? sizeof(buf) : 1);
if (l < 0) {
r = -errno;
goto finish;
}
assert((size_t) l <= sizeof(buf));
buf_full = l;
}
size_t processed;
r = scan_cursor_position_response(&context, buf, buf_full, &processed);
if (r < 0)
goto finish;
assert(processed <= buf_full);
buf_full -= processed;
memmove(buf, buf + processed, buf_full);
if (r > 0) {
if (saved_row == 0) {
assert(saved_column == 0);
/* First sequence, this is the cursor position before we set it somewhere
* into the void at the bottom right. Let's save where we are so that we can
* return later. */
/* Superficial validity checks */
if (context.row <= 0 || context.column <= 0 || context.row >= 32766 || context.column >= 32766) {
r = -ENODATA;
goto finish;
}
saved_row = context.row;
saved_column = context.column;
/* Reset state */
context = (CursorPositionContext) {};
} else {
/* Second sequence, this is the cursor position after we set it somewhere
* into the void at the bottom right. */
/* Superficial validity checks (no particular reason to check for < 4, it's
* just a way to look for unreasonably small values) */
if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766) {
r = -ENODATA;
goto finish;
}
if (ret_rows)
*ret_rows = context.row;
if (ret_columns)
*ret_columns = context.column;
r = 0;
goto finish;
}
}
}
finish:
/* Restore cursor position */
if (saved_row > 0 && saved_column > 0)
RET_GATHER(r, terminal_set_cursor_position(output_fd, saved_row, saved_column));
RET_GATHER(r, RET_NERRNO(tcsetattr(input_fd, TCSADRAIN, &old_termios)));
return r;
}
int terminal_fix_size(int input_fd, int output_fd) {
unsigned rows, columns;
int r;
/* Tries to update the current terminal dimensions to the ones reported via ANSI sequences */
r = terminal_verify_same(input_fd, output_fd);
if (r < 0)
return r;
struct winsize ws = {};
if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
r = terminal_get_size_by_dsr(input_fd, output_fd, &rows, &columns);
if (r < 0)
return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
if (ws.ws_row == rows && ws.ws_col == columns) {
log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
return 0;
}
ws.ws_col = columns;
ws.ws_row = rows;
if (ioctl(output_fd, TIOCSWINSZ, &ws) < 0)
return log_debug_errno(errno, "Failed to update terminal dimensions, ignoring: %m");
log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
return 1;
}
int terminal_is_pty_fd(int fd) {
int r;
assert(fd >= 0);
/* Returns true if we are looking at a pty, i.e. if it's backed by the /dev/pts/ file system */
if (!isatty_safe(fd))
return false;
r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
if (r != 0)
return r;
/* The ptmx device is weird, it exists twice, once inside and once outside devpts. To detect the
* latter case, let's fire off an ioctl() that only works on ptmx devices. */
int v;
if (ioctl(fd, TIOCGPKT, &v) < 0) {
if (ERRNO_IS_NOT_SUPPORTED(errno))
return false;
return -errno;
}
return true;
}
|