summaryrefslogtreecommitdiffstats
path: root/src/shared/pretty-print.c
blob: c75f74a6c6e8fd2d91ab34c8fd24e3064498fa37 (plain)
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
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <sys/utsname.h>
#include <errno.h>
#include <stdio.h>

#include "alloc-util.h"
#include "color-util.h"
#include "conf-files.h"
#include "constants.h"
#include "env-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "pager.h"
#include "path-util.h"
#include "pretty-print.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"

void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
        char *p = buffer;

        assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
        assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */

        if (pos > 1) {
                if (pos > 2)
                        p = mempset(p, ' ', pos-2);
                if (log_get_show_color())
                        p = stpcpy(p, ANSI_RED);
                *p++ = '*';
        }

        if (pos > 0 && pos <= width) {
                if (log_get_show_color())
                        p = stpcpy(p, ANSI_HIGHLIGHT_RED);
                *p++ = '*';
        }

        if (log_get_show_color())
                p = stpcpy(p, ANSI_NORMAL);

        if (pos < width) {
                if (log_get_show_color())
                        p = stpcpy(p, ANSI_RED);
                *p++ = '*';
                if (pos < width-1)
                        p = mempset(p, ' ', width-1-pos);
                if (log_get_show_color())
                        p = stpcpy(p, ANSI_NORMAL);
        }

        *p = '\0';
}

bool urlify_enabled(void) {
#if ENABLE_URLIFY
        static int cached_urlify_enabled = -1;

        if (cached_urlify_enabled < 0) {
                int val;

                val = getenv_bool("SYSTEMD_URLIFY");
                if (val >= 0)
                        cached_urlify_enabled = val;
                else
                        cached_urlify_enabled = colors_enabled();
        }

        return cached_urlify_enabled;
#else
        return 0;
#endif
}

int terminal_urlify(const char *url, const char *text, char **ret) {
        char *n;

        assert(url);

        /* Takes a URL and a pretty string and formats it as clickable link for the terminal. See
         * https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda for details. */

        if (isempty(text))
                text = url;

        if (urlify_enabled())
                n = strjoin("\x1B]8;;", url, "\a", text, "\x1B]8;;\a");
        else
                n = strdup(text);
        if (!n)
                return -ENOMEM;

        *ret = n;
        return 0;
}

int file_url_from_path(const char *path, char **ret) {
        _cleanup_free_ char *absolute = NULL;
        struct utsname u;
        char *url = NULL;
        int r;

        if (uname(&u) < 0)
                return -errno;

        if (!path_is_absolute(path)) {
                r = path_make_absolute_cwd(path, &absolute);
                if (r < 0)
                        return r;

                path = absolute;
        }

        /* As suggested by https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda, let's include the local
         * hostname here. Note that we don't use gethostname_malloc() or gethostname_strict() since we are interested
         * in the raw string the kernel has set, whatever it may be, under the assumption that terminals are not overly
         * careful with validating the strings either. */

        url = strjoin("file://", u.nodename, path);
        if (!url)
                return -ENOMEM;

        *ret = url;
        return 0;
}

int terminal_urlify_path(const char *path, const char *text, char **ret) {
        _cleanup_free_ char *url = NULL;
        int r;

        assert(path);

        /* Much like terminal_urlify() above, but takes a file system path as input
         * and turns it into a proper file:// URL first. */

        if (isempty(path))
                return -EINVAL;

        if (isempty(text))
                text = path;

        if (!urlify_enabled())
                return strdup_to(ret, text);

        r = file_url_from_path(path, &url);
        if (r < 0)
                return r;

        return terminal_urlify(url, text, ret);
}

int terminal_urlify_man(const char *page, const char *section, char **ret) {
        const char *url, *text;

        url = strjoina("man:", page, "(", section, ")");
        text = strjoina(page, "(", section, ") man page");

        return terminal_urlify(url, text, ret);
}

