xref: /freebsd/bin/cat/cat.c (revision 3f0164abf32b9b761e0a2cb4bdca3a8b84f156d4)
1 /*-
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kevin Fall.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if 0
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 #endif
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)cat.c	8.2 (Berkeley) 4/27/95";
44 #endif
45 #endif /* not lint */
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #ifndef NO_UDOM_SUPPORT
52 #include <sys/socket.h>
53 #include <sys/un.h>
54 #include <errno.h>
55 #endif
56 
57 #include <ctype.h>
58 #include <err.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <stddef.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 static int bflag, eflag, lflag, nflag, sflag, tflag, vflag;
68 static int rval;
69 static const char *filename;
70 
71 static void usage(void) __dead2;
72 static void scanfiles(char *argv[], int cooked);
73 static void cook_cat(FILE *);
74 static void raw_cat(int);
75 
76 #ifndef NO_UDOM_SUPPORT
77 static int udom_open(const char *path, int flags);
78 #endif
79 
80 /*
81  * Memory strategy threshold, in pages: if physmem is larger than this,
82  * use a large buffer.
83  */
84 #define	PHYSPAGES_THRESHOLD (32 * 1024)
85 
86 /* Maximum buffer size in bytes - do not allow it to grow larger than this. */
87 #define	BUFSIZE_MAX (2 * 1024 * 1024)
88 
89 /*
90  * Small (default) buffer size in bytes. It's inefficient for this to be
91  * smaller than MAXPHYS.
92  */
93 #define	BUFSIZE_SMALL (MAXPHYS)
94 
95 int
96 main(int argc, char *argv[])
97 {
98 	int ch;
99 	struct flock stdout_lock;
100 
101 	setlocale(LC_CTYPE, "");
102 
103 	while ((ch = getopt(argc, argv, "belnstuv")) != -1)
104 		switch (ch) {
105 		case 'b':
106 			bflag = nflag = 1;	/* -b implies -n */
107 			break;
108 		case 'e':
109 			eflag = vflag = 1;	/* -e implies -v */
110 			break;
111 		case 'l':
112 			lflag = 1;
113 			break;
114 		case 'n':
115 			nflag = 1;
116 			break;
117 		case 's':
118 			sflag = 1;
119 			break;
120 		case 't':
121 			tflag = vflag = 1;	/* -t implies -v */
122 			break;
123 		case 'u':
124 			setbuf(stdout, NULL);
125 			break;
126 		case 'v':
127 			vflag = 1;
128 			break;
129 		default:
130 			usage();
131 		}
132 	argv += optind;
133 
134 	if (lflag) {
135 		stdout_lock.l_len = 0;
136 		stdout_lock.l_start = 0;
137 		stdout_lock.l_type = F_WRLCK;
138 		stdout_lock.l_whence = SEEK_SET;
139 		if (fcntl(STDOUT_FILENO, F_SETLKW, &stdout_lock) == -1)
140 			err(EXIT_FAILURE, "stdout");
141 	}
142 
143 	if (bflag || eflag || nflag || sflag || tflag || vflag)
144 		scanfiles(argv, 1);
145 	else
146 		scanfiles(argv, 0);
147 	if (fclose(stdout))
148 		err(1, "stdout");
149 	exit(rval);
150 	/* NOTREACHED */
151 }
152 
153 static void
154 usage(void)
155 {
156 
157 	fprintf(stderr, "usage: cat [-belnstuv] [file ...]\n");
158 	exit(1);
159 	/* NOTREACHED */
160 }
161 
162 static void
163 scanfiles(char *argv[], int cooked)
164 {
165 	int fd, i;
166 	char *path;
167 	FILE *fp;
168 
169 	i = 0;
170 	while ((path = argv[i]) != NULL || i == 0) {
171 		if (path == NULL || strcmp(path, "-") == 0) {
172 			filename = "stdin";
173 			fd = STDIN_FILENO;
174 		} else {
175 			filename = path;
176 			fd = open(path, O_RDONLY);
177 #ifndef NO_UDOM_SUPPORT
178 			if (fd < 0 && errno == EOPNOTSUPP)
179 				fd = udom_open(path, O_RDONLY);
180 #endif
181 		}
182 		if (fd < 0) {
183 			warn("%s", path);
184 			rval = 1;
185 		} else if (cooked) {
186 			if (fd == STDIN_FILENO)
187 				cook_cat(stdin);
188 			else {
189 				fp = fdopen(fd, "r");
190 				cook_cat(fp);
191 				fclose(fp);
192 			}
193 		} else {
194 			raw_cat(fd);
195 			if (fd != STDIN_FILENO)
196 				close(fd);
197 		}
198 		if (path == NULL)
199 			break;
200 		++i;
201 	}
202 }
203 
204 static void
205 cook_cat(FILE *fp)
206 {
207 	int ch, gobble, line, prev;
208 
209 	/* Reset EOF condition on stdin. */
210 	if (fp == stdin && feof(stdin))
211 		clearerr(stdin);
212 
213 	line = gobble = 0;
214 	for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
215 		if (prev == '\n') {
216 			if (sflag) {
217 				if (ch == '\n') {
218 					if (gobble)
219 						continue;
220 					gobble = 1;
221 				} else
222 					gobble = 0;
223 			}
224 			if (nflag && (!bflag || ch != '\n')) {
225 				(void)fprintf(stdout, "%6d\t", ++line);
226 				if (ferror(stdout))
227 					break;
228 			}
229 		}
230 		if (ch == '\n') {
231 			if (eflag && putchar('$') == EOF)
232 				break;
233 		} else if (ch == '\t') {
234 			if (tflag) {
235 				if (putchar('^') == EOF || putchar('I') == EOF)
236 					break;
237 				continue;
238 			}
239 		} else if (vflag) {
240 			if (!isascii(ch) && !isprint(ch)) {
241 				if (putchar('M') == EOF || putchar('-') == EOF)
242 					break;
243 				ch = toascii(ch);
244 			}
245 			if (iscntrl(ch)) {
246 				if (putchar('^') == EOF ||
247 				    putchar(ch == '\177' ? '?' :
248 				    ch | 0100) == EOF)
249 					break;
250 				continue;
251 			}
252 		}
253 		if (putchar(ch) == EOF)
254 			break;
255 	}
256 	if (ferror(fp)) {
257 		warn("%s", filename);
258 		rval = 1;
259 		clearerr(fp);
260 	}
261 	if (ferror(stdout))
262 		err(1, "stdout");
263 }
264 
265 static void
266 raw_cat(int rfd)
267 {
268 	int off, wfd;
269 	ssize_t nr, nw;
270 	static size_t bsize;
271 	static char *buf = NULL;
272 	struct stat sbuf;
273 
274 	wfd = fileno(stdout);
275 	if (buf == NULL) {
276 		if (fstat(wfd, &sbuf))
277 			err(1, "stdout");
278 		if (S_ISREG(sbuf.st_mode)) {
279 			/* If there's plenty of RAM, use a large copy buffer */
280 			if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
281 				bsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
282 			else
283 				bsize = BUFSIZE_SMALL;
284 		} else
285 			bsize = MAX(sbuf.st_blksize,
286 			    (blksize_t)sysconf(_SC_PAGESIZE));
287 		if ((buf = malloc(bsize)) == NULL)
288 			err(1, "malloc() failure of IO buffer");
289 	}
290 	while ((nr = read(rfd, buf, bsize)) > 0)
291 		for (off = 0; nr; nr -= nw, off += nw)
292 			if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
293 				err(1, "stdout");
294 	if (nr < 0) {
295 		warn("%s", filename);
296 		rval = 1;
297 	}
298 }
299 
300 #ifndef NO_UDOM_SUPPORT
301 
302 static int
303 udom_open(const char *path, int flags)
304 {
305 	struct sockaddr_un sou;
306 	int fd;
307 	unsigned int len;
308 
309 	bzero(&sou, sizeof(sou));
310 
311 	/*
312 	 * Construct the unix domain socket address and attempt to connect
313 	 */
314 	fd = socket(AF_UNIX, SOCK_STREAM, 0);
315 	if (fd >= 0) {
316 		sou.sun_family = AF_UNIX;
317 		if ((len = strlcpy(sou.sun_path, path,
318 		    sizeof(sou.sun_path))) >= sizeof(sou.sun_path)) {
319 			errno = ENAMETOOLONG;
320 			return (-1);
321 		}
322 		len = offsetof(struct sockaddr_un, sun_path[len+1]);
323 
324 		if (connect(fd, (void *)&sou, len) < 0) {
325 			close(fd);
326 			fd = -1;
327 		}
328 	}
329 
330 	/*
331 	 * handle the open flags by shutting down appropriate directions
332 	 */
333 	if (fd >= 0) {
334 		switch(flags & O_ACCMODE) {
335 		case O_RDONLY:
336 			if (shutdown(fd, SHUT_WR) == -1)
337 				warn(NULL);
338 			break;
339 		case O_WRONLY:
340 			if (shutdown(fd, SHUT_RD) == -1)
341 				warn(NULL);
342 			break;
343 		default:
344 			break;
345 		}
346 	}
347 	return (fd);
348 }
349 
350 #endif
351