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