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