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