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