1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Chris Torek.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include "namespace.h"
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <errno.h>
39#include <fcntl.h>
40#include <limits.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include "un-namespace.h"
44#include "local.h"
45#include "libc_private.h"
46
47#define	POS_ERR	(-(fpos_t)1)
48
49int
50fseek(FILE *fp, long offset, int whence)
51{
52	int ret;
53	int serrno = errno;
54
55	/* make sure stdio is set up */
56	if (!__sdidinit)
57		__sinit();
58
59	FLOCKFILE_CANCELSAFE(fp);
60	ret = _fseeko(fp, (off_t)offset, whence, 1);
61	FUNLOCKFILE_CANCELSAFE();
62	if (ret == 0)
63		errno = serrno;
64	return (ret);
65}
66
67int
68fseeko(FILE *fp, off_t offset, int whence)
69{
70	int ret;
71	int serrno = errno;
72
73	/* make sure stdio is set up */
74	if (!__sdidinit)
75		__sinit();
76
77	FLOCKFILE_CANCELSAFE(fp);
78	ret = _fseeko(fp, offset, whence, 0);
79	FUNLOCKFILE_CANCELSAFE();
80	if (ret == 0)
81		errno = serrno;
82	return (ret);
83}
84
85/*
86 * Seek the given file to the given offset.
87 * `Whence' must be one of the three SEEK_* macros.
88 */
89int
90_fseeko(FILE *fp, off_t offset, int whence, int ltest)
91{
92	fpos_t (*seekfn)(void *, fpos_t, int);
93	fpos_t target, curoff, ret;
94	size_t n;
95	struct stat st;
96	int havepos;
97
98	/*
99	 * Have to be able to seek.
100	 */
101	if ((seekfn = fp->_seek) == NULL) {
102		errno = ESPIPE;		/* historic practice */
103		return (-1);
104	}
105
106	/*
107	 * Change any SEEK_CUR to SEEK_SET, and check `whence' argument.
108	 * After this, whence is either SEEK_SET or SEEK_END.
109	 */
110	switch (whence) {
111
112	case SEEK_CUR:
113		/*
114		 * In order to seek relative to the current stream offset,
115		 * we have to first find the current stream offset via
116		 * ftell (see ftell for details).
117		 */
118		if (_ftello(fp, &curoff))
119			return (-1);
120		if (curoff < 0) {
121			/* Unspecified position because of ungetc() at 0 */
122			errno = ESPIPE;
123			return (-1);
124		}
125		if (offset > 0 && curoff > OFF_MAX - offset) {
126			errno = EOVERFLOW;
127			return (-1);
128		}
129		offset += curoff;
130		if (offset < 0) {
131			errno = EINVAL;
132			return (-1);
133		}
134		if (ltest && offset > LONG_MAX) {
135			errno = EOVERFLOW;
136			return (-1);
137		}
138		whence = SEEK_SET;
139		havepos = 1;
140		break;
141
142	case SEEK_SET:
143		if (offset < 0) {
144			errno = EINVAL;
145			return (-1);
146		}
147	case SEEK_END:
148		curoff = 0;		/* XXX just to keep gcc quiet */
149		havepos = 0;
150		break;
151
152	default:
153		errno = EINVAL;
154		return (-1);
155	}
156
157	/*
158	 * Can only optimise if:
159	 *	reading (and not reading-and-writing);
160	 *	not unbuffered; and
161	 *	this is a `regular' Unix file (and hence seekfn==__sseek).
162	 * We must check __NBF first, because it is possible to have __NBF
163	 * and __SOPT both set.
164	 */
165	if (fp->_bf._base == NULL)
166		__smakebuf(fp);
167	if (fp->_flags & (__SWR | __SRW | __SNBF | __SNPT))
168		goto dumb;
169	if ((fp->_flags & __SOPT) == 0) {
170		if (seekfn != __sseek ||
171		    fp->_file < 0 || _fstat(fp->_file, &st) ||
172		    (st.st_mode & S_IFMT) != S_IFREG) {
173			fp->_flags |= __SNPT;
174			goto dumb;
175		}
176		fp->_blksize = st.st_blksize;
177		fp->_flags |= __SOPT;
178	}
179
180	/*
181	 * We are reading; we can try to optimise.
182	 * Figure out where we are going and where we are now.
183	 */
184	if (whence == SEEK_SET)
185		target = offset;
186	else {
187		if (_fstat(fp->_file, &st))
188			goto dumb;
189		if (offset > 0 && st.st_size > OFF_MAX - offset) {
190			errno = EOVERFLOW;
191			return (-1);
192		}
193		target = st.st_size + offset;
194		if ((off_t)target < 0) {
195			errno = EINVAL;
196			return (-1);
197		}
198		if (ltest && (off_t)target > LONG_MAX) {
199			errno = EOVERFLOW;
200			return (-1);
201		}
202	}
203
204	if (!havepos && _ftello(fp, &curoff))
205		goto dumb;
206
207	/*
208	 * (If the buffer was modified, we have to
209	 * skip this; see fgetln.c.)
210	 */
211	if (fp->_flags & __SMOD)
212		goto abspos;
213
214	/*
215	 * Compute the number of bytes in the input buffer (pretending
216	 * that any ungetc() input has been discarded).  Adjust current
217	 * offset backwards by this count so that it represents the
218	 * file offset for the first byte in the current input buffer.
219	 */
220	if (HASUB(fp)) {
221		curoff += fp->_r;	/* kill off ungetc */
222		n = fp->_up - fp->_bf._base;
223		curoff -= n;
224		n += fp->_ur;
225	} else {
226		n = fp->_p - fp->_bf._base;
227		curoff -= n;
228		n += fp->_r;
229	}
230
231	/*
232	 * If the target offset is within the current buffer,
233	 * simply adjust the pointers, clear EOF, undo ungetc(),
234	 * and return.
235	 */
236	if (target >= curoff && target < curoff + n) {
237		size_t o = target - curoff;
238
239		fp->_p = fp->_bf._base + o;
240		fp->_r = n - o;
241		if (HASUB(fp))
242			FREEUB(fp);
243		fp->_flags &= ~__SEOF;
244		memset(&fp->_mbstate, 0, sizeof(mbstate_t));
245		return (0);
246	}
247
248abspos:
249	/*
250	 * The place we want to get to is not within the current buffer,
251	 * but we can still be kind to the kernel copyout mechanism.
252	 * By aligning the file offset to a block boundary, we can let
253	 * the kernel use the VM hardware to map pages instead of
254	 * copying bytes laboriously.  Using a block boundary also
255	 * ensures that we only read one block, rather than two.
256	 */
257	curoff = target & ~(fp->_blksize - 1);
258	if (_sseek(fp, curoff, SEEK_SET) == POS_ERR)
259		goto dumb;
260	fp->_r = 0;
261	fp->_p = fp->_bf._base;
262	if (HASUB(fp))
263		FREEUB(fp);
264	n = target - curoff;
265	if (n) {
266		if (__srefill(fp) || fp->_r < n)
267			goto dumb;
268		fp->_p += n;
269		fp->_r -= n;
270	}
271	fp->_flags &= ~__SEOF;
272	memset(&fp->_mbstate, 0, sizeof(mbstate_t));
273	return (0);
274
275	/*
276	 * We get here if we cannot optimise the seek ... just
277	 * do it.  Allow the seek function to change fp->_bf._base.
278	 */
279dumb:
280	if (__sflush(fp) ||
281	    (ret = _sseek(fp, (fpos_t)offset, whence)) == POS_ERR)
282		return (-1);
283	if (ltest && ret > LONG_MAX) {
284		fp->_flags |= __SERR;
285		errno = EOVERFLOW;
286		return (-1);
287	}
288	/* success: clear EOF indicator and discard ungetc() data */
289	if (HASUB(fp))
290		FREEUB(fp);
291	fp->_p = fp->_bf._base;
292	fp->_r = 0;
293	/* fp->_w = 0; */	/* unnecessary (I think...) */
294	fp->_flags &= ~__SEOF;
295	memset(&fp->_mbstate, 0, sizeof(mbstate_t));
296	return (0);
297}
298