xref: /freebsd/usr.sbin/lpr/common_source/common.c (revision f0adf7f5cdd241db2f2c817683191a6ef64a4e95)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
42 #endif /* not lint */
43 #endif
44 
45 #include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
46 __FBSDID("$FreeBSD$");
47 
48 #include <sys/param.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/types.h>
52 
53 #include <dirent.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include "lp.h"
62 #include "lp.local.h"
63 #include "pathnames.h"
64 
65 /*
66  * Routines and data common to all the line printer functions.
67  */
68 char	line[BUFSIZ];
69 const char	*progname;		/* program name */
70 
71 extern uid_t	uid, euid;
72 
73 static int compar(const void *_p1, const void *_p2);
74 
75 /*
76  * Getline reads a line from the control file cfp, removes tabs, converts
77  *  new-line to null and leaves it in line.
78  * Returns 0 at EOF or the number of characters read.
79  */
80 int
81 getline(FILE *cfp)
82 {
83 	register int linel = 0;
84 	register char *lp = line;
85 	register int c;
86 
87 	while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
88 		if (c == EOF)
89 			return(0);
90 		if (c == '\t') {
91 			do {
92 				*lp++ = ' ';
93 				linel++;
94 			} while ((linel & 07) != 0 && (size_t)(linel+1) <
95 			    sizeof(line));
96 			continue;
97 		}
98 		*lp++ = c;
99 		linel++;
100 	}
101 	*lp++ = '\0';
102 	return(linel);
103 }
104 
105 /*
106  * Scan the current directory and make a list of daemon files sorted by
107  * creation time.
108  * Return the number of entries and a pointer to the list.
109  */
110 int
111 getq(const struct printer *pp, struct jobqueue *(*namelist[]))
112 {
113 	register struct dirent *d;
114 	register struct jobqueue *q, **queue;
115 	size_t arraysz, entrysz, nitems;
116 	struct stat stbuf;
117 	DIR *dirp;
118 	int statres;
119 
120 	seteuid(euid);
121 	if ((dirp = opendir(pp->spool_dir)) == NULL) {
122 		seteuid(uid);
123 		return (-1);
124 	}
125 	if (fstat(dirp->dd_fd, &stbuf) < 0)
126 		goto errdone;
127 	seteuid(uid);
128 
129 	/*
130 	 * Estimate the array size by taking the size of the directory file
131 	 * and dividing it by a multiple of the minimum size entry.
132 	 */
133 	arraysz = (stbuf.st_size / 24);
134 	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
135 	if (queue == NULL)
136 		goto errdone;
137 
138 	nitems = 0;
139 	while ((d = readdir(dirp)) != NULL) {
140 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
141 			continue;	/* daemon control files only */
142 		seteuid(euid);
143 		statres = stat(d->d_name, &stbuf);
144 		seteuid(uid);
145 		if (statres < 0)
146 			continue;	/* Doesn't exist */
147 		entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
148 		    strlen(d->d_name) + 1;
149 		q = (struct jobqueue *)malloc(entrysz);
150 		if (q == NULL)
151 			goto errdone;
152 		q->job_matched = 0;
153 		q->job_processed = 0;
154 		q->job_time = stbuf.st_mtime;
155 		strcpy(q->job_cfname, d->d_name);
156 		/*
157 		 * Check to make sure the array has space left and
158 		 * realloc the maximum size.
159 		 */
160 		if (++nitems > arraysz) {
161 			arraysz *= 2;
162 			queue = (struct jobqueue **)realloc((char *)queue,
163 			    arraysz * sizeof(struct jobqueue *));
164 			if (queue == NULL)
165 				goto errdone;
166 		}
167 		queue[nitems-1] = q;
168 	}
169 	closedir(dirp);
170 	if (nitems)
171 		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
172 	*namelist = queue;
173 	return(nitems);
174 
175 errdone:
176 	closedir(dirp);
177 	seteuid(uid);
178 	return (-1);
179 }
180 
181 /*
182  * Compare modification times.
183  */
184 static int
185 compar(const void *p1, const void *p2)
186 {
187 	const struct jobqueue *qe1, *qe2;
188 
189 	qe1 = *(const struct jobqueue * const *)p1;
190 	qe2 = *(const struct jobqueue * const *)p2;
191 
192 	if (qe1->job_time < qe2->job_time)
193 		return (-1);
194 	if (qe1->job_time > qe2->job_time)
195 		return (1);
196 	/*
197 	 * At this point, the two files have the same last-modification time.
198 	 * return a result based on filenames, so that 'cfA001some.host' will
199 	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
200 	 * around when it gets to '999', we also assume that '9xx' jobs are
201 	 * older than '0xx' jobs.
202 	*/
203 	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
204 		return (-1);
205 	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
206 		return (1);
207 	return (strcmp(qe1->job_cfname, qe2->job_cfname));
208 }
209 
210 /* sleep n milliseconds */
211 void
212 delay(int millisec)
213 {
214 	struct timeval tdelay;
215 
216 	if (millisec <= 0 || millisec > 10000)
217 		fatal((struct printer *)0, /* fatal() knows how to deal */
218 		    "unreasonable delay period (%d)", millisec);
219 	tdelay.tv_sec = millisec / 1000;
220 	tdelay.tv_usec = millisec * 1000 % 1000000;
221 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
222 }
223 
224 char *
225 lock_file_name(const struct printer *pp, char *buf, size_t len)
226 {
227 	static char staticbuf[MAXPATHLEN];
228 
229 	if (buf == 0)
230 		buf = staticbuf;
231 	if (len == 0)
232 		len = MAXPATHLEN;
233 
234 	if (pp->lock_file[0] == '/')
235 		strlcpy(buf, pp->lock_file, len);
236 	else
237 		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
238 
239 	return buf;
240 }
241 
242 char *
243 status_file_name(const struct printer *pp, char *buf, size_t len)
244 {
245 	static char staticbuf[MAXPATHLEN];
246 
247 	if (buf == 0)
248 		buf = staticbuf;
249 	if (len == 0)
250 		len = MAXPATHLEN;
251 
252 	if (pp->status_file[0] == '/')
253 		strlcpy(buf, pp->status_file, len);
254 	else
255 		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
256 
257 	return buf;
258 }
259 
260 /*
261  * Routine to change operational state of a print queue.  The operational
262  * state is indicated by the access bits on the lock file for the queue.
263  * At present, this is only called from various routines in lpc/cmds.c.
264  *
265  *  XXX - Note that this works by changing access-bits on the
266  *	file, and you can only do that if you are the owner of
267  *	the file, or root.  Thus, this won't really work for
268  *	userids in the "LPR_OPER" group, unless lpc is running
269  *	setuid to root (or maybe setuid to daemon).
270  *	Generally lpc is installed setgid to daemon, but does
271  *	not run setuid.
272  */
273 int
274 set_qstate(int action, const char *lfname)
275 {
276 	struct stat stbuf;
277 	mode_t chgbits, newbits, oldmask;
278 	const char *failmsg, *okmsg;
279 	static const char *nomsg = "no state msg";
280 	int chres, errsav, fd, res, statres;
281 
282 	/*
283 	 * Find what the current access-bits are.
284 	 */
285 	memset(&stbuf, 0, sizeof(stbuf));
286 	seteuid(euid);
287 	statres = stat(lfname, &stbuf);
288 	errsav = errno;
289 	seteuid(uid);
290 	if ((statres < 0) && (errsav != ENOENT)) {
291 		printf("\tcannot stat() lock file\n");
292 		return (SQS_STATFAIL);
293 		/* NOTREACHED */
294 	}
295 
296 	/*
297 	 * Determine which bit(s) should change for the requested action.
298 	 */
299 	chgbits = stbuf.st_mode;
300 	newbits = LOCK_FILE_MODE;
301 	okmsg = NULL;
302 	failmsg = NULL;
303 	if (action & SQS_QCHANGED) {
304 		chgbits |= LFM_RESET_QUE;
305 		newbits |= LFM_RESET_QUE;
306 		/* The okmsg is not actually printed for this case. */
307 		okmsg = nomsg;
308 		failmsg = "set queue-changed";
309 	}
310 	if (action & SQS_DISABLEQ) {
311 		chgbits |= LFM_QUEUE_DIS;
312 		newbits |= LFM_QUEUE_DIS;
313 		okmsg = "queuing disabled";
314 		failmsg = "disable queuing";
315 	}
316 	if (action & SQS_STOPP) {
317 		chgbits |= LFM_PRINT_DIS;
318 		newbits |= LFM_PRINT_DIS;
319 		okmsg = "printing disabled";
320 		failmsg = "disable printing";
321 		if (action & SQS_DISABLEQ) {
322 			okmsg = "printer and queuing disabled";
323 			failmsg = "disable queuing and printing";
324 		}
325 	}
326 	if (action & SQS_ENABLEQ) {
327 		chgbits &= ~LFM_QUEUE_DIS;
328 		newbits &= ~LFM_QUEUE_DIS;
329 		okmsg = "queuing enabled";
330 		failmsg = "enable queuing";
331 	}
332 	if (action & SQS_STARTP) {
333 		chgbits &= ~LFM_PRINT_DIS;
334 		newbits &= ~LFM_PRINT_DIS;
335 		okmsg = "printing enabled";
336 		failmsg = "enable printing";
337 	}
338 	if (okmsg == NULL) {
339 		/* This routine was called with an invalid action. */
340 		printf("\t<error in set_qstate!>\n");
341 		return (SQS_PARMERR);
342 		/* NOTREACHED */
343 	}
344 
345 	res = 0;
346 	if (statres >= 0) {
347 		/* The file already exists, so change the access. */
348 		seteuid(euid);
349 		chres = chmod(lfname, chgbits);
350 		errsav = errno;
351 		seteuid(uid);
352 		res = SQS_CHGOK;
353 		if (chres < 0)
354 			res = SQS_CHGFAIL;
355 	} else if (newbits == LOCK_FILE_MODE) {
356 		/*
357 		 * The file does not exist, but the state requested is
358 		 * the same as the default state when no file exists.
359 		 * Thus, there is no need to create the file.
360 		 */
361 		res = SQS_SKIPCREOK;
362 	} else {
363 		/*
364 		 * The file did not exist, so create it with the
365 		 * appropriate access bits for the requested action.
366 		 * Push a new umask around that create, to make sure
367 		 * all the read/write bits are set as desired.
368 		 */
369 		oldmask = umask(S_IWOTH);
370 		seteuid(euid);
371 		fd = open(lfname, O_WRONLY|O_CREAT, newbits);
372 		errsav = errno;
373 		seteuid(uid);
374 		umask(oldmask);
375 		res = SQS_CREFAIL;
376 		if (fd >= 0) {
377 			res = SQS_CREOK;
378 			close(fd);
379 		}
380 	}
381 
382 	switch (res) {
383 	case SQS_CHGOK:
384 	case SQS_CREOK:
385 	case SQS_SKIPCREOK:
386 		if (okmsg != nomsg)
387 			printf("\t%s\n", okmsg);
388 		break;
389 	case SQS_CREFAIL:
390 		printf("\tcannot create lock file: %s\n",
391 		    strerror(errsav));
392 		break;
393 	default:
394 		printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
395 		break;
396 	}
397 
398 	return (res);
399 }
400 
401 /* routine to get a current timestamp, optionally in a standard-fmt string */
402 void
403 lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
404 {
405 	struct timespec local_ts;
406 	struct timeval btime;
407 	char tempstr[TIMESTR_SIZE];
408 #ifdef STRFTIME_WRONG_z
409 	char *destp;
410 #endif
411 
412 	if (tsp == NULL)
413 		tsp = &local_ts;
414 
415 	/* some platforms have a routine called clock_gettime, but the
416 	 * routine does nothing but return "not implemented". */
417 	memset(tsp, 0, sizeof(struct timespec));
418 	if (clock_gettime(CLOCK_REALTIME, tsp)) {
419 		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
420 		memset(tsp, 0, sizeof(struct timespec));
421 		gettimeofday(&btime, NULL);
422 		tsp->tv_sec = btime.tv_sec;
423 		tsp->tv_nsec = btime.tv_usec * 1000;
424 	}
425 
426 	/* caller may not need a character-ized version */
427 	if ((strp == NULL) || (strsize < 1))
428 		return;
429 
430 	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
431 		 localtime(&tsp->tv_sec));
432 
433 	/*
434 	 * This check is for implementations of strftime which treat %z
435 	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
436 	 * completely ignore %z.  This section is not needed on freebsd.
437 	 * I'm not sure this is completely right, but it should work OK
438 	 * for EST and EDT...
439 	 */
440 #ifdef STRFTIME_WRONG_z
441 	destp = strrchr(tempstr, ':');
442 	if (destp != NULL) {
443 		destp += 3;
444 		if ((*destp != '+') && (*destp != '-')) {
445 			char savday[6];
446 			int tzmin = timezone / 60;
447 			int tzhr = tzmin / 60;
448 			if (daylight)
449 				tzhr--;
450 			strcpy(savday, destp + strlen(destp) - 4);
451 			snprintf(destp, (destp - tempstr), "%+03d%02d",
452 			    (-1*tzhr), tzmin % 60);
453 			strcat(destp, savday);
454 		}
455 	}
456 #endif
457 
458 	if (strsize > TIMESTR_SIZE) {
459 		strsize = TIMESTR_SIZE;
460 		strp[TIMESTR_SIZE+1] = '\0';
461 	}
462 	strlcpy(strp, tempstr, strsize);
463 }
464 
465 /* routines for writing transfer-statistic records */
466 void
467 trstat_init(struct printer *pp, const char *fname, int filenum)
468 {
469 	register const char *srcp;
470 	register char *destp, *endp;
471 
472 	/*
473 	 * Figure out the job id of this file.  The filename should be
474 	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
475 	 * two), followed by the jobnum, followed by a hostname.
476 	 * The jobnum is usually 3 digits, but might be as many as 5.
477 	 * Note that some care has to be taken parsing this, as the
478 	 * filename could be coming from a remote-host, and thus might
479 	 * not look anything like what is expected...
480 	 */
481 	memset(pp->jobnum, 0, sizeof(pp->jobnum));
482 	pp->jobnum[0] = '0';
483 	srcp = strchr(fname, '/');
484 	if (srcp == NULL)
485 		srcp = fname;
486 	destp = &(pp->jobnum[0]);
487 	endp = destp + 5;
488 	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
489 		srcp++;
490 	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
491 		*(destp++) = *(srcp++);
492 
493 	/* get the starting time in both numeric and string formats, and
494 	 * save those away along with the file-number */
495 	pp->jobdfnum = filenum;
496 	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
497 
498 	return;
499 }
500 
501 void
502 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
503     const char *userid, const char *otherhost, const char *orighost)
504 {
505 #define STATLINE_SIZE 1024
506 	double trtime;
507 	size_t remspace;
508 	int statfile;
509 	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
510 	char *eostat;
511 	const char *lprhost, *recvdev, *recvhost, *rectype;
512 	const char *sendhost, *statfname;
513 #define UPD_EOSTAT(xStr) do {         \
514 	eostat = strchr(xStr, '\0');  \
515 	remspace = eostat - xStr;     \
516 } while(0)
517 
518 	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
519 	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
520 
521 	gethostname(thishost, sizeof(thishost));
522 	lprhost = sendhost = recvhost = recvdev = NULL;
523 	switch (sendrecv) {
524 	    case TR_SENDING:
525 		rectype = "send";
526 		statfname = pp->stat_send;
527 		sendhost = thishost;
528 		recvhost = otherhost;
529 		break;
530 	    case TR_RECVING:
531 		rectype = "recv";
532 		statfname = pp->stat_recv;
533 		sendhost = otherhost;
534 		recvhost = thishost;
535 		break;
536 	    case TR_PRINTING:
537 		/*
538 		 * This case is for copying to a device (presumably local,
539 		 * though filters using things like 'net/CAP' can confuse
540 		 * this assumption...).
541 		 */
542 		rectype = "prnt";
543 		statfname = pp->stat_send;
544 		sendhost = thishost;
545 		recvdev = _PATH_DEFDEVLP;
546 		if (pp->lp) recvdev = pp->lp;
547 		break;
548 	    default:
549 		/* internal error...  should we syslog/printf an error? */
550 		return;
551 	}
552 	if (statfname == NULL)
553 		return;
554 
555 	/*
556 	 * the original-host and userid are found out by reading thru the
557 	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
558 	 * the df's (data-files) are sent before the matching cf, so the
559 	 * orighost & userid are generally not-available for incoming jobs.
560 	 *
561 	 * (it would be nice to create a work-around for that..)
562 	 */
563 	if (orighost && (*orighost != '\0'))
564 		lprhost = orighost;
565 	else
566 		lprhost = ".na.";
567 	if (*userid == '\0')
568 		userid = NULL;
569 
570 	/*
571 	 * Format of statline.
572 	 * Some of the keywords listed here are not implemented here, but
573 	 * they are listed to reserve the meaning for a given keyword.
574 	 * Fields are separated by a blank.  The fields in statline are:
575 	 *   <tstamp>      - time the transfer started
576 	 *   <ptrqueue>    - name of the printer queue (the short-name...)
577 	 *   <hname>       - hostname the file originally came from (the
578 	 *		     'lpr host'), if known, or  "_na_" if not known.
579 	 *   <xxx>         - id of job from that host (generally three digits)
580 	 *   <n>           - file count (# of file within job)
581 	 *   <rectype>     - 4-byte field indicating the type of transfer
582 	 *		     statistics record.  "send" means it's from the
583 	 *		     host sending a datafile, "recv" means it's from
584 	 *		     a host as it receives a datafile.
585 	 *   user=<userid> - user who sent the job (if known)
586 	 *   secs=<n>      - seconds it took to transfer the file
587 	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
588 	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
589 	 *		     for this to be useful)
590 	 * ! top=<str>     - type of printer (if the type is defined in
591 	 *		     printcap, and if this statline is for sending
592 	 *		     a file to that ptr)
593 	 * ! qls=<n>       - queue-length at start of send/print-ing a job
594 	 * ! qle=<n>       - queue-length at end of send/print-ing a job
595 	 *   sip=<addr>    - IP address of sending host, only included when
596 	 *		     receiving a job.
597 	 *   shost=<hname> - sending host (if that does != the original host)
598 	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
599 	 *   rdev=<dev>    - device receiving the file, when the file is being
600 	 *		     send to a device instead of a remote host.
601 	 *
602 	 * Note: A single print job may be transferred multiple times.  The
603 	 * original 'lpr' occurs on one host, and that original host might
604 	 * send to some interim host (or print server).  That interim host
605 	 * might turn around and send the job to yet another host (most likely
606 	 * the real printer).  The 'shost=' parameter is only included if the
607 	 * sending host for this particular transfer is NOT the same as the
608 	 * host which did the original 'lpr'.
609 	 *
610 	 * Many values have 'something=' tags before them, because they are
611 	 * in some sense "optional", or their order may vary.  "Optional" may
612 	 * mean in the sense that different SITES might choose to have other
613 	 * fields in the record, or that some fields are only included under
614 	 * some circumstances.  Programs processing these records should not
615 	 * assume the order or existence of any of these keyword fields.
616 	 */
617 	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
618 	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
619 	    pp->jobdfnum, rectype);
620 	UPD_EOSTAT(statline);
621 
622 	if (userid != NULL) {
623 		snprintf(eostat, remspace, " user=%s", userid);
624 		UPD_EOSTAT(statline);
625 	}
626 	snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
627 	    (unsigned long)bytecnt);
628 	UPD_EOSTAT(statline);
629 
630 	/*
631 	 * The bps field duplicates info from bytes and secs, so do
632 	 * not bother to include it for very small files.
633 	 */
634 	if ((bytecnt > 25000) && (trtime > 1.1)) {
635 		snprintf(eostat, remspace, " bps=%#.2e",
636 		    ((double)bytecnt/trtime));
637 		UPD_EOSTAT(statline);
638 	}
639 
640 	if (sendrecv == TR_RECVING) {
641 		if (remspace > 5+strlen(from_ip) ) {
642 			snprintf(eostat, remspace, " sip=%s", from_ip);
643 			UPD_EOSTAT(statline);
644 		}
645 	}
646 	if (0 != strcmp(lprhost, sendhost)) {
647 		if (remspace > 7+strlen(sendhost) ) {
648 			snprintf(eostat, remspace, " shost=%s", sendhost);
649 			UPD_EOSTAT(statline);
650 		}
651 	}
652 	if (recvhost) {
653 		if (remspace > 7+strlen(recvhost) ) {
654 			snprintf(eostat, remspace, " rhost=%s", recvhost);
655 			UPD_EOSTAT(statline);
656 		}
657 	}
658 	if (recvdev) {
659 		if (remspace > 6+strlen(recvdev) ) {
660 			snprintf(eostat, remspace, " rdev=%s", recvdev);
661 			UPD_EOSTAT(statline);
662 		}
663 	}
664 	if (remspace > 1) {
665 		strcpy(eostat, "\n");
666 	} else {
667 		/* probably should back up to just before the final " x=".. */
668 		strcpy(statline+STATLINE_SIZE-2, "\n");
669 	}
670 	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
671 	if (statfile < 0) {
672 		/* statfile was given, but we can't open it.  should we
673 		 * syslog/printf this as an error? */
674 		return;
675 	}
676 	write(statfile, statline, strlen(statline));
677 	close(statfile);
678 
679 	return;
680 #undef UPD_EOSTAT
681 }
682 
683 #include <stdarg.h>
684 
685 void
686 fatal(const struct printer *pp, const char *msg, ...)
687 {
688 	va_list ap;
689 	va_start(ap, msg);
690 	/* this error message is being sent to the 'from_host' */
691 	if (from_host != local_host)
692 		(void)printf("%s: ", local_host);
693 	(void)printf("%s: ", progname);
694 	if (pp && pp->printer)
695 		(void)printf("%s: ", pp->printer);
696 	(void)vprintf(msg, ap);
697 	va_end(ap);
698 	(void)putchar('\n');
699 	exit(1);
700 }
701 
702 /*
703  * Close all file descriptors from START on up.
704  * This is a horrific kluge, since getdtablesize() might return
705  * ``infinity'', in which case we will be spending a long time
706  * closing ``files'' which were never open.  Perhaps it would
707  * be better to close the first N fds, for some small value of N.
708  */
709 void
710 closeallfds(int start)
711 {
712 	int stop = getdtablesize();
713 	for (; start < stop; start++)
714 		close(start);
715 }
716 
717