• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$OpenBSD: shf.c,v 1.15 2006/04/02 00:48:33 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011
5  *	Thorsten Glaser <tg@mirbsd.org>
6  *
7  * Provided that these terms and disclaimer and all copyright notices
8  * are retained or reproduced in an accompanying document, permission
9  * is granted to deal in this work without restriction, including un-
10  * limited rights to use, publicly perform, distribute, sell, modify,
11  * merge, give away, or sublicence.
12  *
13  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
14  * the utmost extent permitted by applicable law, neither express nor
15  * implied; without malicious intent or gross negligence. In no event
16  * may a licensor, author or contributor be held liable for indirect,
17  * direct, other damage, loss, or other issues arising in any way out
18  * of dealing in the work, even if advised of the possibility of such
19  * damage or existence of a defect, except proven that it results out
20  * of said person's immediate fault when using the work as intended.
21  *-
22  * Use %zX instead of %p and floating point isn't supported at all.
23  */
24 
25 #include "sh.h"
26 
27 __RCSID("$MirOS: src/bin/mksh/shf.c,v 1.44 2011/09/07 15:24:20 tg Exp $");
28 
29 /* flags to shf_emptybuf() */
30 #define EB_READSW	0x01	/* about to switch to reading */
31 #define EB_GROW		0x02	/* grow buffer if necessary (STRING+DYNAMIC) */
32 
33 /*
34  * Replacement stdio routines. Stdio is too flakey on too many machines
35  * to be useful when you have multiple processes using the same underlying
36  * file descriptors.
37  */
38 
39 static int shf_fillbuf(struct shf *);
40 static int shf_emptybuf(struct shf *, int);
41 
42 /*
43  * Open a file. First three args are for open(), last arg is flags for
44  * this package. Returns NULL if file could not be opened, or if a dup
45  * fails.
46  */
47 struct shf *
shf_open(const char * name,int oflags,int mode,int sflags)48 shf_open(const char *name, int oflags, int mode, int sflags)
49 {
50 	struct shf *shf;
51 	ssize_t bsize =
52 	    /* at most 512 */
53 	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
54 	int fd;
55 
56 	/* Done before open so if alloca fails, fd won't be lost. */
57 	shf = alloc(sizeof(struct shf) + bsize, ATEMP);
58 	shf->areap = ATEMP;
59 	shf->buf = (unsigned char *)&shf[1];
60 	shf->bsize = bsize;
61 	shf->flags = SHF_ALLOCS;
62 	/* Rest filled in by reopen. */
63 
64 	fd = open(name, oflags, mode);
65 	if (fd < 0) {
66 		afree(shf, shf->areap);
67 		return (NULL);
68 	}
69 	if ((sflags & SHF_MAPHI) && fd < FDBASE) {
70 		int nfd;
71 
72 		nfd = fcntl(fd, F_DUPFD, FDBASE);
73 		close(fd);
74 		if (nfd < 0) {
75 			afree(shf, shf->areap);
76 			return (NULL);
77 		}
78 		fd = nfd;
79 	}
80 	sflags &= ~SHF_ACCMODE;
81 	sflags |= (oflags & O_ACCMODE) == O_RDONLY ? SHF_RD :
82 	    ((oflags & O_ACCMODE) == O_WRONLY ? SHF_WR : SHF_RDWR);
83 
84 	return (shf_reopen(fd, sflags, shf));
85 }
86 
87 /* helper function for shf_fdopen and shf_reopen */
88 static void
shf_open_hlp(int fd,int * sflagsp,const char * where)89 shf_open_hlp(int fd, int *sflagsp, const char *where)
90 {
91 	int sflags = *sflagsp;
92 
93 	/* use fcntl() to figure out correct read/write flags */
94 	if (sflags & SHF_GETFL) {
95 		int flags = fcntl(fd, F_GETFL, 0);
96 
97 		if (flags < 0)
98 			/* will get an error on first read/write */
99 			sflags |= SHF_RDWR;
100 		else {
101 			switch (flags & O_ACCMODE) {
102 			case O_RDONLY:
103 				sflags |= SHF_RD;
104 				break;
105 			case O_WRONLY:
106 				sflags |= SHF_WR;
107 				break;
108 			case O_RDWR:
109 				sflags |= SHF_RDWR;
110 				break;
111 			}
112 		}
113 		*sflagsp = sflags;
114 	}
115 
116 	if (!(sflags & (SHF_RD | SHF_WR)))
117 		internal_errorf("%s: %s", where, "missing read/write");
118 }
119 
120 /* Set up the shf structure for a file descriptor. Doesn't fail. */
121 struct shf *
shf_fdopen(int fd,int sflags,struct shf * shf)122 shf_fdopen(int fd, int sflags, struct shf *shf)
123 {
124 	ssize_t bsize =
125 	    /* at most 512 */
126 	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
127 
128 	shf_open_hlp(fd, &sflags, "shf_fdopen");
129 	if (shf) {
130 		if (bsize) {
131 			shf->buf = alloc(bsize, ATEMP);
132 			sflags |= SHF_ALLOCB;
133 		} else
134 			shf->buf = NULL;
135 	} else {
136 		shf = alloc(sizeof(struct shf) + bsize, ATEMP);
137 		shf->buf = (unsigned char *)&shf[1];
138 		sflags |= SHF_ALLOCS;
139 	}
140 	shf->areap = ATEMP;
141 	shf->fd = fd;
142 	shf->rp = shf->wp = shf->buf;
143 	shf->rnleft = 0;
144 	shf->rbsize = bsize;
145 	shf->wnleft = 0; /* force call to shf_emptybuf() */
146 	shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize;
147 	shf->flags = sflags;
148 	shf->errnosv = 0;
149 	shf->bsize = bsize;
150 	if (sflags & SHF_CLEXEC)
151 		fcntl(fd, F_SETFD, FD_CLOEXEC);
152 	return (shf);
153 }
154 
155 /* Set up an existing shf (and buffer) to use the given fd */
156 struct shf *
shf_reopen(int fd,int sflags,struct shf * shf)157 shf_reopen(int fd, int sflags, struct shf *shf)
158 {
159 	ssize_t bsize =
160 	    /* at most 512 */
161 	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
162 
163 	shf_open_hlp(fd, &sflags, "shf_reopen");
164 	if (!shf || !shf->buf || shf->bsize < bsize)
165 		internal_errorf("%s: %s", "shf_reopen", "bad shf/buf/bsize");
166 
167 	/* assumes shf->buf and shf->bsize already set up */
168 	shf->fd = fd;
169 	shf->rp = shf->wp = shf->buf;
170 	shf->rnleft = 0;
171 	shf->rbsize = bsize;
172 	shf->wnleft = 0; /* force call to shf_emptybuf() */
173 	shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize;
174 	shf->flags = (shf->flags & (SHF_ALLOCS | SHF_ALLOCB)) | sflags;
175 	shf->errnosv = 0;
176 	if (sflags & SHF_CLEXEC)
177 		fcntl(fd, F_SETFD, FD_CLOEXEC);
178 	return (shf);
179 }
180 
181 /*
182  * Open a string for reading or writing. If reading, bsize is the number
183  * of bytes that can be read. If writing, bsize is the maximum number of
184  * bytes that can be written. If shf is not NULL, it is filled in and
185  * returned, if it is NULL, shf is allocated. If writing and buf is NULL
186  * and SHF_DYNAMIC is set, the buffer is allocated (if bsize > 0, it is
187  * used for the initial size). Doesn't fail.
188  * When writing, a byte is reserved for a trailing NUL - see shf_sclose().
189  */
190 struct shf *
shf_sopen(char * buf,ssize_t bsize,int sflags,struct shf * shf)191 shf_sopen(char *buf, ssize_t bsize, int sflags, struct shf *shf)
192 {
193 	/* can't have a read+write string */
194 	if (!(!(sflags & SHF_RD) ^ !(sflags & SHF_WR)))
195 		internal_errorf("%s: flags 0x%X", "shf_sopen", sflags);
196 
197 	if (!shf) {
198 		shf = alloc(sizeof(struct shf), ATEMP);
199 		sflags |= SHF_ALLOCS;
200 	}
201 	shf->areap = ATEMP;
202 	if (!buf && (sflags & SHF_WR) && (sflags & SHF_DYNAMIC)) {
203 		if (bsize <= 0)
204 			bsize = 64;
205 		sflags |= SHF_ALLOCB;
206 		buf = alloc(bsize, shf->areap);
207 	}
208 	shf->fd = -1;
209 	shf->buf = shf->rp = shf->wp = (unsigned char *)buf;
210 	shf->rnleft = bsize;
211 	shf->rbsize = bsize;
212 	shf->wnleft = bsize - 1;	/* space for a '\0' */
213 	shf->wbsize = bsize;
214 	shf->flags = sflags | SHF_STRING;
215 	shf->errnosv = 0;
216 	shf->bsize = bsize;
217 
218 	return (shf);
219 }
220 
221 /* Flush and close file descriptor, free the shf structure */
222 int
shf_close(struct shf * shf)223 shf_close(struct shf *shf)
224 {
225 	int ret = 0;
226 
227 	if (shf->fd >= 0) {
228 		ret = shf_flush(shf);
229 		if (close(shf->fd) < 0)
230 			ret = EOF;
231 	}
232 	if (shf->flags & SHF_ALLOCS)
233 		afree(shf, shf->areap);
234 	else if (shf->flags & SHF_ALLOCB)
235 		afree(shf->buf, shf->areap);
236 
237 	return (ret);
238 }
239 
240 /* Flush and close file descriptor, don't free file structure */
241 int
shf_fdclose(struct shf * shf)242 shf_fdclose(struct shf *shf)
243 {
244 	int ret = 0;
245 
246 	if (shf->fd >= 0) {
247 		ret = shf_flush(shf);
248 		if (close(shf->fd) < 0)
249 			ret = EOF;
250 		shf->rnleft = 0;
251 		shf->rp = shf->buf;
252 		shf->wnleft = 0;
253 		shf->fd = -1;
254 	}
255 
256 	return (ret);
257 }
258 
259 /*
260  * Close a string - if it was opened for writing, it is NUL terminated;
261  * returns a pointer to the string and frees shf if it was allocated
262  * (does not free string if it was allocated).
263  */
264 char *
shf_sclose(struct shf * shf)265 shf_sclose(struct shf *shf)
266 {
267 	unsigned char *s = shf->buf;
268 
269 	/* NUL terminate */
270 	if (shf->flags & SHF_WR) {
271 		shf->wnleft++;
272 		shf_putc('\0', shf);
273 	}
274 	if (shf->flags & SHF_ALLOCS)
275 		afree(shf, shf->areap);
276 	return ((char *)s);
277 }
278 
279 /*
280  * Un-read what has been read but not examined, or write what has been
281  * buffered. Returns 0 for success, EOF for (write) error.
282  */
283 int
shf_flush(struct shf * shf)284 shf_flush(struct shf *shf)
285 {
286 	if (shf->flags & SHF_STRING)
287 		return ((shf->flags & SHF_WR) ? EOF : 0);
288 
289 	if (shf->fd < 0)
290 		internal_errorf("%s: %s", "shf_flush", "no fd");
291 
292 	if (shf->flags & SHF_ERROR) {
293 		errno = shf->errnosv;
294 		return (EOF);
295 	}
296 
297 	if (shf->flags & SHF_READING) {
298 		shf->flags &= ~(SHF_EOF | SHF_READING);
299 		if (shf->rnleft > 0) {
300 			lseek(shf->fd, (off_t)-shf->rnleft, SEEK_CUR);
301 			shf->rnleft = 0;
302 			shf->rp = shf->buf;
303 		}
304 		return (0);
305 	} else if (shf->flags & SHF_WRITING)
306 		return (shf_emptybuf(shf, 0));
307 
308 	return (0);
309 }
310 
311 /*
312  * Write out any buffered data. If currently reading, flushes the read
313  * buffer. Returns 0 for success, EOF for (write) error.
314  */
315 static int
shf_emptybuf(struct shf * shf,int flags)316 shf_emptybuf(struct shf *shf, int flags)
317 {
318 	int ret = 0;
319 
320 	if (!(shf->flags & SHF_STRING) && shf->fd < 0)
321 		internal_errorf("%s: %s", "shf_emptybuf", "no fd");
322 
323 	if (shf->flags & SHF_ERROR) {
324 		errno = shf->errnosv;
325 		return (EOF);
326 	}
327 
328 	if (shf->flags & SHF_READING) {
329 		if (flags & EB_READSW)
330 			/* doesn't happen */
331 			return (0);
332 		ret = shf_flush(shf);
333 		shf->flags &= ~SHF_READING;
334 	}
335 	if (shf->flags & SHF_STRING) {
336 		unsigned char *nbuf;
337 
338 		/*
339 		 * Note that we assume SHF_ALLOCS is not set if
340 		 * SHF_ALLOCB is set... (changing the shf pointer could
341 		 * cause problems)
342 		 */
343 		if (!(flags & EB_GROW) || !(shf->flags & SHF_DYNAMIC) ||
344 		    !(shf->flags & SHF_ALLOCB))
345 			return (EOF);
346 		/* allocate more space for buffer */
347 		nbuf = aresize2(shf->buf, 2, shf->wbsize, shf->areap);
348 		shf->rp = nbuf + (shf->rp - shf->buf);
349 		shf->wp = nbuf + (shf->wp - shf->buf);
350 		shf->rbsize += shf->wbsize;
351 		shf->wnleft += shf->wbsize;
352 		shf->wbsize <<= 1;
353 		shf->buf = nbuf;
354 	} else {
355 		if (shf->flags & SHF_WRITING) {
356 			ssize_t n, ntowrite = shf->wp - shf->buf;
357 			unsigned char *buf = shf->buf;
358 
359 			while (ntowrite > 0) {
360 				n = write(shf->fd, buf, ntowrite);
361 				if (n < 0) {
362 					if (errno == EINTR &&
363 					    !(shf->flags & SHF_INTERRUPT))
364 						continue;
365 					shf->flags |= SHF_ERROR;
366 					shf->errnosv = errno;
367 					shf->wnleft = 0;
368 					if (buf != shf->buf) {
369 						/*
370 						 * allow a second flush
371 						 * to work
372 						 */
373 						memmove(shf->buf, buf,
374 						    ntowrite);
375 						shf->wp = shf->buf + ntowrite;
376 					}
377 					return (EOF);
378 				}
379 				buf += n;
380 				ntowrite -= n;
381 			}
382 			if (flags & EB_READSW) {
383 				shf->wp = shf->buf;
384 				shf->wnleft = 0;
385 				shf->flags &= ~SHF_WRITING;
386 				return (0);
387 			}
388 		}
389 		shf->wp = shf->buf;
390 		shf->wnleft = shf->wbsize;
391 	}
392 	shf->flags |= SHF_WRITING;
393 
394 	return (ret);
395 }
396 
397 /* Fill up a read buffer. Returns EOF for a read error, 0 otherwise. */
398 static int
shf_fillbuf(struct shf * shf)399 shf_fillbuf(struct shf *shf)
400 {
401 	ssize_t n;
402 
403 	if (shf->flags & SHF_STRING)
404 		return (0);
405 
406 	if (shf->fd < 0)
407 		internal_errorf("%s: %s", "shf_fillbuf", "no fd");
408 
409 	if (shf->flags & (SHF_EOF | SHF_ERROR)) {
410 		if (shf->flags & SHF_ERROR)
411 			errno = shf->errnosv;
412 		return (EOF);
413 	}
414 
415 	if ((shf->flags & SHF_WRITING) && shf_emptybuf(shf, EB_READSW) == EOF)
416 		return (EOF);
417 
418 	shf->flags |= SHF_READING;
419 
420 	shf->rp = shf->buf;
421 	while (/* CONSTCOND */ 1) {
422 		n = blocking_read(shf->fd, (char *)shf->buf, shf->rbsize);
423 		if (n < 0 && errno == EINTR && !(shf->flags & SHF_INTERRUPT))
424 			continue;
425 		break;
426 	}
427 	if (n < 0) {
428 		shf->flags |= SHF_ERROR;
429 		shf->errnosv = errno;
430 		shf->rnleft = 0;
431 		shf->rp = shf->buf;
432 		return (EOF);
433 	}
434 	if ((shf->rnleft = n) == 0)
435 		shf->flags |= SHF_EOF;
436 	return (0);
437 }
438 
439 /*
440  * Read a buffer from shf. Returns the number of bytes read into buf, if
441  * no bytes were read, returns 0 if end of file was seen, EOF if a read
442  * error occurred.
443  */
444 ssize_t
shf_read(char * buf,ssize_t bsize,struct shf * shf)445 shf_read(char *buf, ssize_t bsize, struct shf *shf)
446 {
447 	ssize_t ncopy, orig_bsize = bsize;
448 
449 	if (!(shf->flags & SHF_RD))
450 		internal_errorf("%s: flags 0x%X", "shf_read", shf->flags);
451 
452 	if (bsize <= 0)
453 		internal_errorf("%s: %s %zd", "shf_write", "bsize", bsize);
454 
455 	while (bsize > 0) {
456 		if (shf->rnleft == 0 &&
457 		    (shf_fillbuf(shf) == EOF || shf->rnleft == 0))
458 			break;
459 		ncopy = shf->rnleft;
460 		if (ncopy > bsize)
461 			ncopy = bsize;
462 		memcpy(buf, shf->rp, ncopy);
463 		buf += ncopy;
464 		bsize -= ncopy;
465 		shf->rp += ncopy;
466 		shf->rnleft -= ncopy;
467 	}
468 	/* Note: fread(3S) returns 0 for errors - this doesn't */
469 	return (orig_bsize == bsize ? (shf_error(shf) ? EOF : 0) :
470 	    orig_bsize - bsize);
471 }
472 
473 /*
474  * Read up to a newline or EOF. The newline is put in buf; buf is always
475  * NUL terminated. Returns NULL on read error or if nothing was read
476  * before end of file, returns a pointer to the NUL byte in buf
477  * otherwise.
478  */
479 char *
shf_getse(char * buf,ssize_t bsize,struct shf * shf)480 shf_getse(char *buf, ssize_t bsize, struct shf *shf)
481 {
482 	unsigned char *end;
483 	ssize_t ncopy;
484 	char *orig_buf = buf;
485 
486 	if (!(shf->flags & SHF_RD))
487 		internal_errorf("%s: flags 0x%X", "shf_getse", shf->flags);
488 
489 	if (bsize <= 0)
490 		return (NULL);
491 
492 	/* save room for NUL */
493 	--bsize;
494 	do {
495 		if (shf->rnleft == 0) {
496 			if (shf_fillbuf(shf) == EOF)
497 				return (NULL);
498 			if (shf->rnleft == 0) {
499 				*buf = '\0';
500 				return (buf == orig_buf ? NULL : buf);
501 			}
502 		}
503 		end = (unsigned char *)memchr((char *)shf->rp, '\n',
504 		    shf->rnleft);
505 		ncopy = end ? end - shf->rp + 1 : shf->rnleft;
506 		if (ncopy > bsize)
507 			ncopy = bsize;
508 		memcpy(buf, (char *) shf->rp, ncopy);
509 		shf->rp += ncopy;
510 		shf->rnleft -= ncopy;
511 		buf += ncopy;
512 		bsize -= ncopy;
513 	} while (!end && bsize);
514 	*buf = '\0';
515 	return (buf);
516 }
517 
518 /* Returns the char read. Returns EOF for error and end of file. */
519 int
shf_getchar(struct shf * shf)520 shf_getchar(struct shf *shf)
521 {
522 	if (!(shf->flags & SHF_RD))
523 		internal_errorf("%s: flags 0x%X", "shf_getchar", shf->flags);
524 
525 	if (shf->rnleft == 0 && (shf_fillbuf(shf) == EOF || shf->rnleft == 0))
526 		return (EOF);
527 	--shf->rnleft;
528 	return (*shf->rp++);
529 }
530 
531 /*
532  * Put a character back in the input stream. Returns the character if
533  * successful, EOF if there is no room.
534  */
535 int
shf_ungetc(int c,struct shf * shf)536 shf_ungetc(int c, struct shf *shf)
537 {
538 	if (!(shf->flags & SHF_RD))
539 		internal_errorf("%s: flags 0x%X", "shf_ungetc", shf->flags);
540 
541 	if ((shf->flags & SHF_ERROR) || c == EOF ||
542 	    (shf->rp == shf->buf && shf->rnleft))
543 		return (EOF);
544 
545 	if ((shf->flags & SHF_WRITING) && shf_emptybuf(shf, EB_READSW) == EOF)
546 		return (EOF);
547 
548 	if (shf->rp == shf->buf)
549 		shf->rp = shf->buf + shf->rbsize;
550 	if (shf->flags & SHF_STRING) {
551 		/*
552 		 * Can unget what was read, but not something different;
553 		 * we don't want to modify a string.
554 		 */
555 		if (shf->rp[-1] != c)
556 			return (EOF);
557 		shf->flags &= ~SHF_EOF;
558 		shf->rp--;
559 		shf->rnleft++;
560 		return (c);
561 	}
562 	shf->flags &= ~SHF_EOF;
563 	*--(shf->rp) = c;
564 	shf->rnleft++;
565 	return (c);
566 }
567 
568 /*
569  * Write a character. Returns the character if successful, EOF if the
570  * char could not be written.
571  */
572 int
shf_putchar(int c,struct shf * shf)573 shf_putchar(int c, struct shf *shf)
574 {
575 	if (!(shf->flags & SHF_WR))
576 		internal_errorf("%s: flags 0x%X", "shf_putchar", shf->flags);
577 
578 	if (c == EOF)
579 		return (EOF);
580 
581 	if (shf->flags & SHF_UNBUF) {
582 		unsigned char cc = (unsigned char)c;
583 		ssize_t n;
584 
585 		if (shf->fd < 0)
586 			internal_errorf("%s: %s", "shf_putchar", "no fd");
587 		if (shf->flags & SHF_ERROR) {
588 			errno = shf->errnosv;
589 			return (EOF);
590 		}
591 		while ((n = write(shf->fd, &cc, 1)) != 1)
592 			if (n < 0) {
593 				if (errno == EINTR &&
594 				    !(shf->flags & SHF_INTERRUPT))
595 					continue;
596 				shf->flags |= SHF_ERROR;
597 				shf->errnosv = errno;
598 				return (EOF);
599 			}
600 	} else {
601 		/* Flush deals with strings and sticky errors */
602 		if (shf->wnleft == 0 && shf_emptybuf(shf, EB_GROW) == EOF)
603 			return (EOF);
604 		shf->wnleft--;
605 		*shf->wp++ = c;
606 	}
607 
608 	return (c);
609 }
610 
611 /*
612  * Write a string. Returns the length of the string if successful, EOF
613  * if the string could not be written.
614  */
615 ssize_t
shf_puts(const char * s,struct shf * shf)616 shf_puts(const char *s, struct shf *shf)
617 {
618 	if (!s)
619 		return (EOF);
620 
621 	return (shf_write(s, strlen(s), shf));
622 }
623 
624 /* Write a buffer. Returns nbytes if successful, EOF if there is an error. */
625 ssize_t
shf_write(const char * buf,ssize_t nbytes,struct shf * shf)626 shf_write(const char *buf, ssize_t nbytes, struct shf *shf)
627 {
628 	ssize_t n, ncopy, orig_nbytes = nbytes;
629 
630 	if (!(shf->flags & SHF_WR))
631 		internal_errorf("%s: flags 0x%X", "shf_write", shf->flags);
632 
633 	if (nbytes < 0)
634 		internal_errorf("%s: %s %zd", "shf_write", "nbytes", nbytes);
635 
636 	/* Don't buffer if buffer is empty and we're writting a large amount. */
637 	if ((ncopy = shf->wnleft) &&
638 	    (shf->wp != shf->buf || nbytes < shf->wnleft)) {
639 		if (ncopy > nbytes)
640 			ncopy = nbytes;
641 		memcpy(shf->wp, buf, ncopy);
642 		nbytes -= ncopy;
643 		buf += ncopy;
644 		shf->wp += ncopy;
645 		shf->wnleft -= ncopy;
646 	}
647 	if (nbytes > 0) {
648 		if (shf->flags & SHF_STRING) {
649 			/* resize buffer until there's enough space left */
650 			while (nbytes > shf->wnleft)
651 				if (shf_emptybuf(shf, EB_GROW) == EOF)
652 					return (EOF);
653 			/* then write everything into the buffer */
654 		} else {
655 			/* flush deals with sticky errors */
656 			if (shf_emptybuf(shf, EB_GROW) == EOF)
657 				return (EOF);
658 			/* write chunks larger than window size directly */
659 			if (nbytes > shf->wbsize) {
660 				ncopy = nbytes;
661 				if (shf->wbsize)
662 					ncopy -= nbytes % shf->wbsize;
663 				nbytes -= ncopy;
664 				while (ncopy > 0) {
665 					n = write(shf->fd, buf, ncopy);
666 					if (n < 0) {
667 						if (errno == EINTR &&
668 						    !(shf->flags & SHF_INTERRUPT))
669 							continue;
670 						shf->flags |= SHF_ERROR;
671 						shf->errnosv = errno;
672 						shf->wnleft = 0;
673 						/*
674 						 * Note: fwrite(3) returns 0
675 						 * for errors - this doesn't
676 						 */
677 						return (EOF);
678 					}
679 					buf += n;
680 					ncopy -= n;
681 				}
682 			}
683 			/* ... and buffer the rest */
684 		}
685 		if (nbytes > 0) {
686 			/* write remaining bytes to buffer */
687 			memcpy(shf->wp, buf, nbytes);
688 			shf->wp += nbytes;
689 			shf->wnleft -= nbytes;
690 		}
691 	}
692 
693 	return (orig_nbytes);
694 }
695 
696 ssize_t
shf_fprintf(struct shf * shf,const char * fmt,...)697 shf_fprintf(struct shf *shf, const char *fmt, ...)
698 {
699 	va_list args;
700 	ssize_t n;
701 
702 	va_start(args, fmt);
703 	n = shf_vfprintf(shf, fmt, args);
704 	va_end(args);
705 
706 	return (n);
707 }
708 
709 ssize_t
shf_snprintf(char * buf,ssize_t bsize,const char * fmt,...)710 shf_snprintf(char *buf, ssize_t bsize, const char *fmt, ...)
711 {
712 	struct shf shf;
713 	va_list args;
714 	ssize_t n;
715 
716 	if (!buf || bsize <= 0)
717 		internal_errorf("shf_snprintf: buf %zX, bsize %zd",
718 		    (size_t)buf, bsize);
719 
720 	shf_sopen(buf, bsize, SHF_WR, &shf);
721 	va_start(args, fmt);
722 	n = shf_vfprintf(&shf, fmt, args);
723 	va_end(args);
724 	/* NUL terminates */
725 	shf_sclose(&shf);
726 	return (n);
727 }
728 
729 char *
shf_smprintf(const char * fmt,...)730 shf_smprintf(const char *fmt, ...)
731 {
732 	struct shf shf;
733 	va_list args;
734 
735 	shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
736 	va_start(args, fmt);
737 	shf_vfprintf(&shf, fmt, args);
738 	va_end(args);
739 	/* NUL terminates */
740 	return (shf_sclose(&shf));
741 }
742 
743 #define BUF_SIZE	128
744 
745 #define	FL_HASH		0x001	/* '#' seen */
746 #define FL_PLUS		0x002	/* '+' seen */
747 #define FL_RIGHT	0x004	/* '-' seen */
748 #define FL_BLANK	0x008	/* ' ' seen */
749 #define FL_SHORT	0x010	/* 'h' seen */
750 #define FL_LONG		0x020	/* 'l' seen */
751 #define FL_ZERO		0x040	/* '0' seen */
752 #define FL_DOT		0x080	/* '.' seen */
753 #define FL_UPPER	0x100	/* format character was uppercase */
754 #define FL_NUMBER	0x200	/* a number was formated %[douxefg] */
755 #define FL_SIZET	0x400	/* 'z' seen */
756 #define FM_SIZES	0x430	/* h/l/z mask */
757 
758 ssize_t
shf_vfprintf(struct shf * shf,const char * fmt,va_list args)759 shf_vfprintf(struct shf *shf, const char *fmt, va_list args)
760 {
761 	const char *s;
762 	char c, *cp;
763 	int tmp = 0, flags;
764 	ssize_t field, precision, len;
765 	unsigned long lnum;
766 	/* %#o produces the longest output */
767 	char numbuf[(8 * sizeof(long) + 2) / 3 + 1];
768 	/* this stuff for dealing with the buffer */
769 	ssize_t nwritten = 0;
770 
771 #define VA(type) va_arg(args, type)
772 
773 	if (!fmt)
774 		return (0);
775 
776 	while ((c = *fmt++)) {
777 		if (c != '%') {
778 			shf_putc(c, shf);
779 			nwritten++;
780 			continue;
781 		}
782 		/*
783 		 * This will accept flags/fields in any order - not just
784 		 * the order specified in printf(3), but this is the way
785 		 * _doprnt() seems to work (on BSD and SYSV). The only
786 		 * restriction is that the format character must come
787 		 * last :-).
788 		 */
789 		flags = 0;
790 		field = precision = 0;
791 		for ( ; (c = *fmt++) ; ) {
792 			switch (c) {
793 			case '#':
794 				flags |= FL_HASH;
795 				continue;
796 
797 			case '+':
798 				flags |= FL_PLUS;
799 				continue;
800 
801 			case '-':
802 				flags |= FL_RIGHT;
803 				continue;
804 
805 			case ' ':
806 				flags |= FL_BLANK;
807 				continue;
808 
809 			case '0':
810 				if (!(flags & FL_DOT))
811 					flags |= FL_ZERO;
812 				continue;
813 
814 			case '.':
815 				flags |= FL_DOT;
816 				precision = 0;
817 				continue;
818 
819 			case '*':
820 				tmp = VA(int);
821 				if (flags & FL_DOT)
822 					precision = tmp;
823 				else if ((field = tmp) < 0) {
824 					field = -field;
825 					flags |= FL_RIGHT;
826 				}
827 				continue;
828 
829 			case 'l':
830 				flags &= ~FM_SIZES;
831 				flags |= FL_LONG;
832 				continue;
833 
834 			case 'h':
835 				flags &= ~FM_SIZES;
836 				flags |= FL_SHORT;
837 				continue;
838 
839 			case 'z':
840 				flags &= ~FM_SIZES;
841 				flags |= FL_SIZET;
842 				continue;
843 			}
844 			if (ksh_isdigit(c)) {
845 				tmp = c - '0';
846 				while (c = *fmt++, ksh_isdigit(c))
847 					tmp = tmp * 10 + c - '0';
848 				--fmt;
849 				if (tmp < 0)
850 					/* overflow? */
851 					tmp = 0;
852 				if (flags & FL_DOT)
853 					precision = tmp;
854 				else
855 					field = tmp;
856 				continue;
857 			}
858 			break;
859 		}
860 
861 		if (precision < 0)
862 			precision = 0;
863 
864 		if (!c)
865 			/* nasty format */
866 			break;
867 
868 		if (c >= 'A' && c <= 'Z') {
869 			flags |= FL_UPPER;
870 			c = ksh_tolower(c);
871 		}
872 
873 		switch (c) {
874 		case 'd':
875 		case 'i':
876 			if (flags & FL_SIZET)
877 				lnum = (long)VA(ssize_t);
878 			else if (flags & FL_LONG)
879 				lnum = VA(long);
880 			else if (flags & FL_SHORT)
881 				lnum = (long)(short)VA(int);
882 			else
883 				lnum = (long)VA(int);
884 			goto integral;
885 
886 		case 'o':
887 		case 'u':
888 		case 'x':
889 			if (flags & FL_SIZET)
890 				lnum = VA(size_t);
891 			else if (flags & FL_LONG)
892 				lnum = VA(unsigned long);
893 			else if (flags & FL_SHORT)
894 				lnum = (unsigned long)(unsigned short)VA(int);
895 			else
896 				lnum = (unsigned long)VA(unsigned int);
897 
898  integral:
899 			flags |= FL_NUMBER;
900 			cp = numbuf + sizeof(numbuf);
901 
902 			switch (c) {
903 			case 'd':
904 			case 'i':
905 				if (0 > (long)lnum) {
906 					lnum = -(long)lnum;
907 					tmp = 1;
908 				} else
909 					tmp = 0;
910 				/* FALLTHROUGH */
911 			case 'u':
912 				do {
913 					*--cp = lnum % 10 + '0';
914 					lnum /= 10;
915 				} while (lnum);
916 
917 				if (c != 'u') {
918 					if (tmp)
919 						*--cp = '-';
920 					else if (flags & FL_PLUS)
921 						*--cp = '+';
922 					else if (flags & FL_BLANK)
923 						*--cp = ' ';
924 				}
925 				break;
926 
927 			case 'o':
928 				do {
929 					*--cp = (lnum & 0x7) + '0';
930 					lnum >>= 3;
931 				} while (lnum);
932 
933 				if ((flags & FL_HASH) && *cp != '0')
934 					*--cp = '0';
935 				break;
936 
937 			case 'x': {
938 				const char *digits = (flags & FL_UPPER) ?
939 				    digits_uc : digits_lc;
940 				do {
941 					*--cp = digits[lnum & 0xf];
942 					lnum >>= 4;
943 				} while (lnum);
944 
945 				if (flags & FL_HASH) {
946 					*--cp = (flags & FL_UPPER) ? 'X' : 'x';
947 					*--cp = '0';
948 				}
949 			}
950 			}
951 			len = numbuf + sizeof(numbuf) - (s = cp);
952 			if (flags & FL_DOT) {
953 				if (precision > len) {
954 					field = precision;
955 					flags |= FL_ZERO;
956 				} else
957 					/* no loss */
958 					precision = len;
959 			}
960 			break;
961 
962 		case 's':
963 			if ((s = VA(const char *)) == NULL)
964 				s = "(null)";
965 			len = utf_mbswidth(s);
966 			break;
967 
968 		case 'c':
969 			flags &= ~FL_DOT;
970 			numbuf[0] = (char)(VA(int));
971 			s = numbuf;
972 			len = 1;
973 			break;
974 
975 		case '%':
976 		default:
977 			numbuf[0] = c;
978 			s = numbuf;
979 			len = 1;
980 			break;
981 		}
982 
983 		/*
984 		 * At this point s should point to a string that is to be
985 		 * formatted, and len should be the length of the string.
986 		 */
987 		if (!(flags & FL_DOT) || len < precision)
988 			precision = len;
989 		if (field > precision) {
990 			field -= precision;
991 			if (!(flags & FL_RIGHT)) {
992 				field = -field;
993 				/* skip past sign or 0x when padding with 0 */
994 				if ((flags & FL_ZERO) && (flags & FL_NUMBER)) {
995 					if (*s == '+' || *s == '-' ||
996 					    *s == ' ') {
997 						shf_putc(*s, shf);
998 						s++;
999 						precision--;
1000 						nwritten++;
1001 					} else if (*s == '0') {
1002 						shf_putc(*s, shf);
1003 						s++;
1004 						nwritten++;
1005 						if (--precision > 0 &&
1006 						    (*s | 0x20) == 'x') {
1007 							shf_putc(*s, shf);
1008 							s++;
1009 							precision--;
1010 							nwritten++;
1011 						}
1012 					}
1013 					c = '0';
1014 				} else
1015 					c = flags & FL_ZERO ? '0' : ' ';
1016 				if (field < 0) {
1017 					nwritten += -field;
1018 					for ( ; field < 0 ; field++)
1019 						shf_putc(c, shf);
1020 				}
1021 			} else
1022 				c = ' ';
1023 		} else
1024 			field = 0;
1025 
1026 		if (precision > 0) {
1027 			const char *q;
1028 
1029 			nwritten += precision;
1030 			q = utf_skipcols(s, precision);
1031 			do {
1032 				shf_putc(*s, shf);
1033 			} while (++s < q);
1034 		}
1035 		if (field > 0) {
1036 			nwritten += field;
1037 			for ( ; field > 0 ; --field)
1038 				shf_putc(c, shf);
1039 		}
1040 	}
1041 
1042 	return (shf_error(shf) ? EOF : nwritten);
1043 }
1044 
1045 #ifdef MKSH_SMALL
1046 int
shf_getc(struct shf * shf)1047 shf_getc(struct shf *shf)
1048 {
1049 	return (shf_getc_(shf));
1050 }
1051 
1052 int
shf_putc(int c,struct shf * shf)1053 shf_putc(int c, struct shf *shf)
1054 {
1055 	return (shf_putc_(c, shf));
1056 }
1057 #endif
1058