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