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