typedef enum {
        LINE_SECTION,
        LINE_COMMENT,
        LINE_NORMAL,
} LineType;

static LineType classify_line_type(const char *line, CatFlags flags) {
        const char *t = skip_leading_chars(line, WHITESPACE);

        if ((flags & CAT_FORMAT_HAS_SECTIONS) && *t == '[')
                return LINE_SECTION;
        if (IN_SET(*t, '#', ';', '\0'))
                return LINE_COMMENT;
        return LINE_NORMAL;
}

static int cat_file(const char *filename, bool newline, CatFlags flags) {
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *urlified = NULL, *section = NULL, *old_section = NULL;
        int r;

        f = fopen(filename, "re");
        if (!f)
                return -errno;

        r = terminal_urlify_path(filename, NULL, &urlified);
        if (r < 0)
                return r;

        printf("%s%s# %s%s\n",
               newline ? "\n" : "",
               ansi_highlight_blue(),
               urlified,
               ansi_normal());
        fflush(stdout);

        for (;;) {
                _cleanup_free_ char *line = NULL;

                r = read_line(f, LONG_LINE_MAX, &line);
                if (r < 0)
                        return log_error_errno(r, "Failed to read \"%s\": %m", filename);
                if (r == 0)
                        break;

                LineType line_type = classify_line_type(line, flags);
                if (FLAGS_SET(flags, CAT_TLDR)) {
                        if (line_type == LINE_SECTION) {
                                /* The start of a section, let's not print it yet. */
                                free_and_replace(section, line);
                                continue;
                        }

                        if (line_type == LINE_COMMENT)
                                continue;

                        /* Before we print the actual line, print the last section header */
                        if (section) {
                                /* Do not print redundant section headers */
                                if (!streq_ptr(section, old_section))
                                        printf("%s%s%s\n",
                                               ansi_highlight_cyan(),
                                               section,
                                               ansi_normal());

                                free_and_replace(old_section, section);
                        }
                }

                /* Highlight the left side (directive) of a Foo=bar assignment */
                if (FLAGS_SET(flags, CAT_FORMAT_HAS_SECTIONS) && line_type == LINE_NORMAL) {
                        const char *p = strchr(line, '=');
                        if (p) {
                                _cleanup_free_ char *highlighted = NULL, *directive = NULL;

                                directive = strndup(line, p - line);
                                if (!directive)
                                        return log_oom();

                                highlighted = strjoin(ansi_highlight_green(),
                                                      directive,
                                                      "=",
                                                      ansi_normal(),
                                                      p + 1);
                                if (!highlighted)
                                        return log_oom();

                                free_and_replace(line, highlighted);
                        }
                }

                printf("%s%s%s\n",
                       line_type == LINE_SECTION ? ansi_highlight_cyan() :
                       line_type == LINE_COMMENT ? ansi_highlight_grey() :
                       "",
                       line,
                       line_type != LINE_NORMAL ? ansi_normal() : "");
        }

        return 0;
}

int cat_files(const char *file, char **dropins, CatFlags flags) {
        int r;

        if (file) {
                r = cat_file(file, /* newline= */ false, flags);
                if (r < 0)
                        return log_warning_errno(r, "Failed to cat %s: %m", file);
        }

        STRV_FOREACH(path, dropins) {
                r = cat_file(*path, /* newline= */ file || path != dropins, flags);
                if (r < 0)
                        return log_warning_errno(r, "Failed to cat %s: %m", *path);
        }

        return 0;
}

void print_separator(void) {

        /* Outputs a separator line that resolves to whitespace when copied from the terminal. We do that by outputting
         * one line filled with spaces with ANSI underline set, followed by a second (empty) line. */

        if (underline_enabled()) {
                size_t c = columns();

                flockfile(stdout);
                fputs_unlocked(ANSI_UNDERLINE, stdout);

                for (size_t i = 0; i < c; i++)
                        fputc_unlocked(' ', stdout);

                fputs_unlocked(ANSI_NORMAL "\n\n", stdout);
                funlockfile(stdout);
        } else
                fputs("\n\n", stdout);
}

