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