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