Debian Codegraph @

src/test/test-terminal-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/ioctl.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9
10 #include "alloc-util.h"
11 #include "ansi-color.h"
12 #include "errno-util.h"
13 #include "fd-util.h"
14 #include "path-util.h"
15 #include "process-util.h"
16 #include "stat-util.h"
17 #include "strv.h"
18 #include "terminal-util.h"
19 #include "tests.h"
20 #include "time-util.h"
21 #include "tmpfile-util.h"
22
23 #define LOREM_IPSUM "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " \
24 "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation " \
25 "ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " \
26 "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " \
27 "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
28
29 TEST(colors_enabled) {
30 log_info("colors_enabled: %s", yes_no(colors_enabled()));
31 }
32
33 TEST(read_one_char) {
34 _cleanup_fclose_ FILE *file = NULL;
35 char r;
36 bool need_nl;
37 _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-read_one_char.XXXXXX";
38
39 ASSERT_OK_ZERO(fmkostemp_safe(name, "r+", &file));
40
41 ASSERT_OK_ERRNO(fputs("c\n", file));
42 rewind(file);
43 ASSERT_OK(read_one_char(file, &r, 1000000, /* echo= */ true, &need_nl));
44 ASSERT_FALSE(need_nl);
45 ASSERT_EQ(r, 'c');
46 ASSERT_FAIL(read_one_char(file, &r, 1000000, /* echo= */ true, &need_nl));
47
48 rewind(file);
49 ASSERT_OK_ERRNO(fputs("foobar\n", file));
50 rewind(file);
51 ASSERT_FAIL(read_one_char(file, &r, 1000000, /* echo= */ true, &need_nl));
52
53 rewind(file);
54 ASSERT_OK_ERRNO(fputs("\n", file));
55 rewind(file);
56 ASSERT_FAIL(read_one_char(file, &r, 1000000, /* echo= */ true, &need_nl));
57 }
58
59 TEST(getttyname_malloc) {
60 _cleanup_free_ char *ttyname = NULL;
61
62 _cleanup_close_ int master = ASSERT_OK_ERRNO(posix_openpt(O_RDWR|O_NOCTTY));
63 ASSERT_OK(getttyname_malloc(master, &ttyname));
64 log_info("ttyname = %s", ttyname);
65
66 ASSERT_TRUE(PATH_IN_SET(ttyname, "ptmx", "pts/ptmx"));
67 }
68
69 typedef struct {
70 const char *name;
71 const char* (*func)(void);
72 } Color;
73
74 static const Color colors[] = {
75 { "normal", ansi_normal },
76 { "highlight", ansi_highlight },
77 { "black", ansi_black },
78 { "red", ansi_red },
79 { "green", ansi_green },
80 { "yellow", ansi_yellow },
81 { "blue", ansi_blue },
82 { "magenta", ansi_magenta },
83 { "cyan", ansi_cyan },
84 { "white", ansi_white },
85 { "grey", ansi_grey },
86
87 { "bright-black", ansi_bright_black },
88 { "bright-red", ansi_bright_red },
89 { "bright-green", ansi_bright_green },
90 { "bright-yellow", ansi_bright_yellow },
91 { "bright-blue", ansi_bright_blue },
92 { "bright-magenta", ansi_bright_magenta },
93 { "bright-cyan", ansi_bright_cyan },
94 { "bright-white", ansi_bright_white },
95
96 { "highlight-black", ansi_highlight_black },
97 { "highlight-red", ansi_highlight_red },
98 { "highlight-green", ansi_highlight_green },
99 { "highlight-yellow (original)", _ansi_highlight_yellow },
100 { "highlight-yellow (replacement)", ansi_highlight_yellow },
101 { "highlight-blue", ansi_highlight_blue },
102 { "highlight-magenta", ansi_highlight_magenta },
103 { "highlight-cyan", ansi_highlight_cyan },
104 { "highlight-white", ansi_highlight_white },
105 { "highlight-grey", ansi_highlight_grey },
106
107 { "underline", ansi_underline },
108 { "highlight-underline", ansi_highlight_underline },
109 { "highlight-red-underline", ansi_highlight_red_underline },
110 { "highlight-green-underline", ansi_highlight_green_underline },
111 { "highlight-yellow-underline", ansi_highlight_yellow_underline },
112 { "highlight-blue-underline", ansi_highlight_blue_underline },
113 { "highlight-magenta-underline", ansi_highlight_magenta_underline },
114 { "highlight-grey-underline", ansi_highlight_grey_underline },
115 };
116
117 TEST(colors) {
118 FOREACH_ELEMENT(color, colors)
119 printf("<%s%s%s>\n", colors->func(), color->name, ansi_normal());
120 }
121
122 TEST(text) {
123 for (size_t i = 0; !streq(colors[i].name, "underline"); i++) {
124 bool blwh = strstr(colors[i].name, "black")
125 || strstr(colors[i].name, "white");
126
127 printf("\n"
128 "Testing color %s%s\n%s%s%s\n",
129 colors[i].name,
130 blwh ? "" : ", this text should be readable",
131 colors[i].func(),
132 LOREM_IPSUM,
133 ansi_normal());
134 }
135 }
136
137 TEST(get_ctty) {
138 _cleanup_free_ char *ctty = NULL;
139 struct stat st;
140 dev_t devnr;
141 int r;
142
143 r = get_ctty(0, &devnr, &ctty);
144 if (r < 0) {
145 log_notice_errno(r, "Apparently called without a controlling TTY, cutting get_ctty() test short: %m");
146 return;
147 }
148
149 /* In almost all cases STDIN will match our controlling TTY. Let's verify that and then compare paths */
150 ASSERT_OK_ERRNO(fstat(STDIN_FILENO, &st));
151 if (S_ISCHR(st.st_mode) && st.st_rdev == devnr) {
152 _cleanup_free_ char *stdin_name = NULL;
153
154 ASSERT_OK(getttyname_malloc(STDIN_FILENO, &stdin_name));
155 ASSERT_TRUE(path_equal(stdin_name, ctty));
156 } else
157 log_notice("Not invoked with stdin == ctty, cutting get_ctty() test short");
158 }
159
160 TEST(get_default_background_color) {
161 double red, green, blue;
162 int r;
163
164 usec_t n = now(CLOCK_MONOTONIC);
165 r = get_default_background_color(&red, &green, &blue);
166 log_info("%s took %s", __func__+5,
167 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), n), USEC_PER_MSEC));
168 if (r < 0)
169 log_notice_errno(r, "Can't get terminal default background color: %m");
170 else
171 log_notice("R=%g G=%g B=%g", red, green, blue);
172 }
173
174 TEST(terminal_get_size_csi18) {
175 unsigned rows, columns;
176 int r;
177
178 usec_t n = now(CLOCK_MONOTONIC);
179 r = terminal_get_size(STDIN_FILENO, STDOUT_FILENO, &rows, &columns, /* try_dsr= */ false, /* try_csi18= */ true);
180 log_info("%s took %s", __func__+5,
181 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), n), USEC_PER_MSEC));
182 if (r < 0)
183 return (void) log_notice_errno(r, "Can't get screen dimensions via CSI 18: %m");
184
185 log_notice("terminal size via CSI 18: rows=%u columns=%u", rows, columns);
186
187 struct winsize ws = {};
188
189 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) < 0)
190 log_warning_errno(errno, "Can't get terminal size via ioctl, ignoring: %m");
191 else
192 log_notice("terminal size via ioctl: rows=%u columns=%u", ws.ws_row, ws.ws_col);
193 }
194
195 TEST(terminal_get_size_dsr) {
196 unsigned rows, columns;
197 int r;
198
199 usec_t n = now(CLOCK_MONOTONIC);
200 r = terminal_get_size(STDIN_FILENO, STDOUT_FILENO, &rows, &columns, /* try_dsr= */ true, /* try_csi18= */ false);
201 log_info("%s took %s", __func__+5,
202 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), n), USEC_PER_MSEC));
203 if (r < 0)
204 return (void) log_notice_errno(r, "Can't get screen dimensions via DSR: %m");
205
206 log_notice("terminal size via DSR: rows=%u columns=%u", rows, columns);
207
208 struct winsize ws = {};
209
210 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) < 0)
211 log_warning_errno(errno, "Can't get terminal size via ioctl, ignoring: %m");
212 else
213 log_notice("terminal size via ioctl: rows=%u columns=%u", ws.ws_row, ws.ws_col);
214 }
215
216 TEST(terminal_fix_size) {
217 int r;
218
219 usec_t n = now(CLOCK_MONOTONIC);
220
221 r = terminal_fix_size(STDIN_FILENO, STDOUT_FILENO);
222 log_info("%s took %s", __func__+5,
223 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), n), USEC_PER_MSEC));
224 if (r < 0)
225 log_warning_errno(r, "Failed to fix terminal size: %m");
226 else if (r == 0)
227 log_notice("Not fixing terminal size, nothing to do.");
228 else
229 log_notice("Fixed terminal size.");
230 }
231
232 TEST(terminal_get_terminfo_by_dcs) {
233 _cleanup_free_ char *name = NULL;
234 int r;
235
236 /* We need a non-blocking read-write fd. */
237 _cleanup_close_ int fd = fd_reopen(STDIN_FILENO, O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
238 if (fd < 0)
239 return (void) log_info_errno(fd, "Cannot reopen stdin in read-write mode: %m");
240
241 usec_t n = now(CLOCK_MONOTONIC);
242
243 r = terminal_get_terminfo_by_dcs(fd, &name);
244 log_info("%s took %s", __func__+5,
245 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), n), USEC_PER_MSEC));
246 if (r < 0)
247 return (void) log_info_errno(r, "Can't get terminal terminfo via DCS: %m");
248 log_info("terminal terminfo via DCS: %s, $TERM: %s", name, strnull(getenv("TERM")));
249 }
250
251 TEST(have_terminfo_file) {
252 int r;
253
254 FOREACH_STRING(s,
255 "linux",
256 "xterm",
257 "vt220",
258 "xterm-256color",
259 "nosuchfile") {
260 r = have_terminfo_file(s);
261 log_info("%s: %s → %s", __func__+5, s, r >= 0 ? yes_no(r) : STRERROR(r));
262 ASSERT_OK(r);
263 }
264 }
265
266 TEST(query_term_for_tty) {
267 int r;
268
269 FOREACH_STRING(s,
270 "/dev/console",
271 "/dev/stdin",
272 "/dev/stdout") {
273 _cleanup_free_ char *term = NULL;
274
275 r = query_term_for_tty(s, &term);
276 log_info("%s: %s → %s/%s", __func__+5, s, STRERROR(r), strnull(term));
277 }
278 }
279
280 TEST(terminal_is_pty_fd) {
281 int r;
282
283 _cleanup_close_ int fd1 = ASSERT_OK(openpt_allocate(O_RDWR, /* ret_peer_path= */ NULL));
284 ASSERT_OK_POSITIVE(terminal_is_pty_fd(fd1));
285
286 _cleanup_close_ int fd2 = ASSERT_OK(pty_open_peer(fd1, O_RDWR|O_CLOEXEC|O_NOCTTY));
287 ASSERT_OK_POSITIVE(terminal_is_pty_fd(fd2));
288
289 fd1 = safe_close(fd1);
290 fd2 = safe_close(fd2);
291
292 fd1 = ASSERT_OK_ERRNO(open("/dev/null", O_RDONLY|O_CLOEXEC));
293 ASSERT_OK_ZERO(terminal_is_pty_fd(fd1));
294
295 /* In container managers real tty devices might be weird, avoid them. */
296 r = path_is_read_only_fs("/sys");
297 if (r != 0)
298 return;
299
300 FOREACH_STRING(p, "/dev/ttyS0", "/dev/tty1") {
301 _cleanup_close_ int tfd = -EBADF;
302
303 tfd = open_terminal(p, O_CLOEXEC|O_NOCTTY|O_RDONLY|O_NONBLOCK);
304 if (tfd == -ENOENT)
305 continue;
306 if (tfd < 0) {
307 log_notice_errno(tfd, "Failed to open '%s', skipping: %m", p);
308 continue;
309 }
310
311 ASSERT_LE(terminal_is_pty_fd(tfd), 0);
312 }
313 }
314
315 static void test_get_color_mode_with_env(const char *key, const char *val, ColorMode expected) {
316 ASSERT_OK_ERRNO(setenv(key, val, true));
317 reset_terminal_feature_caches();
318 log_info("get_color_mode($%s=%s): %s", key, val, color_mode_to_string(get_color_mode()));
319 ASSERT_EQ(get_color_mode(), expected);
320 }
321
322 TEST(get_color_mode) {
323 log_info("get_color_mode(default): %s", color_mode_to_string(get_color_mode()));
324 ASSERT_OK(get_color_mode());
325
326 test_get_color_mode_with_env("SYSTEMD_COLORS", "0", COLOR_OFF);
327 test_get_color_mode_with_env("SYSTEMD_COLORS", "no", COLOR_OFF);
328 test_get_color_mode_with_env("SYSTEMD_COLORS", "16", COLOR_16);
329 test_get_color_mode_with_env("SYSTEMD_COLORS", "256", COLOR_256);
330 test_get_color_mode_with_env("SYSTEMD_COLORS", "24bit", COLOR_24BIT);
331
332 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-16", terminal_is_dumb() ? COLOR_OFF : COLOR_16);
333 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-256", terminal_is_dumb() ? COLOR_OFF : COLOR_256);
334 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-24bit", terminal_is_dumb() ? COLOR_OFF : COLOR_24BIT);
335 ASSERT_OK_ERRNO(setenv("COLORTERM", "truecolor", true));
336 /* SYSTEMD_COLORS=1/yes/true all map to COLOR_TRUE and must force colors on
337 * even when stdout is not a TTY (piped). With COLORTERM=truecolor, we get 24bit. */
338 test_get_color_mode_with_env("SYSTEMD_COLORS", "1", COLOR_24BIT);
339 test_get_color_mode_with_env("SYSTEMD_COLORS", "yes", COLOR_24BIT);
340 ASSERT_OK_ERRNO(unsetenv("COLORTERM"));
341 /* Without COLORTERM, COLOR_TRUE still bypasses the TTY check but autodetects depth. */
342 test_get_color_mode_with_env("SYSTEMD_COLORS", "true", COLOR_256);
343
344 ASSERT_OK_ERRNO(setenv("NO_COLOR", "1", true));
345 /* COLOR_TRUE also bypasses NO_COLOR. */
346 test_get_color_mode_with_env("SYSTEMD_COLORS", "true", COLOR_256);
347 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-16", COLOR_OFF);
348 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-256", COLOR_OFF);
349 test_get_color_mode_with_env("SYSTEMD_COLORS", "auto-24bit", COLOR_OFF);
350 test_get_color_mode_with_env("SYSTEMD_COLORS", "42", COLOR_OFF);
351 test_get_color_mode_with_env("SYSTEMD_COLORS", "invalid", COLOR_OFF);
352 ASSERT_OK_ERRNO(unsetenv("NO_COLOR"));
353 ASSERT_OK_ERRNO(unsetenv("SYSTEMD_COLORS"));
354
355 test_get_color_mode_with_env("COLORTERM", "truecolor", terminal_is_dumb() ? COLOR_OFF : COLOR_24BIT);
356 test_get_color_mode_with_env("COLORTERM", "24bit", terminal_is_dumb() ? COLOR_OFF : COLOR_24BIT);
357 test_get_color_mode_with_env("COLORTERM", "invalid", terminal_is_dumb() ? COLOR_OFF : COLOR_256);
358 test_get_color_mode_with_env("COLORTERM", "42", terminal_is_dumb() ? COLOR_OFF : COLOR_256);
359 ASSERT_OK_ERRNO(unsetenv("COLORTERM"));
360 reset_terminal_feature_caches();
361 }
362
363 TEST(terminal_reset_defensive) {
364 int r;
365
366 r = terminal_reset_defensive(STDOUT_FILENO, /* flags= */ 0);
367 if (r < 0)
368 log_notice_errno(r, "Failed to reset terminal: %m");
369 }
370
371 TEST(pty_open_peer) {
372 _cleanup_free_ char *pty_path = NULL;
373
374 _cleanup_close_ int pty_fd = ASSERT_OK(openpt_allocate(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK, &pty_path));
375 ASSERT_NOT_NULL(pty_path);
376
377 _cleanup_close_ int peer_fd = ASSERT_OK(pty_open_peer(pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC));
378
379 static const char x[] = { 'x', '\n' };
380 ASSERT_OK_EQ_ERRNO(write(pty_fd, x, sizeof(x)), (ssize_t) sizeof(x));
381
382 char buf[3];
383 ASSERT_OK_EQ_ERRNO(read(peer_fd, &buf, sizeof(buf)), (ssize_t) sizeof(x));
384 ASSERT_EQ(buf[0], x[0]);
385 ASSERT_EQ(buf[1], x[1]);
386 }
387
388 TEST(terminal_new_session) {
389 int r;
390
391 _cleanup_close_ int pty_fd = ASSERT_OK(openpt_allocate(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK, NULL));
392 _cleanup_close_ int peer_fd = ASSERT_OK(pty_open_peer(pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC));
393
394 r = pidref_safe_fork_full(
395 "test-term-session",
396 (int[]) { peer_fd, peer_fd, peer_fd },
397 NULL, 0,
398 FORK_DEATHSIG_SIGKILL|FORK_LOG|FORK_WAIT|FORK_REARRANGE_STDIO,
399 NULL);
400 ASSERT_OK(r);
401 if (r == 0) {
402 ASSERT_OK(terminal_new_session());
403 ASSERT_OK(get_ctty_devnr(0, NULL));
404
405 terminal_detach_session();
406 ASSERT_ERROR(get_ctty_devnr(0, NULL), ENXIO);
407
408 ASSERT_OK(terminal_new_session());
409 ASSERT_OK(get_ctty_devnr(0, NULL));
410
411 terminal_detach_session();
412 ASSERT_OK(rearrange_stdio(-EBADF, STDOUT_FILENO, STDERR_FILENO));
413 ASSERT_ERROR(get_ctty_devnr(0, NULL), ENXIO);
414 ASSERT_ERROR(terminal_new_session(), ENXIO);
415
416 _exit(EXIT_SUCCESS);
417 }
418 }
419
420 DEFINE_TEST_MAIN(LOG_INFO);