loksh-noxz

[fork] a Linux port of OpenBSD's ksh
git clone https://noxz.tech/git/loksh-noxz.git
Log | Files | README

io.c
1/*	$OpenBSD: io.c,v 1.38 2019/07/24 14:33:16 bcallah Exp $	*/
2
3/*
4 * shell buffered IO and formatted output
5 */
6
7#include <sys/stat.h>
8
9#include <ctype.h>
10#include <errno.h>
11#include <fcntl.h>
12#include <stdlib.h>
13#include <string.h>
14#include <unistd.h>
15
16#include "sh.h"
17
18static int initio_done;
19
20/*
21 * formatted output functions
22 */
23
24
25/* A shell error occurred (eg, syntax error, etc.) */
26void
27errorf(const char *fmt, ...)
28{
29	va_list va;
30
31	shl_stdout_ok = 0;	/* debugging: note that stdout not valid */
32	exstat = 1;
33	if (fmt != NULL && *fmt != '\0') {
34		error_prefix(true);
35		va_start(va, fmt);
36		shf_vfprintf(shl_out, fmt, va);
37		va_end(va);
38		shf_putchar('\n', shl_out);
39	}
40	shf_flush(shl_out);
41	unwind(LERROR);
42}
43
44/* like errorf(), but no unwind is done */
45void
46warningf(bool show_lineno, const char *fmt, ...)
47{
48	va_list va;
49
50	error_prefix(show_lineno);
51	va_start(va, fmt);
52	shf_vfprintf(shl_out, fmt, va);
53	va_end(va);
54	shf_putchar('\n', shl_out);
55	shf_flush(shl_out);
56}
57
58/* Used by built-in utilities to prefix shell and utility name to message
59 * (also unwinds environments for special builtins).
60 */
61void
62bi_errorf(const char *fmt, ...)
63{
64	va_list va;
65
66	shl_stdout_ok = 0;	/* debugging: note that stdout not valid */
67	exstat = 1;
68	if (fmt != NULL && *fmt != '\0') {
69		error_prefix(true);
70		/* not set when main() calls parse_args() */
71		if (builtin_argv0)
72			shf_fprintf(shl_out, "%s: ", builtin_argv0);
73		va_start(va, fmt);
74		shf_vfprintf(shl_out, fmt, va);
75		va_end(va);
76		shf_putchar('\n', shl_out);
77	}
78	shf_flush(shl_out);
79	/* POSIX special builtins and ksh special builtins cause
80	 * non-interactive shells to exit.
81	 * XXX odd use of KEEPASN; also may not want LERROR here
82	 */
83	if ((builtin_flag & SPEC_BI) ||
84	    (Flag(FPOSIX) && (builtin_flag & KEEPASN))) {
85		builtin_argv0 = NULL;
86		unwind(LERROR);
87	}
88}
89
90static void
91internal_error_vwarn(const char *fmt, va_list va)
92{
93	error_prefix(true);
94	shf_fprintf(shl_out, "internal error: ");
95	shf_vfprintf(shl_out, fmt, va);
96	shf_putchar('\n', shl_out);
97	shf_flush(shl_out);
98}
99
100/* Warn when something that shouldn't happen does */
101void
102internal_warningf(const char *fmt, ...)
103{
104	va_list va;
105
106	va_start(va, fmt);
107	internal_error_vwarn(fmt, va);
108	va_end(va);
109}
110
111/* Warn and unwind when something that shouldn't happen does */
112__dead void
113internal_errorf(const char *fmt, ...)
114{
115	va_list va;
116
117	va_start(va, fmt);
118	internal_error_vwarn(fmt, va);
119	va_end(va);
120	unwind(LERROR);
121}
122
123/* used by error reporting functions to print "ksh: .kshrc[25]: " */
124void
125error_prefix(int fileline)
126{
127	/* Avoid foo: foo[2]: ... */
128	if (!fileline || !source || !source->file ||
129	    strcmp(source->file, kshname) != 0)
130		shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
131	if (fileline && source && source->file != NULL) {
132		shf_fprintf(shl_out, "%s[%d]: ", source->file,
133		    source->errline > 0 ? source->errline : source->line);
134		source->errline = 0;
135	}
136}
137
138/* printf to shl_out (stderr) with flush */
139void
140shellf(const char *fmt, ...)
141{
142	va_list va;
143
144	if (!initio_done) /* shl_out may not be set up yet... */
145		return;
146	va_start(va, fmt);
147	shf_vfprintf(shl_out, fmt, va);
148	va_end(va);
149	shf_flush(shl_out);
150}
151
152/* printf to shl_stdout (stdout) */
153void
154shprintf(const char *fmt, ...)
155{
156	va_list va;
157
158	if (!shl_stdout_ok)
159		internal_errorf("shl_stdout not valid");
160	va_start(va, fmt);
161	shf_vfprintf(shl_stdout, fmt, va);
162	va_end(va);
163}
164
165#ifdef KSH_DEBUG
166static struct shf *kshdebug_shf;
167
168void
169kshdebug_init_(void)
170{
171	if (kshdebug_shf)
172		shf_close(kshdebug_shf);
173	kshdebug_shf = shf_open("/tmp/ksh-debug.log",
174	    O_WRONLY|O_APPEND|O_CREAT, 0600, SHF_WR|SHF_MAPHI);
175	if (kshdebug_shf) {
176		shf_fprintf(kshdebug_shf, "\nNew shell[pid %d]\n", getpid());
177		shf_flush(kshdebug_shf);
178	}
179}
180
181/* print to debugging log */
182void
183kshdebug_printf_(const char *fmt, ...)
184{
185	va_list va;
186
187	if (!kshdebug_shf)
188		return;
189	va_start(va, fmt);
190	shf_fprintf(kshdebug_shf, "[%d] ", getpid());
191	shf_vfprintf(kshdebug_shf, fmt, va);
192	va_end(va);
193	shf_flush(kshdebug_shf);
194}
195
196void
197kshdebug_dump_(const char *str, const void *mem, int nbytes)
198{
199	int i, j;
200	int nprow = 16;
201
202	if (!kshdebug_shf)
203		return;
204	shf_fprintf(kshdebug_shf, "[%d] %s:\n", getpid(), str);
205	for (i = 0; i < nbytes; i += nprow) {
206		char c = '\t';
207
208		for (j = 0; j < nprow && i + j < nbytes; j++) {
209			shf_fprintf(kshdebug_shf, "%c%02x", c,
210			    ((const unsigned char *) mem)[i + j]);
211			c = ' ';
212		}
213		shf_fprintf(kshdebug_shf, "\n");
214	}
215	shf_flush(kshdebug_shf);
216}
217#endif /* KSH_DEBUG */
218
219/* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
220int
221can_seek(int fd)
222{
223	struct stat statb;
224
225	return fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
226	    SHF_UNBUF : 0;
227}
228
229struct shf	shf_iob[3];
230
231void
232initio(void)
233{
234	shf_fdopen(1, SHF_WR, shl_stdout);	/* force buffer allocation */
235	shf_fdopen(2, SHF_WR, shl_out);
236	shf_fdopen(2, SHF_WR, shl_spare);	/* force buffer allocation */
237	initio_done = 1;
238	kshdebug_init();
239}
240
241/* A dup2() with error checking */
242int
243ksh_dup2(int ofd, int nfd, int errok)
244{
245	int ret = dup2(ofd, nfd);
246
247	if (ret == -1 && errno != EBADF && !errok)
248		errorf("too many files open in shell");
249
250	return ret;
251}
252
253/*
254 * move fd from user space (0<=fd<10) to shell space (fd>=10),
255 * set close-on-exec flag.
256 */
257int
258savefd(int fd)
259{
260	int nfd;
261
262	if (fd < FDBASE) {
263		nfd = fcntl(fd, F_DUPFD_CLOEXEC, FDBASE);
264		if (nfd == -1) {
265			if (errno == EBADF)
266				return -1;
267			else
268				errorf("too many files open in shell");
269		}
270	} else {
271		nfd = fd;
272		fcntl(nfd, F_SETFD, FD_CLOEXEC);
273	}
274	return nfd;
275}
276
277void
278restfd(int fd, int ofd)
279{
280	if (fd == 2)
281		shf_flush(&shf_iob[fd]);
282	if (ofd < 0)		/* original fd closed */
283		close(fd);
284	else if (fd != ofd) {
285		ksh_dup2(ofd, fd, true); /* XXX: what to do if this fails? */
286		close(ofd);
287	}
288}
289
290void
291openpipe(int *pv)
292{
293	int lpv[2];
294
295	if (pipe(lpv) == -1)
296		errorf("can't create pipe - try again");
297	pv[0] = savefd(lpv[0]);
298	if (pv[0] != lpv[0])
299		close(lpv[0]);
300	pv[1] = savefd(lpv[1]);
301	if (pv[1] != lpv[1])
302		close(lpv[1]);
303}
304
305void
306closepipe(int *pv)
307{
308	close(pv[0]);
309	close(pv[1]);
310}
311
312/* Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
313 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
314 */
315int
316check_fd(char *name, int mode, const char **emsgp)
317{
318	int fd, fl;
319
320	if (isdigit((unsigned char)name[0]) && !name[1]) {
321		fd = name[0] - '0';
322		if ((fl = fcntl(fd, F_GETFL)) == -1) {
323			if (emsgp)
324				*emsgp = "bad file descriptor";
325			return -1;
326		}
327		fl &= O_ACCMODE;
328		/* X_OK is a kludge to disable this check for dups (x<&1):
329		 * historical shells never did this check (XXX don't know what
330		 * posix has to say).
331		 */
332		if (!(mode & X_OK) && fl != O_RDWR &&
333		    (((mode & R_OK) && fl != O_RDONLY) ||
334		    ((mode & W_OK) && fl != O_WRONLY))) {
335			if (emsgp)
336				*emsgp = (fl == O_WRONLY) ?
337				    "fd not open for reading" :
338				    "fd not open for writing";
339			return -1;
340		}
341		return fd;
342	} else if (name[0] == 'p' && !name[1])
343		return coproc_getfd(mode, emsgp);
344	if (emsgp)
345		*emsgp = "illegal file descriptor name";
346	return -1;
347}
348
349/* Called once from main */
350void
351coproc_init(void)
352{
353	coproc.read = coproc.readw = coproc.write = -1;
354	coproc.njobs = 0;
355	coproc.id = 0;
356}
357
358/* Called by c_read() when eof is read - close fd if it is the co-process fd */
359void
360coproc_read_close(int fd)
361{
362	if (coproc.read >= 0 && fd == coproc.read) {
363		coproc_readw_close(fd);
364		close(coproc.read);
365		coproc.read = -1;
366	}
367}
368
369/* Called by c_read() and by iosetup() to close the other side of the
370 * read pipe, so reads will actually terminate.
371 */
372void
373coproc_readw_close(int fd)
374{
375	if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
376		close(coproc.readw);
377		coproc.readw = -1;
378	}
379}
380
381/* Called by c_print when a write to a fd fails with EPIPE and by iosetup
382 * when co-process input is dup'd
383 */
384void
385coproc_write_close(int fd)
386{
387	if (coproc.write >= 0 && fd == coproc.write) {
388		close(coproc.write);
389		coproc.write = -1;
390	}
391}
392
393/* Called to check for existence of/value of the co-process file descriptor.
394 * (Used by check_fd() and by c_read/c_print to deal with -p option).
395 */
396int
397coproc_getfd(int mode, const char **emsgp)
398{
399	int fd = (mode & R_OK) ? coproc.read : coproc.write;
400
401	if (fd >= 0)
402		return fd;
403	if (emsgp)
404		*emsgp = "no coprocess";
405	return -1;
406}
407
408/* called to close file descriptors related to the coprocess (if any)
409 * Should be called with SIGCHLD blocked.
410 */
411void
412coproc_cleanup(int reuse)
413{
414	/* This to allow co-processes to share output pipe */
415	if (!reuse || coproc.readw < 0 || coproc.read < 0) {
416		if (coproc.read >= 0) {
417			close(coproc.read);
418			coproc.read = -1;
419		}
420		if (coproc.readw >= 0) {
421			close(coproc.readw);
422			coproc.readw = -1;
423		}
424	}
425	if (coproc.write >= 0) {
426		close(coproc.write);
427		coproc.write = -1;
428	}
429}
430
431
432/*
433 * temporary files
434 */
435
436struct temp *
437maketemp(Area *ap, Temp_type type, struct temp **tlist)
438{
439	struct temp *tp;
440	int len;
441	int fd;
442	char *path;
443	const char *dir;
444
445	dir = tmpdir ? tmpdir : "/tmp";
446	/* The 20 + 20 is a paranoid worst case for pid/inc */
447	len = strlen(dir) + 3 + 20 + 20 + 1;
448	tp = alloc(sizeof(struct temp) + len, ap);
449	tp->name = path = (char *) &tp[1];
450	tp->shf = NULL;
451	tp->type = type;
452	shf_snprintf(path, len, "%s/shXXXXXXXX", dir);
453	fd = mkstemp(path);
454	if (fd >= 0)
455		tp->shf = shf_fdopen(fd, SHF_WR, NULL);
456	tp->pid = procpid;
457
458	tp->next = *tlist;
459	*tlist = tp;
460	return tp;
461}