]> git.refcnt.org Git - colorize.git/blob - colorize.c
Move option processing code to a function
[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-2015 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 _BSD_SOURCE
23 #define _XOPEN_SOURCE 700
24 #define _FILE_OFFSET_BITS 64
25 #include <assert.h>
26 #include <ctype.h>
27 #include <errno.h>
28 #include <getopt.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <time.h>
37 #include <unistd.h>
38
39 #ifndef DEBUG
40 # define DEBUG 0
41 #endif
42
43 #define str(arg) #arg
44 #define to_str(arg) str(arg)
45
46 #define streq(s1, s2) (strcmp (s1, s2) == 0)
47
48 #if !DEBUG
49 # define xmalloc(size) malloc_wrap(size)
50 # define xcalloc(nmemb, size) calloc_wrap(nmemb, size)
51 # define xrealloc(ptr, size) realloc_wrap(ptr, size)
52 # define xstrdup(str) strdup_wrap(str, NULL, 0)
53 # define str_concat(str1, str2) str_concat_wrap(str1, str2, NULL, 0)
54 #else
55 # define xmalloc(size) malloc_wrap_debug(size, __FILE__, __LINE__)
56 # define xcalloc(nmemb, size) calloc_wrap_debug(nmemb, size, __FILE__, __LINE__)
57 # define xrealloc(ptr, size) realloc_wrap_debug(ptr, size, __FILE__, __LINE__)
58 # define xstrdup(str) strdup_wrap(str, __FILE__, __LINE__)
59 # define str_concat(str1, str2) str_concat_wrap(str1, str2, __FILE__, __LINE__)
60 #endif
61
62 #define free_null(ptr) free_wrap((void **)&ptr)
63
64 #if defined(BUF_SIZE) && (BUF_SIZE <= 0 || BUF_SIZE > 65536)
65 # undef BUF_SIZE
66 #endif
67 #ifndef BUF_SIZE
68 # define BUF_SIZE 4096
69 #endif
70
71 #define LF 0x01
72 #define CR 0x02
73
74 #define SKIP_LINE_ENDINGS(flags) (((flags) & CR) && ((flags) & LF) ? 2 : 1)
75
76 #define VALID_FILE_TYPE(mode) (S_ISREG (mode) || S_ISLNK (mode) || S_ISFIFO (mode))
77
78 #define STACK_VAR(ptr) do { \
79 stack_var (&vars_list, &stacked_vars, stacked_vars, ptr); \
80 } while (false)
81
82 #define RELEASE_VAR(ptr) do { \
83 release_var (vars_list, stacked_vars, (void **)&ptr); \
84 } while (false)
85
86 #if !DEBUG
87 # define MEM_ALLOC_FAIL() do { \
88 fprintf (stderr, "%s: memory allocation failure\n", program_name); \
89 exit (EXIT_FAILURE); \
90 } while (false)
91 #else
92 # define MEM_ALLOC_FAIL_DEBUG(file, line) do { \
93 fprintf (stderr, "Memory allocation failure in source file %s, line %u\n", file, line); \
94 exit (EXIT_FAILURE); \
95 } while (false)
96 #endif
97
98 #define ABORT_TRACE() \
99 fprintf (stderr, "Aborting in source file %s, line %u\n", __FILE__, __LINE__); \
100 abort (); \
101
102 #define CHECK_COLORS_RANDOM(color1, color2) \
103 streq (color_names[color1]->name, "random") \
104 && (streq (color_names[color2]->name, "none") \
105 || streq (color_names[color2]->name, "default")) \
106
107 #define COLOR_SEP_CHAR '/'
108
109 #define DEBUG_FILE "debug.txt"
110
111 #define VERSION "0.56"
112
113 typedef enum { false, true } bool;
114
115 struct color_name {
116 char *name;
117 char *orig;
118 };
119
120 static struct color_name *color_names[3] = { NULL, NULL, NULL };
121
122 struct color {
123 const char *name;
124 const char *code;
125 };
126
127 static const struct color fg_colors[] = {
128 { "none", NULL },
129 { "black", "30m" },
130 { "red", "31m" },
131 { "green", "32m" },
132 { "yellow", "33m" },
133 { "blue", "34m" },
134 { "magenta", "35m" },
135 { "cyan", "36m" },
136 { "white", "37m" },
137 { "default", "39m" },
138 };
139 static const struct color bg_colors[] = {
140 { "none", NULL },
141 { "black", "40m" },
142 { "red", "41m" },
143 { "green", "42m" },
144 { "yellow", "43m" },
145 { "blue", "44m" },
146 { "magenta", "45m" },
147 { "cyan", "46m" },
148 { "white", "47m" },
149 { "default", "49m" },
150 };
151
152 struct bytes_size {
153 unsigned int size;
154 char unit;
155 };
156
157 enum fmts {
158 FMT_GENERIC,
159 FMT_STRING,
160 FMT_QUOTE,
161 FMT_COLOR,
162 FMT_RANDOM,
163 FMT_ERROR,
164 FMT_FILE,
165 FMT_TYPE
166 };
167 static const char *formats[] = {
168 "%s", /* generic */
169 "%s '%s'", /* string */
170 "%s `%s' %s", /* quote */
171 "%s color '%s' %s", /* color */
172 "%s color '%s' %s '%s'", /* random */
173 "less than %lu bytes %s", /* error */
174 "%s: %s", /* file */
175 "%s: %s: %s", /* type */
176 };
177
178 enum { FOREGROUND, BACKGROUND };
179
180 static const struct {
181 struct color const *entries;
182 unsigned int count;
183 const char *desc;
184 } tables[] = {
185 { fg_colors, sizeof (fg_colors) / sizeof (struct color), "foreground" },
186 { bg_colors, sizeof (bg_colors) / sizeof (struct color), "background" },
187 };
188
189 static FILE *stream;
190 #if DEBUG
191 static FILE *log;
192 #endif
193
194 static unsigned int stacked_vars;
195 static void **vars_list;
196
197 static bool clean;
198 static bool clean_all;
199
200 static char *exclude;
201
202 static const char *program_name;
203
204 static void process_opts (int, char **);
205 static void print_hint (void);
206 static void print_help (void);
207 static void print_version (void);
208 static void cleanup (void);
209 static void free_color_names (struct color_name **);
210 static void process_args (unsigned int, char **, bool *, const struct color **, const char **, FILE **);
211 static void process_file_arg (const char *, const char **, FILE **);
212 static void read_print_stream (bool, const struct color **, const char *, FILE *);
213 static void find_color_entries (struct color_name **, const struct color **);
214 static void find_color_entry (const struct color_name *, unsigned int, const struct color **);
215 static void print_line (bool, const struct color **, const char * const, unsigned int);
216 static void print_clean (const char *);
217 static bool is_esc (const char *);
218 static const char *get_end_of_esc (const char *);
219 static const char *get_end_of_text (const char *);
220 static void print_text (const char *, size_t);
221 static bool gather_esc_offsets (const char *, const char **, const char **);
222 static bool validate_esc_clean_all (const char **);
223 static bool validate_esc_clean (int, unsigned int, const char **, bool *);
224 static bool is_reset (int, unsigned int, const char **);
225 static bool is_bold (int, unsigned int, const char **);
226 static bool is_fg_color (int, const char **);
227 static bool is_bg_color (int, unsigned int, const char **);
228 #if !DEBUG
229 static void *malloc_wrap (size_t);
230 static void *calloc_wrap (size_t, size_t);
231 static void *realloc_wrap (void *, size_t);
232 #else
233 static void *malloc_wrap_debug (size_t, const char *, unsigned int);
234 static void *calloc_wrap_debug (size_t, size_t, const char *, unsigned int);
235 static void *realloc_wrap_debug (void *, size_t, const char *, unsigned int);
236 #endif
237 static void free_wrap (void **);
238 static char *strdup_wrap (const char *, const char *, unsigned int);
239 static char *str_concat_wrap (const char *, const char *, const char *, unsigned int);
240 static bool get_bytes_size (unsigned long, struct bytes_size *);
241 static char *get_file_type (mode_t);
242 static bool has_color_name (const char *, const char *);
243 static FILE *open_file (const char *, const char *);
244 static void vfprintf_diag (const char *, ...);
245 static void vfprintf_fail (const char *, ...);
246 static void stack_var (void ***, unsigned int *, unsigned int, void *);
247 static void release_var (void **, unsigned int, void **);
248
249 extern int optind;
250
251 int
252 main (int argc, char **argv)
253 {
254 unsigned int arg_cnt = 0;
255
256 bool bold = false;
257
258 const struct color *colors[2] = {
259 NULL, /* foreground */
260 NULL, /* background */
261 };
262
263 const char *file = NULL;
264
265 program_name = argv[0];
266 atexit (cleanup);
267
268 setvbuf (stdout, NULL, _IOLBF, 0);
269
270 #if DEBUG
271 log = open_file (DEBUG_FILE, "w");
272 #endif
273
274 process_opts (argc, argv);
275
276 arg_cnt = argc - optind;
277
278 if (clean || clean_all)
279 {
280 if (clean && clean_all)
281 vfprintf_fail (formats[FMT_GENERIC], "--clean and --clean-all switch are mutually exclusive");
282 if (arg_cnt > 1)
283 {
284 const char *format = "%s %s";
285 const char *message = "switch cannot be used with more than one file";
286 if (clean)
287 vfprintf_fail (format, "--clean", message);
288 else if (clean_all)
289 vfprintf_fail (format, "--clean-all", message);
290 }
291 }
292 else
293 {
294 if (arg_cnt == 0 || arg_cnt > 2)
295 {
296 vfprintf_diag ("%u arguments provided, expected 1-2 arguments or clean option", arg_cnt);
297 print_hint ();
298 exit (EXIT_FAILURE);
299 }
300 }
301
302 if (clean || clean_all)
303 process_file_arg (argv[optind], &file, &stream);
304 else
305 process_args (arg_cnt, &argv[optind], &bold, colors, &file, &stream);
306 read_print_stream (bold, colors, file, stream);
307
308 RELEASE_VAR (exclude);
309
310 exit (EXIT_SUCCESS);
311 }
312
313 #define SET_OPT_TYPE(type) \
314 opt_type = type; \
315 opt = 0; \
316 goto PARSE_OPT; \
317
318 extern char *optarg;
319 static int opt_type;
320
321 static void
322 process_opts (int argc, char **argv)
323 {
324 enum {
325 OPT_CLEAN = 1,
326 OPT_CLEAN_ALL,
327 OPT_EXCLUDE_RANDOM,
328 OPT_HELP,
329 OPT_VERSION
330 };
331
332 int opt;
333 struct option long_opts[] = {
334 { "clean", no_argument, &opt_type, OPT_CLEAN },
335 { "clean-all", no_argument, &opt_type, OPT_CLEAN_ALL },
336 { "exclude-random", required_argument, &opt_type, OPT_EXCLUDE_RANDOM },
337 { "help", no_argument, &opt_type, OPT_HELP },
338 { "version", no_argument, &opt_type, OPT_VERSION },
339 { NULL, 0, NULL, 0 },
340 };
341
342 while ((opt = getopt_long (argc, argv, "hV", long_opts, NULL)) != -1)
343 {
344 PARSE_OPT:
345 switch (opt)
346 {
347 case 0: /* long opts */
348 switch (opt_type)
349 {
350 case OPT_CLEAN:
351 clean = true;
352 break;
353 case OPT_CLEAN_ALL:
354 clean_all = true;
355 break;
356 case OPT_EXCLUDE_RANDOM: {
357 bool valid = false;
358 unsigned int i;
359 exclude = xstrdup (optarg);
360 STACK_VAR (exclude);
361 for (i = 1; i < tables[FOREGROUND].count - 1; i++) /* skip color none and default */
362 {
363 const struct color *entry = &tables[FOREGROUND].entries[i];
364 if (streq (exclude, entry->name))
365 {
366 valid = true;
367 break;
368 }
369 }
370 if (!valid)
371 vfprintf_fail (formats[FMT_GENERIC], "--exclude-random switch must be provided a plain color");
372 break;
373 }
374 case OPT_HELP:
375 print_help ();
376 exit (EXIT_SUCCESS);
377 case OPT_VERSION:
378 print_version ();
379 exit (EXIT_SUCCESS);
380 default: /* never reached */
381 ABORT_TRACE ();
382 }
383 break;
384 case 'h':
385 SET_OPT_TYPE (OPT_HELP);
386 case 'V':
387 SET_OPT_TYPE (OPT_VERSION);
388 case '?':
389 print_hint ();
390 exit (EXIT_FAILURE);
391 default: /* never reached */
392 ABORT_TRACE ();
393 }
394 }
395 }
396
397 static void
398 print_hint (void)
399 {
400 fprintf (stderr, "Type `%s --help' for help screen.\n", program_name);
401 }
402
403 static void
404 print_help (void)
405 {
406 unsigned int i;
407
408 printf ("Usage: %s (foreground) OR (foreground)%c(background) OR --clean[-all] [-|file]\n\n", program_name, COLOR_SEP_CHAR);
409 printf ("\tColors (foreground) (background)\n");
410 for (i = 0; i < tables[FOREGROUND].count; i++)
411 {
412 const struct color *entry = &tables[FOREGROUND].entries[i];
413 const char *name = entry->name;
414 const char *code = entry->code;
415 if (code)
416 printf ("\t\t{\033[%s#\033[0m} [%c%c]%s%*s%s\n",
417 code, toupper (*name), *name, name + 1, 10 - (int)strlen (name), " ", name);
418 else
419 printf ("\t\t{-} %s%*s%s\n", name, 13 - (int)strlen (name), " ", name);
420 }
421 printf ("\t\t{*} [Rr]%s%*s%s [--exclude-random=<foreground color>]\n", "andom", 10 - (int)strlen ("random"), " ", "random");
422
423 printf ("\n\tFirst character of color name in upper case denotes increased intensity,\n");
424 printf ("\twhereas for lower case colors will be of normal intensity.\n");
425
426 printf ("\n\tOptions\n");
427 printf ("\t\t --clean\n");
428 printf ("\t\t --clean-all\n");
429 printf ("\t\t --exclude-random\n");
430 printf ("\t\t-h, --help\n");
431 printf ("\t\t-V, --version\n\n");
432 }
433
434 static void
435 print_version (void)
436 {
437 #ifdef HAVE_VERSION
438 # include "version.h"
439 #else
440 const char *version = NULL;
441 #endif
442 const char *version_prefix, *version_string;
443 const char *c_flags;
444 struct bytes_size bytes_size;
445 bool debug;
446 #ifdef CFLAGS
447 c_flags = to_str (CFLAGS);
448 #else
449 c_flags = "unknown";
450 #endif
451 #if DEBUG
452 debug = true;
453 #else
454 debug = false;
455 #endif
456 version_prefix = version ? "" : "v";
457 version_string = version ? version : VERSION;
458 printf ("colorize %s%s (compiled at %s, %s)\n", version_prefix, version_string, __DATE__, __TIME__);
459
460 printf ("Compiler flags: %s\n", c_flags);
461 if (get_bytes_size (BUF_SIZE, &bytes_size))
462 {
463 if (BUF_SIZE % 1024 == 0)
464 printf ("Buffer size: %u%c\n", bytes_size.size, bytes_size.unit);
465 else
466 printf ("Buffer size: %u%c, %u byte%s\n", bytes_size.size, bytes_size.unit,
467 BUF_SIZE % 1024, BUF_SIZE % 1024 > 1 ? "s" : "");
468 }
469 else
470 printf ("Buffer size: %lu byte%s\n", (unsigned long)BUF_SIZE, BUF_SIZE > 1 ? "s" : "");
471 printf ("Debugging: %s\n", debug ? "yes" : "no");
472 }
473
474 static void
475 cleanup (void)
476 {
477 free_color_names (color_names);
478
479 if (stream && fileno (stream) != STDIN_FILENO)
480 fclose (stream);
481 #if DEBUG
482 if (log)
483 fclose (log);
484 #endif
485
486 if (vars_list)
487 {
488 unsigned int i;
489 for (i = 0; i < stacked_vars; i++)
490 if (vars_list[i])
491 free (vars_list[i]);
492
493 free_null (vars_list);
494 }
495 }
496
497 static void
498 free_color_names (struct color_name **color_names)
499 {
500 unsigned int i;
501 for (i = 0; color_names[i]; i++)
502 {
503 free (color_names[i]->name);
504 free (color_names[i]->orig);
505 free_null (color_names[i]);
506 }
507 }
508
509 static void
510 process_args (unsigned int arg_cnt, char **arg_strings, bool *bold, const struct color **colors, const char **file, FILE **stream)
511 {
512 int ret;
513 unsigned int index;
514 char *color, *p, *str;
515 struct stat sb;
516
517 const char *color_string = arg_cnt >= 1 ? arg_strings[0] : NULL;
518 const char *file_string = arg_cnt == 2 ? arg_strings[1] : NULL;
519
520 assert (color_string);
521
522 if (streq (color_string, "-"))
523 {
524 if (file_string)
525 vfprintf_fail (formats[FMT_GENERIC], "hyphen cannot be used as color string");
526 else
527 vfprintf_fail (formats[FMT_GENERIC], "hyphen must be preceeded by color string");
528 }
529
530 ret = lstat (color_string, &sb);
531
532 /* Ensure that we don't fail if there's a file with one or more
533 color names in its path. */
534 if (ret == 0) /* success */
535 {
536 bool have_file;
537 unsigned int c;
538 const char *color = color_string;
539 const mode_t mode = sb.st_mode;
540
541 for (c = 1; c <= 2 && *color; c++)
542 {
543 bool matched = false;
544 unsigned int i;
545 for (i = 0; i < tables[FOREGROUND].count; i++)
546 {
547 const struct color *entry = &tables[FOREGROUND].entries[i];
548 if (has_color_name (color, entry->name))
549 {
550 color += strlen (entry->name);
551 matched = true;
552 break;
553 }
554 }
555 if (!matched && has_color_name (color, "random"))
556 {
557 color += strlen ("random");
558 matched = true;
559 }
560 if (matched && *color == COLOR_SEP_CHAR && *(color + 1))
561 color++;
562 else
563 break;
564 }
565
566 have_file = (*color != '\0');
567
568 if (have_file)
569 {
570 const char *file_exists = color_string;
571 if (file_string)
572 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_exists, "cannot be used as color string");
573 else
574 {
575 if (VALID_FILE_TYPE (mode))
576 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_exists, "must be preceeded by color string");
577 else
578 vfprintf_fail (formats[FMT_QUOTE], get_file_type (mode), file_exists, "is not a valid file type");
579 }
580 }
581 }
582
583 if ((p = strchr (color_string, COLOR_SEP_CHAR)))
584 {
585 if (p == color_string)
586 vfprintf_fail (formats[FMT_STRING], "foreground color missing in string", color_string);
587 else if (p == color_string + strlen (color_string) - 1)
588 vfprintf_fail (formats[FMT_STRING], "background color missing in string", color_string);
589 else if (strchr (++p, COLOR_SEP_CHAR))
590 vfprintf_fail (formats[FMT_STRING], "one color pair allowed only for string", color_string);
591 }
592
593 str = xstrdup (color_string);
594 STACK_VAR (str);
595
596 for (index = 0, color = str; *color; index++, color = p)
597 {
598 char *ch, *sep;
599
600 p = NULL;
601 if ((sep = strchr (color, COLOR_SEP_CHAR)))
602 {
603 *sep = '\0';
604 p = sep + 1;
605 }
606 else
607 p = color + strlen (color);
608 assert (p);
609
610 for (ch = color; *ch; ch++)
611 if (!isalpha (*ch))
612 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be made of non-alphabetic characters");
613
614 for (ch = color + 1; *ch; ch++)
615 if (!islower (*ch))
616 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be in mixed lower/upper case");
617
618 if (streq (color, "None"))
619 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color, "cannot be bold");
620
621 if (isupper (*color))
622 {
623 switch (index)
624 {
625 case FOREGROUND:
626 *bold = true;
627 break;
628 case BACKGROUND:
629 vfprintf_fail (formats[FMT_COLOR], tables[BACKGROUND].desc, color, "cannot be bold");
630 default: /* never reached */
631 ABORT_TRACE ();
632 }
633 }
634
635 color_names[index] = xcalloc (1, sizeof (struct color_name));
636
637 color_names[index]->orig = xstrdup (color);
638
639 for (ch = color; *ch; ch++)
640 *ch = tolower (*ch);
641
642 color_names[index]->name = xstrdup (color);
643 }
644
645 RELEASE_VAR (str);
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 #define MERGE_PRINT_LINE(part_line, line, flags, check_eof) do { \
713 char *current_line, *merged_line = NULL; \
714 if (part_line) \
715 { \
716 merged_line = str_concat (part_line, line); \
717 free_null (part_line); \
718 } \
719 current_line = merged_line ? merged_line : (char *)line; \
720 if (!check_eof || *current_line != '\0') \
721 print_line (bold, colors, current_line, flags); \
722 free (merged_line); \
723 } while (false)
724
725 static void
726 read_print_stream (bool bold, const struct color **colors, const char *file, FILE *stream)
727 {
728 char buf[BUF_SIZE + 1], *part_line = NULL;
729 unsigned int flags = 0;
730
731 while (!feof (stream))
732 {
733 size_t bytes_read;
734 char *eol;
735 const char *line;
736 memset (buf, '\0', BUF_SIZE + 1);
737 bytes_read = fread (buf, 1, BUF_SIZE, stream);
738 if (bytes_read != BUF_SIZE && ferror (stream))
739 vfprintf_fail (formats[FMT_ERROR], BUF_SIZE, "read");
740 line = buf;
741 while ((eol = strpbrk (line, "\n\r")))
742 {
743 char *p;
744 flags &= ~(CR|LF);
745 if (*eol == '\r')
746 {
747 flags |= CR;
748 if (*(eol + 1) == '\n')
749 flags |= LF;
750 }
751 else if (*eol == '\n')
752 flags |= LF;
753 else
754 vfprintf_fail (formats[FMT_FILE], file, "unrecognized line ending");
755 p = eol + SKIP_LINE_ENDINGS (flags);
756 *eol = '\0';
757 MERGE_PRINT_LINE (part_line, line, flags, false);
758 line = p;
759 }
760 if (feof (stream)) {
761 MERGE_PRINT_LINE (part_line, line, 0, true);
762 }
763 else if (*line != '\0')
764 {
765 if (!clean && !clean_all) /* efficiency */
766 print_line (bold, colors, line, 0);
767 else if (!part_line)
768 part_line = xstrdup (line);
769 else
770 {
771 char *merged_line = str_concat (part_line, line);
772 free (part_line);
773 part_line = merged_line;
774 }
775 }
776 }
777 }
778
779 static void
780 find_color_entries (struct color_name **color_names, const struct color **colors)
781 {
782 struct timeval tv;
783 unsigned int index;
784
785 /* randomness */
786 gettimeofday (&tv, NULL);
787 srand (tv.tv_usec * tv.tv_sec);
788
789 for (index = 0; color_names[index]; index++)
790 {
791 const char *color_name = color_names[index]->name;
792
793 const unsigned int count = tables[index].count;
794 const struct color *const color_entries = tables[index].entries;
795
796 if (streq (color_name, "random"))
797 {
798 bool excludable;
799 unsigned int i;
800 do {
801 excludable = false;
802 i = rand() % (count - 2) + 1; /* omit color none and default */
803 switch (index)
804 {
805 case FOREGROUND:
806 /* --exclude-random */
807 if (exclude && streq (exclude, color_entries[i].name))
808 excludable = true;
809 else if (color_names[BACKGROUND] && streq (color_names[BACKGROUND]->name, color_entries[i].name))
810 excludable = true;
811 break;
812 case BACKGROUND:
813 if (streq (colors[FOREGROUND]->name, color_entries[i].name))
814 excludable = true;
815 break;
816 default: /* never reached */
817 ABORT_TRACE ();
818 }
819 } while (excludable);
820 colors[index] = (struct color *)&color_entries[i];
821 }
822 else
823 find_color_entry (color_names[index], index, colors);
824 }
825 }
826
827 static void
828 find_color_entry (const struct color_name *color_name, unsigned int index, const struct color **colors)
829 {
830 bool found = false;
831 unsigned int i;
832
833 const unsigned int count = tables[index].count;
834 const struct color *const color_entries = tables[index].entries;
835
836 for (i = 0; i < count; i++)
837 if (streq (color_name->name, color_entries[i].name))
838 {
839 colors[index] = (struct color *)&color_entries[i];
840 found = true;
841 break;
842 }
843 if (!found)
844 vfprintf_fail (formats[FMT_COLOR], tables[index].desc, color_name->orig, "not recognized");
845 }
846
847 static void
848 print_line (bool bold, const struct color **colors, const char *const line, unsigned int flags)
849 {
850 /* --clean[-all] */
851 if (clean || clean_all)
852 print_clean (line);
853 else
854 {
855 /* Foreground color code is guaranteed to be set when background color code is present. */
856 if (colors[BACKGROUND] && colors[BACKGROUND]->code)
857 printf ("\033[%s", colors[BACKGROUND]->code);
858 if (colors[FOREGROUND]->code)
859 printf ("\033[%s%s%s\033[0m", bold ? "1;" : "", colors[FOREGROUND]->code, line);
860 else
861 printf (formats[FMT_GENERIC], line);
862 }
863 if (flags & CR)
864 putchar ('\r');
865 if (flags & LF)
866 putchar ('\n');
867 }
868
869 static void
870 print_clean (const char *line)
871 {
872 const char *p = line;
873
874 if (is_esc (p))
875 p = get_end_of_esc (p);
876
877 while (*p != '\0')
878 {
879 const char *text_start = p;
880 const char *text_end = get_end_of_text (p);
881 print_text (text_start, text_end - text_start);
882 p = get_end_of_esc (text_end);
883 }
884 }
885
886 static bool
887 is_esc (const char *p)
888 {
889 return gather_esc_offsets (p, NULL, NULL);
890 }
891
892 static const char *
893 get_end_of_esc (const char *p)
894 {
895 const char *esc;
896 const char *end = NULL;
897 while ((esc = strchr (p, '\033')))
898 {
899 if (gather_esc_offsets (esc, NULL, &end))
900 break;
901 p = esc + 1;
902 }
903 return end ? end + 1 : p + strlen (p);
904 }
905
906 static const char *
907 get_end_of_text (const char *p)
908 {
909 const char *esc;
910 const char *start = NULL;
911 while ((esc = strchr (p, '\033')))
912 {
913 if (gather_esc_offsets (esc, &start, NULL))
914 break;
915 p = esc + 1;
916 }
917 return start ? start : p + strlen (p);
918 }
919
920 static void
921 print_text (const char *p, size_t len)
922 {
923 size_t bytes_written;
924 bytes_written = fwrite (p, 1, len, stdout);
925 if (bytes_written != len)
926 vfprintf_fail (formats[FMT_ERROR], (unsigned long)len, "written");
927 }
928
929 static bool
930 gather_esc_offsets (const char *p, const char **start, const char **end)
931 {
932 /* ESC[ */
933 if (*p == 27 && *(p + 1) == '[')
934 {
935 bool valid = false;
936 const char *begin = p;
937 p += 2;
938 if (clean_all)
939 valid = validate_esc_clean_all (&p);
940 else if (clean)
941 {
942 bool check_values;
943 unsigned int iter = 0;
944 const char *digit;
945 do {
946 check_values = false;
947 iter++;
948 if (!isdigit (*p))
949 break;
950 digit = p;
951 while (isdigit (*p))
952 p++;
953 if (p - digit > 2)
954 break;
955 else /* check range */
956 {
957 char val[3];
958 int value;
959 unsigned int i;
960 const unsigned int digits = p - digit;
961 for (i = 0; i < digits; i++)
962 val[i] = *digit++;
963 val[i] = '\0';
964 value = atoi (val);
965 valid = validate_esc_clean (value, iter, &p, &check_values);
966 }
967 } while (check_values);
968 }
969 if (valid)
970 {
971 if (start)
972 *start = begin;
973 if (end)
974 *end = p;
975 return true;
976 }
977 }
978 return false;
979 }
980
981 static bool
982 validate_esc_clean_all (const char **p)
983 {
984 while (isdigit (**p) || **p == ';')
985 (*p)++;
986 return (**p == 'm');
987 }
988
989 static bool
990 validate_esc_clean (int value, unsigned int iter, const char **p, bool *check_values)
991 {
992 if (is_reset (value, iter, p))
993 return true;
994 else if (is_bold (value, iter, p))
995 {
996 (*p)++;
997 *check_values = true;
998 return false; /* partial escape sequence, need another valid value */
999 }
1000 else if (is_fg_color (value, p))
1001 return true;
1002 else if (is_bg_color (value, iter, p))
1003 return true;
1004 else
1005 return false;
1006 }
1007
1008 static bool
1009 is_reset (int value, unsigned int iter, const char **p)
1010 {
1011 return (value == 0 && iter == 1 && **p == 'm');
1012 }
1013
1014 static bool
1015 is_bold (int value, unsigned int iter, const char **p)
1016 {
1017 return (value == 1 && iter == 1 && **p == ';');
1018 }
1019
1020 static bool
1021 is_fg_color (int value, const char **p)
1022 {
1023 return (((value >= 30 && value <= 37) || value == 39) && **p == 'm');
1024 }
1025
1026 static bool
1027 is_bg_color (int value, unsigned int iter, const char **p)
1028 {
1029 return (((value >= 40 && value <= 47) || value == 49) && iter == 1 && **p == 'm');
1030 }
1031
1032 #if !DEBUG
1033 static void *
1034 malloc_wrap (size_t size)
1035 {
1036 void *p = malloc (size);
1037 if (!p)
1038 MEM_ALLOC_FAIL ();
1039 return p;
1040 }
1041
1042 static void *
1043 calloc_wrap (size_t nmemb, size_t size)
1044 {
1045 void *p = calloc (nmemb, size);
1046 if (!p)
1047 MEM_ALLOC_FAIL ();
1048 return p;
1049 }
1050
1051 static void *
1052 realloc_wrap (void *ptr, size_t size)
1053 {
1054 void *p = realloc (ptr, size);
1055 if (!p)
1056 MEM_ALLOC_FAIL ();
1057 return p;
1058 }
1059 #else
1060 static void *
1061 malloc_wrap_debug (size_t size, const char *file, unsigned int line)
1062 {
1063 void *p = malloc (size);
1064 if (!p)
1065 MEM_ALLOC_FAIL_DEBUG (file, line);
1066 fprintf (log, "%s: malloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1067 return p;
1068 }
1069
1070 static void *
1071 calloc_wrap_debug (size_t nmemb, size_t size, const char *file, unsigned int line)
1072 {
1073 void *p = calloc (nmemb, size);
1074 if (!p)
1075 MEM_ALLOC_FAIL_DEBUG (file, line);
1076 fprintf (log, "%s: calloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)(nmemb * size), file, line);
1077 return p;
1078 }
1079
1080 static void *
1081 realloc_wrap_debug (void *ptr, size_t size, const char *file, unsigned int line)
1082 {
1083 void *p = realloc (ptr, size);
1084 if (!p)
1085 MEM_ALLOC_FAIL_DEBUG (file, line);
1086 fprintf (log, "%s: realloc'ed %lu bytes [source file %s, line %u]\n", program_name, (unsigned long)size, file, line);
1087 return p;
1088 }
1089 #endif /* !DEBUG */
1090
1091 static void
1092 free_wrap (void **ptr)
1093 {
1094 free (*ptr);
1095 *ptr = NULL;
1096 }
1097
1098 #if !DEBUG
1099 # define do_malloc(len, file, line) malloc_wrap(len)
1100 #else
1101 # define do_malloc(len, file, line) malloc_wrap_debug(len, file, line)
1102 #endif
1103
1104 static char *
1105 strdup_wrap (const char *str, const char *file, unsigned int line)
1106 {
1107 const size_t len = strlen (str) + 1;
1108 char *p = do_malloc (len, file, line);
1109 strncpy (p, str, len);
1110 return p;
1111 }
1112
1113 static char *
1114 str_concat_wrap (const char *str1, const char *str2, const char *file, unsigned int line)
1115 {
1116 const size_t len = strlen (str1) + strlen (str2) + 1;
1117 char *p, *str;
1118
1119 p = str = do_malloc (len, file, line);
1120 strncpy (p, str1, strlen (str1));
1121 p += strlen (str1);
1122 strncpy (p, str2, strlen (str2));
1123 p += strlen (str2);
1124 *p = '\0';
1125
1126 return str;
1127 }
1128
1129 static bool
1130 get_bytes_size (unsigned long bytes, struct bytes_size *bytes_size)
1131 {
1132 const char *unit, units[] = { '0', 'K', 'M', 'G', '\0' };
1133 unsigned long size = bytes;
1134 if (bytes < 1024)
1135 return false;
1136 unit = units;
1137 while (size >= 1024 && *(unit + 1))
1138 {
1139 size /= 1024;
1140 unit++;
1141 }
1142 bytes_size->size = (unsigned int)size;
1143 bytes_size->unit = *unit;
1144 return true;
1145 }
1146
1147 static char *
1148 get_file_type (mode_t mode)
1149 {
1150 if (S_ISREG (mode))
1151 return "file";
1152 else if (S_ISDIR (mode))
1153 return "directory";
1154 else if (S_ISCHR (mode))
1155 return "character device";
1156 else if (S_ISBLK (mode))
1157 return "block device";
1158 else if (S_ISFIFO (mode))
1159 return "named pipe";
1160 else if (S_ISLNK (mode))
1161 return "symbolic link";
1162 else if (S_ISSOCK (mode))
1163 return "socket";
1164 else
1165 return "file";
1166 }
1167
1168 static bool
1169 has_color_name (const char *str, const char *name)
1170 {
1171 char *p;
1172
1173 assert (strlen (str));
1174 assert (strlen (name));
1175
1176 if (!(*str == *name || *str == toupper (*name)))
1177 return false;
1178 else if (*(name + 1) != '\0'
1179 && !((p = strstr (str + 1, name + 1)) && p == str + 1))
1180 return false;
1181
1182 return true;
1183 }
1184
1185 static FILE *
1186 open_file (const char *file, const char *mode)
1187 {
1188 FILE *stream;
1189
1190 errno = 0;
1191 stream = fopen (file, mode);
1192 if (!stream)
1193 vfprintf_fail (formats[FMT_FILE], file, strerror (errno));
1194
1195 return stream;
1196 }
1197
1198 #define DO_VFPRINTF(fmt) \
1199 va_list ap; \
1200 fprintf (stderr, "%s: ", program_name); \
1201 va_start (ap, fmt); \
1202 vfprintf (stderr, fmt, ap); \
1203 va_end (ap); \
1204 fprintf (stderr, "\n"); \
1205
1206 static void
1207 vfprintf_diag (const char *fmt, ...)
1208 {
1209 DO_VFPRINTF (fmt);
1210 }
1211
1212 static void
1213 vfprintf_fail (const char *fmt, ...)
1214 {
1215 DO_VFPRINTF (fmt);
1216 exit (EXIT_FAILURE);
1217 }
1218
1219 static void
1220 stack_var (void ***list, unsigned int *stacked, unsigned int index, void *ptr)
1221 {
1222 /* nothing to stack */
1223 if (ptr == NULL)
1224 return;
1225 if (!*list)
1226 *list = xmalloc (sizeof (void *));
1227 else
1228 {
1229 unsigned int i;
1230 for (i = 0; i < *stacked; i++)
1231 if (!(*list)[i])
1232 {
1233 (*list)[i] = ptr;
1234 return; /* reused */
1235 }
1236 *list = xrealloc (*list, (*stacked + 1) * sizeof (void *));
1237 }
1238 (*list)[index] = ptr;
1239 (*stacked)++;
1240 }
1241
1242 static void
1243 release_var (void **list, unsigned int stacked, void **ptr)
1244 {
1245 unsigned int i;
1246 /* nothing to release */
1247 if (*ptr == NULL)
1248 return;
1249 for (i = 0; i < stacked; i++)
1250 if (list[i] == *ptr)
1251 {
1252 free (*ptr);
1253 *ptr = NULL;
1254 list[i] = NULL;
1255 return;
1256 }
1257 }