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