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