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