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#ifdef F_DUPFD_CLOEXEC
278 nfd = fcntl(fd, F_DUPFD_CLOEXEC, FDBASE);
279 if (nfd == -1) {
280 if (errno == EBADF)
281 return -1;
282 else
283 errorf("too many files open in shell");
284 }
285#else
286 nfd = fcntl(fd, F_DUPFD, FDBASE);
287 if (nfd < 0) {
288 if (errno == EBADF)
289 return -1;
290 else
291 errorf("too many files open in shell");
292 }
293 fcntl(nfd, F_SETFD, FD_CLOEXEC);
294#endif
295 } else {
296 nfd = fd;
297 fcntl(nfd, F_SETFD, FD_CLOEXEC);
298 }
299 return nfd;
300}
301
302void
303restfd(int fd, int ofd)
304{
305 if (fd == 2)
306 shf_flush(&shf_iob[fd]);
307 if (ofd < 0) /* original fd closed */
308 close(fd);
309 else if (fd != ofd) {
310 ksh_dup2(ofd, fd, true); /* XXX: what to do if this fails? */
311 close(ofd);
312 }
313}
314
315void
316openpipe(int *pv)
317{
318 int lpv[2];
319
320 if (pipe(lpv) == -1)
321 errorf("can't create pipe - try again");
322 pv[0] = savefd(lpv[0]);
323 if (pv[0] != lpv[0])
324 close(lpv[0]);
325 pv[1] = savefd(lpv[1]);
326 if (pv[1] != lpv[1])
327 close(lpv[1]);
328}
329
330void
331closepipe(int *pv)
332{
333 close(pv[0]);
334 close(pv[1]);
335}
336
337/* Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
338 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
339 */
340int
341check_fd(char *name, int mode, const char **emsgp)
342{
343 int fd, fl;
344
345 if (isdigit((unsigned char)name[0]) && !name[1]) {
346 fd = name[0] - '0';
347 if ((fl = fcntl(fd, F_GETFL)) == -1) {
348 if (emsgp)
349 *emsgp = "bad file descriptor";
350 return -1;
351 }
352 fl &= O_ACCMODE;
353 /* X_OK is a kludge to disable this check for dups (x<&1):
354 * historical shells never did this check (XXX don't know what
355 * posix has to say).
356 */
357 if (!(mode & X_OK) && fl != O_RDWR &&
358 (((mode & R_OK) && fl != O_RDONLY) ||
359 ((mode & W_OK) && fl != O_WRONLY))) {
360 if (emsgp)
361 *emsgp = (fl == O_WRONLY) ?
362 "fd not open for reading" :
363 "fd not open for writing";
364 return -1;
365 }
366 return fd;
367 } else if (name[0] == 'p' && !name[1])
368 return coproc_getfd(mode, emsgp);
369 if (emsgp)
370 *emsgp = "illegal file descriptor name";
371 return -1;
372}
373
374/* Called once from main */
375void
376coproc_init(void)
377{
378 coproc.read = coproc.readw = coproc.write = -1;
379 coproc.njobs = 0;
380 coproc.id = 0;
381}
382
383/* Called by c_read() when eof is read - close fd if it is the co-process fd */
384void
385coproc_read_close(int fd)
386{
387 if (coproc.read >= 0 && fd == coproc.read) {
388 coproc_readw_close(fd);
389 close(coproc.read);
390 coproc.read = -1;
391 }
392}
393
394/* Called by c_read() and by iosetup() to close the other side of the
395 * read pipe, so reads will actually terminate.
396 */
397void
398coproc_readw_close(int fd)
399{
400 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
401 close(coproc.readw);
402 coproc.readw = -1;
403 }
404}
405
406/* Called by c_print when a write to a fd fails with EPIPE and by iosetup
407 * when co-process input is dup'd
408 */
409void
410coproc_write_close(int fd)
411{
412 if (coproc.write >= 0 && fd == coproc.write) {
413 close(coproc.write);
414 coproc.write = -1;
415 }
416}
417
418/* Called to check for existence of/value of the co-process file descriptor.
419 * (Used by check_fd() and by c_read/c_print to deal with -p option).
420 */
421int
422coproc_getfd(int mode, const char **emsgp)
423{
424 int fd = (mode & R_OK) ? coproc.read : coproc.write;
425
426 if (fd >= 0)
427 return fd;
428 if (emsgp)
429 *emsgp = "no coprocess";
430 return -1;
431}
432
433/* called to close file descriptors related to the coprocess (if any)
434 * Should be called with SIGCHLD blocked.
435 */
436void
437coproc_cleanup(int reuse)
438{
439 /* This to allow co-processes to share output pipe */
440 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
441 if (coproc.read >= 0) {
442 close(coproc.read);
443 coproc.read = -1;
444 }
445 if (coproc.readw >= 0) {
446 close(coproc.readw);
447 coproc.readw = -1;
448 }
449 }
450 if (coproc.write >= 0) {
451 close(coproc.write);
452 coproc.write = -1;
453 }
454}
455
456
457/*
458 * temporary files
459 */
460
461struct temp *
462maketemp(Area *ap, Temp_type type, struct temp **tlist)
463{
464 struct temp *tp;
465 int len;
466 int fd;
467 char *path;
468 const char *dir;
469
470 dir = tmpdir ? tmpdir : "/tmp";
471 /* The 20 + 20 is a paranoid worst case for pid/inc */
472 len = strlen(dir) + 3 + 20 + 20 + 1;
473 tp = alloc(sizeof(struct temp) + len, ap);
474 tp->name = path = (char *) &tp[1];
475 tp->shf = NULL;
476 tp->type = type;
477 shf_snprintf(path, len, "%s/shXXXXXXXX", dir);
478 fd = mkstemp(path);
479 if (fd >= 0)
480 tp->shf = shf_fdopen(fd, SHF_WR, NULL);
481 tp->pid = procpid;
482
483 tp->next = *tlist;
484 *tlist = tp;
485 return tp;
486}