]> git.refcnt.org Git - colorize.git/blob - colorize.c
456611223623f182106f63278ffc914778701d0c
[colorize.git] / colorize.c
1 /*
2 * colorize - Read text from standard input stream or file and print
3 * it colorized through use of ANSI escape sequences
4 *
5 * Copyright (c) 2011-2019 Steven Schubiger
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 #define _DEFAULT_SOURCE
23 #define _BSD_SOURCE
24 #define _XOPEN_SOURCE 700
25 #define _FILE_OFFSET_BITS 64
26 #include <assert.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <getopt.h>
30 #include <pwd.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <wordexp.h>
41
42 #ifndef DEBUG
43 # define DEBUG 0
44 #endif
45
46 #define str(arg) #arg
47 #define to_str(arg) str(arg)
48
49 #define streq(s1, s2) (strcmp (s1, s2) == 0)
50 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
51
52 #if !DEBUG
53 # define xmalloc(size) malloc_wrap(size)
54 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
55 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
56 # define xstrdup(str) strdup_wrap(str, NULL, 0)
57 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
58 #else
59 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
60 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
61 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
62 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
63 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
64 #endif
65
66 #define free_null(ptr) free_wrap((void **)&ptr)
67
68 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
69 # undef BUF_SIZE
70 #endif
71 #ifndef BUF_SIZE
72 # define BUF_SIZE 4096
73 #endif
74
75 #define LF 0x01
76 #define CR 0x02
77
78 #define COUNT_OF(obj, type) (sizeof (obj) / sizeof (type))
79
80 #define SKIP_LINE_ENDINGS(flags) ((flags) == (CR|LF) ? 2 : 1)
81
82 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
83
84 #define STACK_VAR(ptr) do { \
85 stack (&vars_list, &stacked_vars, stacked_vars, ptr, IS_GENERIC); \
86 } while (false)
87 #define STACK_FILE(ptr) do { \
88 stack (&vars_list, &stacked_vars, stacked_vars, ptr, IS_FILE); \
89 } while (false)
90 #define RELEASE(ptr) do { \
91 release (vars_list, stacked_vars, (void **)&ptr); \
92 } while (false)
93
94 #if !DEBUG
95 # define MEM_ALLOC_FAIL() do { \
96 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
97 exit (EXIT_FAILURE); \
98 } while (false)
99 #else
100 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
101 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
102 exit (EXIT_FAILURE); \
103 } while (false)
104 #endif
105
106 #define ABORT_TRACE() \
107 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
108 abort ();
109
110 #define CHECK_COLORS_RANDOM(color1, color2) \
111 streq (color_names[color1]->name, "random") \
112 && (streq (color_names[color2]->name, "none") \
113 || streq (color_names[color2]->name, "default"))
114
115 #define ALLOC_COMPLETE_PART_LINE 8
116
117 #if defined(COLOR_SEP_CHAR_COLON)
118 # define COLOR_SEP_CHAR ':'
119 #elif defined(COLOR_SEP_CHAR_SLASH)
120 # define COLOR_SEP_CHAR '/'
121 #else
122 # define COLOR_SEP_CHAR '/'
123 #endif
124
125 #define CONF_FILE ".colorize.conf"
126
127 #if DEBUG
128 # define DEBUG_FILE "debug.txt"
129 #endif
130
131 #define MAX_ATTRIBUTE_CHARS (6 * 2)
132
133 #define PROGRAM_NAME "colorize"
134
135 #define VERSION "0.65"
136
137 typedef enum { false, true } bool;
138
139 struct conf {
140 char *attr;
141 char *color;
142 char *exclude_random;
143 char *omit_color_empty;
144 };
145
146 enum { DESC_OPTION, DESC_CONF };
147
148 struct color_name {
149 char *name;
150 char *orig;
151 };
152
153 struct color {
154 const char *name;
155 const char *code;
156 };
157
158 static const struct color fg_colors[] = {
159 { "none", NULL },
160 { "black", "30m" },
161 { "red", "31m" },
162 { "green", "32m" },
163 { "yellow", "33m" },
164 { "blue", "34m" },
165 { "magenta", "35m" },
166 { "cyan", "36m" },
167 { "white", "37m" },
168 { "default", "39m" },
169 };
170 static const struct color bg_colors[] = {
171 { "none", NULL },
172 { "black", "40m" },
173 { "red", "41m" },
174 { "green", "42m" },
175 { "yellow", "43m" },
176 { "blue", "44m" },
177 { "magenta", "45m" },
178 { "cyan", "46m" },
179 { "white", "47m" },
180 { "default", "49m" },
181 };
182
183 struct bytes_size {
184 unsigned int size;
185 char unit;
186 };
187
188 enum {
189 FMT_GENERIC,
190 FMT_STRING,
191 FMT_QUOTE,
192 FMT_COLOR,
193 FMT_RANDOM,
194 FMT_ERROR,
195 FMT_FILE,
196 FMT_TYPE,
197 FMT_CONF,
198 FMT_CONF_FILE
199 };
200 static const char *formats[] = {
201 "%s", /* generic */
202 "%s '%s'", /* string */
203 "%s `%s' %s", /* quote */
204 "%s color '%s' %s", /* color */
205 "%s color '%s' %s '%s'", /* random */
206 "less than %lu bytes %s", /* error */
207 "%s: %s", /* file */
208 "%s: %s: %s", /* type */
209 "%s: option '%s' %s", /* conf */
210 "config file %s: %s" /* conf file */
211 };
212
213 enum { GENERIC, FOREGROUND = 0, BACKGROUND };
214
215 static const struct {
216 const struct color *entries;
217 unsigned int count;
218 const char *desc;
219 } tables[] = {
220 { fg_colors, COUNT_OF (fg_colors, struct color), "foreground" },
221 { bg_colors, COUNT_OF (bg_colors, struct color), "background" },
222 };
223
224 static unsigned int opts_set;
225 enum opt_set {
226 OPT_ATTR_SET = 0x01,
227 OPT_EXCLUDE_RANDOM_SET = 0x02,
228 OPT_OMIT_COLOR_EMPTY_SET = 0x04
229 };
230 static struct {
231 char *attr;
232 char *exclude_random;
233 } opts_arg = { NULL, NULL };
234
235 enum {
236 OPT_ATTR = 1,
237 OPT_CLEAN,
238 OPT_CLEAN_ALL,
239 OPT_CONFIG,
240 OPT_EXCLUDE_RANDOM,
241 OPT_OMIT_COLOR_EMPTY,
242 OPT_HELP,
243 OPT_VERSION
244 };
245 static int opt_type;
246 static const struct option long_opts[] = {
247 { "attr", required_argument, &opt_type, OPT_ATTR },
248 { "clean", no_argument, &opt_type, OPT_CLEAN },
249 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
250 { "config", required_argument, &opt_type, OPT_CONFIG },
251 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
252 { "omit-color-empty", no_argument, &opt_type, OPT_OMIT_COLOR_EMPTY },
253 { "help", no_argument, &opt_type, OPT_HELP },
254 { "version", no_argument, &opt_type, OPT_VERSION },
255 { NULL, 0, NULL, 0 },
256 };
257
258 enum attr_type {
259 ATTR_BOLD = 0x01,
260 ATTR_UNDERSCORE = 0x02,
261 ATTR_BLINK = 0x04,
262 ATTR_REVERSE = 0x08,
263 ATTR_CONCEALED = 0x10
264 };
265 struct attr {
266 const char *name;
267 unsigned int val;
268 enum attr_type type;
269 };
270
271 enum var_type {
272 IS_GENERIC,
273 IS_FILE,
274 IS_UNUSED
275 };
276 struct var_list {
277 void *ptr;
278 enum var_type type;
279 };
280
281 static FILE *stream;
282 #if DEBUG
283 static FILE *log;
284 #endif
285
286 static unsigned int stacked_vars;
287 static struct var_list *vars_list;
288
289 static bool clean;
290 static bool clean_all;
291 static bool omit_color_empty;
292
293 static char attr[MAX_ATTRIBUTE_CHARS + 1];
294 static char *exclude;
295
296 static const char *program_name;
297
298 #if DEBUG
299 static void print_tstamp (FILE *);
300 #endif
301 static void process_opts (int, char **, char **);
302 static void conf_file_path (char **);
303 static void process_opt_attr (const char *, const bool);
304 static void write_attr (const struct attr *, unsigned int *, const bool);
305 static void process_opt_exclude_random (const char *, const bool);
306 static void parse_conf (const char *, struct conf *);
307 static void assign_conf (const char *, struct conf *, const char *, char *);
308 static void init_conf_vars (const struct conf *);
309 static void init_opts_vars (void);
310 static void print_hint (void);
311 static void print_help (void);
312 static void print_version (void);
313 static void cleanup (void);
314 static void free_color_names (struct color_name **);
315 static void free_conf (struct conf *);
316 static void process_args (unsigned int, char **, char *, const struct color **, const char **, FILE **, struct conf *);
317 static void process_file_arg (const char *, const char **, FILE **);
318 static bool skip_path_colors (const char *, const char *, const struct stat *, const bool);
319 static void gather_color_names (const char *, char *, struct color_name **);
320 static void read_print_stream (const char *, const struct color **, const char *, FILE *);
321 static void merge_print_line (const char *, const char *, FILE *);
322 static void complete_part_line (const char *, char **, FILE *);
323 static bool get_next_char (char *, const char **, FILE *, bool *);
324 static void save_char (char, char **, size_t *, size_t *);
325 static void find_color_entries (struct color_name **, const struct color **);
326 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
327 static void print_line (const char *, const struct color **, const char * const, unsigned int, bool);
328 static void print_clean (const char *);
329 static bool is_esc (const char *);
330 static const char *get_end_of_esc (const char *);
331 static const char *get_end_of_text (const char *);
332 static void print_text (const char *, size_t);
333 static bool gather_esc_offsets (const char *, const char **, const char **);
334 static bool validate_esc_clean_all (const char **);
335 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
336 static bool is_reset (int, unsigned int, const char **);
337 static bool is_attr (int, unsigned int, unsigned int, const char **);
338 static bool is_fg_color (int, const char **);
339 static bool is_bg_color (int, unsigned int, const char **);
340 #if !DEBUG
341 static void *malloc_wrap (size_t);
342 static void *calloc_wrap (size_t, size_t);
343 static void *realloc_wrap (void *, size_t);
344 #else
345 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
346 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
347 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
348 #endif
349 static void free_wrap (void **);
350 static char *strdup_wrap (const char *, const char *, unsigned int);
351 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
352 static char *expand_string (const char *);
353 static bool get_bytes_size (unsigned long, struct bytes_size *);
354 static char *get_file_type (mode_t);
355 static bool has_color_name (const char *, const char *);
356 static FILE *open_file (const char *, const char *);
357 static void vfprintf_diag (const char *, ...);
358 static void vfprintf_fail (const char *, ...);
359 static void stack (struct var_list **, unsigned int *, unsigned int, void *, enum var_type);
360 static void release (struct var_list *, unsigned int, void **);
361
362 extern int optind;
363
364 int
365 main (int argc, char **argv)
366 {
367 unsigned int arg_cnt;
368
369 const struct color *colors[2] = {
370 NULL, /* foreground */
371 NULL, /* background */
372 };
373
374 const char *file = NULL;
375
376 char *conf_file = NULL;
377 struct conf config = { NULL, NULL, NULL, NULL };
378
379 program_name = argv[0];
380 atexit (cleanup);
381
382 setvbuf (stdout, NULL, _IOLBF, 0);
383
384 #if DEBUG
385 log = open_file (DEBUG_FILE, "w");
386 print_tstamp (log);
387 /* We're in debugging mode, hence we can't invoke STACK_FILE()
388 prior to print_tstamp(), because both cause text to be written
389 to the same logfile which is expected to have the timestamp
390 first. */
391 STACK_FILE (log);
392 #endif
393
394 attr[0] = '\0';
395
396 process_opts (argc, argv, &conf_file);
397
398 #ifdef CONF_FILE_TEST
399 conf_file = to_str (CONF_FILE_TEST);
400 #elif !defined(TEST)
401 if (conf_file == NULL)
402 {
403 conf_file_path (&conf_file);
404 STACK_VAR (conf_file);
405 }
406 else
407 {
408 char *s;
409 if ((s = expand_string (conf_file)))
410 {
411 free (conf_file);
412 conf_file = s;
413 }
414 STACK_VAR (conf_file);
415 errno = 0;
416 if (access (conf_file, F_OK) == -1)
417 vfprintf_fail (formats[FMT_CONF_FILE], conf_file, strerror (errno));
418 }
419 #endif
420 #if defined(CONF_FILE_TEST) || !defined(TEST)
421 if (access (conf_file, F_OK) != -1)
422 parse_conf (conf_file, &config);
423 #endif
424 #if !defined(CONF_FILE_TEST) && !defined(TEST)
425 RELEASE (conf_file);
426 #endif
427 init_conf_vars (&config);
428
429 init_opts_vars ();
430
431 arg_cnt = argc - optind;
432
433 if (clean || clean_all)
434 {
435 if (clean && clean_all)
436 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
437 if (arg_cnt > 1)
438 vfprintf_fail ("--clean%s switch cannot be used with more than one file", clean_all ? "-all" : "");
439 {
440 unsigned int i;
441 const struct option_set {
442 const char *option;
443 enum opt_set set;
444 } options[] = {
445 { "attr", OPT_ATTR_SET },
446 { "exclude-random", OPT_EXCLUDE_RANDOM_SET },
447 { "omit-color-empty", OPT_OMIT_COLOR_EMPTY_SET },
448 };
449 for (i = 0; i < COUNT_OF (options, struct option_set); i++)
450 if (opts_set & options[i].set)
451 vfprintf_diag ("--%s switch has no meaning with --clean%s", options[i].option, clean_all ? "-all" : "");
452 }
453 }
454 else
455 {
456 if (arg_cnt == 0 || arg_cnt > 2)
457 {
458 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or --clean[-all]", arg_cnt);
459 print_hint ();
460 exit (EXIT_FAILURE);
461 }
462 }
463
464 if (clean || clean_all)
465 process_file_arg (argv[optind], &file, &stream);
466 else
467 process_args (arg_cnt, &argv[optind], &attr[0], colors, &file, &stream, &config);
468 read_print_stream (&attr[0], colors, file, stream);
469
470 free_conf (&config);
471
472 RELEASE (exclude);
473
474 exit (EXIT_SUCCESS);
475 }
476
477 #if DEBUG
478 static void
479 print_tstamp (FILE *log)
480 {
481 time_t t;
482 struct tm *tm;
483 char str[128];
484 size_t written;
485
486 t = time (NULL);
487 tm = localtime (&t);
488 if (tm == NULL)
489 {
490 perror ("localtime");
491 exit (EXIT_FAILURE);
492 }
493 written = strftime (str, sizeof (str), "%Y-%m-%d %H:%M:%S %Z", tm);
494 if (written == 0)
495 vfprintf_fail (formats[FMT_GENERIC], "strftime: 0 returned");
496
497 fprintf (log, "%s\n", str);
498 while (written--)
499 fprintf (log, "=");
500 fprintf (log, "\n");
501 }
502 #endif
503
504 #define DUP_CONFIG() \
505 *conf_file = xstrdup (optarg); \
506 break;
507
508 #define PRINT_HELP_EXIT() \
509 print_help (); \
510 exit (EXIT_SUCCESS);
511
512 #define PRINT_VERSION_EXIT() \
513 print_version (); \
514 exit (EXIT_SUCCESS);
515
516 extern char *optarg;
517
518 static void
519 process_opts (int argc, char **argv, char **conf_file)
520 {
521 int opt;
522 while ((opt = getopt_long (argc, argv, "c:hV", long_opts, NULL)) != -1)
523 {
524 switch (opt)
525 {
526 case 0: /* long opts */
527 switch (opt_type)
528 {
529 case OPT_ATTR:
530 opts_set |= OPT_ATTR_SET;
531 opts_arg.attr = xstrdup (optarg);
532 STACK_VAR (opts_arg.attr);
533 break;
534 case OPT_CLEAN:
535 clean = true;
536 break;
537 case OPT_CLEAN_ALL:
538 clean_all = true;
539 break;
540 case OPT_CONFIG:
541 DUP_CONFIG ();
542 case OPT_EXCLUDE_RANDOM:
543 opts_set |= OPT_EXCLUDE_RANDOM_SET;
544 opts_arg.exclude_random = xstrdup (optarg);
545 STACK_VAR (opts_arg.exclude_random);
546 break;
547 case OPT_OMIT_COLOR_EMPTY:
548 opts_set |= OPT_OMIT_COLOR_EMPTY_SET;
549 break;
550 case OPT_HELP:
551 PRINT_HELP_EXIT ();
552 case OPT_VERSION:
553 PRINT_VERSION_EXIT ();
554 default: /* never reached */
555 ABORT_TRACE ();
556 }
557 break;
558 case 'c':
559 DUP_CONFIG ();
560 case 'h':
561 PRINT_HELP_EXIT ();
562 case 'V':
563 PRINT_VERSION_EXIT ();
564 case '?':
565 print_hint ();
566 exit (EXIT_FAILURE);
567 default: /* never reached */
568 ABORT_TRACE ();
569 }
570 }
571 }
572
573 static void
574 conf_file_path (char **conf_file)
575 {
576 char *path;
577 uid_t uid;
578 struct passwd *passwd;
579 size_t size;
580
581 uid = getuid ();
582 errno = 0;
583 if ((passwd = getpwuid (uid)) == NULL)
584 {
585 if (errno == 0)
586 vfprintf_diag ("password file entry for uid %lu not found", (unsigned long)uid);
587 else
588 perror ("getpwuid");
589 exit (EXIT_FAILURE);
590 }
591 /* getpwuid() leaks memory */
592 size = strlen (passwd->pw_dir) + 1 + strlen (CONF_FILE) + 1;
593 path = xmalloc (size);
594 snprintf (path, size, "%s/%s", passwd->pw_dir, CONF_FILE);
595
596 *conf_file = path;
597 }
598
599 static void
600 process_opt_attr (const char *p, const bool is_opt)
601 {
602 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
603 const struct attr attrs[] = {
604 { "bold", 1, ATTR_BOLD },
605 { "underscore", 4, ATTR_UNDERSCORE },
606 { "blink", 5, ATTR_BLINK },
607 { "reverse", 7, ATTR_REVERSE },
608 { "concealed", 8, ATTR_CONCEALED },
609 };
610 unsigned int attr_types = 0;
611 const char *desc_type[2] = { "--attr switch", "attr conf option" };
612 const unsigned int DESC_TYPE = is_opt ? DESC_OPTION : DESC_CONF;
613
614 while (*p)
615 {
616 const char *s;
617 if (!isalnum ((unsigned char)*p))
618 vfprintf_fail ("%s must be provided a string", desc_type[DESC_TYPE]);
619 s = p;
620 while (isalnum ((unsigned char)*p))
621 p++;
622 if (*p != '\0' && *p != ',')
623 vfprintf_fail ("%s must have strings separated by ,", desc_type[DESC_TYPE]);
624 else
625 {
626 bool valid_attr = false;
627 unsigned int i;
628 for (i = 0; i < COUNT_OF (attrs, struct attr); i++)
629 {
630 const size_t name_len = strlen (attrs[i].name);
631 if ((size_t)(p - s) == name_len && strneq (s, attrs[i].name, name_len))
632 {
633 write_attr (&attrs[i], &attr_types, is_opt);
634 valid_attr = true;
635 break;
636 }
637 }
638 if (!valid_attr)
639 {
640 char *attr_invalid = xmalloc ((p - s) + 1);
641 STACK_VAR (attr_invalid);
642 strncpy (attr_invalid, s, p - s);
643 attr_invalid[p - s] = '\0';
644 vfprintf_fail ("%s attribute '%s' is not valid", desc_type[DESC_TYPE], attr_invalid);
645 RELEASE (attr_invalid); /* never reached */
646 }
647 }
648 if (*p)
649 p++;
650 }
651 }
652
653 static void
654 write_attr (const struct attr *attr_i, unsigned int *attr_types, const bool is_opt)
655 {
656 const unsigned int val = attr_i->val;
657 const enum attr_type attr_type = attr_i->type;
658 const char *attr_name = attr_i->name;
659
660 if (*attr_types & attr_type)
661 vfprintf_fail ("%s has attribute '%s' twice or more",
662 is_opt ? "--attr switch" : "attr conf option", attr_name);
663 snprintf (attr + strlen (attr), 3, "%u;", val);
664 *attr_types |= attr_type;
665 }
666
667 static void
668 process_opt_exclude_random (const char *s, const bool is_opt)
669 {
670 bool valid = false;
671 unsigned int i;
672 RELEASE (exclude);
673 exclude = xstrdup (s);
674 STACK_VAR (exclude);
675 for (i = 1; i < tables[GENERIC].count - 1; i++) /* skip color none and default */
676 {
677 const struct color *entry = &tables[GENERIC].entries[i];
678 if (streq (exclude, entry->name))
679 {
680 valid = true;
681 break;
682 }
683 }
684 if (!valid)
685 vfprintf_fail ("%s must be provided a plain color",
686 is_opt ? "--exclude-random switch" : "exclude-random conf option");
687 }
688
689 static void
690 init_opts_vars (void)
691 {
692 if (opts_set & OPT_ATTR_SET)
693 {
694 attr[0] = '\0'; /* Clear attr string to discard values from the config file. */
695 process_opt_attr (opts_arg.attr, true);
696 }
697 if (opts_set & OPT_EXCLUDE_RANDOM_SET)
698 process_opt_exclude_random (opts_arg.exclude_random, true);
699 if (opts_set & OPT_OMIT_COLOR_EMPTY_SET)
700 omit_color_empty = true;
701
702 RELEASE (opts_arg.attr);
703 RELEASE (opts_arg.exclude_random);
704 }
705
706 #define IS_SPACE(c) ((c) == ' ' || (c) == '\t')
707
708 static void
709 parse_conf (const char *conf_file, struct conf *config)
710 {
711 unsigned int cnt = 0;
712 char line[256 + 1];
713 FILE *conf;
714
715 conf = open_file (conf_file, "r");
716 STACK_FILE (conf);
717
718 while (fgets (line, sizeof (line), conf))
719 {
720 char *cfg, *val;
721 char *assign, *comment, *opt, *value;
722 char *p;
723
724 cnt++;
725 if ((p = strchr (line, '\r')) && *(p + 1) != '\n')
726 vfprintf_fail ("%s: CR ending of line %u is not supported, switch to CRLF/LF instead", conf_file, cnt);
727 if (strlen (line) > (sizeof (line) - 2))
728 vfprintf_fail ("%s: line %u exceeds maximum of %u characters", conf_file, cnt, (unsigned int)(sizeof (line) - 2));
729 if ((p = strpbrk (line, "\n\r")))
730 *p = '\0';
731 /* NAME PARSING (start) */
732 p = line;
733 /* skip leading spaces and tabs for name */
734 while (IS_SPACE (*p))
735 p++;
736 /* skip line if a) string end, b) comment, [cd]) newline */
737 if (*p == '\0' || *p == '#' || *p == '\n' || *p == '\r')
738 continue;
739 opt = p;
740 if (!(assign = strchr (opt, '='))) /* check for = */
741 {
742 char *s;
743 if ((s = strpbrk (opt, "# ")))
744 *s = '\0';
745 vfprintf_fail (formats[FMT_CONF], conf_file, opt, "not followed by =");
746 }
747 p = assign;
748 /* skip trailing spaces and tabs for name */
749 while (IS_SPACE (*(p - 1)))
750 p--;
751 *p = '\0';
752 /* NAME PARSING (end) */
753 /* NAME VALIDATION (start) */
754 for (p = opt; *p; p++)
755 if (!isalnum ((unsigned char)*p) && *p != '-')
756 vfprintf_fail (formats[FMT_CONF], conf_file, opt, "cannot be made of non-option characters");
757 /* NAME VALIDATION (end) */
758 /* VALUE PARSING (start) */
759 p = assign + 1;
760 /* skip leading spaces and tabs for value */
761 while (IS_SPACE (*p))
762 p++;
763 /* skip line if comment */
764 if (*p == '#')
765 continue;
766 value = p;
767 if ((comment = strchr (p, '#')))
768 p = comment;
769 else
770 p += strlen (p);
771 /* skip trailing spaces and tabs for value */
772 while (IS_SPACE (*(p - 1)))
773 p--;
774 *p = '\0';
775 /* VALUE PARSING (end) */
776
777 /* save option name */
778 cfg = xstrdup (opt);
779 STACK_VAR (cfg);
780 /* save option value (allow empty ones) */
781 val = strlen (value) ? xstrdup (value) : NULL;
782 STACK_VAR (val);
783
784 assign_conf (conf_file, config, cfg, val);
785 RELEASE (cfg);
786 }
787
788 RELEASE (conf);
789 }
790
791 #define ASSIGN_CONF(str,val) do { \
792 RELEASE (str); \
793 str = val; \
794 } while (false)
795
796 static void
797 assign_conf (const char *conf_file, struct conf *config, const char *cfg, char *val)
798 {
799 if (streq (cfg, "attr"))
800 ASSIGN_CONF (config->attr, val);
801 else if (streq (cfg, "color"))
802 ASSIGN_CONF (config->color, val);
803 else if (streq (cfg, "exclude-random"))
804 ASSIGN_CONF (config->exclude_random, val);
805 else if (streq (cfg, "omit-color-empty"))
806 ASSIGN_CONF (config->omit_color_empty, val);
807 else
808 vfprintf_fail (formats[FMT_CONF], conf_file, cfg, "not recognized");
809 }
810
811 static void
812 init_conf_vars (const struct conf *config)
813 {
814 if (config->attr)
815 process_opt_attr (config->attr, false);
816 if (config->exclude_random)
817 process_opt_exclude_random (config->exclude_random, false);
818 if (config->omit_color_empty)
819 {
820 if (streq (config->omit_color_empty, "yes"))
821 omit_color_empty = true;
822 else if (streq (config->omit_color_empty, "no"))
823 omit_color_empty = false;
824 else
825 vfprintf_fail (formats[FMT_GENERIC], "omit-color-empty conf option is not valid");
826 }
827 }
828
829 static void
830 print_hint (void)
831 {
832 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
833 }
834
835 static void
836 print_help (void)
837 {
838 struct opt_data {
839 const char *name;
840 const char *short_opt;
841 const char *arg;
842 };
843 const struct opt_data opts_data[] = {
844 { "attr", NULL, "=ATTR1,ATTR2,..." },
845 { "config", "c", "=PATH" },
846 { "exclude-random", NULL, "=COLOR" },
847 { "help", "h", NULL },
848 { "version", "V", NULL },
849 };
850 const struct option *opt = long_opts;
851 unsigned int i;
852
853 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
854 printf ("\tColors (foreground) (background)\n");
855 for (i = 0; i < tables[FOREGROUND].count; i++)
856 {
857 const struct color *entry = &tables[FOREGROUND].entries[i];
858 const char *name = entry->name;
859 const char *code = entry->code;
860 if (code)
861 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
862 code, toupper ((unsigned char)*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
863 else
864 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
865 }
866 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
867
868 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
869 printf ("\twhereas for lower case colors will be of normal intensity.\n");
870
871 printf ("\n\tOptions\n");
872 for (; opt->name; opt++)
873 {
874 const struct opt_data *opt_data = NULL;
875 unsigned int i;
876 for (i = 0; i < COUNT_OF (opts_data, struct opt_data); i++)
877 if (streq (opt->name, opts_data[i].name))
878 {
879 opt_data = &opts_data[i];
880 break;
881 }
882 if (opt_data)
883 {
884 if (opt_data->short_opt)
885 printf ("\t\t-%s, --%s", opt_data->short_opt, opt->name);
886 else
887 printf ("\t\t --%s", opt->name);
888 if (opt_data->arg)
889 printf ("%s", opt_data->arg);
890 printf ("\n");
891 }
892 else
893 printf ("\t\t --%s\n", opt->name);
894 }
895 printf ("\n");
896 }
897
898 static void
899 print_version (void)
900 {
901 #ifdef HAVE_VERSION
902 # include "version.h"
903 #else
904 const char *const version = NULL;
905 #endif
906 const char *version_prefix, *version_string;
907 const char *c_flags, *ld_flags, *cpp_flags;
908 const char *const desc_flags_unknown = "unknown";
909 struct bytes_size bytes_size;
910 bool debug;
911 #ifdef CFLAGS
912 c_flags = to_str (CFLAGS);
913 #else
914 c_flags = desc_flags_unknown;
915 #endif
916 #ifdef LDFLAGS
917 ld_flags = to_str (LDFLAGS);
918 #else
919 ld_flags = desc_flags_unknown;
920 #endif
921 #ifdef CPPFLAGS
922 cpp_flags = to_str (CPPFLAGS);
923 #else
924 cpp_flags = desc_flags_unknown;
925 #endif
926 #if DEBUG
927 debug = true;
928 #else
929 debug = false;
930 #endif
931 version_prefix = version ? "" : "v";
932 version_string = version ? version : VERSION;
933 printf ("%s %s%s (compiled at %s, %s)\n", PROGRAM_NAME, version_prefix, version_string, __DATE__, __TIME__);
934
935 printf ("Compiler flags: %s\n", c_flags);
936 printf ("Linker flags: %s\n", ld_flags);
937 printf ("Preprocessor flags: %s\n", cpp_flags);
938 if (get_bytes_size (BUF_SIZE, &bytes_size))
939 {
940 if (BUF_SIZE % 1024 == 0)
941 printf ("Buffer size: %u%c\n", bytes_size.size, bytes_size.unit);
942 else
943 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size.size, bytes_size.unit,
944 BUF_SIZE % 1024, BUF_SIZE % 1024 > 1 ? "s" : "");
945 }
946 else
947 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE, BUF_SIZE > 1 ? "s" : "");
948 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR);
949 printf ("Debugging: %s\n", debug ? "yes" : "no");
950 }
951
952 static void
953 cleanup (void)
954 {
955 if (stream && fileno (stream) != STDIN_FILENO)
956 RELEASE (stream);
957 #if DEBUG
958 if (log)
959 RELEASE (log);
960 #endif
961
962 if (vars_list)
963 {
964 unsigned int i;
965 for (i = 0; i < stacked_vars; i++)
966 {
967 struct var_list *var = &vars_list[i];
968 switch (var->type)
969 {
970 case IS_GENERIC:
971 free (var->ptr);
972 break;
973 case IS_FILE:
974 fclose (var->ptr);
975 break;
976 case IS_UNUSED:
977 break;
978 default: /* never reached */
979 ABORT_TRACE ();
980 }
981 }
982 free_null (vars_list);
983 }
984 }
985
986 static void
987 free_color_names (struct color_name **color_names)
988 {
989 unsigned int i;
990 for (i = 0; color_names[i]; i++)
991 {
992 RELEASE (color_names[i]->name);
993 RELEASE (color_names[i]->orig);
994 RELEASE (color_names[i]);
995 }
996 }
997
998 static void
999 free_conf (struct conf *config)
1000 {
1001 RELEASE (config->attr);
1002 RELEASE (config->color);
1003 RELEASE (config->exclude_random);
1004 RELEASE (config->omit_color_empty);
1005 }
1006
1007 static void
1008 process_args (unsigned int arg_cnt, char **arg_strings, char *attr, const struct color **colors, const char **file, FILE **stream, struct conf *config)
1009 {
1010 bool has_hyphen, use_conf_color;
1011 int ret;
1012 char *p;
1013 struct stat sb;
1014 struct color_name *color_names[3] = {
1015 NULL, /* foreground */
1016 NULL, /* background */
1017 NULL, /* sentinel value */
1018 };
1019
1020 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
1021 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
1022
1023 assert (color_string != NULL);
1024
1025 has_hyphen = streq (color_string, "-");
1026
1027 if (has_hyphen)
1028 {
1029 if (file_string)
1030 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
1031 else if (!config->color)
1032 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceded by color string");
1033 }
1034
1035 if (!has_hyphen && (ret = lstat (color_string, &sb)) == 0) /* exists */
1036 /* Ensure that we don't fail if there's a file with one or more
1037 color names in its path. */
1038 use_conf_color = skip_path_colors (color_string, file_string, &sb, !!config->color);
1039 else if (has_hyphen)
1040 use_conf_color = true;
1041 else
1042 use_conf_color = false;
1043
1044 /* Use color from config file. */
1045 if (arg_cnt == 1 && use_conf_color)
1046 {
1047 file_string = color_string;
1048 color_string = config->color;
1049 }
1050
1051 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
1052 {
1053 if (p == color_string)
1054 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
1055 else if (p == color_string + strlen (color_string) - 1)
1056 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
1057 else if (strchr (++p, COLOR_SEP_CHAR))
1058 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
1059 }
1060
1061 gather_color_names (color_string, attr, color_names);
1062
1063 assert (color_names[FOREGROUND] != NULL);
1064
1065 if (color_names[BACKGROUND])
1066 {
1067 unsigned int i;
1068 const unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
1069 for (i = 0; i < 2; i++)
1070 {
1071 const unsigned int color1 = color_sets[i][0];
1072 const unsigned int color2 = color_sets[i][1];
1073 if (CHECK_COLORS_RANDOM (color1, color2))
1074 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
1075 }
1076 }
1077
1078 find_color_entries (color_names, colors);
1079 assert (colors[FOREGROUND] != NULL);
1080 free_color_names (color_names);
1081
1082 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
1083 {
1084 struct color_name color_name;
1085 color_name.name = color_name.orig = "default";
1086
1087 find_color_entry (&color_name, FOREGROUND, colors);
1088 assert (colors[FOREGROUND]->code != NULL);
1089 }
1090
1091 process_file_arg (file_string, file, stream);
1092 }
1093
1094 static void
1095 process_file_arg (const char *file_string, const char **file, FILE **stream)
1096 {
1097 if (file_string)
1098 {
1099 if (streq (file_string, "-"))
1100 *stream = stdin;
1101 else
1102 {
1103 const char *file = file_string;
1104 struct stat sb;
1105 int ret;
1106
1107 errno = 0;
1108 ret = stat (file, &sb);
1109
1110 if (ret == -1)
1111 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1112
1113 if (!VALID_FILE_TYPE (sb.st_mode))
1114 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
1115
1116 *stream = open_file (file, "r");
1117 STACK_FILE (*stream);
1118 }
1119 *file = file_string;
1120 }
1121 else
1122 {
1123 *stream = stdin;
1124 *file = "stdin";
1125 }
1126
1127 assert (*stream != NULL);
1128 assert (*file != NULL);
1129 }
1130
1131 static bool
1132 skip_path_colors (const char *color_string, const char *file_string, const struct stat *sb, const bool has_conf)
1133 {
1134 bool have_file;
1135 unsigned int c;
1136 const char *color = color_string;
1137 const mode_t mode = sb->st_mode;
1138
1139 for (c = 1; c <= 2 && *color; c++)
1140 {
1141 bool matched = false;
1142 unsigned int i;
1143 for (i = 0; i < tables[GENERIC].count; i++)
1144 {
1145 const struct color *entry = &tables[GENERIC].entries[i];
1146 if (has_color_name (color, entry->name))
1147 {
1148 color += strlen (entry->name);
1149 matched = true;
1150 break;
1151 }
1152 }
1153 if (!matched && has_color_name (color, "random"))
1154 {
1155 color += strlen ("random");
1156 matched = true;
1157 }
1158 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
1159 color++;
1160 else
1161 break;
1162 }
1163
1164 have_file = (*color != '\0');
1165
1166 if (have_file)
1167 {
1168 const char *file_existing = color_string;
1169 if (file_string)
1170 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "cannot be used as color string");
1171 else
1172 {
1173 if (VALID_FILE_TYPE (mode))
1174 {
1175 if (has_conf)
1176 return true;
1177 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "must be preceded by color string");
1178 }
1179 else
1180 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "is not a valid file type");
1181 }
1182 }
1183 return false;
1184 }
1185
1186 static void
1187 gather_color_names (const char *color_string, char *attr, struct color_name **color_names)
1188 {
1189 unsigned int index;
1190 char *color, *p, *str;
1191
1192 str = xstrdup (color_string);
1193 STACK_VAR (str);
1194
1195 for (index = 0, color = str; *color; index++, color = p)
1196 {
1197 char *ch, *sep;
1198
1199 p = NULL;
1200 if ((sep = strchr (color, COLOR_SEP_CHAR)))
1201 {
1202 *sep = '\0';
1203 p = sep + 1;
1204 }
1205 else
1206 p = color + strlen (color);
1207 assert (p != NULL);
1208
1209 for (ch = color; *ch; ch++)
1210 if (!isalpha ((unsigned char)*ch))
1211 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
1212
1213 for (ch = color + 1; *ch; ch++)
1214 if (!islower ((unsigned char)*ch))
1215 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
1216
1217 if (streq (color, "None"))
1218 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
1219
1220 if (isupper ((unsigned char)*color))
1221 {
1222 switch (index)
1223 {
1224 case FOREGROUND:
1225 snprintf (attr + strlen (attr), 3, "1;");
1226 break;
1227 case BACKGROUND:
1228 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
1229 break;
1230 default: /* never reached */
1231 ABORT_TRACE ();
1232 }
1233 }
1234
1235 color_names[index] = xcalloc (1, sizeof (struct color_name));
1236 STACK_VAR (color_names[index]);
1237
1238 color_names[index]->orig = xstrdup (color);
1239 STACK_VAR (color_names[index]->orig);
1240
1241 for (ch = color; *ch; ch++)
1242 *ch = tolower ((unsigned char)*ch);
1243
1244 color_names[index]->name = xstrdup (color);
1245 STACK_VAR (color_names[index]->name);
1246 }
1247
1248 RELEASE (str);
1249 }
1250
1251 static void
1252 read_print_stream (const char *attr, const struct color **colors, const char *file, FILE *stream)
1253 {
1254 char buf[BUF_SIZE + 1];
1255 unsigned int flags = 0;
1256
1257 while (!feof (stream))
1258 {
1259 size_t bytes_read;
1260 char *eol;
1261 const char *line;
1262 bytes_read = fread (buf, 1, BUF_SIZE, stream);
1263 if (bytes_read != BUF_SIZE && ferror (stream))
1264 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
1265 buf[bytes_read] = '\0';
1266 line = buf;
1267 while ((eol = strpbrk (line, "\n\r")))
1268 {
1269 const bool has_text = (eol > line);
1270 const char *p;
1271 flags &= ~(CR|LF);
1272 if (*eol == '\r')
1273 {
1274 flags |= CR;
1275 if (*(eol + 1) == '\n')
1276 flags |= LF;
1277 }
1278 else if (*eol == '\n')
1279 flags |= LF;
1280 else /* never reached */
1281 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
1282 p = eol + SKIP_LINE_ENDINGS (flags);
1283 *eol = '\0';
1284 print_line (attr, colors, line, flags,
1285 omit_color_empty ? has_text : true);
1286 line = p;
1287 }
1288 if (feof (stream))
1289 {
1290 if (*line != '\0')
1291 print_line (attr, colors, line, 0, true);
1292 }
1293 else if (*line != '\0')
1294 {
1295 char *p;
1296 if ((clean || clean_all) && (p = strrchr (line, '\033')))
1297 merge_print_line (line, p, stream);
1298 else
1299 print_line (attr, colors, line, 0, true);
1300 }
1301 }
1302 }
1303
1304 static void
1305 merge_print_line (const char *line, const char *p, FILE *stream)
1306 {
1307 char *buf = NULL;
1308 char *merged_esc = NULL;
1309 const char *esc = "";
1310 const char char_restore = *p;
1311
1312 complete_part_line (p + 1, &buf, stream);
1313
1314 if (buf)
1315 {
1316 /* form escape sequence */
1317 esc = merged_esc = str_concat (p, buf);
1318 /* shorten partial line accordingly */
1319 *(char *)p = '\0';
1320 free (buf);
1321 }
1322
1323 #ifdef TEST_MERGE_PART_LINE
1324 printf ("%s%s", line, esc);
1325 fflush (stdout);
1326 _exit (EXIT_SUCCESS);
1327 #else
1328 print_clean (line);
1329 *(char *)p = char_restore;
1330 print_clean (esc);
1331 free (merged_esc);
1332 #endif
1333 }
1334
1335 static void
1336 complete_part_line (const char *p, char **buf, FILE *stream)
1337 {
1338 bool got_next_char = false, read_from_stream;
1339 char ch;
1340 size_t i = 0, size;
1341
1342 if (get_next_char (&ch, &p, stream, &read_from_stream))
1343 {
1344 if (ch == '[')
1345 {
1346 if (read_from_stream)
1347 save_char (ch, buf, &i, &size);
1348 }
1349 else
1350 {
1351 if (read_from_stream)
1352 ungetc ((int)ch, stream);
1353 return; /* cancel */
1354 }
1355 }
1356 else
1357 return; /* cancel */
1358
1359 while (get_next_char (&ch, &p, stream, &read_from_stream))
1360 {
1361 if (isdigit (ch) || ch == ';')
1362 {
1363 if (read_from_stream)
1364 save_char (ch, buf, &i, &size);
1365 }
1366 else /* got next character */
1367 {
1368 got_next_char = true;
1369 break;
1370 }
1371 }
1372
1373 if (got_next_char)
1374 {
1375 if (ch == 'm')
1376 {
1377 if (read_from_stream)
1378 save_char (ch, buf, &i, &size);
1379 }
1380 else
1381 {
1382 if (read_from_stream)
1383 ungetc ((int)ch, stream);
1384 return; /* cancel */
1385 }
1386 }
1387 else
1388 return; /* cancel */
1389 }
1390
1391 static bool
1392 get_next_char (char *ch, const char **p, FILE *stream, bool *read_from_stream)
1393 {
1394 if (**p == '\0')
1395 {
1396 int c;
1397 if ((c = fgetc (stream)) != EOF)
1398 {
1399 *ch = (char)c;
1400 *read_from_stream = true;
1401 return true;
1402 }
1403 else
1404 {
1405 *read_from_stream = false;
1406 return false;
1407 }
1408 }
1409 else
1410 {
1411 *ch = **p;
1412 (*p)++;
1413 *read_from_stream = false;
1414 return true;
1415 }
1416 }
1417
1418 static void
1419 save_char (char ch, char **buf, size_t *i, size_t *size)
1420 {
1421 if (!*buf)
1422 {
1423 *size = ALLOC_COMPLETE_PART_LINE;
1424 *buf = xmalloc (*size);
1425 }
1426 /* +1: effective occupied size of buffer */
1427 else if ((*i + 1) == *size)
1428 {
1429 *size *= 2;
1430 *buf = xrealloc (*buf, *size);
1431 }
1432 (*buf)[*i] = ch;
1433 (*buf)[*i + 1] = '\0';
1434 (*i)++;
1435 }
1436
1437 static void
1438 find_color_entries (struct color_name **color_names, const struct color **colors)
1439 {
1440 struct timeval tv;
1441 unsigned int index;
1442
1443 /* randomness */
1444 gettimeofday (&tv, NULL);
1445 srand (tv.tv_usec * tv.tv_sec);
1446
1447 for (index = 0; color_names[index]; index++)
1448 {
1449 const char *color_name = color_names[index]->name;
1450
1451 const unsigned int count = tables[index].count;
1452 const struct color *const color_entries = tables[index].entries;
1453
1454 if (streq (color_name, "random"))
1455 {
1456 bool excludable;
1457 unsigned int i;
1458 do {
1459 excludable = false;
1460 i = rand() % (count - 2) + 1; /* omit color none and default */
1461 switch (index)
1462 {
1463 case FOREGROUND:
1464 /* --exclude-random */
1465 if (exclude && streq (exclude, color_entries[i].name))
1466 excludable = true;
1467 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
1468 excludable = true;
1469 break;
1470 case BACKGROUND:
1471 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
1472 excludable = true;
1473 break;
1474 default: /* never reached */
1475 ABORT_TRACE ();
1476 }
1477 } while (excludable);
1478 colors[index] = (struct color *)&color_entries[i];
1479 }
1480 else
1481 find_color_entry (color_names[index], index, colors);
1482 }
1483 }
1484
1485 static void
1486 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
1487 {
1488 bool found = false;
1489 unsigned int i;
1490
1491 const unsigned int count = tables[index].count;
1492 const struct color *const color_entries = tables[index].entries;
1493
1494 for (i = 0; i < count; i++)
1495 if (streq (color_name->name, color_entries[i].name))
1496 {
1497 colors[index] = (struct color *)&color_entries[i];
1498 found = true;
1499 break;
1500 }
1501 if (!found)
1502 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
1503 }
1504
1505 static void
1506 print_line (const char *attr, const struct color **colors, const char *const line, unsigned int flags, bool emit_colors)
1507 {
1508 /* --clean[-all] */
1509 if (clean || clean_all)
1510 print_clean (line);
1511 /* skip for --omit-color-empty? */
1512 else if (emit_colors)
1513 {
1514 /* Foreground color code is guaranteed to be set when background color code is present. */
1515 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
1516 printf ("\033[%s", colors[BACKGROUND]->code);
1517 if (colors[FOREGROUND]->code)
1518 printf ("\033[%s%s%s\033[0m", attr, colors[FOREGROUND]->code, line);
1519 else
1520 printf (formats[FMT_GENERIC], line);
1521 }
1522 if (flags & CR)
1523 putchar ('\r');
1524 if (flags & LF)
1525 putchar ('\n');
1526 }
1527
1528 static void
1529 print_clean (const char *line)
1530 {
1531 const char *p = line;
1532
1533 if (is_esc (p))
1534 p = get_end_of_esc (p);
1535
1536 while (*p != '\0')
1537 {
1538 const char *text_start = p;
1539 const char *text_end = get_end_of_text (p);
1540 print_text (text_start, text_end - text_start);
1541 p = get_end_of_esc (text_end);
1542 }
1543 }
1544
1545 static bool
1546 is_esc (const char *p)
1547 {
1548 return gather_esc_offsets (p, NULL, NULL);
1549 }
1550
1551 static const char *
1552 get_end_of_esc (const char *p)
1553 {
1554 const char *esc;
1555 const char *end = NULL;
1556 while ((esc = strchr (p, '\033')))
1557 {
1558 if (gather_esc_offsets (esc, NULL, &end))
1559 break;
1560 p = esc + 1;
1561 }
1562 return end ? end + 1 : p + strlen (p);
1563 }
1564
1565 static const char *
1566 get_end_of_text (const char *p)
1567 {
1568 const char *esc;
1569 const char *start = NULL;
1570 while ((esc = strchr (p, '\033')))
1571 {
1572 if (gather_esc_offsets (esc, &start, NULL))
1573 break;
1574 p = esc + 1;
1575 }
1576 return start ? start : p + strlen (p);
1577 }
1578
1579 static void
1580 print_text (const char *p, size_t len)
1581 {
1582 size_t bytes_written;
1583 bytes_written = fwrite (p, 1, len, stdout);
1584 if (bytes_written != len)
1585 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
1586 }
1587
1588 static bool
1589 gather_esc_offsets (const char *p, const char **start, const char **end)
1590 {
1591 /* ESC[ */
1592 if (*p == 27 && *(p + 1) == '[')
1593 {
1594 bool valid = false;
1595 const char *const begin = p;
1596 p += 2;
1597 if (clean_all)
1598 valid = validate_esc_clean_all (&p);
1599 else if (clean)
1600 {
1601 bool check_values;
1602 unsigned int prev_iter, iter;
1603 const char *digit;
1604 prev_iter = iter = 0;
1605 do {
1606 check_values = false;
1607 iter++;
1608 if (!isdigit ((unsigned char)*p))
1609 break;
1610 digit = p;
1611 while (isdigit ((unsigned char)*p))
1612 p++;
1613 if (p - digit > 2)
1614 break;
1615 else /* check range */
1616 {
1617 char val[3];
1618 int value;
1619 unsigned int i;
1620 const unsigned int digits = p - digit;
1621 for (i = 0; i < digits; i++)
1622 val[i] = *digit++;
1623 val[i] = '\0';
1624 value = atoi (val);
1625 valid = validate_esc_clean (value, iter, &prev_iter, &p, &check_values);
1626 }
1627 } while (check_values);
1628 }
1629 if (valid)
1630 {
1631 if (start)
1632 *start = begin;
1633 if (end)
1634 *end = p;
1635 return true;
1636 }
1637 }
1638 return false;
1639 }
1640
1641 static bool
1642 validate_esc_clean_all (const char **p)
1643 {
1644 while (isdigit ((unsigned char)**p) || **p == ';')
1645 (*p)++;
1646 return (**p == 'm');
1647 }
1648
1649 static bool
1650 validate_esc_clean (int value, unsigned int iter, unsigned int *prev_iter, const char **p, bool *check_values)
1651 {
1652 if (is_reset (value, iter, p))
1653 return true;
1654 else if (is_attr (value, iter, *prev_iter, p))
1655 {
1656 (*p)++;
1657 *check_values = true;
1658 *prev_iter = iter;
1659 return false; /* partial escape sequence, need another valid value */
1660 }
1661 else if (is_fg_color (value, p))
1662 return true;
1663 else if (is_bg_color (value, iter, p))
1664 return true;
1665 else
1666 return false;
1667 }
1668
1669 static bool
1670 is_reset (int value, unsigned int iter, const char **p)
1671 {
1672 return (value == 0 && iter == 1 && **p == 'm');
1673 }
1674
1675 static bool
1676 is_attr (int value, unsigned int iter, unsigned int prev_iter, const char **p)
1677 {
1678 return ((value > 0 && value < 10) && (iter - prev_iter == 1) && **p == ';');
1679 }
1680
1681 static bool
1682 is_fg_color (int value, const char **p)
1683 {
1684 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1685 }
1686
1687 static bool
1688 is_bg_color (int value, unsigned int iter, const char **p)
1689 {
1690 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1691 }
1692
1693 #if !DEBUG
1694 static void *
1695 malloc_wrap (size_t size)
1696 {
1697 void *p = malloc (size);
1698 if (!p)
1699 MEM_ALLOC_FAIL ();
1700 return p;
1701 }
1702
1703 static void *
1704 calloc_wrap (size_t nmemb, size_t size)
1705 {
1706 void *p = calloc (nmemb, size);
1707 if (!p)
1708 MEM_ALLOC_FAIL ();
1709 return p;
1710 }
1711
1712 static void *
1713 realloc_wrap (void *ptr, size_t size)
1714 {
1715 void *p = realloc (ptr, size);
1716 if (!p)
1717 MEM_ALLOC_FAIL ();
1718 return p;
1719 }
1720 #else
1721 static const char *const format_debug = "%s: %10s %7lu bytes [source file %s, line %5u]\n";
1722 static void *
1723 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1724 {
1725 void *p = malloc (size);
1726 if (!p)
1727 MEM_ALLOC_FAIL_DEBUG (file, line);
1728 fprintf (log, format_debug, program_name, "malloc'ed", (unsigned long)size, file, line);
1729 return p;
1730 }
1731
1732 static void *
1733 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1734 {
1735 void *p = calloc (nmemb, size);
1736 if (!p)
1737 MEM_ALLOC_FAIL_DEBUG (file, line);
1738 fprintf (log, format_debug, program_name, "calloc'ed", (unsigned long)(nmemb * size), file, line);
1739 return p;
1740 }
1741
1742 static void *
1743 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1744 {
1745 void *p = realloc (ptr, size);
1746 if (!p)
1747 MEM_ALLOC_FAIL_DEBUG (file, line);
1748 fprintf (log, format_debug, program_name, "realloc'ed", (unsigned long)size, file, line);
1749 return p;
1750 }
1751 #endif /* !DEBUG */
1752
1753 static void
1754 free_wrap (void **ptr)
1755 {
1756 free (*ptr);
1757 *ptr = NULL;
1758 }
1759
1760 #if !DEBUG
1761 # define do_malloc(len, file, line) malloc_wrap(len)
1762 #else
1763 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1764 #endif
1765
1766 static char *
1767 strdup_wrap (const char *str, const char *file, unsigned int line)
1768 {
1769 const size_t len = strlen (str) + 1;
1770 char *p = do_malloc (len, file, line);
1771 strncpy (p, str, len);
1772 return p;
1773 }
1774
1775 static char *
1776 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1777 {
1778 const size_t len = strlen (str1) + strlen (str2) + 1;
1779 char *p, *str;
1780
1781 p = str = do_malloc (len, file, line);
1782 strncpy (p, str1, strlen (str1));
1783 p += strlen (str1);
1784 strncpy (p, str2, strlen (str2));
1785 p += strlen (str2);
1786 *p = '\0';
1787
1788 return str;
1789 }
1790
1791 static char *
1792 expand_string (const char *str)
1793 {
1794 char *s = NULL;
1795 wordexp_t p;
1796
1797 wordexp (str, &p, 0);
1798 if (p.we_wordc >= 1)
1799 s = xstrdup (p.we_wordv[0]);
1800 wordfree (&p);
1801
1802 return s;
1803 }
1804
1805 static bool
1806 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1807 {
1808 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1809 unsigned long size = bytes;
1810 if (bytes < 1024)
1811 return false;
1812 unit = units;
1813 while (size >= 1024 && *(unit + 1))
1814 {
1815 size /= 1024;
1816 unit++;
1817 }
1818 bytes_size->size = (unsigned int)size;
1819 bytes_size->unit = *unit;
1820 return true;
1821 }
1822
1823 static char *
1824 get_file_type (mode_t mode)
1825 {
1826 if (S_ISREG (mode))
1827 return "file";
1828 else if (S_ISDIR (mode))
1829 return "directory";
1830 else if (S_ISCHR (mode))
1831 return "character device";
1832 else if (S_ISBLK (mode))
1833 return "block device";
1834 else if (S_ISFIFO (mode))
1835 return "named pipe";
1836 else if (S_ISLNK (mode))
1837 return "symbolic link";
1838 else if (S_ISSOCK (mode))
1839 return "socket";
1840 else
1841 return "file";
1842 }
1843
1844 static bool
1845 has_color_name (const char *str, const char *name)
1846 {
1847 char *p;
1848
1849 assert (strlen (str) > 0);
1850 assert (strlen (name) > 0);
1851
1852 if (!(*str == *name || *str == toupper ((unsigned char)*name)))
1853 return false;
1854 else if (*(name + 1) != '\0'
1855 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1856 return false;
1857 else
1858 return true;
1859 }
1860
1861 static FILE *
1862 open_file (const char *file, const char *mode)
1863 {
1864 FILE *stream;
1865
1866 errno = 0;
1867 stream = fopen (file, mode);
1868 if (!stream)
1869 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1870
1871 return stream;
1872 }
1873
1874 #define DO_VFPRINTF(fmt) \
1875 va_list ap; \
1876 fprintf (stderr, "%s: ", program_name); \
1877 va_start (ap, fmt); \
1878 vfprintf (stderr, fmt, ap); \
1879 va_end (ap); \
1880 fprintf (stderr, "\n");
1881
1882 static void
1883 vfprintf_diag (const char *fmt, ...)
1884 {
1885 DO_VFPRINTF (fmt);
1886 }
1887
1888 static void
1889 vfprintf_fail (const char *fmt, ...)
1890 {
1891 DO_VFPRINTF (fmt);
1892 exit (EXIT_FAILURE);
1893 }
1894
1895 static void
1896 stack (struct var_list **list, unsigned int *stacked, unsigned int index, void *ptr, enum var_type type)
1897 {
1898 struct var_list *var;
1899 /* nothing to stack */
1900 if (ptr == NULL)
1901 return;
1902 if (!*list)
1903 *list = xmalloc (sizeof (struct var_list));
1904 else
1905 {
1906 unsigned int i;
1907 for (i = 0; i < *stacked; i++)
1908 {
1909 var = &(*list)[i];
1910 if (var->type == IS_UNUSED)
1911 {
1912 var->ptr = ptr;
1913 var->type = type;
1914 return; /* reused */
1915 }
1916 }
1917 *list = xrealloc (*list, (*stacked + 1) * sizeof (struct var_list));
1918 }
1919 var = &(*list)[index];
1920 var->ptr = ptr;
1921 var->type = type;
1922 (*stacked)++;
1923 }
1924
1925 static void
1926 release (struct var_list *list, unsigned int stacked, void **ptr)
1927 {
1928 unsigned int i;
1929 /* nothing to release */
1930 if (*ptr == NULL)
1931 return;
1932 for (i = 0; i < stacked; i++)
1933 {
1934 struct var_list *var = &list[i];
1935 if (var->type != IS_UNUSED
1936 && var->ptr == *ptr)
1937 {
1938 switch (var->type)
1939 {
1940 case IS_GENERIC:
1941 free (*ptr);
1942 break;
1943 case IS_FILE:
1944 fclose (*ptr);
1945 break;
1946 default: /* never reached */
1947 ABORT_TRACE ();
1948 }
1949 *ptr = NULL;
1950 var->ptr = NULL;
1951 var->type = IS_UNUSED;
1952 return;
1953 }
1954 }
1955 }