ksh: build with __EXTENSIONS__ to expose confstr
[unleashed.git] / bin / ksh / io.c
blob590d7beaadc5bdb2c699d8bf509e8b1d7421b48f
1 /* $OpenBSD: io.c,v 1.36 2018/01/16 22:52:32 jca Exp $ */
3 /*
4 * shell buffered IO and formatted output
5 */
7 #include <sys/stat.h>
9 #include <ctype.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <stdlib.h>
16 #include "sh.h"
18 static int initio_done;
21 * formatted output functions
25 /* A shell error occurred (eg, syntax error, etc.) */
26 void
27 errorf(const char *fmt, ...)
29 va_list va;
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);
40 shf_flush(shl_out);
41 unwind(LERROR);
44 /* like errorf(), but no unwind is done */
45 void
46 warningf(bool show_lineno, const char *fmt, ...)
48 va_list va;
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);
58 /* Used by built-in utilities to prefix shell and utility name to message
59 * (also unwinds environments for special builtins).
61 void
62 bi_errorf(const char *fmt, ...)
64 va_list va;
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);
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
83 if ((builtin_flag & SPEC_BI) ||
84 (Flag(FPOSIX) && (builtin_flag & KEEPASN))) {
85 builtin_argv0 = NULL;
86 unwind(LERROR);
90 static void
91 internal_error_vwarn(const char *fmt, va_list va)
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);
100 /* Warn when something that shouldn't happen does */
101 void
102 internal_warningf(const char *fmt, ...)
104 va_list va;
106 va_start(va, fmt);
107 internal_error_vwarn(fmt, va);
108 va_end(va);
111 /* Warn and unwind when something that shouldn't happen does */
112 __dead void
113 internal_errorf(const char *fmt, ...)
115 va_list va;
117 va_start(va, fmt);
118 internal_error_vwarn(fmt, va);
119 va_end(va);
120 unwind(LERROR);
123 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
124 void
125 error_prefix(int fileline)
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;
138 /* printf to shl_out (stderr) with flush */
139 void
140 shellf(const char *fmt, ...)
142 va_list va;
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);
152 /* printf to shl_stdout (stdout) */
153 void
154 shprintf(const char *fmt, ...)
156 va_list va;
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);
165 #ifdef KSH_DEBUG
166 static struct shf *kshdebug_shf;
168 void
169 kshdebug_init_(void)
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);
181 /* print to debugging log */
182 void
183 kshdebug_printf_(const char *fmt, ...)
185 va_list va;
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);
196 void
197 kshdebug_dump_(const char *str, const void *mem, int nbytes)
199 int i, j;
200 int nprow = 16;
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';
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 = ' ';
213 shf_fprintf(kshdebug_shf, "\n");
215 shf_flush(kshdebug_shf);
217 #endif /* KSH_DEBUG */
219 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
221 can_seek(int fd)
223 struct stat statb;
225 return fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
226 SHF_UNBUF : 0;
229 struct shf shf_iob[3];
231 void
232 initio(void)
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();
241 /* A dup2() with error checking */
243 ksh_dup2(int ofd, int nfd, int errok)
245 int ret = dup2(ofd, nfd);
247 if (ret < 0 && errno != EBADF && !errok)
248 errorf("too many files open in shell");
250 return ret;
254 * move fd from user space (0<=fd<10) to shell space (fd>=10),
255 * set close-on-exec flag.
258 savefd(int fd)
260 int nfd;
262 if (fd < FDBASE) {
263 nfd = fcntl(fd, F_DUPFD_CLOEXEC, FDBASE);
264 if (nfd < 0) {
265 if (errno == EBADF)
266 return -1;
267 else
268 errorf("too many files open in shell");
270 } else {
271 nfd = fd;
272 fcntl(nfd, F_SETFD, FD_CLOEXEC);
274 return nfd;
277 void
278 restfd(int fd, int ofd)
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);
290 void
291 openpipe(int *pv)
293 int lpv[2];
295 if (pipe(lpv) < 0)
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]);
305 void
306 closepipe(int *pv)
308 close(pv[0]);
309 close(pv[1]);
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.
316 check_fd(char *name, int mode, const char **emsgp)
318 int fd, fl;
320 if (isdigit((unsigned char)name[0]) && !name[1]) {
321 fd = name[0] - '0';
322 if ((fl = fcntl(fd, F_GETFL)) < 0) {
323 if (emsgp)
324 *emsgp = "bad file descriptor";
325 return -1;
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).
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;
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;
349 /* Called once from main */
350 void
351 coproc_init(void)
353 coproc.read = coproc.readw = coproc.write = -1;
354 coproc.njobs = 0;
355 coproc.id = 0;
358 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
359 void
360 coproc_read_close(int fd)
362 if (coproc.read >= 0 && fd == coproc.read) {
363 coproc_readw_close(fd);
364 close(coproc.read);
365 coproc.read = -1;
369 /* Called by c_read() and by iosetup() to close the other side of the
370 * read pipe, so reads will actually terminate.
372 void
373 coproc_readw_close(int fd)
375 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
376 close(coproc.readw);
377 coproc.readw = -1;
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
384 void
385 coproc_write_close(int fd)
387 if (coproc.write >= 0 && fd == coproc.write) {
388 close(coproc.write);
389 coproc.write = -1;
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).
397 coproc_getfd(int mode, const char **emsgp)
399 int fd = (mode & R_OK) ? coproc.read : coproc.write;
401 if (fd >= 0)
402 return fd;
403 if (emsgp)
404 *emsgp = "no coprocess";
405 return -1;
408 /* called to close file descriptors related to the coprocess (if any)
409 * Should be called with SIGCHLD blocked.
411 void
412 coproc_cleanup(int reuse)
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;
420 if (coproc.readw >= 0) {
421 close(coproc.readw);
422 coproc.readw = -1;
425 if (coproc.write >= 0) {
426 close(coproc.write);
427 coproc.write = -1;
433 * temporary files
436 struct temp *
437 maketemp(Area *ap, Temp_type type, struct temp **tlist)
439 struct temp *tp;
440 int len;
441 int fd;
442 char *path;
443 const char *dir;
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;
458 tp->next = *tlist;
459 *tlist = tp;
460 return tp;