cat.c revision 240407
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
35static 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
43static char sccsid[] = "@(#)cat.c	8.2 (Berkeley) 4/27/95";
44#endif
45#endif /* not lint */
46#include <sys/cdefs.h>
47__FBSDID("$FreeBSD: stable/9/bin/cat/cat.c 240407 2012-09-12 15:59:03Z jh $");
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
67int bflag, eflag, nflag, sflag, tflag, vflag;
68int rval;
69const char *filename;
70
71static void usage(void);
72static void scanfiles(char *argv[], int cooked);
73static void cook_cat(FILE *);
74static void raw_cat(int);
75
76#ifndef NO_UDOM_SUPPORT
77static 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
95int
96main(int argc, char *argv[])
97{
98	int ch;
99
100	setlocale(LC_CTYPE, "");
101
102	while ((ch = getopt(argc, argv, "benstuv")) != -1)
103		switch (ch) {
104		case 'b':
105			bflag = nflag = 1;	/* -b implies -n */
106			break;
107		case 'e':
108			eflag = vflag = 1;	/* -e implies -v */
109			break;
110		case 'n':
111			nflag = 1;
112			break;
113		case 's':
114			sflag = 1;
115			break;
116		case 't':
117			tflag = vflag = 1;	/* -t implies -v */
118			break;
119		case 'u':
120			setbuf(stdout, NULL);
121			break;
122		case 'v':
123			vflag = 1;
124			break;
125		default:
126			usage();
127		}
128	argv += optind;
129
130	if (bflag || eflag || nflag || sflag || tflag || vflag)
131		scanfiles(argv, 1);
132	else
133		scanfiles(argv, 0);
134	if (fclose(stdout))
135		err(1, "stdout");
136	exit(rval);
137	/* NOTREACHED */
138}
139
140static void
141usage(void)
142{
143	fprintf(stderr, "usage: cat [-benstuv] [file ...]\n");
144	exit(1);
145	/* NOTREACHED */
146}
147
148static void
149scanfiles(char *argv[], int cooked)
150{
151	int fd, i;
152	char *path;
153	FILE *fp;
154
155	i = 0;
156	while ((path = argv[i]) != NULL || i == 0) {
157		if (path == NULL || strcmp(path, "-") == 0) {
158			filename = "stdin";
159			fd = STDIN_FILENO;
160		} else {
161			filename = path;
162			fd = open(path, O_RDONLY);
163#ifndef NO_UDOM_SUPPORT
164			if (fd < 0 && errno == EOPNOTSUPP)
165				fd = udom_open(path, O_RDONLY);
166#endif
167		}
168		if (fd < 0) {
169			warn("%s", path);
170			rval = 1;
171		} else if (cooked) {
172			if (fd == STDIN_FILENO)
173				cook_cat(stdin);
174			else {
175				fp = fdopen(fd, "r");
176				cook_cat(fp);
177				fclose(fp);
178			}
179		} else {
180			raw_cat(fd);
181			if (fd != STDIN_FILENO)
182				close(fd);
183		}
184		if (path == NULL)
185			break;
186		++i;
187	}
188}
189
190static void
191cook_cat(FILE *fp)
192{
193	int ch, gobble, line, prev;
194
195	/* Reset EOF condition on stdin. */
196	if (fp == stdin && feof(stdin))
197		clearerr(stdin);
198
199	line = gobble = 0;
200	for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
201		if (prev == '\n') {
202			if (sflag) {
203				if (ch == '\n') {
204					if (gobble)
205						continue;
206					gobble = 1;
207				} else
208					gobble = 0;
209			}
210			if (nflag && (!bflag || ch != '\n')) {
211				(void)fprintf(stdout, "%6d\t", ++line);
212				if (ferror(stdout))
213					break;
214			}
215		}
216		if (ch == '\n') {
217			if (eflag && putchar('$') == EOF)
218				break;
219		} else if (ch == '\t') {
220			if (tflag) {
221				if (putchar('^') == EOF || putchar('I') == EOF)
222					break;
223				continue;
224			}
225		} else if (vflag) {
226			if (!isascii(ch) && !isprint(ch)) {
227				if (putchar('M') == EOF || putchar('-') == EOF)
228					break;
229				ch = toascii(ch);
230			}
231			if (iscntrl(ch)) {
232				if (putchar('^') == EOF ||
233				    putchar(ch == '\177' ? '?' :
234				    ch | 0100) == EOF)
235					break;
236				continue;
237			}
238		}
239		if (putchar(ch) == EOF)
240			break;
241	}
242	if (ferror(fp)) {
243		warn("%s", filename);
244		rval = 1;
245		clearerr(fp);
246	}
247	if (ferror(stdout))
248		err(1, "stdout");
249}
250
251static void
252raw_cat(int rfd)
253{
254	int off, wfd;
255	ssize_t nr, nw;
256	static size_t bsize;
257	static char *buf = NULL;
258	struct stat sbuf;
259
260	wfd = fileno(stdout);
261	if (buf == NULL) {
262		if (fstat(wfd, &sbuf))
263			err(1, "%s", filename);
264		if (S_ISREG(sbuf.st_mode)) {
265			/* If there's plenty of RAM, use a large copy buffer */
266			if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
267				bsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
268			else
269				bsize = BUFSIZE_SMALL;
270		} else
271			bsize = MAX(sbuf.st_blksize,
272			    (blksize_t)sysconf(_SC_PAGESIZE));
273		if ((buf = malloc(bsize)) == NULL)
274			err(1, "malloc() failure of IO buffer");
275	}
276	while ((nr = read(rfd, buf, bsize)) > 0)
277		for (off = 0; nr; nr -= nw, off += nw)
278			if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
279				err(1, "stdout");
280	if (nr < 0) {
281		warn("%s", filename);
282		rval = 1;
283	}
284}
285
286#ifndef NO_UDOM_SUPPORT
287
288static int
289udom_open(const char *path, int flags)
290{
291	struct sockaddr_un sou;
292	int fd;
293	unsigned int len;
294
295	bzero(&sou, sizeof(sou));
296
297	/*
298	 * Construct the unix domain socket address and attempt to connect
299	 */
300	fd = socket(AF_UNIX, SOCK_STREAM, 0);
301	if (fd >= 0) {
302		sou.sun_family = AF_UNIX;
303		if ((len = strlcpy(sou.sun_path, path,
304		    sizeof(sou.sun_path))) >= sizeof(sou.sun_path)) {
305			errno = ENAMETOOLONG;
306			return (-1);
307		}
308		len = offsetof(struct sockaddr_un, sun_path[len+1]);
309
310		if (connect(fd, (void *)&sou, len) < 0) {
311			close(fd);
312			fd = -1;
313		}
314	}
315
316	/*
317	 * handle the open flags by shutting down appropriate directions
318	 */
319	if (fd >= 0) {
320		switch(flags & O_ACCMODE) {
321		case O_RDONLY:
322			if (shutdown(fd, SHUT_WR) == -1)
323				warn(NULL);
324			break;
325		case O_WRONLY:
326			if (shutdown(fd, SHUT_RD) == -1)
327				warn(NULL);
328			break;
329		default:
330			break;
331		}
332	}
333	return (fd);
334}
335
336#endif
337