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