loksh-noxz

[discontinued] 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_out (stderr) without flush */
153void
154shellnof(const char *fmt, ...)
155{
156	va_list va;
157
158	if (!initio_done) /* shl_out may not be set up yet... */
159		return;
160	va_start(va, fmt);
161	shf_vfprintf(shl_out, fmt, va);
162	va_end(va);
163}
164
165
166/* printf to shl_stdout (stdout) */
167void
168shprintf(const char *fmt, ...)
169{
170	va_list va;
171
172	if (!shl_stdout_ok)
173		internal_errorf("shl_stdout not valid");
174	va_start(va, fmt);
175	shf_vfprintf(shl_stdout, fmt, va);
176	va_end(va);
177}
178
179#ifdef KSH_DEBUG
180static struct shf *kshdebug_shf;
181
182void
183kshdebug_init_(void)
184{
185	if (kshdebug_shf)
186		shf_close(kshdebug_shf);
187	kshdebug_shf = shf_open("/tmp/ksh-debug.log",
188	    O_WRONLY|O_APPEND|O_CREAT, 0600, SHF_WR|SHF_MAPHI);
189	if (kshdebug_shf) {
190		shf_fprintf(kshdebug_shf, "\nNew shell[pid %d]\n", getpid());
191		shf_flush(kshdebug_shf);
192	}
193}
194
195/* print to debugging log */
196void
197kshdebug_printf_(const char *fmt, ...)
198{
199	va_list va;
200
201	if (!kshdebug_shf)
202		return;
203	va_start(va, fmt);
204	shf_fprintf(kshdebug_shf, "[%d] ", getpid());
205	shf_vfprintf(kshdebug_shf, fmt, va);
206	va_end(va);
207	shf_flush(kshdebug_shf);
208}
209
210void
211kshdebug_dump_(const char *str, const void *mem, int nbytes)
212{
213	int i, j;
214	int nprow = 16;
215
216	if (!kshdebug_shf)
217		return;
218	shf_fprintf(kshdebug_shf, "[%d] %s:\n", getpid(), str);
219	for (i = 0; i < nbytes; i += nprow) {
220		char c = '\t';
221
222		for (j = 0; j < nprow && i + j < nbytes; j++) {
223			shf_fprintf(kshdebug_shf, "%c%02x", c,
224			    ((const unsigned char *) mem)[i + j]);
225			c = ' ';
226		}
227		shf_fprintf(kshdebug_shf, "\n");
228	}
229	shf_flush(kshdebug_shf);
230}
231#endif /* KSH_DEBUG */
232
233/* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
234int
235can_seek(int fd)
236{
237	struct stat statb;
238
239	return fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
240	    SHF_UNBUF : 0;
241}
242
243struct shf	shf_iob[3];
244
245void
246initio(void)
247{
248	shf_fdopen(1, SHF_WR, shl_stdout);	/* force buffer allocation */
249	shf_fdopen(2, SHF_WR, shl_out);
250	shf_fdopen(2, SHF_WR, shl_spare);	/* force buffer allocation */
251	initio_done = 1;
252	kshdebug_init();
253}
254
255/* A dup2() with error checking */
256int
257ksh_dup2(int ofd, int nfd, int errok)
258{
259	int ret = dup2(ofd, nfd);
260
261	if (ret == -1 && errno != EBADF && !errok)
262		errorf("too many files open in shell");
263
264	return ret;
265}
266
267/*
268 * move fd from user space (0<=fd<10) to shell space (fd>=10),
269 * set close-on-exec flag.
270 */
271int
272savefd(int fd)
273{
274	int nfd;
275
276	if (fd < FDBASE) {
277		nfd = fcntl(fd, F_DUPFD_CLOEXEC, FDBASE);
278		if (nfd == -1) {
279			if (errno == EBADF)
280				return -1;
281			else
282				errorf("too many files open in shell");
283		}
284	} else {
285		nfd = fd;
286		fcntl(nfd, F_SETFD, FD_CLOEXEC);
287	}
288	return nfd;
289}
290
291void
292restfd(int fd, int ofd)
293{
294	if (fd == 2)
295		shf_flush(&shf_iob[fd]);
296	if (ofd < 0)		/* original fd closed */
297		close(fd);
298	else if (fd != ofd) {
299		ksh_dup2(ofd, fd, true); /* XXX: what to do if this fails? */
300		close(ofd);
301	}
302}
303
304void
305openpipe(int *pv)
306{
307	int lpv[2];
308
309	if (pipe(lpv) == -1)
310		errorf("can't create pipe - try again");
311	pv[0] = savefd(lpv[0]);
312	if (pv[0] != lpv[0])
313		close(lpv[0]);
314	pv[1] = savefd(lpv[1]);
315	if (pv[1] != lpv[1])
316		close(lpv[1]);
317}
318
319void
320closepipe(int *pv)
321{
322	close(pv[0]);
323	close(pv[1]);
324}
325
326/* Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
327 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
328 */
329int
330check_fd(char *name, int mode, const char **emsgp)
331{
332	int fd, fl;
333
334	if (isdigit((unsigned char)name[0]) && !name[1]) {
335		fd = name[0] - '0';
336		if ((fl = fcntl(fd, F_GETFL)) == -1) {
337			if (emsgp)
338				*emsgp = "bad file descriptor";
339			return -1;
340		}
341		fl &= O_ACCMODE;
342		/* X_OK is a kludge to disable this check for dups (x<&1):
343		 * historical shells never did this check (XXX don't know what
344		 * posix has to say).
345		 */
346		if (!(mode & X_OK) && fl != O_RDWR &&
347		    (((mode & R_OK) && fl != O_RDONLY) ||
348		    ((mode & W_OK) && fl != O_WRONLY))) {
349			if (emsgp)
350				*emsgp = (fl == O_WRONLY) ?
351				    "fd not open for reading" :
352				    "fd not open for writing";
353			return -1;
354		}
355		return fd;
356	} else if (name[0] == 'p' && !name[1])
357		return coproc_getfd(mode, emsgp);
358	if (emsgp)
359		*emsgp = "illegal file descriptor name";
360	return -1;
361}
362
363/* Called once from main */
364void
365coproc_init(void)
366{
367	coproc.read = coproc.readw = coproc.write = -1;
368	coproc.njobs = 0;
369	coproc.id = 0;
370}
371
372/* Called by c_read() when eof is read - close fd if it is the co-process fd */
373void
374coproc_read_close(int fd)
375{
376	if (coproc.read >= 0 && fd == coproc.read) {
377		coproc_readw_close(fd);
378		close(coproc.read);
379		coproc.read = -1;
380	}
381}
382
383/* Called by c_read() and by iosetup() to close the other side of the
384 * read pipe, so reads will actually terminate.
385 */
386void
387coproc_readw_close(int fd)
388{
389	if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
390		close(coproc.readw);
391		coproc.readw = -1;
392	}
393}
394
395/* Called by c_print when a write to a fd fails with EPIPE and by iosetup
396 * when co-process input is dup'd
397 */
398void
399coproc_write_close(int fd)
400{
401	if (coproc.write >= 0 && fd == coproc.write) {
402		close(coproc.write);
403		coproc.write = -1;
404	}
405}
406
407/* Called to check for existence of/value of the co-process file descriptor.
408 * (Used by check_fd() and by c_read/c_print to deal with -p option).
409 */
410int
411coproc_getfd(int mode, const char **emsgp)
412{
413	int fd = (mode & R_OK) ? coproc.read : coproc.write;
414
415	if (fd >= 0)
416		return fd;
417	if (emsgp)
418		*emsgp = "no coprocess";
419	return -1;
420}
421
422/* called to close file descriptors related to the coprocess (if any)
423 * Should be called with SIGCHLD blocked.
424 */
425void
426coproc_cleanup(int reuse)
427{
428	/* This to allow co-processes to share output pipe */
429	if (!reuse || coproc.readw < 0 || coproc.read < 0) {
430		if (coproc.read >= 0) {
431			close(coproc.read);
432			coproc.read = -1;
433		}
434		if (coproc.readw >= 0) {
435			close(coproc.readw);
436			coproc.readw = -1;
437		}
438	}
439	if (coproc.write >= 0) {
440		close(coproc.write);
441		coproc.write = -1;
442	}
443}
444
445
446/*
447 * temporary files
448 */
449
450struct temp *
451maketemp(Area *ap, Temp_type type, struct temp **tlist)
452{
453	struct temp *tp;
454	int len;
455	int fd;
456	char *path;
457	const char *dir;
458
459	dir = tmpdir ? tmpdir : "/tmp";
460	/* The 20 + 20 is a paranoid worst case for pid/inc */
461	len = strlen(dir) + 3 + 20 + 20 + 1;
462	tp = alloc(sizeof(struct temp) + len, ap);
463	tp->name = path = (char *) &tp[1];
464	tp->shf = NULL;
465	tp->type = type;
466	shf_snprintf(path, len, "%s/shXXXXXXXX", dir);
467	fd = mkstemp(path);
468	if (fd >= 0)
469		tp->shf = shf_fdopen(fd, SHF_WR, NULL);
470	tp->pid = procpid;
471
472	tp->next = *tlist;
473	*tlist = tp;
474	return tp;
475}