static int guess_type(const char **name, char ***ret_prefixes, bool *ret_is_collection, const char **ret_extension) {
        /* Try to figure out if name is like tmpfiles.d/ or systemd/system-presets/,
         * i.e. a collection of directories without a main config file.
         * Incidentally, all those formats don't use sections. So we return a single
         * is_collection boolean, which also means that the format doesn't use sections.
         */

        _cleanup_free_ char *n = NULL;
        bool run = false, coll = false;
        const char *ext = ".conf";
        /* This is static so that the array doesn't get deallocated when we exit the function */
        static const char* const std_prefixes[] = { CONF_PATHS(""), NULL };
        static const char* const run_prefixes[] = { "/run/", NULL };

        if (path_equal(*name, "environment.d"))
                /* Special case: we need to include /etc/environment in the search path, even
                 * though the whole concept is called environment.d. */
                *name = "environment";

        n = strdup(*name);
        if (!n)
                return log_oom();

        delete_trailing_chars(n, "/");

        /* We assume systemd-style config files support the /usr-/run-/etc split and dropins. */

        if (endswith(n, ".d"))
                coll = true;

        if (path_equal(n, "udev/hwdb.d"))
                ext = ".hwdb";
        else if (path_equal(n, "udev/rules.d"))
                ext = ".rules";
        else if (path_equal(n, "kernel/install.d"))
                ext = ".install";
        else if (path_equal(n, "systemd/ntp-units.d")) {
                coll = true;
                ext = ".list";
        } else if (path_equal(n, "systemd/relabel-extra.d")) {
                coll = run = true;
                ext = ".relabel";
        } else if (PATH_IN_SET(n, "systemd/system-preset", "systemd/user-preset")) {
                coll = true;
                ext = ".preset";
        }

        *ret_prefixes = (char**) (run ? run_prefixes : std_prefixes);
        *ret_is_collection = coll;
        *ret_extension = ext;
        return 0;
}

int conf_files_cat(const char *root, const char *name, CatFlags flags) {
        _cleanup_strv_free_ char **dirs = NULL, **files = NULL;
        _cleanup_free_ char *path = NULL;
        char **prefixes = NULL; /* explicit initialization to appease gcc */
        bool is_collection;
        const char *extension;
        int r;

        r = guess_type(&name, &prefixes, &is_collection, &extension);
        if (r < 0)
                return r;
        assert(prefixes);
        assert(extension);

        STRV_FOREACH(prefix, prefixes) {
                assert(endswith(*prefix, "/"));
                r = strv_extendf(&dirs, "%s%s%s", *prefix, name,
                                 is_collection ? "" : ".d");
                if (r < 0)
                        return log_error_errno(r, "Failed to build directory list: %m");
        }

        if (DEBUG_LOGGING) {
                log_debug("Looking for configuration in:");
                if (!is_collection)
                        STRV_FOREACH(prefix, prefixes)
                                log_debug("   %s%s%s", strempty(root), *prefix, name);

                STRV_FOREACH(t, dirs)
                        log_debug("   %s%s/*%s", strempty(root), *t, extension);
        }

        /* First locate the main config file, if any */
        if (!is_collection) {
                STRV_FOREACH(prefix, prefixes) {
                        path = path_join(root, *prefix, name);
                        if (!path)
                                return log_oom();
                        if (access(path, F_OK) == 0)
                                break;
                        path = mfree(path);
                }

                if (!path)
                        printf("%s# Main configuration file %s not found%s\n",
                               ansi_highlight_magenta(),
                               name,
                               ansi_normal());
        }

        /* Then locate the drop-ins, if any */
        r = conf_files_list_strv(&files, extension, root, 0, (const char* const*) dirs);
        if (r < 0)
                return log_error_errno(r, "Failed to query file list: %m");

        /* Show */
        if (is_collection)
                flags |= CAT_FORMAT_HAS_SECTIONS;

        return cat_files(path, files, flags);
}

