]> git.refcnt.org Git - colorize.git/blob - colorize.c
Enhance message if attribute is invalid
[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.61"
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 *sep;
473 char *attr_invalid = xstrdup (s);
474 STACK_VAR (attr_invalid);
475 if ((sep = strchr (attr_invalid, ',')))
476 *sep = '\0';
477 vfprintf_fail ("--attr switch attribute '%s' is not valid", attr_invalid);
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 {
543 if (streq (opt->name, short_opts[i].name))
544 {
545 short_opt = short_opts[i].short_opt;
546 break;
547 }
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);
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]);
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 free_color_names (color_names);
699
700 if (!colors[FOREGROUND]->code && colors[BACKGROUND] && colors[BACKGROUND]->code)
701 {
702 struct color_name color_name;
703 color_name.name = color_name.orig = "default";
704
705 find_color_entry (&color_name, FOREGROUND, colors);
706 }
707
708 process_file_arg (file_string, file, stream);
709 }
710
711 static void
712 process_file_arg (const char *file_string, const char **file, FILE **stream)
713 {
714 if (file_string)
715 {
716 if (streq (file_string, "-"))
717 *stream = stdin;
718 else
719 {
720 const char *file = file_string;
721 struct stat sb;
722 int ret;
723
724 errno = 0;
725 ret = stat (file, &sb);
726
727 if (ret == -1)
728 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
729
730 if (!VALID_FILE_TYPE (sb.st_mode))
731 vfprintf_fail (formats[FMT_TYPE], file, "unrecognized type", get_file_type (sb.st_mode));
732
733 *stream = open_file (file, "r");
734 }
735 *file = file_string;
736 }
737 else
738 {
739 *stream = stdin;
740 *file = "stdin";
741 }
742
743 assert (*stream);
744 assert (*file);
745 }
746
747 static void
748 skip_path_colors (const char *color_string, const char *file_string, const struct stat *sb)
749 {
750 bool have_file;
751 unsigned int c;
752 const char *color = color_string;
753 const mode_t mode = sb->st_mode;
754
755 for (c = 1; c <= 2 && *color; c++)
756 {
757 bool matched = false;
758 unsigned int i;
759 for (i = 0; i < tables[GENERIC].count; i++)
760 {
761 const struct color *entry = &tables[GENERIC].entries[i];
762 if (has_color_name (color, entry->name))
763 {
764 color += strlen (entry->name);
765 matched = true;
766 break;
767 }
768 }
769 if (!matched && has_color_name (color, "random"))
770 {
771 color += strlen ("random");
772 matched = true;
773 }
774 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
775 color++;
776 else
777 break;
778 }
779
780 have_file = (*color != '\0');
781
782 if (have_file)
783 {
784 const char *file_existing = color_string;
785 if (file_string)
786 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "cannot be used as color string");
787 else
788 {
789 if (VALID_FILE_TYPE (mode))
790 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "must be preceded by color string");
791 else
792 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_existing, "is not a valid file type");
793 }
794 }
795 }
796
797 static void
798 gather_color_names (const char *color_string, char *attr, struct color_name **color_names)
799 {
800 unsigned int index;
801 char *color, *p, *str;
802
803 str = xstrdup (color_string);
804 STACK_VAR (str);
805
806 for (index = 0, color = str; *color; index++, color = p)
807 {
808 char *ch, *sep;
809
810 p = NULL;
811 if ((sep = strchr (color, COLOR_SEP_CHAR)))
812 {
813 *sep = '\0';
814 p = sep + 1;
815 }
816 else
817 p = color + strlen (color);
818 assert (p);
819
820 for (ch = color; *ch; ch++)
821 if (!isalpha (*ch))
822 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
823
824 for (ch = color + 1; *ch; ch++)
825 if (!islower (*ch))
826 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
827
828 if (streq (color, "None"))
829 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
830
831 if (isupper (*color))
832 {
833 switch (index)
834 {
835 case FOREGROUND:
836 snprintf (attr + strlen (attr), 3, "1;");
837 break;
838 case BACKGROUND:
839 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
840 default: /* never reached */
841 ABORT_TRACE ();
842 }
843 }
844
845 color_names[index] = xcalloc (1, sizeof (struct color_name));
846 STACK_VAR (color_names[index]);
847
848 color_names[index]->orig = xstrdup (color);
849 STACK_VAR (color_names[index]->orig);
850
851 for (ch = color; *ch; ch++)
852 *ch = tolower (*ch);
853
854 color_names[index]->name = xstrdup (color);
855 STACK_VAR (color_names[index]->name);
856 }
857
858 RELEASE_VAR (str);
859 }
860
861 static void
862 read_print_stream (const char *attr, const struct color **colors, const char *file, FILE *stream)
863 {
864 char buf[BUF_SIZE + 1];
865 unsigned int flags = 0;
866
867 while (!feof (stream))
868 {
869 size_t bytes_read;
870 char *eol;
871 const char *line;
872 bytes_read = fread (buf, 1, BUF_SIZE, stream);
873 if (bytes_read != BUF_SIZE && ferror (stream))
874 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
875 buf[bytes_read] = '\0';
876 line = buf;
877 while ((eol = strpbrk (line, "\n\r")))
878 {
879 const char *p;
880 flags &= ~(CR|LF);
881 if (*eol == '\r')
882 {
883 flags |= CR;
884 if (*(eol + 1) == '\n')
885 flags |= LF;
886 }
887 else if (*eol == '\n')
888 flags |= LF;
889 else
890 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
891 p = eol + SKIP_LINE_ENDINGS (flags);
892 *eol = '\0';
893 print_line (attr, colors, line, flags);
894 line = p;
895 }
896 if (feof (stream))
897 {
898 if (*line != '\0')
899 print_line (attr, colors, line, 0);
900 }
901 else if (*line != '\0')
902 {
903 char *p;
904 if ((clean || clean_all) && (p = strrchr (line, '\033')))
905 merge_print_line (line, p, stream);
906 else
907 print_line (attr, colors, line, 0);
908 }
909 }
910 }
911
912 static void
913 merge_print_line (const char *line, const char *p, FILE *stream)
914 {
915 char *buf = NULL;
916 char *merged_esc = NULL;
917 const char *esc = "";
918 const char char_restore = *p;
919
920 complete_part_line (p + 1, &buf, stream);
921
922 if (buf)
923 {
924 /* form escape sequence */
925 esc = merged_esc = str_concat (p, buf);
926 /* shorten partial line accordingly */
927 *(char *)p = '\0';
928 free (buf);
929 }
930
931 #ifdef TEST_MERGE_PART_LINE
932 printf ("%s%s", line, esc);
933 fflush (stdout);
934 _exit (EXIT_SUCCESS);
935 #else
936 print_clean (line);
937 *(char *)p = char_restore;
938 print_clean (esc);
939 free (merged_esc);
940 #endif
941 }
942
943 static void
944 complete_part_line (const char *p, char **buf, FILE *stream)
945 {
946 bool got_next_char = false, read_from_stream;
947 char ch;
948 size_t i = 0, size;
949
950 if (get_next_char (&ch, &p, stream, &read_from_stream))
951 {
952 if (ch == '[')
953 {
954 if (read_from_stream)
955 save_char (ch, buf, &i, &size);
956 }
957 else
958 {
959 if (read_from_stream)
960 ungetc ((int)ch, stream);
961 return; /* cancel */
962 }
963 }
964 else
965 return; /* cancel */
966
967 while (get_next_char (&ch, &p, stream, &read_from_stream))
968 {
969 if (isdigit (ch) || ch == ';')
970 {
971 if (read_from_stream)
972 save_char (ch, buf, &i, &size);
973 }
974 else /* got next character */
975 {
976 got_next_char = true;
977 break;
978 }
979 }
980
981 if (got_next_char)
982 {
983 if (ch == 'm')
984 {
985 if (read_from_stream)
986 save_char (ch, buf, &i, &size);
987 }
988 else
989 {
990 if (read_from_stream)
991 ungetc ((int)ch, stream);
992 return; /* cancel */
993 }
994 }
995 else
996 return; /* cancel */
997 }
998
999 static bool
1000 get_next_char (char *ch, const char **p, FILE *stream, bool *read_from_stream)
1001 {
1002 if (**p == '\0')
1003 {
1004 int c;
1005 if ((c = fgetc (stream)) != EOF)
1006 {
1007 *ch = (char)c;
1008 *read_from_stream = true;
1009 return true;
1010 }
1011 else
1012 {
1013 *read_from_stream = false;
1014 return false;
1015 }
1016 }
1017 else
1018 {
1019 *ch = **p;
1020 (*p)++;
1021 *read_from_stream = false;
1022 return true;
1023 }
1024 }
1025
1026 static void
1027 save_char (char ch, char **buf, size_t *i, size_t *size)
1028 {
1029 if (!*buf)
1030 {
1031 *size = ALLOC_COMPLETE_PART_LINE;
1032 *buf = xmalloc (*size);
1033 }
1034 /* +1: effective occupied size of buffer */
1035 else if ((*i + 1) == *size)
1036 {
1037 *size *= 2;
1038 *buf = xrealloc (*buf, *size);
1039 }
1040 (*buf)[*i] = ch;
1041 (*buf)[*i + 1] = '\0';
1042 (*i)++;
1043 }
1044
1045 static void
1046 find_color_entries (struct color_name **color_names, const struct color **colors)
1047 {
1048 struct timeval tv;
1049 unsigned int index;
1050
1051 /* randomness */
1052 gettimeofday (&tv, NULL);
1053 srand (tv.tv_usec * tv.tv_sec);
1054
1055 for (index = 0; color_names[index]; index++)
1056 {
1057 const char *color_name = color_names[index]->name;
1058
1059 const unsigned int count = tables[index].count;
1060 const struct color *const color_entries = tables[index].entries;
1061
1062 if (streq (color_name, "random"))
1063 {
1064 bool excludable;
1065 unsigned int i;
1066 do {
1067 excludable = false;
1068 i = rand() % (count - 2) + 1; /* omit color none and default */
1069 switch (index)
1070 {
1071 case FOREGROUND:
1072 /* --exclude-random */
1073 if (exclude && streq (exclude, color_entries[i].name))
1074 excludable = true;
1075 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
1076 excludable = true;
1077 break;
1078 case BACKGROUND:
1079 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
1080 excludable = true;
1081 break;
1082 default: /* never reached */
1083 ABORT_TRACE ();
1084 }
1085 } while (excludable);
1086 colors[index] = (struct color *)&color_entries[i];
1087 }
1088 else
1089 find_color_entry (color_names[index], index, colors);
1090 }
1091 }
1092
1093 static void
1094 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
1095 {
1096 bool found = false;
1097 unsigned int i;
1098
1099 const unsigned int count = tables[index].count;
1100 const struct color *const color_entries = tables[index].entries;
1101
1102 for (i = 0; i < count; i++)
1103 if (streq (color_name->name, color_entries[i].name))
1104 {
1105 colors[index] = (struct color *)&color_entries[i];
1106 found = true;
1107 break;
1108 }
1109 if (!found)
1110 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
1111 }
1112
1113 static void
1114 print_line (const char *attr, const struct color **colors, const char *const line, unsigned int flags)
1115 {
1116 /* --clean[-all] */
1117 if (clean || clean_all)
1118 print_clean (line);
1119 else
1120 {
1121 /* Foreground color code is guaranteed to be set when background color code is present. */
1122 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
1123 printf ("\033[%s", colors[BACKGROUND]->code);
1124 if (colors[FOREGROUND]->code)
1125 printf ("\033[%s%s%s\033[0m", attr, colors[FOREGROUND]->code, line);
1126 else
1127 printf (formats[FMT_GENERIC], line);
1128 }
1129 if (flags & CR)
1130 putchar ('\r');
1131 if (flags & LF)
1132 putchar ('\n');
1133 }
1134
1135 static void
1136 print_clean (const char *line)
1137 {
1138 const char *p = line;
1139
1140 if (is_esc (p))
1141 p = get_end_of_esc (p);
1142
1143 while (*p != '\0')
1144 {
1145 const char *text_start = p;
1146 const char *text_end = get_end_of_text (p);
1147 print_text (text_start, text_end - text_start);
1148 p = get_end_of_esc (text_end);
1149 }
1150 }
1151
1152 static bool
1153 is_esc (const char *p)
1154 {
1155 return gather_esc_offsets (p, NULL, NULL);
1156 }
1157
1158 static const char *
1159 get_end_of_esc (const char *p)
1160 {
1161 const char *esc;
1162 const char *end = NULL;
1163 while ((esc = strchr (p, '\033')))
1164 {
1165 if (gather_esc_offsets (esc, NULL, &end))
1166 break;
1167 p = esc + 1;
1168 }
1169 return end ? end + 1 : p + strlen (p);
1170 }
1171
1172 static const char *
1173 get_end_of_text (const char *p)
1174 {
1175 const char *esc;
1176 const char *start = NULL;
1177 while ((esc = strchr (p, '\033')))
1178 {
1179 if (gather_esc_offsets (esc, &start, NULL))
1180 break;
1181 p = esc + 1;
1182 }
1183 return start ? start : p + strlen (p);
1184 }
1185
1186 static void
1187 print_text (const char *p, size_t len)
1188 {
1189 size_t bytes_written;
1190 bytes_written = fwrite (p, 1, len, stdout);
1191 if (bytes_written != len)
1192 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
1193 }
1194
1195 static bool
1196 gather_esc_offsets (const char *p, const char **start, const char **end)
1197 {
1198 /* ESC[ */
1199 if (*p == 27 && *(p + 1) == '[')
1200 {
1201 bool valid = false;
1202 const char *const begin = p;
1203 p += 2;
1204 if (clean_all)
1205 valid = validate_esc_clean_all (&p);
1206 else if (clean)
1207 {
1208 bool check_values;
1209 unsigned int prev_iter, iter;
1210 const char *digit;
1211 prev_iter = iter = 0;
1212 do {
1213 check_values = false;
1214 iter++;
1215 if (!isdigit (*p))
1216 break;
1217 digit = p;
1218 while (isdigit (*p))
1219 p++;
1220 if (p - digit > 2)
1221 break;
1222 else /* check range */
1223 {
1224 char val[3];
1225 int value;
1226 unsigned int i;
1227 const unsigned int digits = p - digit;
1228 for (i = 0; i < digits; i++)
1229 val[i] = *digit++;
1230 val[i] = '\0';
1231 value = atoi (val);
1232 valid = validate_esc_clean (value, iter, &prev_iter, &p, &check_values);
1233 }
1234 } while (check_values);
1235 }
1236 if (valid)
1237 {
1238 if (start)
1239 *start = begin;
1240 if (end)
1241 *end = p;
1242 return true;
1243 }
1244 }
1245 return false;
1246 }
1247
1248 static bool
1249 validate_esc_clean_all (const char **p)
1250 {
1251 while (isdigit (**p) || **p == ';')
1252 (*p)++;
1253 return (**p == 'm');
1254 }
1255
1256 static bool
1257 validate_esc_clean (int value, unsigned int iter, unsigned int *prev_iter, const char **p, bool *check_values)
1258 {
1259 if (is_reset (value, iter, p))
1260 return true;
1261 else if (is_attr (value, iter, *prev_iter, p))
1262 {
1263 (*p)++;
1264 *check_values = true;
1265 *prev_iter = iter;
1266 return false; /* partial escape sequence, need another valid value */
1267 }
1268 else if (is_fg_color (value, p))
1269 return true;
1270 else if (is_bg_color (value, iter, p))
1271 return true;
1272 else
1273 return false;
1274 }
1275
1276 static bool
1277 is_reset (int value, unsigned int iter, const char **p)
1278 {
1279 return (value == 0 && iter == 1 && **p == 'm');
1280 }
1281
1282 static bool
1283 is_attr (int value, unsigned int iter, unsigned int prev_iter, const char **p)
1284 {
1285 return ((value > 0 && value < 10) && (iter - prev_iter == 1) && **p == ';');
1286 }
1287
1288 static bool
1289 is_fg_color (int value, const char **p)
1290 {
1291 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1292 }
1293
1294 static bool
1295 is_bg_color (int value, unsigned int iter, const char **p)
1296 {
1297 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1298 }
1299
1300 #if !DEBUG
1301 static void *
1302 malloc_wrap (size_t size)
1303 {
1304 void *p = malloc (size);
1305 if (!p)
1306 MEM_ALLOC_FAIL ();
1307 return p;
1308 }
1309
1310 static void *
1311 calloc_wrap (size_t nmemb, size_t size)
1312 {
1313 void *p = calloc (nmemb, size);
1314 if (!p)
1315 MEM_ALLOC_FAIL ();
1316 return p;
1317 }
1318
1319 static void *
1320 realloc_wrap (void *ptr, size_t size)
1321 {
1322 void *p = realloc (ptr, size);
1323 if (!p)
1324 MEM_ALLOC_FAIL ();
1325 return p;
1326 }
1327 #else
1328 static void *
1329 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1330 {
1331 void *p = malloc (size);
1332 if (!p)
1333 MEM_ALLOC_FAIL_DEBUG (file, line);
1334 fprintf (log, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1335 return p;
1336 }
1337
1338 static void *
1339 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1340 {
1341 void *p = calloc (nmemb, size);
1342 if (!p)
1343 MEM_ALLOC_FAIL_DEBUG (file, line);
1344 fprintf (log, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)(nmemb * size), file, line);
1345 return p;
1346 }
1347
1348 static void *
1349 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1350 {
1351 void *p = realloc (ptr, size);
1352 if (!p)
1353 MEM_ALLOC_FAIL_DEBUG (file, line);
1354 fprintf (log, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1355 return p;
1356 }
1357 #endif /* !DEBUG */
1358
1359 static void
1360 free_wrap (void **ptr)
1361 {
1362 free (*ptr);
1363 *ptr = NULL;
1364 }
1365
1366 #if !DEBUG
1367 # define do_malloc(len, file, line) malloc_wrap(len)
1368 #else
1369 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1370 #endif
1371
1372 static char *
1373 strdup_wrap (const char *str, const char *file, unsigned int line)
1374 {
1375 const size_t len = strlen (str) + 1;
1376 char *p = do_malloc (len, file, line);
1377 strncpy (p, str, len);
1378 return p;
1379 }
1380
1381 static char *
1382 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1383 {
1384 const size_t len = strlen (str1) + strlen (str2) + 1;
1385 char *p, *str;
1386
1387 p = str = do_malloc (len, file, line);
1388 strncpy (p, str1, strlen (str1));
1389 p += strlen (str1);
1390 strncpy (p, str2, strlen (str2));
1391 p += strlen (str2);
1392 *p = '\0';
1393
1394 return str;
1395 }
1396
1397 static bool
1398 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1399 {
1400 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1401 unsigned long size = bytes;
1402 if (bytes < 1024)
1403 return false;
1404 unit = units;
1405 while (size >= 1024 && *(unit + 1))
1406 {
1407 size /= 1024;
1408 unit++;
1409 }
1410 bytes_size->size = (unsigned int)size;
1411 bytes_size->unit = *unit;
1412 return true;
1413 }
1414
1415 static char *
1416 get_file_type (mode_t mode)
1417 {
1418 if (S_ISREG (mode))
1419 return "file";
1420 else if (S_ISDIR (mode))
1421 return "directory";
1422 else if (S_ISCHR (mode))
1423 return "character device";
1424 else if (S_ISBLK (mode))
1425 return "block device";
1426 else if (S_ISFIFO (mode))
1427 return "named pipe";
1428 else if (S_ISLNK (mode))
1429 return "symbolic link";
1430 else if (S_ISSOCK (mode))
1431 return "socket";
1432 else
1433 return "file";
1434 }
1435
1436 static bool
1437 has_color_name (const char *str, const char *name)
1438 {
1439 char *p;
1440
1441 assert (strlen (str));
1442 assert (strlen (name));
1443
1444 if (!(*str == *name || *str == toupper (*name)))
1445 return false;
1446 else if (*(name + 1) != '\0'
1447 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1448 return false;
1449
1450 return true;
1451 }
1452
1453 static FILE *
1454 open_file (const char *file, const char *mode)
1455 {
1456 FILE *stream;
1457
1458 errno = 0;
1459 stream = fopen (file, mode);
1460 if (!stream)
1461 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1462
1463 return stream;
1464 }
1465
1466 #define DO_VFPRINTF(fmt) \
1467 va_list ap; \
1468 fprintf (stderr, "%s: ", program_name); \
1469 va_start (ap, fmt); \
1470 vfprintf (stderr, fmt, ap); \
1471 va_end (ap); \
1472 fprintf (stderr, "\n"); \
1473
1474 static void
1475 vfprintf_diag (const char *fmt, ...)
1476 {
1477 DO_VFPRINTF (fmt);
1478 }
1479
1480 static void
1481 vfprintf_fail (const char *fmt, ...)
1482 {
1483 DO_VFPRINTF (fmt);
1484 exit (EXIT_FAILURE);
1485 }
1486
1487 static void
1488 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1489 {
1490 /* nothing to stack */
1491 if (ptr == NULL)
1492 return;
1493 if (!*list)
1494 *list = xmalloc (sizeof (void *));
1495 else
1496 {
1497 unsigned int i;
1498 for (i = 0; i < *stacked; i++)
1499 if (!(*list)[i])
1500 {
1501 (*list)[i] = ptr;
1502 return; /* reused */
1503 }
1504 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1505 }
1506 (*list)[index] = ptr;
1507 (*stacked)++;
1508 }
1509
1510 static void
1511 release_var (void **list, unsigned int stacked, void **ptr)
1512 {
1513 unsigned int i;
1514 /* nothing to release */
1515 if (*ptr == NULL)
1516 return;
1517 for (i = 0; i < stacked; i++)
1518 if (list[i] == *ptr)
1519 {
1520 free (*ptr);
1521 *ptr = NULL;
1522 list[i] = NULL;
1523 return;
1524 }
1525 }