Audit bb_common_bufsiz usage, add script which looks for misuse.
[oweals/busybox.git] / coreutils / catv.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * cat -v implementation for busybox
4  *
5  * Copyright (C) 2006 Rob Landley <rob@landley.net>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 /* See "Cat -v considered harmful" at
11  * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
12
13 #include "libbb.h"
14
15 int catv_main(int argc, char **argv);
16 int catv_main(int argc, char **argv)
17 {
18         int retval = EXIT_SUCCESS, fd;
19         unsigned flags;
20
21         flags = getopt32(argc, argv, "etv");
22 #define CATV_OPT_e (1<<0)
23 #define CATV_OPT_t (1<<1)
24 #define CATV_OPT_v (1<<2)
25         flags ^= CATV_OPT_v;
26
27         argv += optind;
28         do {
29                 /* Read from stdin if there's nothing else to do. */
30                 fd = 0;
31                 if (*argv && 0 > (fd = xopen(*argv, O_RDONLY)))
32                         retval = EXIT_FAILURE;
33                 else for (;;) {
34                         int i, res;
35
36 #define read_buf bb_common_bufsiz1
37                         res = read(fd, read_buf, COMMON_BUFSIZE);
38                         if (res < 0)
39                                 retval = EXIT_FAILURE;
40                         if (res < 1)
41                                 break;
42                         for (i = 0; i < res; i++) {
43                                 char c = read_buf[i];
44
45                                 if (c > 126 && (flags & CATV_OPT_v)) {
46                                         if (c == 127) {
47                                                 printf("^?");
48                                                 continue;
49                                         } else {
50                                                 printf("M-");
51                                                 c -= 128;
52                                         }
53                                 }
54                                 if (c < 32) {
55                                         if (c == 10) {
56                                                 if (flags & CATV_OPT_e)
57                                                         putchar('$');
58                                         } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
59                                                 printf("^%c", c+'@');
60                                                 continue;
61                                         }
62                                 }
63                                 putchar(c);
64                         }
65                 }
66                 if (ENABLE_FEATURE_CLEAN_UP && fd)
67                         close(fd);
68         } while (*++argv);
69
70         fflush_stdout_and_exit(retval);
71 }