xref: /freebsd/bin/cat/cat.c (revision 86c9d9918f1db7cdd968b60f8902466887bcd9e9)
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 #include <netdb.h>
56 #endif
57 
58 #include <ctype.h>
59 #include <err.h>
60 #include <fcntl.h>
61 #include <locale.h>
62 #include <stddef.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 
68 static int bflag, eflag, lflag, nflag, sflag, tflag, vflag;
69 static int rval;
70 static const char *filename;
71 
72 static void usage(void) __dead2;
73 static void scanfiles(char *argv[], int cooked);
74 static void cook_cat(FILE *);
75 static void raw_cat(int);
76 
77 #ifndef NO_UDOM_SUPPORT
78 static int udom_open(const char *path, int flags);
79 #endif
80 
81 /*
82  * Memory strategy threshold, in pages: if physmem is larger than this,
83  * use a large buffer.
84  */
85 #define	PHYSPAGES_THRESHOLD (32 * 1024)
86 
87 /* Maximum buffer size in bytes - do not allow it to grow larger than this. */
88 #define	BUFSIZE_MAX (2 * 1024 * 1024)
89 
90 /*
91  * Small (default) buffer size in bytes. It's inefficient for this to be
92  * smaller than MAXPHYS.
93  */
94 #define	BUFSIZE_SMALL (MAXPHYS)
95 
96 int
97 main(int argc, char *argv[])
98 {
99 	int ch;
100 	struct flock stdout_lock;
101 
102 	setlocale(LC_CTYPE, "");
103 
104 	while ((ch = getopt(argc, argv, "belnstuv")) != -1)
105 		switch (ch) {
106 		case 'b':
107 			bflag = nflag = 1;	/* -b implies -n */
108 			break;
109 		case 'e':
110 			eflag = vflag = 1;	/* -e implies -v */
111 			break;
112 		case 'l':
113 			lflag = 1;
114 			break;
115 		case 'n':
116 			nflag = 1;
117 			break;
118 		case 's':
119 			sflag = 1;
120 			break;
121 		case 't':
122 			tflag = vflag = 1;	/* -t implies -v */
123 			break;
124 		case 'u':
125 			setbuf(stdout, NULL);
126 			break;
127 		case 'v':
128 			vflag = 1;
129 			break;
130 		default:
131 			usage();
132 		}
133 	argv += optind;
134 
135 	if (lflag) {
136 		stdout_lock.l_len = 0;
137 		stdout_lock.l_start = 0;
138 		stdout_lock.l_type = F_WRLCK;
139 		stdout_lock.l_whence = SEEK_SET;
140 		if (fcntl(STDOUT_FILENO, F_SETLKW, &stdout_lock) == -1)
141 			err(EXIT_FAILURE, "stdout");
142 	}
143 
144 	if (bflag || eflag || nflag || sflag || tflag || vflag)
145 		scanfiles(argv, 1);
146 	else
147 		scanfiles(argv, 0);
148 	if (fclose(stdout))
149 		err(1, "stdout");
150 	exit(rval);
151 	/* NOTREACHED */
152 }
153 
154 static void
155 usage(void)
156 {
157 
158 	fprintf(stderr, "usage: cat [-belnstuv] [file ...]\n");
159 	exit(1);
160 	/* NOTREACHED */
161 }
162 
163 static void
164 scanfiles(char *argv[], int cooked)
165 {
166 	int fd, i;
167 	char *path;
168 	FILE *fp;
169 
170 	i = 0;
171 	fd = -1;
172 	while ((path = argv[i]) != NULL || i == 0) {
173 		if (path == NULL || strcmp(path, "-") == 0) {
174 			filename = "stdin";
175 			fd = STDIN_FILENO;
176 		} else {
177 			filename = path;
178 			fd = open(path, O_RDONLY);
179 #ifndef NO_UDOM_SUPPORT
180 			if (fd < 0 && errno == EOPNOTSUPP)
181 				fd = udom_open(path, O_RDONLY);
182 #endif
183 		}
184 		if (fd < 0) {
185 			warn("%s", path);
186 			rval = 1;
187 		} else if (cooked) {
188 			if (fd == STDIN_FILENO)
189 				cook_cat(stdin);
190 			else {
191 				fp = fdopen(fd, "r");
192 				cook_cat(fp);
193 				fclose(fp);
194 			}
195 		} else {
196 			raw_cat(fd);
197 			if (fd != STDIN_FILENO)
198 				close(fd);
199 		}
200 		if (path == NULL)
201 			break;
202 		++i;
203 	}
204 }
205 
206 static void
207 cook_cat(FILE *fp)
208 {
209 	int ch, gobble, line, prev;
210 
211 	/* Reset EOF condition on stdin. */
212 	if (fp == stdin && feof(stdin))
213 		clearerr(stdin);
214 
215 	line = gobble = 0;
216 	for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
217 		if (prev == '\n') {
218 			if (sflag) {
219 				if (ch == '\n') {
220 					if (gobble)
221 						continue;
222 					gobble = 1;
223 				} else
224 					gobble = 0;
225 			}
226 			if (nflag && (!bflag || ch != '\n')) {
227 				(void)fprintf(stdout, "%6d\t", ++line);
228 				if (ferror(stdout))
229 					break;
230 			}
231 		}
232 		if (ch == '\n') {
233 			if (eflag && putchar('$') == EOF)
234 				break;
235 		} else if (ch == '\t') {
236 			if (tflag) {
237 				if (putchar('^') == EOF || putchar('I') == EOF)
238 					break;
239 				continue;
240 			}
241 		} else if (vflag) {
242 			if (!isascii(ch) && !isprint(ch)) {
243 				if (putchar('M') == EOF || putchar('-') == EOF)
244 					break;
245 				ch = toascii(ch);
246 			}
247 			if (iscntrl(ch)) {
248 				if (putchar('^') == EOF ||
249 				    putchar(ch == '\177' ? '?' :
250 				    ch | 0100) == EOF)
251 					break;
252 				continue;
253 			}
254 		}
255 		if (putchar(ch) == EOF)
256 			break;
257 	}
258 	if (ferror(fp)) {
259 		warn("%s", filename);
260 		rval = 1;
261 		clearerr(fp);
262 	}
263 	if (ferror(stdout))
264 		err(1, "stdout");
265 }
266 
267 static void
268 raw_cat(int rfd)
269 {
270 	int off, wfd;
271 	ssize_t nr, nw;
272 	static size_t bsize;
273 	static char *buf = NULL;
274 	struct stat sbuf;
275 
276 	wfd = fileno(stdout);
277 	if (buf == NULL) {
278 		if (fstat(wfd, &sbuf))
279 			err(1, "stdout");
280 		if (S_ISREG(sbuf.st_mode)) {
281 			/* If there's plenty of RAM, use a large copy buffer */
282 			if (sysconf(_SC_PHYS_PAGES) > PHYSPAGES_THRESHOLD)
283 				bsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
284 			else
285 				bsize = BUFSIZE_SMALL;
286 		} else
287 			bsize = MAX(sbuf.st_blksize,
288 			    (blksize_t)sysconf(_SC_PAGESIZE));
289 		if ((buf = malloc(bsize)) == NULL)
290 			err(1, "malloc() failure of IO buffer");
291 	}
292 	while ((nr = read(rfd, buf, bsize)) > 0)
293 		for (off = 0; nr; nr -= nw, off += nw)
294 			if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
295 				err(1, "stdout");
296 	if (nr < 0) {
297 		warn("%s", filename);
298 		rval = 1;
299 	}
300 }
301 
302 #ifndef NO_UDOM_SUPPORT
303 
304 static int
305 udom_open(const char *path, int flags)
306 {
307 	struct addrinfo hints, *res, *res0;
308 	char rpath[PATH_MAX];
309 	int fd = -1;
310 	int error;
311 
312 	/*
313 	 * Construct the unix domain socket address and attempt to connect.
314 	 */
315 	bzero(&hints, sizeof(hints));
316 	hints.ai_family = AF_LOCAL;
317 	if (realpath(path, rpath) == NULL)
318 		return (-1);
319 	error = getaddrinfo(rpath, NULL, &hints, &res0);
320 	if (error) {
321 		warn("%s", gai_strerror(error));
322 		errno = EINVAL;
323 		return (-1);
324 	}
325 	for (res = res0; res != NULL; res = res->ai_next) {
326 		fd = socket(res->ai_family, res->ai_socktype,
327 		    res->ai_protocol);
328 		if (fd < 0) {
329 			freeaddrinfo(res0);
330 			return (-1);
331 		}
332 		error = connect(fd, res->ai_addr, res->ai_addrlen);
333 		if (error == 0)
334 			break;
335 		else {
336 			close(fd);
337 			fd = -1;
338 		}
339 	}
340 	freeaddrinfo(res0);
341 
342 	/*
343 	 * handle the open flags by shutting down appropriate directions
344 	 */
345 	if (fd >= 0) {
346 		switch(flags & O_ACCMODE) {
347 		case O_RDONLY:
348 			if (shutdown(fd, SHUT_WR) == -1)
349 				warn(NULL);
350 			break;
351 		case O_WRONLY:
352 			if (shutdown(fd, SHUT_RD) == -1)
353 				warn(NULL);
354 			break;
355 		default:
356 			break;
357 		}
358 	}
359 	return (fd);
360 }
361 
362 #endif
363