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