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