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