int terminal_tint_color(double hue, char **ret) {
        double red, green, blue;
        int r;

        assert(ret);

        r = get_default_background_color(&red, &green, &blue);
        if (r < 0)
                return log_debug_errno(r, "Unable to get terminal background color: %m");

        double s, v;
        rgb_to_hsv(red, green, blue, /* h= */ NULL, &s, &v);

        if (v > 50) /* If the background is bright, then pull down saturation */
                s = 25;
        else        /* otherwise pump it up */
                s = 75;

        v = MAX(20, v); /* Make sure we don't hide the color in black */

        uint8_t r8, g8, b8;
        hsv_to_rgb(hue, s, v, &r8, &g8, &b8);

        if (asprintf(ret, "48;2;%u;%u;%u", r8, g8, b8) < 0)
                return -ENOMEM;

        return 0;
}

bool shall_tint_background(void) {
        static int cache = -1;

        if (cache >= 0)
                return cache;

        cache = getenv_bool("SYSTEMD_TINT_BACKGROUND");
        if (cache == -ENXIO)
                return (cache = true);
        if (cache < 0)
                log_debug_errno(cache, "Failed to parse $SYSTEMD_TINT_BACKGROUND, leaving background tinting enabled: %m");

        return cache != 0;
}

void draw_progress_bar(const char *prefix, double percentage) {

        fputc('\r', stderr);
        if (prefix)
                fputs(prefix, stderr);

        if (!terminal_is_dumb()) {
                size_t cols = columns();
                size_t prefix_length = strlen_ptr(prefix);
                size_t length = cols > prefix_length + 6 ? cols - prefix_length - 6 : 0;

                if (length > 5 && percentage >= 0.0 && percentage <= 100.0) {
                        size_t p = (size_t) (length * percentage / 100.0);
                        bool separator_done = false;

                        fputs(ansi_highlight_green(), stderr);

                        for (size_t i = 0; i < length; i++) {

                                if (i <= p) {
                                        if (get_color_mode() == COLOR_24BIT) {
                                                uint8_t r8, g8, b8;
                                                double z = i == 0 ? 0 : (((double) i / p) * 100);
                                                hsv_to_rgb(145 /* green */, z, 33 + z*2/3, &r8, &g8, &b8);
                                                fprintf(stderr, "\x1B[38;2;%u;%u;%um", r8, g8, b8);
                                        }

                                        fputs(special_glyph(SPECIAL_GLYPH_HORIZONTAL_FAT), stderr);
                                } else if (i+1 < length && !separator_done) {
                                        fputs(ansi_normal(), stderr);
                                        fputc(' ', stderr);
                                        separator_done = true;
                                        fputs(ansi_grey(), stderr);
                                } else
                                        fputs(special_glyph(SPECIAL_GLYPH_HORIZONTAL_DOTTED), stderr);
                        }

                        fputs(ansi_normal(), stderr);
                        fputc(' ', stderr);
                }
        }

        fprintf(stderr,
                "%s%3.0f%%%s",
                ansi_highlight(),
                percentage,
                ansi_normal());

        if (!terminal_is_dumb())
                fputs(ANSI_ERASE_TO_END_OF_LINE, stderr);

        fputc('\r', stderr);
        fflush(stderr);
}

void clear_progress_bar(const char *prefix) {

        fputc('\r', stderr);

        if (terminal_is_dumb())
                fputs(strrepa(" ", strlen_ptr(prefix) + 4), /* 4: %3.0f%% */
                      stderr);
        else
                fputs(ANSI_ERASE_TO_END_OF_LINE, stderr);

        fputc('\r', stderr);
        fflush(stderr);
}