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