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