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