]> git.refcnt.org Git - colorize.git/blob - colorize.c
0cf44cb310efebb3d17e5c8756b272622f427ade
[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|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 opt_data {
510 const char *name;
511 const char *short_opt;
512 const char *arg;
513 };
514 const struct opt_data opts_data[] = {
515 { "attr", NULL, "=ATTR1,ATTR2,..." },
516 { "exclude-random", NULL, "=COLOR" },
517 { "help", "h", NULL },
518 { "version", "V", NULL },
519 };
520 const struct option *opt = long_opts;
521 unsigned int i;
522
523 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
524 printf ("\tColors (foreground) (background)\n");
525 for (i = 0; i < tables[FOREGROUND].count; i++)
526 {
527 const struct color *entry = &tables[FOREGROUND].entries[i];
528 const char *name = entry->name;
529 const char *code = entry->code;
530 if (code)
531 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
532 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
533 else
534 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
535 }
536 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
537
538 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
539 printf ("\twhereas for lower case colors will be of normal intensity.\n");
540
541 printf ("\n\tOptions\n");
542 for (; opt->name; opt++)
543 {
544 const struct opt_data *opt_data = NULL;
545 unsigned int i;
546 for (i = 0; i < sizeof (opts_data) / sizeof (struct opt_data); i++)
547 if (streq (opt->name, opts_data[i].name))
548 {
549 opt_data = &opts_data[i];
550 break;
551 }
552 if (opt_data)
553 {
554 if (opt_data->short_opt)
555 printf ("\t\t-%s, --%s\n", opt_data->short_opt, opt->name);
556 else
557 printf ("\t\t --%s%s\n", opt->name, opt_data->arg);
558 }
559 else
560 printf ("\t\t --%s\n", opt->name);
561 }
562 printf ("\n");
563 }
564
565 static void
566 print_version (void)
567 {
568 #ifdef HAVE_VERSION
569 # include "version.h"
570 #else
571 const char *version = NULL;
572 #endif
573 const char *version_prefix, *version_string;
574 const char *c_flags, *ld_flags, *cpp_flags;
575 const char *const desc_flags_unknown = "unknown";
576 struct bytes_size bytes_size;
577 bool debug;
578 #ifdef CFLAGS
579 c_flags = to_str (CFLAGS);
580 #else
581 c_flags = desc_flags_unknown;
582 #endif
583 #ifdef LDFLAGS
584 ld_flags = to_str (LDFLAGS);
585 #else
586 ld_flags = desc_flags_unknown;
587 #endif
588 #ifdef CPPFLAGS
589 cpp_flags = to_str (CPPFLAGS);
590 #else
591 cpp_flags = desc_flags_unknown;
592 #endif
593 #if DEBUG
594 debug = true;
595 #else
596 debug = false;
597 #endif
598 version_prefix = version ? "" : "v";
599 version_string = version ? version : VERSION;
600 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix, version_string, __DATE__, __TIME__);
601
602 printf ("Compiler flags: %s\n", c_flags);
603 printf ("Linker flags: %s\n", ld_flags);
604 printf ("Preprocessor flags: %s\n", cpp_flags);
605 if (get_bytes_size (BUF_SIZE, &bytes_size))
606 {
607 if (BUF_SIZE % 1024 == 0)
608 printf ("Buffer size: %u%c\n", bytes_size.size, bytes_size.unit);
609 else
610 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size.size, bytes_size.unit,
611 BUF_SIZE % 1024, BUF_SIZE % 1024 > 1 ? "s" : "");
612 }
613 else
614 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE, BUF_SIZE > 1 ? "s" : "");
615 printf ("Color separator: '%c'\n", COLOR_SEP_CHAR);
616 printf ("Debugging: %s\n", debug ? "yes" : "no");
617 }
618
619 static void
620 cleanup (void)
621 {
622 if (stream && fileno (stream) != STDIN_FILENO)
623 fclose (stream);
624 #if DEBUG
625 if (log)
626 fclose (log);
627 #endif
628
629 if (vars_list)
630 {
631 unsigned int i;
632 for (i = 0; i < stacked_vars; i++)
633 free (vars_list[i]);
634 free_null (vars_list);
635 }
636 }
637
638 static void
639 free_color_names (struct color_name **color_names)
640 {
641 unsigned int i;
642 for (i = 0; color_names[i]; i++)
643 {
644 RELEASE_VAR (color_names[i]->name);
645 RELEASE_VAR (color_names[i]->orig);
646 RELEASE_VAR (color_names[i]);
647 }
648 }
649
650 static void
651 process_args (unsigned int arg_cnt, char **arg_strings, char *attr, const struct color **colors, const char **file, FILE **stream)
652 {
653 int ret;
654 char *p;
655 struct stat sb;
656 struct color_name *color_names[3] = { NULL, NULL, NULL };
657
658 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
659 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
660
661 assert (color_string != NULL);
662
663 if (streq (color_string, "-"))
664 {
665 if (file_string)
666 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
667 else
668 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceded by color string");
669 }
670
671 ret = lstat (color_string, &sb);
672
673 /* Ensure that we don't fail if there's a file with one or more
674 color names in its path. */
675 if (ret == 0) /* success */
676 skip_path_colors (color_string, file_string, &sb);
677
678 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
679 {
680 if (p == color_string)
681 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
682 else if (p == color_string + strlen (color_string) - 1)
683 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
684 else if (strchr (++p, COLOR_SEP_CHAR))
685 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
686 }
687
688 gather_color_names (color_string, attr, color_names);
689
690 assert (color_names[FOREGROUND] != NULL);
691
692 if (color_names[BACKGROUND])
693 {
694 unsigned int i;
695 const unsigned int color_sets[2][2] = { { FOREGROUND, BACKGROUND }, { BACKGROUND, FOREGROUND } };
696 for (i = 0; i < 2; i++)
697 {
698 const unsigned int color1 = color_sets[i][0];
699 const unsigned int color2 = color_sets[i][1];
700 if (CHECK_COLORS_RANDOM (color1, color2))
701 vfprintf_fail (formats[FMT_RANDOM], tables[color1].desc, color_names[color1]->orig, "cannot be combined with", color_names[color2]->orig);
702 }
703 }
704
705 find_color_entries (color_names, colors);
706 assert (colors[FOREGROUND] != NULL);
707 free_color_names (color_names);
708
709 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
710 {
711 struct color_name color_name;
712 color_name.name = color_name.orig = "default";
713
714 find_color_entry (&color_name, FOREGROUND, colors);
715 assert (colors[FOREGROUND]->code != NULL);
716 }
717
718 process_file_arg (file_string, file, stream);
719 }
720
721 static void
722 process_file_arg (const char *file_string, const char **file, FILE **stream)
723 {
724 if (file_string)
725 {
726 if (streq (file_string, "-"))
727 *stream = stdin;
728 else
729 {
730 const char *file = file_string;
731 struct stat sb;
732 int ret;
733
734 errno = 0;
735 ret = stat (file, &sb);
736
737 if (ret == -1)
738 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
739
740 if (!VALID_FILE_TYPE (sb.st_mode))
741 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
742
743 *stream = open_file (file, "r");
744 }
745 *file = file_string;
746 }
747 else
748 {
749 *stream = stdin;
750 *file = "stdin";
751 }
752
753 assert (*stream != NULL);
754 assert (*file != NULL);
755 }
756
757 static void
758 skip_path_colors (const char *color_string, const char *file_string, const struct stat *sb)
759 {
760 bool have_file;
761 unsigned int c;
762 const char *color = color_string;
763 const mode_t mode = sb->st_mode;
764
765 for (c = 1; c <= 2 && *color; c++)
766 {
767 bool matched = false;
768 unsigned int i;
769 for (i = 0; i < tables[GENERIC].count; i++)
770 {
771 const struct color *entry = &tables[GENERIC].entries[i];
772 if (has_color_name (color, entry->name))
773 {
774 color += strlen (entry->name);
775 matched = true;
776 break;
777 }
778 }
779 if (!matched && has_color_name (color, "random"))
780 {
781 color += strlen ("random");
782 matched = true;
783 }
784 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
785 color++;
786 else
787 break;
788 }
789
790 have_file = (*color != '\0');
791
792 if (have_file)
793 {
794 const char *file_existing = color_string;
795 if (file_string)
796 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "cannot be used as color string");
797 else
798 {
799 if (VALID_FILE_TYPE (mode))
800 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "must be preceded by color string");
801 else
802 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "is not a valid file type");
803 }
804 }
805 }
806
807 static void
808 gather_color_names (const char *color_string, char *attr, struct color_name **color_names)
809 {
810 unsigned int index;
811 char *color, *p, *str;
812
813 str = xstrdup (color_string);
814 STACK_VAR (str);
815
816 for (index = 0, color = str; *color; index++, color = p)
817 {
818 char *ch, *sep;
819
820 p = NULL;
821 if ((sep = strchr (color, COLOR_SEP_CHAR)))
822 {
823 *sep = '\0';
824 p = sep + 1;
825 }
826 else
827 p = color + strlen (color);
828 assert (p != NULL);
829
830 for (ch = color; *ch; ch++)
831 if (!isalpha (*ch))
832 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
833
834 for (ch = color + 1; *ch; ch++)
835 if (!islower (*ch))
836 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
837
838 if (streq (color, "None"))
839 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
840
841 if (isupper (*color))
842 {
843 switch (index)
844 {
845 case FOREGROUND:
846 snprintf (attr + strlen (attr), 3, "1;");
847 break;
848 case BACKGROUND:
849 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
850 default: /* never reached */
851 ABORT_TRACE ();
852 }
853 }
854
855 color_names[index] = xcalloc (1, sizeof (struct color_name));
856 STACK_VAR (color_names[index]);
857
858 color_names[index]->orig = xstrdup (color);
859 STACK_VAR (color_names[index]->orig);
860
861 for (ch = color; *ch; ch++)
862 *ch = tolower (*ch);
863
864 color_names[index]->name = xstrdup (color);
865 STACK_VAR (color_names[index]->name);
866 }
867
868 RELEASE_VAR (str);
869 }
870
871 static void
872 read_print_stream (const char *attr, const struct color **colors, const char *file, FILE *stream)
873 {
874 char buf[BUF_SIZE + 1];
875 unsigned int flags = 0;
876
877 while (!feof (stream))
878 {
879 size_t bytes_read;
880 char *eol;
881 const char *line;
882 bytes_read = fread (buf, 1, BUF_SIZE, stream);
883 if (bytes_read != BUF_SIZE && ferror (stream))
884 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
885 buf[bytes_read] = '\0';
886 line = buf;
887 while ((eol = strpbrk (line, "\n\r")))
888 {
889 const char *p;
890 flags &= ~(CR|LF);
891 if (*eol == '\r')
892 {
893 flags |= CR;
894 if (*(eol + 1) == '\n')
895 flags |= LF;
896 }
897 else if (*eol == '\n')
898 flags |= LF;
899 else
900 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
901 p = eol + SKIP_LINE_ENDINGS (flags);
902 *eol = '\0';
903 print_line (attr, colors, line, flags);
904 line = p;
905 }
906 if (feof (stream))
907 {
908 if (*line != '\0')
909 print_line (attr, colors, line, 0);
910 }
911 else if (*line != '\0')
912 {
913 char *p;
914 if ((clean || clean_all) && (p = strrchr (line, '\033')))
915 merge_print_line (line, p, stream);
916 else
917 print_line (attr, colors, line, 0);
918 }
919 }
920 }
921
922 static void
923 merge_print_line (const char *line, const char *p, FILE *stream)
924 {
925 char *buf = NULL;
926 char *merged_esc = NULL;
927 const char *esc = "";
928 const char char_restore = *p;
929
930 complete_part_line (p + 1, &buf, stream);
931
932 if (buf)
933 {
934 /* form escape sequence */
935 esc = merged_esc = str_concat (p, buf);
936 /* shorten partial line accordingly */
937 *(char *)p = '\0';
938 free (buf);
939 }
940
941 #ifdef TEST_MERGE_PART_LINE
942 printf ("%s%s", line, esc);
943 fflush (stdout);
944 _exit (EXIT_SUCCESS);
945 #else
946 print_clean (line);
947 *(char *)p = char_restore;
948 print_clean (esc);
949 free (merged_esc);
950 #endif
951 }
952
953 static void
954 complete_part_line (const char *p, char **buf, FILE *stream)
955 {
956 bool got_next_char = false, read_from_stream;
957 char ch;
958 size_t i = 0, size;
959
960 if (get_next_char (&ch, &p, stream, &read_from_stream))
961 {
962 if (ch == '[')
963 {
964 if (read_from_stream)
965 save_char (ch, buf, &i, &size);
966 }
967 else
968 {
969 if (read_from_stream)
970 ungetc ((int)ch, stream);
971 return; /* cancel */
972 }
973 }
974 else
975 return; /* cancel */
976
977 while (get_next_char (&ch, &p, stream, &read_from_stream))
978 {
979 if (isdigit (ch) || ch == ';')
980 {
981 if (read_from_stream)
982 save_char (ch, buf, &i, &size);
983 }
984 else /* got next character */
985 {
986 got_next_char = true;
987 break;
988 }
989 }
990
991 if (got_next_char)
992 {
993 if (ch == 'm')
994 {
995 if (read_from_stream)
996 save_char (ch, buf, &i, &size);
997 }
998 else
999 {
1000 if (read_from_stream)
1001 ungetc ((int)ch, stream);
1002 return; /* cancel */
1003 }
1004 }
1005 else
1006 return; /* cancel */
1007 }
1008
1009 static bool
1010 get_next_char (char *ch, const char **p, FILE *stream, bool *read_from_stream)
1011 {
1012 if (**p == '\0')
1013 {
1014 int c;
1015 if ((c = fgetc (stream)) != EOF)
1016 {
1017 *ch = (char)c;
1018 *read_from_stream = true;
1019 return true;
1020 }
1021 else
1022 {
1023 *read_from_stream = false;
1024 return false;
1025 }
1026 }
1027 else
1028 {
1029 *ch = **p;
1030 (*p)++;
1031 *read_from_stream = false;
1032 return true;
1033 }
1034 }
1035
1036 static void
1037 save_char (char ch, char **buf, size_t *i, size_t *size)
1038 {
1039 if (!*buf)
1040 {
1041 *size = ALLOC_COMPLETE_PART_LINE;
1042 *buf = xmalloc (*size);
1043 }
1044 /* +1: effective occupied size of buffer */
1045 else if ((*i + 1) == *size)
1046 {
1047 *size *= 2;
1048 *buf = xrealloc (*buf, *size);
1049 }
1050 (*buf)[*i] = ch;
1051 (*buf)[*i + 1] = '\0';
1052 (*i)++;
1053 }
1054
1055 static void
1056 find_color_entries (struct color_name **color_names, const struct color **colors)
1057 {
1058 struct timeval tv;
1059 unsigned int index;
1060
1061 /* randomness */
1062 gettimeofday (&tv, NULL);
1063 srand (tv.tv_usec * tv.tv_sec);
1064
1065 for (index = 0; color_names[index]; index++)
1066 {
1067 const char *color_name = color_names[index]->name;
1068
1069 const unsigned int count = tables[index].count;
1070 const struct color *const color_entries = tables[index].entries;
1071
1072 if (streq (color_name, "random"))
1073 {
1074 bool excludable;
1075 unsigned int i;
1076 do {
1077 excludable = false;
1078 i = rand() % (count - 2) + 1; /* omit color none and default */
1079 switch (index)
1080 {
1081 case FOREGROUND:
1082 /* --exclude-random */
1083 if (exclude && streq (exclude, color_entries[i].name))
1084 excludable = true;
1085 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
1086 excludable = true;
1087 break;
1088 case BACKGROUND:
1089 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
1090 excludable = true;
1091 break;
1092 default: /* never reached */
1093 ABORT_TRACE ();
1094 }
1095 } while (excludable);
1096 colors[index] = (struct color *)&color_entries[i];
1097 }
1098 else
1099 find_color_entry (color_names[index], index, colors);
1100 }
1101 }
1102
1103 static void
1104 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
1105 {
1106 bool found = false;
1107 unsigned int i;
1108
1109 const unsigned int count = tables[index].count;
1110 const struct color *const color_entries = tables[index].entries;
1111
1112 for (i = 0; i < count; i++)
1113 if (streq (color_name->name, color_entries[i].name))
1114 {
1115 colors[index] = (struct color *)&color_entries[i];
1116 found = true;
1117 break;
1118 }
1119 if (!found)
1120 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
1121 }
1122
1123 static void
1124 print_line (const char *attr, const struct color **colors, const char *const line, unsigned int flags)
1125 {
1126 /* --clean[-all] */
1127 if (clean || clean_all)
1128 print_clean (line);
1129 else
1130 {
1131 /* Foreground color code is guaranteed to be set when background color code is present. */
1132 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
1133 printf ("\033[%s", colors[BACKGROUND]->code);
1134 if (colors[FOREGROUND]->code)
1135 printf ("\033[%s%s%s\033[0m", attr, colors[FOREGROUND]->code, line);
1136 else
1137 printf (formats[FMT_GENERIC], line);
1138 }
1139 if (flags & CR)
1140 putchar ('\r');
1141 if (flags & LF)
1142 putchar ('\n');
1143 }
1144
1145 static void
1146 print_clean (const char *line)
1147 {
1148 const char *p = line;
1149
1150 if (is_esc (p))
1151 p = get_end_of_esc (p);
1152
1153 while (*p != '\0')
1154 {
1155 const char *text_start = p;
1156 const char *text_end = get_end_of_text (p);
1157 print_text (text_start, text_end - text_start);
1158 p = get_end_of_esc (text_end);
1159 }
1160 }
1161
1162 static bool
1163 is_esc (const char *p)
1164 {
1165 return gather_esc_offsets (p, NULL, NULL);
1166 }
1167
1168 static const char *
1169 get_end_of_esc (const char *p)
1170 {
1171 const char *esc;
1172 const char *end = NULL;
1173 while ((esc = strchr (p, '\033')))
1174 {
1175 if (gather_esc_offsets (esc, NULL, &end))
1176 break;
1177 p = esc + 1;
1178 }
1179 return end ? end + 1 : p + strlen (p);
1180 }
1181
1182 static const char *
1183 get_end_of_text (const char *p)
1184 {
1185 const char *esc;
1186 const char *start = NULL;
1187 while ((esc = strchr (p, '\033')))
1188 {
1189 if (gather_esc_offsets (esc, &start, NULL))
1190 break;
1191 p = esc + 1;
1192 }
1193 return start ? start : p + strlen (p);
1194 }
1195
1196 static void
1197 print_text (const char *p, size_t len)
1198 {
1199 size_t bytes_written;
1200 bytes_written = fwrite (p, 1, len, stdout);
1201 if (bytes_written != len)
1202 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
1203 }
1204
1205 static bool
1206 gather_esc_offsets (const char *p, const char **start, const char **end)
1207 {
1208 /* ESC[ */
1209 if (*p == 27 && *(p + 1) == '[')
1210 {
1211 bool valid = false;
1212 const char *const begin = p;
1213 p += 2;
1214 if (clean_all)
1215 valid = validate_esc_clean_all (&p);
1216 else if (clean)
1217 {
1218 bool check_values;
1219 unsigned int prev_iter, iter;
1220 const char *digit;
1221 prev_iter = iter = 0;
1222 do {
1223 check_values = false;
1224 iter++;
1225 if (!isdigit (*p))
1226 break;
1227 digit = p;
1228 while (isdigit (*p))
1229 p++;
1230 if (p - digit > 2)
1231 break;
1232 else /* check range */
1233 {
1234 char val[3];
1235 int value;
1236 unsigned int i;
1237 const unsigned int digits = p - digit;
1238 for (i = 0; i < digits; i++)
1239 val[i] = *digit++;
1240 val[i] = '\0';
1241 value = atoi (val);
1242 valid = validate_esc_clean (value, iter, &prev_iter, &p, &check_values);
1243 }
1244 } while (check_values);
1245 }
1246 if (valid)
1247 {
1248 if (start)
1249 *start = begin;
1250 if (end)
1251 *end = p;
1252 return true;
1253 }
1254 }
1255 return false;
1256 }
1257
1258 static bool
1259 validate_esc_clean_all (const char **p)
1260 {
1261 while (isdigit (**p) || **p == ';')
1262 (*p)++;
1263 return (**p == 'm');
1264 }
1265
1266 static bool
1267 validate_esc_clean (int value, unsigned int iter, unsigned int *prev_iter, const char **p, bool *check_values)
1268 {
1269 if (is_reset (value, iter, p))
1270 return true;
1271 else if (is_attr (value, iter, *prev_iter, p))
1272 {
1273 (*p)++;
1274 *check_values = true;
1275 *prev_iter = iter;
1276 return false; /* partial escape sequence, need another valid value */
1277 }
1278 else if (is_fg_color (value, p))
1279 return true;
1280 else if (is_bg_color (value, iter, p))
1281 return true;
1282 else
1283 return false;
1284 }
1285
1286 static bool
1287 is_reset (int value, unsigned int iter, const char **p)
1288 {
1289 return (value == 0 && iter == 1 && **p == 'm');
1290 }
1291
1292 static bool
1293 is_attr (int value, unsigned int iter, unsigned int prev_iter, const char **p)
1294 {
1295 return ((value > 0 && value < 10) && (iter - prev_iter == 1) && **p == ';');
1296 }
1297
1298 static bool
1299 is_fg_color (int value, const char **p)
1300 {
1301 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1302 }
1303
1304 static bool
1305 is_bg_color (int value, unsigned int iter, const char **p)
1306 {
1307 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1308 }
1309
1310 #if !DEBUG
1311 static void *
1312 malloc_wrap (size_t size)
1313 {
1314 void *p = malloc (size);
1315 if (!p)
1316 MEM_ALLOC_FAIL ();
1317 return p;
1318 }
1319
1320 static void *
1321 calloc_wrap (size_t nmemb, size_t size)
1322 {
1323 void *p = calloc (nmemb, size);
1324 if (!p)
1325 MEM_ALLOC_FAIL ();
1326 return p;
1327 }
1328
1329 static void *
1330 realloc_wrap (void *ptr, size_t size)
1331 {
1332 void *p = realloc (ptr, size);
1333 if (!p)
1334 MEM_ALLOC_FAIL ();
1335 return p;
1336 }
1337 #else
1338 static void *
1339 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1340 {
1341 void *p = malloc (size);
1342 if (!p)
1343 MEM_ALLOC_FAIL_DEBUG (file, line);
1344 fprintf (log, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1345 return p;
1346 }
1347
1348 static void *
1349 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1350 {
1351 void *p = calloc (nmemb, size);
1352 if (!p)
1353 MEM_ALLOC_FAIL_DEBUG (file, line);
1354 fprintf (log, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)(nmemb * size), file, line);
1355 return p;
1356 }
1357
1358 static void *
1359 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1360 {
1361 void *p = realloc (ptr, size);
1362 if (!p)
1363 MEM_ALLOC_FAIL_DEBUG (file, line);
1364 fprintf (log, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1365 return p;
1366 }
1367 #endif /* !DEBUG */
1368
1369 static void
1370 free_wrap (void **ptr)
1371 {
1372 free (*ptr);
1373 *ptr = NULL;
1374 }
1375
1376 #if !DEBUG
1377 # define do_malloc(len, file, line) malloc_wrap(len)
1378 #else
1379 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1380 #endif
1381
1382 static char *
1383 strdup_wrap (const char *str, const char *file, unsigned int line)
1384 {
1385 const size_t len = strlen (str) + 1;
1386 char *p = do_malloc (len, file, line);
1387 strncpy (p, str, len);
1388 return p;
1389 }
1390
1391 static char *
1392 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1393 {
1394 const size_t len = strlen (str1) + strlen (str2) + 1;
1395 char *p, *str;
1396
1397 p = str = do_malloc (len, file, line);
1398 strncpy (p, str1, strlen (str1));
1399 p += strlen (str1);
1400 strncpy (p, str2, strlen (str2));
1401 p += strlen (str2);
1402 *p = '\0';
1403
1404 return str;
1405 }
1406
1407 static bool
1408 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1409 {
1410 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1411 unsigned long size = bytes;
1412 if (bytes < 1024)
1413 return false;
1414 unit = units;
1415 while (size >= 1024 && *(unit + 1))
1416 {
1417 size /= 1024;
1418 unit++;
1419 }
1420 bytes_size->size = (unsigned int)size;
1421 bytes_size->unit = *unit;
1422 return true;
1423 }
1424
1425 static char *
1426 get_file_type (mode_t mode)
1427 {
1428 if (S_ISREG (mode))
1429 return "file";
1430 else if (S_ISDIR (mode))
1431 return "directory";
1432 else if (S_ISCHR (mode))
1433 return "character device";
1434 else if (S_ISBLK (mode))
1435 return "block device";
1436 else if (S_ISFIFO (mode))
1437 return "named pipe";
1438 else if (S_ISLNK (mode))
1439 return "symbolic link";
1440 else if (S_ISSOCK (mode))
1441 return "socket";
1442 else
1443 return "file";
1444 }
1445
1446 static bool
1447 has_color_name (const char *str, const char *name)
1448 {
1449 char *p;
1450
1451 assert (strlen (str) > 0);
1452 assert (strlen (name) > 0);
1453
1454 if (!(*str == *name || *str == toupper (*name)))
1455 return false;
1456 else if (*(name + 1) != '\0'
1457 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1458 return false;
1459
1460 return true;
1461 }
1462
1463 static FILE *
1464 open_file (const char *file, const char *mode)
1465 {
1466 FILE *stream;
1467
1468 errno = 0;
1469 stream = fopen (file, mode);
1470 if (!stream)
1471 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1472
1473 return stream;
1474 }
1475
1476 #define DO_VFPRINTF(fmt) \
1477 va_list ap; \
1478 fprintf (stderr, "%s: ", program_name); \
1479 va_start (ap, fmt); \
1480 vfprintf (stderr, fmt, ap); \
1481 va_end (ap); \
1482 fprintf (stderr, "\n"); \
1483
1484 static void
1485 vfprintf_diag (const char *fmt, ...)
1486 {
1487 DO_VFPRINTF (fmt);
1488 }
1489
1490 static void
1491 vfprintf_fail (const char *fmt, ...)
1492 {
1493 DO_VFPRINTF (fmt);
1494 exit (EXIT_FAILURE);
1495 }
1496
1497 static void
1498 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1499 {
1500 /* nothing to stack */
1501 if (ptr == NULL)
1502 return;
1503 if (!*list)
1504 *list = xmalloc (sizeof (void *));
1505 else
1506 {
1507 unsigned int i;
1508 for (i = 0; i < *stacked; i++)
1509 if (!(*list)[i])
1510 {
1511 (*list)[i] = ptr;
1512 return; /* reused */
1513 }
1514 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1515 }
1516 (*list)[index] = ptr;
1517 (*stacked)++;
1518 }
1519
1520 static void
1521 release_var (void **list, unsigned int stacked, void **ptr)
1522 {
1523 unsigned int i;
1524 /* nothing to release */
1525 if (*ptr == NULL)
1526 return;
1527 for (i = 0; i < stacked; i++)
1528 if (list[i] == *ptr)
1529 {
1530 free (*ptr);
1531 *ptr = NULL;
1532 list[i] = NULL;
1533 return;
1534 }
1535 }