1/*
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1980, 1987, 1992, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#ifndef lint
33static const char copyright[] =
34"@(#) Copyright (c) 1980, 1987, 1992, 1993\n\
35	The Regents of the University of California.  All rights reserved.\n";
36#endif /* not lint */
37
38#ifndef lint
39#if 0
40static char sccsid[] = "@(#)head.c	8.2 (Berkeley) 5/4/95";
41#endif
42#endif /* not lint */
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD$");
45
46#include <sys/capsicum.h>
47#include <sys/types.h>
48
49#include <capsicum_helpers.h>
50#include <ctype.h>
51#include <err.h>
52#include <errno.h>
53#include <getopt.h>
54#include <inttypes.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58#include <unistd.h>
59
60#include <libcasper.h>
61#include <casper/cap_fileargs.h>
62
63/*
64 * head - give the first few lines of a stream or of each of a set of files
65 *
66 * Bill Joy UCB August 24, 1977
67 */
68
69static void head(FILE *, int);
70static void head_bytes(FILE *, off_t);
71static void obsolete(char *[]);
72static void usage(void);
73
74static const struct option long_opts[] =
75{
76	{"bytes",	required_argument,	NULL, 'c'},
77	{"lines",	required_argument,	NULL, 'n'},
78	{NULL,		no_argument,		NULL, 0}
79};
80
81int
82main(int argc, char *argv[])
83{
84	FILE *fp;
85	char *ep;
86	off_t bytecnt;
87	int ch, first, linecnt, eval;
88	fileargs_t *fa;
89	cap_rights_t rights;
90
91	linecnt = -1;
92	eval = 0;
93	bytecnt = -1;
94
95	obsolete(argv);
96	while ((ch = getopt_long(argc, argv, "+n:c:", long_opts, NULL)) != -1) {
97		switch(ch) {
98		case 'c':
99			bytecnt = strtoimax(optarg, &ep, 10);
100			if (*ep || bytecnt <= 0)
101				errx(1, "illegal byte count -- %s", optarg);
102			break;
103		case 'n':
104			linecnt = strtol(optarg, &ep, 10);
105			if (*ep || linecnt <= 0)
106				errx(1, "illegal line count -- %s", optarg);
107			break;
108		case '?':
109		default:
110			usage();
111			/* NOTREACHED */
112		}
113	}
114	argc -= optind;
115	argv += optind;
116
117	fa = fileargs_init(argc, argv, O_RDONLY, 0,
118	    cap_rights_init(&rights, CAP_READ, CAP_FSTAT, CAP_FCNTL), FA_OPEN);
119	if (fa == NULL)
120		err(1, "unable to init casper");
121
122	caph_cache_catpages();
123	if (caph_limit_stdio() < 0 || caph_enter_casper() < 0)
124		err(1, "unable to enter capability mode");
125
126	if (linecnt != -1 && bytecnt != -1)
127		errx(1, "can't combine line and byte counts");
128	if (linecnt == -1)
129		linecnt = 10;
130	if (*argv != NULL) {
131		for (first = 1; *argv != NULL; ++argv) {
132			if ((fp = fileargs_fopen(fa, *argv, "r")) == NULL) {
133				warn("%s", *argv);
134				eval = 1;
135				continue;
136			}
137			if (argc > 1) {
138				(void)printf("%s==> %s <==\n",
139				    first ? "" : "\n", *argv);
140				first = 0;
141			}
142			if (bytecnt == -1)
143				head(fp, linecnt);
144			else
145				head_bytes(fp, bytecnt);
146			(void)fclose(fp);
147		}
148	} else if (bytecnt == -1)
149		head(stdin, linecnt);
150	else
151		head_bytes(stdin, bytecnt);
152
153	fileargs_free(fa);
154	exit(eval);
155}
156
157static void
158head(FILE *fp, int cnt)
159{
160	char *cp;
161	size_t error, readlen;
162
163	while (cnt != 0 && (cp = fgetln(fp, &readlen)) != NULL) {
164		error = fwrite(cp, sizeof(char), readlen, stdout);
165		if (error != readlen)
166			err(1, "stdout");
167		cnt--;
168	}
169}
170
171static void
172head_bytes(FILE *fp, off_t cnt)
173{
174	char buf[4096];
175	size_t readlen;
176
177	while (cnt) {
178		if ((uintmax_t)cnt < sizeof(buf))
179			readlen = cnt;
180		else
181			readlen = sizeof(buf);
182		readlen = fread(buf, sizeof(char), readlen, fp);
183		if (readlen == 0)
184			break;
185		if (fwrite(buf, sizeof(char), readlen, stdout) != readlen)
186			err(1, "stdout");
187		cnt -= readlen;
188	}
189}
190
191static void
192obsolete(char *argv[])
193{
194	char *ap;
195
196	while ((ap = *++argv)) {
197		/* Return if "--" or not "-[0-9]*". */
198		if (ap[0] != '-' || ap[1] == '-' || !isdigit(ap[1]))
199			return;
200		if ((ap = malloc(strlen(*argv) + 2)) == NULL)
201			err(1, NULL);
202		ap[0] = '-';
203		ap[1] = 'n';
204		(void)strcpy(ap + 2, *argv + 1);
205		*argv = ap;
206	}
207}
208
209static void
210usage(void)
211{
212
213	(void)fprintf(stderr, "usage: head [-n lines | -c bytes] [file ...]\n");
214	exit(1);
215}
216