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