]> git.refcnt.org Git - colorize.git/blob - colorize.c
Assert after find_color_entry() returns
[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-2017 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 <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <time.h>
38 #include <unistd.h>
39
40 #ifndef DEBUG
41 # define DEBUG 0
42 #endif
43
44 #define str(arg) #arg
45 #define to_str(arg) str(arg)
46
47 #define streq(s1, s2) (strcmp (s1, s2) == 0)
48 #define strneq(s1, s2, n) (strncmp (s1, s2, n) == 0)
49
50 #if !DEBUG
51 # define xmalloc(size) malloc_wrap(size)
52 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
53 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
54 # define xstrdup(str) strdup_wrap(str, NULL, 0)
55 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
56 #else
57 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
58 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
59 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
60 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
61 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
62 #endif
63
64 #define free_null(ptr) free_wrap((void **)&ptr)
65
66 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
67 # undef BUF_SIZE
68 #endif
69 #ifndef BUF_SIZE
70 # define BUF_SIZE 4096
71 #endif
72
73 #define LF 0x01
74 #define CR 0x02
75
76 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
77
78 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
79
80 #define STACK_VAR(ptr) do { \
81 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
82 } while (false)
83
84 #define RELEASE_VAR(ptr) do { \
85 release_var (vars_list, stacked_vars, (void **)&ptr); \
86 } while (false)
87
88 #if !DEBUG
89 # define MEM_ALLOC_FAIL() do { \
90 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
91 exit (EXIT_FAILURE); \
92 } while (false)
93 #else
94 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
95 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
96 exit (EXIT_FAILURE); \
97 } while (false)
98 #endif
99
100 #define ABORT_TRACE() \
101 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
102 abort (); \
103
104 #define CHECK_COLORS_RANDOM(color1, color2) \
105 streq (color_names[color1]->name, "random") \
106 && (streq (color_names[color2]->name, "none") \
107 || streq (color_names[color2]->name, "default")) \
108
109 #define ALLOC_COMPLETE_PART_LINE 8
110
111 #if defined(COLOR_SEP_CHAR_COLON)
112 # define COLOR_SEP_CHAR ':'
113 #elif defined(COLOR_SEP_CHAR_SLASH)
114 # define COLOR_SEP_CHAR '/'
115 #else
116 # define COLOR_SEP_CHAR '/'
117 #endif
118
119 #if DEBUG
120 # define DEBUG_FILE "debug.txt"
121 #endif
122
123 #define MAX_ATTRIBUTE_CHARS (6 * 2)
124
125 #define VERSION "0.62"
126
127 typedef enum { false, true } bool;
128
129 struct color_name {
130 char *name;
131 char *orig;
132 };
133
134 struct color {
135 const char *name;
136 const char *code;
137 };
138
139 static const struct color fg_colors[] = {
140 { "none", NULL },
141 { "black", "30m" },
142 { "red", "31m" },
143 { "green", "32m" },
144 { "yellow", "33m" },
145 { "blue", "34m" },
146 { "magenta", "35m" },
147 { "cyan", "36m" },
148 { "white", "37m" },
149 { "default", "39m" },
150 };
151 static const struct color bg_colors[] = {
152 { "none", NULL },
153 { "black", "40m" },
154 { "red", "41m" },
155 { "green", "42m" },
156 { "yellow", "43m" },
157 { "blue", "44m" },
158 { "magenta", "45m" },
159 { "cyan", "46m" },
160 { "white", "47m" },
161 { "default", "49m" },
162 };
163
164 struct bytes_size {
165 unsigned int size;
166 char unit;
167 };
168
169 enum {
170 FMT_GENERIC,
171 FMT_STRING,
172 FMT_QUOTE,
173 FMT_COLOR,
174 FMT_RANDOM,
175 FMT_ERROR,
176 FMT_FILE,
177 FMT_TYPE
178 };
179 static const char *formats[] = {
180 "%s", /* generic */
181 "%s '%s'", /* string */
182 "%s `%s' %s", /* quote */
183 "%s color '%s' %s", /* color */
184 "%s color '%s' %s '%s'", /* random */
185 "less than %lu bytes %s", /* error */
186 "%s: %s", /* file */
187 "%s: %s: %s", /* type */
188 };
189
190 enum { GENERIC, FOREGROUND = 0, BACKGROUND };
191
192 static const struct {
193 const struct color *entries;
194 unsigned int count;
195 const char *desc;
196 } tables[] = {
197 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
198 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
199 };
200
201 enum {
202 OPT_ATTR = 1,
203 OPT_CLEAN,
204 OPT_CLEAN_ALL,
205 OPT_EXCLUDE_RANDOM,
206 OPT_HELP,
207 OPT_VERSION
208 };
209 static int opt_type;
210 static const struct option long_opts[] = {
211 { "attr", required_argument, &opt_type, OPT_ATTR },
212 { "clean", no_argument, &opt_type, OPT_CLEAN },
213 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
214 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
215 { "help", no_argument, &opt_type, OPT_HELP },
216 { "version", no_argument, &opt_type, OPT_VERSION },
217 { NULL, 0, NULL, 0 },
218 };
219
220 enum attr_type {
221 ATTR_BOLD = 0x01,
222 ATTR_UNDERSCORE = 0x02,
223 ATTR_BLINK = 0x04,
224 ATTR_REVERSE = 0x08,
225 ATTR_CONCEALED = 0x10
226 };
227 struct attr {
228 const char *name;
229 unsigned int val;
230 enum attr_type type;
231 };
232
233 static FILE *stream;
234 #if DEBUG
235 static FILE *log;
236 #endif
237
238 static unsigned int stacked_vars;
239 static void **vars_list;
240
241 static bool clean;
242 static bool clean_all;
243
244 static char attr[MAX_ATTRIBUTE_CHARS + 1];
245 static char *exclude;
246
247 static const char *program_name;
248
249 static void process_opts (int, char **);
250 static void process_opt_attr (const char *);
251 static void write_attr (const struct attr *, unsigned int *);
252 static void print_hint (void);
253 static void print_help (void);
254 static void print_version (void);
255 static void cleanup (void);
256 static void free_color_names (struct color_name **);
257 static void process_args (unsigned int, char **, char *, const struct color **, const char **, FILE **);
258 static void process_file_arg (const char *, const char **, FILE **);
259 static void skip_path_colors (const char *, const char *, const struct stat *);
260 static void gather_color_names (const char *, char *, struct color_name **);
261 static void read_print_stream (const char *, const struct color **, const char *, FILE *);
262 static void merge_print_line (const char *, const char *, FILE *);
263 static void complete_part_line (const char *, char **, FILE *);
264 static bool get_next_char (char *, const char **, FILE *, bool *);
265 static void save_char (char, char **, size_t *, size_t *);
266 static void find_color_entries (struct color_name **, const struct color **);
267 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
268 static void print_line (const char *, const struct color **, const char * const, unsigned int);
269 static void print_clean (const char *);
270 static bool is_esc (const char *);
271 static const char *get_end_of_esc (const char *);
272 static const char *get_end_of_text (const char *);
273 static void print_text (const char *, size_t);
274 static bool gather_esc_offsets (const char *, const char **, const char **);
275 static bool validate_esc_clean_all (const char **);
276 static bool validate_esc_clean (int, unsigned int, unsigned int *, const char **, bool *);
277 static bool is_reset (int, unsigned int, const char **);
278 static bool is_attr (int, unsigned int, unsigned int, const char **);
279 static bool is_fg_color (int, const char **);
280 static bool is_bg_color (int, unsigned int, const char **);
281 #if !DEBUG
282 static void *malloc_wrap (size_t);
283 static void *calloc_wrap (size_t, size_t);
284 static void *realloc_wrap (void *, size_t);
285 #else
286 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
287 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
288 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
289 #endif
290 static void free_wrap (void **);
291 static char *strdup_wrap (const char *, const char *, unsigned int);
292 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
293 static bool get_bytes_size (unsigned long, struct bytes_size *);
294 static char *get_file_type (mode_t);
295 static bool has_color_name (const char *, const char *);
296 static FILE *open_file (const char *, const char *);
297 static void vfprintf_diag (const char *, ...);
298 static void vfprintf_fail (const char *, ...);
299 static void stack_var (void ***, unsigned int *, unsigned int, void *);
300 static void release_var (void **, unsigned int, void **);
301
302 extern int optind;
303
304 int
305 main (int argc, char **argv)
306 {
307 unsigned int arg_cnt;
308
309 const struct color *colors[2] = {
310 NULL, /* foreground */
311 NULL, /* background */
312 };
313
314 const char *file = NULL;
315
316 program_name = argv[0];
317 atexit (cleanup);
318
319 setvbuf (stdout, NULL, _IOLBF, 0);
320
321 #if DEBUG
322 log = open_file (DEBUG_FILE, "w");
323 #endif
324
325 attr[0] = '\0';
326
327 process_opts (argc, argv);
328
329 arg_cnt = argc - optind;
330
331 if (clean || clean_all)
332 {
333 if (clean && clean_all)
334 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
335 if (arg_cnt > 1)
336 {
337 const char *format = "%s %s";
338 const char *message = "switch cannot be used with more than one file";
339 if (clean)
340 vfprintf_fail (format, "--clean", message);
341 else if (clean_all)
342 vfprintf_fail (format, "--clean-all", message);
343 }
344 }
345 else
346 {
347 if (arg_cnt == 0 || arg_cnt > 2)
348 {
349 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt);
350 print_hint ();
351 exit (EXIT_FAILURE);
352 }
353 }
354
355 if (clean || clean_all)
356 process_file_arg (argv[optind], &file, &stream);
357 else
358 process_args (arg_cnt, &argv[optind], &attr[0], colors, &file, &stream);
359 read_print_stream (&attr[0], colors, file, stream);
360
361 RELEASE_VAR (exclude);
362
363 exit (EXIT_SUCCESS);
364 }
365
366 #define PRINT_HELP_EXIT() \
367 print_help (); \
368 exit (EXIT_SUCCESS); \
369
370 #define PRINT_VERSION_EXIT() \
371 print_version (); \
372 exit (EXIT_SUCCESS); \
373
374 extern char *optarg;
375
376 static void
377 process_opts (int argc, char **argv)
378 {
379 int opt;
380 while ((opt = getopt_long (argc, argv, "hV", long_opts, NULL)) != -1)
381 {
382 switch (opt)
383 {
384 case 0: /* long opts */
385 switch (opt_type)
386 {
387 case OPT_ATTR:
388 process_opt_attr (optarg);
389 break;
390 case OPT_CLEAN:
391 clean = true;
392 break;
393 case OPT_CLEAN_ALL:
394 clean_all = true;
395 break;
396 case OPT_EXCLUDE_RANDOM: {
397 bool valid = false;
398 unsigned int i;
399 exclude = xstrdup (optarg);
400 STACK_VAR (exclude);
401 for (i = 1; i < tables[GENERIC].count - 1; i++) /* skip color none and default */
402 {
403 const struct color *entry = &tables[GENERIC].entries[i];
404 if (streq (exclude, entry->name))
405 {
406 valid = true;
407 break;
408 }
409 }
410 if (!valid)
411 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
412 break;
413 }
414 case OPT_HELP:
415 PRINT_HELP_EXIT ();
416 case OPT_VERSION:
417 PRINT_VERSION_EXIT ();
418 default: /* never reached */
419 ABORT_TRACE ();
420 }
421 break;
422 case 'h':
423 PRINT_HELP_EXIT ();
424 case 'V':
425 PRINT_VERSION_EXIT ();
426 case '?':
427 print_hint ();
428 exit (EXIT_FAILURE);
429 default: /* never reached */
430 ABORT_TRACE ();
431 }
432 }
433 }
434
435 static void
436 process_opt_attr (const char *p)
437 {
438 /* If attributes are added to this "list", also increase MAX_ATTRIBUTE_CHARS! */
439 const struct attr attrs[] = {
440 { "bold", 1, ATTR_BOLD },
441 { "underscore", 4, ATTR_UNDERSCORE },
442 { "blink", 5, ATTR_BLINK },
443 { "reverse", 7, ATTR_REVERSE },
444 { "concealed", 8, ATTR_CONCEALED },
445 };
446 unsigned int attr_types = 0;
447
448 while (*p)
449 {
450 const char *s;
451 if (!isalnum (*p))
452 vfprintf_fail (formats[FMT_GENERIC], "--attr switch must be provided a string");
453 s = p;
454 while (isalnum (*p))
455 p++;
456 if (*p != '\0' && *p != ',')
457 vfprintf_fail (formats[FMT_GENERIC], "--attr switch must have strings separated by ,");
458 else
459 {
460 bool valid_attr = false;
461 unsigned int i;
462 for (i = 0; i < sizeof (attrs) / sizeof (struct attr); i++)
463 {
464 const size_t name_len = strlen (attrs[i].name);
465 if ((size_t)(p - s) == name_len && strneq (s, attrs[i].name, name_len))
466 {
467 write_attr (&attrs[i], &attr_types);
468 valid_attr = true;
469 break;
470 }
471 }
472 if (!valid_attr)
473 {
474 char *attr_invalid = xmalloc ((p - s) + 1);
475 STACK_VAR (attr_invalid);
476 strncpy (attr_invalid, s, p - s);
477 attr_invalid[p - s] = '\0';
478 vfprintf_fail ("--attr switch attribute '%s' is not valid", attr_invalid);
479 RELEASE_VAR (attr_invalid); /* never reached */
480 }
481 }
482 if (*p)
483 p++;
484 }
485 }
486
487 static void
488 write_attr (const struct attr *attr_i, unsigned int *attr_types)
489 {
490 const unsigned int val = attr_i->val;
491 const enum attr_type attr_type = attr_i->type;
492 const char *attr_name = attr_i->name;
493
494 if (*attr_types & attr_type)
495 vfprintf_fail ("--attr switch has attribute '%s' twice or more", attr_name);
496 snprintf (attr + strlen (attr), 3, "%u;", val);
497 *attr_types |= attr_type;
498 }
499
500 static void
501 print_hint (void)
502 {
503 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
504 }
505
506 static void
507 print_help (void)
508 {
509 struct short_opt {
510 const char *name;
511 const char *short_opt;
512 };
513 const struct short_opt short_opts[] = {
514 { "help", "h" },
515 { "version", "V" },
516 };
517 const struct option *opt = long_opts;
518 unsigned int i;
519
520 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
521 printf ("\tColors (foreground) (background)\n");
522 for (i = 0; i < tables[FOREGROUND].count; i++)
523 {
524 const struct color *entry = &tables[FOREGROUND].entries[i];
525 const char *name = entry->name;
526 const char *code = entry->code;
527 if (code)
528 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
529 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
530 else
531 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
532 }
533 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
534
535 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
536 printf ("\twhereas for lower case colors will be of normal intensity.\n");
537
538 printf ("\n\tOptions\n");
539 for (; opt->name; opt++)
540 {
541 const char *short_opt = NULL;
542 unsigned int i;
543 for (i = 0; i < sizeof (short_opts) / sizeof (struct short_opt); i++)
544 if (streq (opt->name, short_opts[i].name))
545 {
546 short_opt = short_opts[i].short_opt;
547 break;
548 }
549 if (short_opt)
550 printf ("\t\t-%s, --%s\n", short_opt, opt->name);
551 else
552 printf ("\t\t --%s\n", opt->name);
553 }
554 printf ("\n");
555 }
556
557 static void
558 print_version (void)
559 {
560 #ifdef HAVE_VERSION
561 # include "version.h"
562 #else
563 const char *version = NULL;
564 #endif
565 const char *version_prefix, *version_string;
566 const char *c_flags, *ld_flags, *cpp_flags;
567 const char *const desc_flags_unknown = "unknown";
568 struct bytes_size bytes_size;
569 bool debug;
570 #ifdef CFLAGS
571 c_flags = to_str (CFLAGS);
572 #else
573 c_flags = desc_flags_unknown;
574 #endif
575 #ifdef LDFLAGS
576 ld_flags = to_str (LDFLAGS);
577 #else
578 ld_flags = desc_flags_unknown;
579 #endif
580 #ifdef CPPFLAGS
581 cpp_flags = to_str (CPPFLAGS);
582 #else
583 cpp_flags = desc_flags_unknown;
584 #endif
585 #if DEBUG
586 debug = true;
587 #else
588 debug = false;
589 #endif
590 version_prefix = version ? "" : "v";
591 version_string = version ? version : VERSION;
592 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix, version_string, __DATE__, __TIME__);
593
594 printf ("Compiler flags: %s\n", c_flags);
595 printf ("Linker flags: %s\n", ld_flags);
596 printf ("Preprocessor flags: %s\n", cpp_flags);
597 if (get_bytes_size (BUF_SIZE, &bytes_size))
598 {
599 if (BUF_SIZE % 1024 == 0)
600 printf ("Buffer size: %u%c\n", bytes_size.size, bytes_size.unit);
601 else
602 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size.size, bytes_size.unit,
603 BUF_SIZE % 1024, BUF_SIZE % 1024 > 1 ? "s" : "");
604 }
605 else
606 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE, BUF_SIZE > 1 ? "s" : "");
607 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR);
608 printf ("Debugging: %s\n", debug ? "yes" : "no");
609 }
610
611 static void
612 cleanup (void)
613 {
614 if (stream && fileno (stream) != STDIN_FILENO)
615 fclose (stream);
616 #if DEBUG
617 if (log)
618 fclose (log);
619 #endif
620
621 if (vars_list)
622 {
623 unsigned int i;
624 for (i = 0; i < stacked_vars; i++)
625 free (vars_list[i]);
626 free_null (vars_list);
627 }
628 }
629
630 static void
631 free_color_names (struct color_name **color_names)
632 {
633 unsigned int i;
634 for (i = 0; color_names[i]; i++)
635 {
636 RELEASE_VAR (color_names[i]->name);
637 RELEASE_VAR (color_names[i]->orig);
638 RELEASE_VAR (color_names[i]);
639 }
640 }
641
642 static void
643 process_args (unsigned int arg_cnt, char **arg_strings, char *attr, const struct color **colors, const char **file, FILE **stream)
644 {
645 int ret;
646 char *p;
647 struct stat sb;
648 struct color_name *color_names[3] = { NULL, NULL, NULL };
649
650 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
651 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
652
653 assert (color_string != NULL);
654
655 if (streq (color_string, "-"))
656 {
657 if (file_string)
658 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
659 else
660 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceded by color string");
661 }
662
663 ret = lstat (color_string, &sb);
664
665 /* Ensure that we don't fail if there's a file with one or more
666 color names in its path. */
667 if (ret == 0) /* success */
668 skip_path_colors (color_string, file_string, &sb);
669
670 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
671 {
672 if (p == color_string)
673 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
674 else if (p == color_string + strlen (color_string) - 1)
675 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
676 else if (strchr (++p, COLOR_SEP_CHAR))
677 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
678 }
679
680 gather_color_names (color_string, attr, color_names);
681
682 assert (color_names[FOREGROUND] != NULL);
683
684 if (color_names[BACKGROUND])
685 {
686 unsigned int i;
687 const unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
688 for (i = 0; i < 2; i++)
689 {
690 const unsigned int color1 = color_sets[i][0];
691 const unsigned int color2 = color_sets[i][1];
692 if (CHECK_COLORS_RANDOM (color1, color2))
693 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
694 }
695 }
696
697 find_color_entries (color_names, colors);
698 assert (colors[FOREGROUND] != NULL);
699 free_color_names (color_names);
700
701 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
702 {
703 struct color_name color_name;
704 color_name.name = color_name.orig = "default";
705
706 find_color_entry (&color_name, FOREGROUND, colors);
707 assert (colors[FOREGROUND]->code != NULL);
708 }
709
710 process_file_arg (file_string, file, stream);
711 }
712
713 static void
714 process_file_arg (const char *file_string, const char **file, FILE **stream)
715 {
716 if (file_string)
717 {
718 if (streq (file_string, "-"))
719 *stream = stdin;
720 else
721 {
722 const char *file = file_string;
723 struct stat sb;
724 int ret;
725
726 errno = 0;
727 ret = stat (file, &sb);
728
729 if (ret == -1)
730 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
731
732 if (!VALID_FILE_TYPE (sb.st_mode))
733 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
734
735 *stream = open_file (file, "r");
736 }
737 *file = file_string;
738 }
739 else
740 {
741 *stream = stdin;
742 *file = "stdin";
743 }
744
745 assert (*stream != NULL);
746 assert (*file != NULL);
747 }
748
749 static void
750 skip_path_colors (const char *color_string, const char *file_string, const struct stat *sb)
751 {
752 bool have_file;
753 unsigned int c;
754 const char *color = color_string;
755 const mode_t mode = sb->st_mode;
756
757 for (c = 1; c <= 2 && *color; c++)
758 {
759 bool matched = false;
760 unsigned int i;
761 for (i = 0; i < tables[GENERIC].count; i++)
762 {
763 const struct color *entry = &tables[GENERIC].entries[i];
764 if (has_color_name (color, entry->name))
765 {
766 color += strlen (entry->name);
767 matched = true;
768 break;
769 }
770 }
771 if (!matched && has_color_name (color, "random"))
772 {
773 color += strlen ("random");
774 matched = true;
775 }
776 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
777 color++;
778 else
779 break;
780 }
781
782 have_file = (*color != '\0');
783
784 if (have_file)
785 {
786 const char *file_existing = color_string;
787 if (file_string)
788 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "cannot be used as color string");
789 else
790 {
791 if (VALID_FILE_TYPE (mode))
792 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "must be preceded by color string");
793 else
794 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "is not a valid file type");
795 }
796 }
797 }
798
799 static void
800 gather_color_names (const char *color_string, char *attr, struct color_name **color_names)
801 {
802 unsigned int index;
803 char *color, *p, *str;
804
805 str = xstrdup (color_string);
806 STACK_VAR (str);
807
808 for (index = 0, color = str; *color; index++, color = p)
809 {
810 char *ch, *sep;
811
812 p = NULL;
813 if ((sep = strchr (color, COLOR_SEP_CHAR)))
814 {
815 *sep = '\0';
816 p = sep + 1;
817 }
818 else
819 p = color + strlen (color);
820 assert (p != NULL);
821
822 for (ch = color; *ch; ch++)
823 if (!isalpha (*ch))
824 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
825
826 for (ch = color + 1; *ch; ch++)
827 if (!islower (*ch))
828 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
829
830 if (streq (color, "None"))
831 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
832
833 if (isupper (*color))
834 {
835 switch (index)
836 {
837 case FOREGROUND:
838 snprintf (attr + strlen (attr), 3, "1;");
839 break;
840 case BACKGROUND:
841 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
842 default: /* never reached */
843 ABORT_TRACE ();
844 }
845 }
846
847 color_names[index] = xcalloc (1, sizeof (struct color_name));
848 STACK_VAR (color_names[index]);
849
850 color_names[index]->orig = xstrdup (color);
851 STACK_VAR (color_names[index]->orig);
852
853 for (ch = color; *ch; ch++)
854 *ch = tolower (*ch);
855
856 color_names[index]->name = xstrdup (color);
857 STACK_VAR (color_names[index]->name);
858 }
859
860 RELEASE_VAR (str);
861 }
862
863 static void
864 read_print_stream (const char *attr, const struct color **colors, const char *file, FILE *stream)
865 {
866 char buf[BUF_SIZE + 1];
867 unsigned int flags = 0;
868
869 while (!feof (stream))
870 {
871 size_t bytes_read;
872 char *eol;
873 const char *line;
874 bytes_read = fread (buf, 1, BUF_SIZE, stream);
875 if (bytes_read != BUF_SIZE && ferror (stream))
876 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
877 buf[bytes_read] = '\0';
878 line = buf;
879 while ((eol = strpbrk (line, "\n\r")))
880 {
881 const char *p;
882 flags &= ~(CR|LF);
883 if (*eol == '\r')
884 {
885 flags |= CR;
886 if (*(eol + 1) == '\n')
887 flags |= LF;
888 }
889 else if (*eol == '\n')
890 flags |= LF;
891 else
892 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
893 p = eol + SKIP_LINE_ENDINGS (flags);
894 *eol = '\0';
895 print_line (attr, colors, line, flags);
896 line = p;
897 }
898 if (feof (stream))
899 {
900 if (*line != '\0')
901 print_line (attr, colors, line, 0);
902 }
903 else if (*line != '\0')
904 {
905 char *p;
906 if ((clean || clean_all) && (p = strrchr (line, '\033')))
907 merge_print_line (line, p, stream);
908 else
909 print_line (attr, colors, line, 0);
910 }
911 }
912 }
913
914 static void
915 merge_print_line (const char *line, const char *p, FILE *stream)
916 {
917 char *buf = NULL;
918 char *merged_esc = NULL;
919 const char *esc = "";
920 const char char_restore = *p;
921
922 complete_part_line (p + 1, &buf, stream);
923
924 if (buf)
925 {
926 /* form escape sequence */
927 esc = merged_esc = str_concat (p, buf);
928 /* shorten partial line accordingly */
929 *(char *)p = '\0';
930 free (buf);
931 }
932
933 #ifdef TEST_MERGE_PART_LINE
934 printf ("%s%s", line, esc);
935 fflush (stdout);
936 _exit (EXIT_SUCCESS);
937 #else
938 print_clean (line);
939 *(char *)p = char_restore;
940 print_clean (esc);
941 free (merged_esc);
942 #endif
943 }
944
945 static void
946 complete_part_line (const char *p, char **buf, FILE *stream)
947 {
948 bool got_next_char = false, read_from_stream;
949 char ch;
950 size_t i = 0, size;
951
952 if (get_next_char (&ch, &p, stream, &read_from_stream))
953 {
954 if (ch == '[')
955 {
956 if (read_from_stream)
957 save_char (ch, buf, &i, &size);
958 }
959 else
960 {
961 if (read_from_stream)
962 ungetc ((int)ch, stream);
963 return; /* cancel */
964 }
965 }
966 else
967 return; /* cancel */
968
969 while (get_next_char (&ch, &p, stream, &read_from_stream))
970 {
971 if (isdigit (ch) || ch == ';')
972 {
973 if (read_from_stream)
974 save_char (ch, buf, &i, &size);
975 }
976 else /* got next character */
977 {
978 got_next_char = true;
979 break;
980 }
981 }
982
983 if (got_next_char)
984 {
985 if (ch == 'm')
986 {
987 if (read_from_stream)
988 save_char (ch, buf, &i, &size);
989 }
990 else
991 {
992 if (read_from_stream)
993 ungetc ((int)ch, stream);
994 return; /* cancel */
995 }
996 }
997 else
998 return; /* cancel */
999 }
1000
1001 static bool
1002 get_next_char (char *ch, const char **p, FILE *stream, bool *read_from_stream)
1003 {
1004 if (**p == '\0')
1005 {
1006 int c;
1007 if ((c = fgetc (stream)) != EOF)
1008 {
1009 *ch = (char)c;
1010 *read_from_stream = true;
1011 return true;
1012 }
1013 else
1014 {
1015 *read_from_stream = false;
1016 return false;
1017 }
1018 }
1019 else
1020 {
1021 *ch = **p;
1022 (*p)++;
1023 *read_from_stream = false;
1024 return true;
1025 }
1026 }
1027
1028 static void
1029 save_char (char ch, char **buf, size_t *i, size_t *size)
1030 {
1031 if (!*buf)
1032 {
1033 *size = ALLOC_COMPLETE_PART_LINE;
1034 *buf = xmalloc (*size);
1035 }
1036 /* +1: effective occupied size of buffer */
1037 else if ((*i + 1) == *size)
1038 {
1039 *size *= 2;
1040 *buf = xrealloc (*buf, *size);
1041 }
1042 (*buf)[*i] = ch;
1043 (*buf)[*i + 1] = '\0';
1044 (*i)++;
1045 }
1046
1047 static void
1048 find_color_entries (struct color_name **color_names, const struct color **colors)
1049 {
1050 struct timeval tv;
1051 unsigned int index;
1052
1053 /* randomness */
1054 gettimeofday (&tv, NULL);
1055 srand (tv.tv_usec * tv.tv_sec);
1056
1057 for (index = 0; color_names[index]; index++)
1058 {
1059 const char *color_name = color_names[index]->name;
1060
1061 const unsigned int count = tables[index].count;
1062 const struct color *const color_entries = tables[index].entries;
1063
1064 if (streq (color_name, "random"))
1065 {
1066 bool excludable;
1067 unsigned int i;
1068 do {
1069 excludable = false;
1070 i = rand() % (count - 2) + 1; /* omit color none and default */
1071 switch (index)
1072 {
1073 case FOREGROUND:
1074 /* --exclude-random */
1075 if (exclude && streq (exclude, color_entries[i].name))
1076 excludable = true;
1077 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
1078 excludable = true;
1079 break;
1080 case BACKGROUND:
1081 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
1082 excludable = true;
1083 break;
1084 default: /* never reached */
1085 ABORT_TRACE ();
1086 }
1087 } while (excludable);
1088 colors[index] = (struct color *)&color_entries[i];
1089 }
1090 else
1091 find_color_entry (color_names[index], index, colors);
1092 }
1093 }
1094
1095 static void
1096 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
1097 {
1098 bool found = false;
1099 unsigned int i;
1100
1101 const unsigned int count = tables[index].count;
1102 const struct color *const color_entries = tables[index].entries;
1103
1104 for (i = 0; i < count; i++)
1105 if (streq (color_name->name, color_entries[i].name))
1106 {
1107 colors[index] = (struct color *)&color_entries[i];
1108 found = true;
1109 break;
1110 }
1111 if (!found)
1112 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
1113 }
1114
1115 static void
1116 print_line (const char *attr, const struct color **colors, const char *const line, unsigned int flags)
1117 {
1118 /* --clean[-all] */
1119 if (clean || clean_all)
1120 print_clean (line);
1121 else
1122 {
1123 /* Foreground color code is guaranteed to be set when background color code is present. */
1124 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
1125 printf ("\033[%s", colors[BACKGROUND]->code);
1126 if (colors[FOREGROUND]->code)
1127 printf ("\033[%s%s%s\033[0m", attr, colors[FOREGROUND]->code, line);
1128 else
1129 printf (formats[FMT_GENERIC], line);
1130 }
1131 if (flags & CR)
1132 putchar ('\r');
1133 if (flags & LF)
1134 putchar ('\n');
1135 }
1136
1137 static void
1138 print_clean (const char *line)
1139 {
1140 const char *p = line;
1141
1142 if (is_esc (p))
1143 p = get_end_of_esc (p);
1144
1145 while (*p != '\0')
1146 {
1147 const char *text_start = p;
1148 const char *text_end = get_end_of_text (p);
1149 print_text (text_start, text_end - text_start);
1150 p = get_end_of_esc (text_end);
1151 }
1152 }
1153
1154 static bool
1155 is_esc (const char *p)
1156 {
1157 return gather_esc_offsets (p, NULL, NULL);
1158 }
1159
1160 static const char *
1161 get_end_of_esc (const char *p)
1162 {
1163 const char *esc;
1164 const char *end = NULL;
1165 while ((esc = strchr (p, '\033')))
1166 {
1167 if (gather_esc_offsets (esc, NULL, &end))
1168 break;
1169 p = esc + 1;
1170 }
1171 return end ? end + 1 : p + strlen (p);
1172 }
1173
1174 static const char *
1175 get_end_of_text (const char *p)
1176 {
1177 const char *esc;
1178 const char *start = NULL;
1179 while ((esc = strchr (p, '\033')))
1180 {
1181 if (gather_esc_offsets (esc, &start, NULL))
1182 break;
1183 p = esc + 1;
1184 }
1185 return start ? start : p + strlen (p);
1186 }
1187
1188 static void
1189 print_text (const char *p, size_t len)
1190 {
1191 size_t bytes_written;
1192 bytes_written = fwrite (p, 1, len, stdout);
1193 if (bytes_written != len)
1194 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
1195 }
1196
1197 static bool
1198 gather_esc_offsets (const char *p, const char **start, const char **end)
1199 {
1200 /* ESC[ */
1201 if (*p == 27 && *(p + 1) == '[')
1202 {
1203 bool valid = false;
1204 const char *const begin = p;
1205 p += 2;
1206 if (clean_all)
1207 valid = validate_esc_clean_all (&p);
1208 else if (clean)
1209 {
1210 bool check_values;
1211 unsigned int prev_iter, iter;
1212 const char *digit;
1213 prev_iter = iter = 0;
1214 do {
1215 check_values = false;
1216 iter++;
1217 if (!isdigit (*p))
1218 break;
1219 digit = p;
1220 while (isdigit (*p))
1221 p++;
1222 if (p - digit > 2)
1223 break;
1224 else /* check range */
1225 {
1226 char val[3];
1227 int value;
1228 unsigned int i;
1229 const unsigned int digits = p - digit;
1230 for (i = 0; i < digits; i++)
1231 val[i] = *digit++;
1232 val[i] = '\0';
1233 value = atoi (val);
1234 valid = validate_esc_clean (value, iter, &prev_iter, &p, &check_values);
1235 }
1236 } while (check_values);
1237 }
1238 if (valid)
1239 {
1240 if (start)
1241 *start = begin;
1242 if (end)
1243 *end = p;
1244 return true;
1245 }
1246 }
1247 return false;
1248 }
1249
1250 static bool
1251 validate_esc_clean_all (const char **p)
1252 {
1253 while (isdigit (**p) || **p == ';')
1254 (*p)++;
1255 return (**p == 'm');
1256 }
1257
1258 static bool
1259 validate_esc_clean (int value, unsigned int iter, unsigned int *prev_iter, const char **p, bool *check_values)
1260 {
1261 if (is_reset (value, iter, p))
1262 return true;
1263 else if (is_attr (value, iter, *prev_iter, p))
1264 {
1265 (*p)++;
1266 *check_values = true;
1267 *prev_iter = iter;
1268 return false; /* partial escape sequence, need another valid value */
1269 }
1270 else if (is_fg_color (value, p))
1271 return true;
1272 else if (is_bg_color (value, iter, p))
1273 return true;
1274 else
1275 return false;
1276 }
1277
1278 static bool
1279 is_reset (int value, unsigned int iter, const char **p)
1280 {
1281 return (value == 0 && iter == 1 && **p == 'm');
1282 }
1283
1284 static bool
1285 is_attr (int value, unsigned int iter, unsigned int prev_iter, const char **p)
1286 {
1287 return ((value > 0 && value < 10) && (iter - prev_iter == 1) && **p == ';');
1288 }
1289
1290 static bool
1291 is_fg_color (int value, const char **p)
1292 {
1293 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1294 }
1295
1296 static bool
1297 is_bg_color (int value, unsigned int iter, const char **p)
1298 {
1299 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1300 }
1301
1302 #if !DEBUG
1303 static void *
1304 malloc_wrap (size_t size)
1305 {
1306 void *p = malloc (size);
1307 if (!p)
1308 MEM_ALLOC_FAIL ();
1309 return p;
1310 }
1311
1312 static void *
1313 calloc_wrap (size_t nmemb, size_t size)
1314 {
1315 void *p = calloc (nmemb, size);
1316 if (!p)
1317 MEM_ALLOC_FAIL ();
1318 return p;
1319 }
1320
1321 static void *
1322 realloc_wrap (void *ptr, size_t size)
1323 {
1324 void *p = realloc (ptr, size);
1325 if (!p)
1326 MEM_ALLOC_FAIL ();
1327 return p;
1328 }
1329 #else
1330 static void *
1331 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1332 {
1333 void *p = malloc (size);
1334 if (!p)
1335 MEM_ALLOC_FAIL_DEBUG (file, line);
1336 fprintf (log, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1337 return p;
1338 }
1339
1340 static void *
1341 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1342 {
1343 void *p = calloc (nmemb, size);
1344 if (!p)
1345 MEM_ALLOC_FAIL_DEBUG (file, line);
1346 fprintf (log, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)(nmemb * size), file, line);
1347 return p;
1348 }
1349
1350 static void *
1351 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1352 {
1353 void *p = realloc (ptr, size);
1354 if (!p)
1355 MEM_ALLOC_FAIL_DEBUG (file, line);
1356 fprintf (log, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1357 return p;
1358 }
1359 #endif /* !DEBUG */
1360
1361 static void
1362 free_wrap (void **ptr)
1363 {
1364 free (*ptr);
1365 *ptr = NULL;
1366 }
1367
1368 #if !DEBUG
1369 # define do_malloc(len, file, line) malloc_wrap(len)
1370 #else
1371 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1372 #endif
1373
1374 static char *
1375 strdup_wrap (const char *str, const char *file, unsigned int line)
1376 {
1377 const size_t len = strlen (str) + 1;
1378 char *p = do_malloc (len, file, line);
1379 strncpy (p, str, len);
1380 return p;
1381 }
1382
1383 static char *
1384 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1385 {
1386 const size_t len = strlen (str1) + strlen (str2) + 1;
1387 char *p, *str;
1388
1389 p = str = do_malloc (len, file, line);
1390 strncpy (p, str1, strlen (str1));
1391 p += strlen (str1);
1392 strncpy (p, str2, strlen (str2));
1393 p += strlen (str2);
1394 *p = '\0';
1395
1396 return str;
1397 }
1398
1399 static bool
1400 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1401 {
1402 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1403 unsigned long size = bytes;
1404 if (bytes < 1024)
1405 return false;
1406 unit = units;
1407 while (size >= 1024 && *(unit + 1))
1408 {
1409 size /= 1024;
1410 unit++;
1411 }
1412 bytes_size->size = (unsigned int)size;
1413 bytes_size->unit = *unit;
1414 return true;
1415 }
1416
1417 static char *
1418 get_file_type (mode_t mode)
1419 {
1420 if (S_ISREG (mode))
1421 return "file";
1422 else if (S_ISDIR (mode))
1423 return "directory";
1424 else if (S_ISCHR (mode))
1425 return "character device";
1426 else if (S_ISBLK (mode))
1427 return "block device";
1428 else if (S_ISFIFO (mode))
1429 return "named pipe";
1430 else if (S_ISLNK (mode))
1431 return "symbolic link";
1432 else if (S_ISSOCK (mode))
1433 return "socket";
1434 else
1435 return "file";
1436 }
1437
1438 static bool
1439 has_color_name (const char *str, const char *name)
1440 {
1441 char *p;
1442
1443 assert (strlen (str));
1444 assert (strlen (name));
1445
1446 if (!(*str == *name || *str == toupper (*name)))
1447 return false;
1448 else if (*(name + 1) != '\0'
1449 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1450 return false;
1451
1452 return true;
1453 }
1454
1455 static FILE *
1456 open_file (const char *file, const char *mode)
1457 {
1458 FILE *stream;
1459
1460 errno = 0;
1461 stream = fopen (file, mode);
1462 if (!stream)
1463 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1464
1465 return stream;
1466 }
1467
1468 #define DO_VFPRINTF(fmt) \
1469 va_list ap; \
1470 fprintf (stderr, "%s: ", program_name); \
1471 va_start (ap, fmt); \
1472 vfprintf (stderr, fmt, ap); \
1473 va_end (ap); \
1474 fprintf (stderr, "\n"); \
1475
1476 static void
1477 vfprintf_diag (const char *fmt, ...)
1478 {
1479 DO_VFPRINTF (fmt);
1480 }
1481
1482 static void
1483 vfprintf_fail (const char *fmt, ...)
1484 {
1485 DO_VFPRINTF (fmt);
1486 exit (EXIT_FAILURE);
1487 }
1488
1489 static void
1490 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1491 {
1492 /* nothing to stack */
1493 if (ptr == NULL)
1494 return;
1495 if (!*list)
1496 *list = xmalloc (sizeof (void *));
1497 else
1498 {
1499 unsigned int i;
1500 for (i = 0; i < *stacked; i++)
1501 if (!(*list)[i])
1502 {
1503 (*list)[i] = ptr;
1504 return; /* reused */
1505 }
1506 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1507 }
1508 (*list)[index] = ptr;
1509 (*stacked)++;
1510 }
1511
1512 static void
1513 release_var (void **list, unsigned int stacked, void **ptr)
1514 {
1515 unsigned int i;
1516 /* nothing to release */
1517 if (*ptr == NULL)
1518 return;
1519 for (i = 0; i < stacked; i++)
1520 if (list[i] == *ptr)
1521 {
1522 free (*ptr);
1523 *ptr = NULL;
1524 list[i] = NULL;
1525 return;
1526 }
1527 }