11553Srgrimes/*
21553Srgrimes * Copyright (c) 1983, 1993
31553Srgrimes *	The Regents of the University of California.  All rights reserved.
41553Srgrimes * (c) UNIX System Laboratories, Inc.
51553Srgrimes * All or some portions of this file are derived from material licensed
61553Srgrimes * to the University of California by American Telephone and Telegraph
71553Srgrimes * Co. or Unix System Laboratories, Inc. and are reproduced herein with
81553Srgrimes * the permission of UNIX System Laboratories, Inc.
91553Srgrimes *
101553Srgrimes * Redistribution and use in source and binary forms, with or without
111553Srgrimes * modification, are permitted provided that the following conditions
121553Srgrimes * are met:
131553Srgrimes * 1. Redistributions of source code must retain the above copyright
141553Srgrimes *    notice, this list of conditions and the following disclaimer.
151553Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
161553Srgrimes *    notice, this list of conditions and the following disclaimer in the
171553Srgrimes *    documentation and/or other materials provided with the distribution.
181553Srgrimes * 3. All advertising materials mentioning features or use of this software
191553Srgrimes *    must display the following acknowledgement:
201553Srgrimes *	This product includes software developed by the University of
211553Srgrimes *	California, Berkeley and its contributors.
221553Srgrimes * 4. Neither the name of the University nor the names of its contributors
231553Srgrimes *    may be used to endorse or promote products derived from this software
241553Srgrimes *    without specific prior written permission.
251553Srgrimes *
261553Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
271553Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
281553Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
291553Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
301553Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
311553Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
321553Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
331553Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
341553Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
351553Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
361553Srgrimes * SUCH DAMAGE.
371553Srgrimes */
381553Srgrimes
39117541Sgad#if 0
40117592Sgad#ifndef lint
4115648Sjoergstatic char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
42117592Sgad#endif /* not lint */
43117541Sgad#endif
44117592Sgad
45117541Sgad#include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
46117541Sgad__FBSDID("$FreeBSD$");
471553Srgrimes
481553Srgrimes#include <sys/param.h>
491553Srgrimes#include <sys/stat.h>
5015648Sjoerg#include <sys/time.h>
5168253Sgad#include <sys/types.h>
521553Srgrimes
53139464Sgad#include <ctype.h>
541553Srgrimes#include <dirent.h>
5598152Sgad#include <errno.h>
5668253Sgad#include <fcntl.h>
5731492Swollman#include <stdio.h>
581553Srgrimes#include <stdlib.h>
591553Srgrimes#include <string.h>
6031492Swollman#include <unistd.h>
6131492Swollman
621553Srgrimes#include "lp.h"
6331492Swollman#include "lp.local.h"
641553Srgrimes#include "pathnames.h"
651553Srgrimes
661553Srgrimes/*
671553Srgrimes * Routines and data common to all the line printer functions.
681553Srgrimes */
691553Srgrimeschar	line[BUFSIZ];
7078280Sgadconst char	*progname;		/* program name */
711553Srgrimes
7227618Simpextern uid_t	uid, euid;
7327618Simp
7478146Sgadstatic int compar(const void *_p1, const void *_p2);
751553Srgrimes
761553Srgrimes/*
77139464Sgad * isdigit() takes a parameter of 'int', but expect values in the range
78139464Sgad * of unsigned char.  Define a wrapper which takes a value of type 'char',
79139464Sgad * whether signed or unsigned, and ensure it ends up in the right range.
80139464Sgad */
81139464Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
82139464Sgad
83139464Sgad/*
841553Srgrimes * Getline reads a line from the control file cfp, removes tabs, converts
851553Srgrimes *  new-line to null and leaves it in line.
861553Srgrimes * Returns 0 at EOF or the number of characters read.
871553Srgrimes */
881553Srgrimesint
8978146Sgadgetline(FILE *cfp)
901553Srgrimes{
911553Srgrimes	register int linel = 0;
921553Srgrimes	register char *lp = line;
9339084Swollman	register int c;
941553Srgrimes
9580172Sgad	while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
961553Srgrimes		if (c == EOF)
971553Srgrimes			return(0);
981553Srgrimes		if (c == '\t') {
991553Srgrimes			do {
1001553Srgrimes				*lp++ = ' ';
1011553Srgrimes				linel++;
10280172Sgad			} while ((linel & 07) != 0 && (size_t)(linel+1) <
10380172Sgad			    sizeof(line));
1041553Srgrimes			continue;
1051553Srgrimes		}
1061553Srgrimes		*lp++ = c;
1071553Srgrimes		linel++;
1081553Srgrimes	}
1091553Srgrimes	*lp++ = '\0';
1101553Srgrimes	return(linel);
1111553Srgrimes}
1121553Srgrimes
1131553Srgrimes/*
1141553Srgrimes * Scan the current directory and make a list of daemon files sorted by
1151553Srgrimes * creation time.
1161553Srgrimes * Return the number of entries and a pointer to the list.
1171553Srgrimes */
1181553Srgrimesint
11978146Sgadgetq(const struct printer *pp, struct jobqueue *(*namelist[]))
1201553Srgrimes{
1211553Srgrimes	register struct dirent *d;
12268401Sgad	register struct jobqueue *q, **queue;
12399842Sgad	size_t arraysz, entrysz, nitems;
1241553Srgrimes	struct stat stbuf;
1251553Srgrimes	DIR *dirp;
12680172Sgad	int statres;
1271553Srgrimes
12827618Simp	seteuid(euid);
12968740Sgad	if ((dirp = opendir(pp->spool_dir)) == NULL) {
13068740Sgad		seteuid(uid);
13168739Sgad		return (-1);
13268740Sgad	}
1331553Srgrimes	if (fstat(dirp->dd_fd, &stbuf) < 0)
1341553Srgrimes		goto errdone;
13527618Simp	seteuid(uid);
1361553Srgrimes
1371553Srgrimes	/*
1381553Srgrimes	 * Estimate the array size by taking the size of the directory file
139240319Sjh	 * and dividing it by a multiple of the minimum size entry.
1401553Srgrimes	 */
1411553Srgrimes	arraysz = (stbuf.st_size / 24);
142240322Sjh	if (arraysz < 16)
143240322Sjh		arraysz = 16;
14468401Sgad	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
1451553Srgrimes	if (queue == NULL)
1461553Srgrimes		goto errdone;
1471553Srgrimes
1481553Srgrimes	nitems = 0;
1491553Srgrimes	while ((d = readdir(dirp)) != NULL) {
1501553Srgrimes		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
1511553Srgrimes			continue;	/* daemon control files only */
15227618Simp		seteuid(euid);
15375253Sgad		statres = stat(d->d_name, &stbuf);
15475253Sgad		seteuid(uid);
15575253Sgad		if (statres < 0)
1561553Srgrimes			continue;	/* Doesn't exist */
15799842Sgad		entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
15899842Sgad		    strlen(d->d_name) + 1;
15999842Sgad		q = (struct jobqueue *)malloc(entrysz);
1601553Srgrimes		if (q == NULL)
1611553Srgrimes			goto errdone;
16299842Sgad		q->job_matched = 0;
16399842Sgad		q->job_processed = 0;
16468401Sgad		q->job_time = stbuf.st_mtime;
16568401Sgad		strcpy(q->job_cfname, d->d_name);
1661553Srgrimes		/*
1671553Srgrimes		 * Check to make sure the array has space left and
1681553Srgrimes		 * realloc the maximum size.
1691553Srgrimes		 */
1701553Srgrimes		if (++nitems > arraysz) {
17115648Sjoerg			arraysz *= 2;
17268401Sgad			queue = (struct jobqueue **)realloc((char *)queue,
17368739Sgad			    arraysz * sizeof(struct jobqueue *));
1741553Srgrimes			if (queue == NULL)
1751553Srgrimes				goto errdone;
1761553Srgrimes		}
1771553Srgrimes		queue[nitems-1] = q;
1781553Srgrimes	}
1791553Srgrimes	closedir(dirp);
1801553Srgrimes	if (nitems)
18168401Sgad		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
1821553Srgrimes	*namelist = queue;
1831553Srgrimes	return(nitems);
1841553Srgrimes
1851553Srgrimeserrdone:
1861553Srgrimes	closedir(dirp);
18768740Sgad	seteuid(uid);
18868739Sgad	return (-1);
1891553Srgrimes}
1901553Srgrimes
1911553Srgrimes/*
1921553Srgrimes * Compare modification times.
1931553Srgrimes */
1941553Srgrimesstatic int
19578146Sgadcompar(const void *p1, const void *p2)
1961553Srgrimes{
19768401Sgad	const struct jobqueue *qe1, *qe2;
19868739Sgad
19995290Sgad	qe1 = *(const struct jobqueue * const *)p1;
20095290Sgad	qe2 = *(const struct jobqueue * const *)p2;
20159920Swollman
20268401Sgad	if (qe1->job_time < qe2->job_time)
20359920Swollman		return (-1);
20468401Sgad	if (qe1->job_time > qe2->job_time)
20559920Swollman		return (1);
20659920Swollman	/*
20759920Swollman	 * At this point, the two files have the same last-modification time.
20859920Swollman	 * return a result based on filenames, so that 'cfA001some.host' will
20959920Swollman	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
21059920Swollman	 * around when it gets to '999', we also assume that '9xx' jobs are
21159920Swollman	 * older than '0xx' jobs.
21259920Swollman	*/
21368401Sgad	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
21459920Swollman		return (-1);
21568401Sgad	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
21659920Swollman		return (1);
21768401Sgad	return (strcmp(qe1->job_cfname, qe2->job_cfname));
2181553Srgrimes}
2191553Srgrimes
220139464Sgad/*
221139464Sgad * A simple routine to determine the job number for a print job based on
222139464Sgad * the name of its control file.  The algorithm used here may look odd, but
223139464Sgad * the main issue is that all parts of `lpd', `lpc', `lpq' & `lprm' must be
224139464Sgad * using the same algorithm, whatever that algorithm may be.  If the caller
225139464Sgad * provides a non-null value for ''hostpp', then this returns a pointer to
226139464Sgad * the start of the hostname (or IP address?) as found in the filename.
227139464Sgad *
228139464Sgad * Algorithm: The standard `cf' file has the job number start in position 4,
229139464Sgad * but some implementations have that as an extra file-sequence letter, and
230139464Sgad * start the job number in position 5.  The job number is usually three bytes,
231139464Sgad * but may be as many as five.  Confusing matters still more, some Windows
232139464Sgad * print servers will append an IP address to the job number, instead of
233139464Sgad * the expected hostname.  So, if the job number ends with a '.', then
234139464Sgad * assume the correct jobnum value is the first three digits.
235139464Sgad */
236139464Sgadint
237139464Sgadcalc_jobnum(const char *cfname, const char **hostpp)
238139464Sgad{
239139464Sgad	int jnum;
240139464Sgad	const char *cp, *numstr, *hoststr;
241139464Sgad
242139464Sgad	numstr = cfname + 3;
243139464Sgad	if (!isdigitch(*numstr))
244139464Sgad		numstr++;
245139464Sgad	jnum = 0;
246139464Sgad	for (cp = numstr; (cp < numstr + 5) && isdigitch(*cp); cp++)
247139464Sgad		jnum = jnum * 10 + (*cp - '0');
248139464Sgad	hoststr = cp;
249139464Sgad
250139464Sgad	/*
251139464Sgad	 * If the filename was built with an IP number instead of a hostname,
252139464Sgad	 * then recalculate using only the first three digits found.
253139464Sgad	 */
254139464Sgad	while(isdigitch(*cp))
255139464Sgad		cp++;
256139464Sgad	if (*cp == '.') {
257139464Sgad		jnum = 0;
258139464Sgad		for (cp = numstr; (cp < numstr + 3) && isdigitch(*cp); cp++)
259139464Sgad			jnum = jnum * 10 + (*cp - '0');
260139464Sgad		hoststr = cp;
261139464Sgad	}
262139464Sgad	if (hostpp != NULL)
263139464Sgad		*hostpp = hoststr;
264139464Sgad	return (jnum);
265139464Sgad}
266139464Sgad
26715648Sjoerg/* sleep n milliseconds */
26815648Sjoergvoid
26978146Sgaddelay(int millisec)
27015648Sjoerg{
27115648Sjoerg	struct timeval tdelay;
27215648Sjoerg
27378146Sgad	if (millisec <= 0 || millisec > 10000)
27431492Swollman		fatal((struct printer *)0, /* fatal() knows how to deal */
27578146Sgad		    "unreasonable delay period (%d)", millisec);
27678146Sgad	tdelay.tv_sec = millisec / 1000;
27778146Sgad	tdelay.tv_usec = millisec * 1000 % 1000000;
27815648Sjoerg	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
27915648Sjoerg}
28015648Sjoerg
28131492Swollmanchar *
28278146Sgadlock_file_name(const struct printer *pp, char *buf, size_t len)
28331492Swollman{
28431492Swollman	static char staticbuf[MAXPATHLEN];
28531492Swollman
28631492Swollman	if (buf == 0)
28731492Swollman		buf = staticbuf;
28831492Swollman	if (len == 0)
28931492Swollman		len = MAXPATHLEN;
29031492Swollman
29179740Sgad	if (pp->lock_file[0] == '/')
29279740Sgad		strlcpy(buf, pp->lock_file, len);
29379740Sgad	else
29431492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
29579740Sgad
29631492Swollman	return buf;
29731492Swollman}
29831492Swollman
29931492Swollmanchar *
30078146Sgadstatus_file_name(const struct printer *pp, char *buf, size_t len)
30131492Swollman{
30231492Swollman	static char staticbuf[MAXPATHLEN];
30331492Swollman
30431492Swollman	if (buf == 0)
30531492Swollman		buf = staticbuf;
30631492Swollman	if (len == 0)
30731492Swollman		len = MAXPATHLEN;
30831492Swollman
30979740Sgad	if (pp->status_file[0] == '/')
31079740Sgad		strlcpy(buf, pp->status_file, len);
31179740Sgad	else
31231492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
31379740Sgad
31431492Swollman	return buf;
31531492Swollman}
31631492Swollman
31798152Sgad/*
31898152Sgad * Routine to change operational state of a print queue.  The operational
31998154Sgad * state is indicated by the access bits on the lock file for the queue.
32098152Sgad * At present, this is only called from various routines in lpc/cmds.c.
32198152Sgad *
32298152Sgad *  XXX - Note that this works by changing access-bits on the
32398152Sgad *	file, and you can only do that if you are the owner of
32498152Sgad *	the file, or root.  Thus, this won't really work for
32598152Sgad *	userids in the "LPR_OPER" group, unless lpc is running
32698152Sgad *	setuid to root (or maybe setuid to daemon).
32798152Sgad *	Generally lpc is installed setgid to daemon, but does
32898152Sgad *	not run setuid.
32998152Sgad */
33098152Sgadint
33198152Sgadset_qstate(int action, const char *lfname)
33298152Sgad{
33398152Sgad	struct stat stbuf;
33498152Sgad	mode_t chgbits, newbits, oldmask;
33598152Sgad	const char *failmsg, *okmsg;
33699844Sgad	static const char *nomsg = "no state msg";
33798152Sgad	int chres, errsav, fd, res, statres;
33898152Sgad
33998152Sgad	/*
34098152Sgad	 * Find what the current access-bits are.
34198152Sgad	 */
34298152Sgad	memset(&stbuf, 0, sizeof(stbuf));
34398152Sgad	seteuid(euid);
34498152Sgad	statres = stat(lfname, &stbuf);
34598152Sgad	errsav = errno;
34698152Sgad	seteuid(uid);
34798152Sgad	if ((statres < 0) && (errsav != ENOENT)) {
34898152Sgad		printf("\tcannot stat() lock file\n");
34998152Sgad		return (SQS_STATFAIL);
35098152Sgad		/* NOTREACHED */
35198152Sgad	}
35298152Sgad
35398152Sgad	/*
35498152Sgad	 * Determine which bit(s) should change for the requested action.
35598152Sgad	 */
35698152Sgad	chgbits = stbuf.st_mode;
35798152Sgad	newbits = LOCK_FILE_MODE;
35898152Sgad	okmsg = NULL;
35998152Sgad	failmsg = NULL;
36099844Sgad	if (action & SQS_QCHANGED) {
36199844Sgad		chgbits |= LFM_RESET_QUE;
36299844Sgad		newbits |= LFM_RESET_QUE;
36399844Sgad		/* The okmsg is not actually printed for this case. */
36499844Sgad		okmsg = nomsg;
36599844Sgad		failmsg = "set queue-changed";
36699844Sgad	}
36798152Sgad	if (action & SQS_DISABLEQ) {
36898152Sgad		chgbits |= LFM_QUEUE_DIS;
36998152Sgad		newbits |= LFM_QUEUE_DIS;
37098152Sgad		okmsg = "queuing disabled";
37198152Sgad		failmsg = "disable queuing";
37298152Sgad	}
37398152Sgad	if (action & SQS_STOPP) {
37498152Sgad		chgbits |= LFM_PRINT_DIS;
37598152Sgad		newbits |= LFM_PRINT_DIS;
37698152Sgad		okmsg = "printing disabled";
37798152Sgad		failmsg = "disable printing";
37898152Sgad		if (action & SQS_DISABLEQ) {
37998152Sgad			okmsg = "printer and queuing disabled";
38098152Sgad			failmsg = "disable queuing and printing";
38198152Sgad		}
38298152Sgad	}
38398152Sgad	if (action & SQS_ENABLEQ) {
38498152Sgad		chgbits &= ~LFM_QUEUE_DIS;
38598152Sgad		newbits &= ~LFM_QUEUE_DIS;
38698152Sgad		okmsg = "queuing enabled";
38798152Sgad		failmsg = "enable queuing";
38898152Sgad	}
38998152Sgad	if (action & SQS_STARTP) {
39098152Sgad		chgbits &= ~LFM_PRINT_DIS;
39198152Sgad		newbits &= ~LFM_PRINT_DIS;
39298152Sgad		okmsg = "printing enabled";
39398152Sgad		failmsg = "enable printing";
39498152Sgad	}
39598152Sgad	if (okmsg == NULL) {
39698152Sgad		/* This routine was called with an invalid action. */
39798152Sgad		printf("\t<error in set_qstate!>\n");
39898152Sgad		return (SQS_PARMERR);
39998152Sgad		/* NOTREACHED */
40098152Sgad	}
40198152Sgad
40298152Sgad	res = 0;
40398152Sgad	if (statres >= 0) {
40498152Sgad		/* The file already exists, so change the access. */
40598152Sgad		seteuid(euid);
40698152Sgad		chres = chmod(lfname, chgbits);
40798152Sgad		errsav = errno;
40898152Sgad		seteuid(uid);
40998152Sgad		res = SQS_CHGOK;
41099845Sgad		if (chres < 0)
41198152Sgad			res = SQS_CHGFAIL;
41298152Sgad	} else if (newbits == LOCK_FILE_MODE) {
41398152Sgad		/*
41498152Sgad		 * The file does not exist, but the state requested is
41598152Sgad		 * the same as the default state when no file exists.
41698152Sgad		 * Thus, there is no need to create the file.
41798152Sgad		 */
41898152Sgad		res = SQS_SKIPCREOK;
41998152Sgad	} else {
42098152Sgad		/*
42198152Sgad		 * The file did not exist, so create it with the
42298152Sgad		 * appropriate access bits for the requested action.
42398152Sgad		 * Push a new umask around that create, to make sure
42498152Sgad		 * all the read/write bits are set as desired.
42598152Sgad		 */
42698152Sgad		oldmask = umask(S_IWOTH);
42798152Sgad		seteuid(euid);
42898152Sgad		fd = open(lfname, O_WRONLY|O_CREAT, newbits);
42998152Sgad		errsav = errno;
43098152Sgad		seteuid(uid);
43198152Sgad		umask(oldmask);
43298152Sgad		res = SQS_CREFAIL;
43398152Sgad		if (fd >= 0) {
43498152Sgad			res = SQS_CREOK;
43598152Sgad			close(fd);
43698152Sgad		}
43798152Sgad	}
43898152Sgad
43998152Sgad	switch (res) {
44098152Sgad	case SQS_CHGOK:
44198152Sgad	case SQS_CREOK:
44298152Sgad	case SQS_SKIPCREOK:
44399844Sgad		if (okmsg != nomsg)
44499844Sgad			printf("\t%s\n", okmsg);
44598152Sgad		break;
44698152Sgad	case SQS_CREFAIL:
44798152Sgad		printf("\tcannot create lock file: %s\n",
44898152Sgad		    strerror(errsav));
44998152Sgad		break;
45098152Sgad	default:
45198152Sgad		printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
45298152Sgad		break;
45398152Sgad	}
45498152Sgad
45598152Sgad	return (res);
45698152Sgad}
45798152Sgad
45868253Sgad/* routine to get a current timestamp, optionally in a standard-fmt string */
45968253Sgadvoid
46079740Sgadlpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
46168253Sgad{
46268253Sgad	struct timespec local_ts;
46368253Sgad	struct timeval btime;
46480172Sgad	char tempstr[TIMESTR_SIZE];
46580172Sgad#ifdef STRFTIME_WRONG_z
46668739Sgad	char *destp;
46780172Sgad#endif
46880172Sgad
46968253Sgad	if (tsp == NULL)
47068253Sgad		tsp = &local_ts;
47168253Sgad
47268253Sgad	/* some platforms have a routine called clock_gettime, but the
47368253Sgad	 * routine does nothing but return "not implemented". */
47468253Sgad	memset(tsp, 0, sizeof(struct timespec));
47568253Sgad	if (clock_gettime(CLOCK_REALTIME, tsp)) {
47668253Sgad		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
47768253Sgad		memset(tsp, 0, sizeof(struct timespec));
47868253Sgad		gettimeofday(&btime, NULL);
47968253Sgad		tsp->tv_sec = btime.tv_sec;
48068253Sgad		tsp->tv_nsec = btime.tv_usec * 1000;
48168253Sgad	}
48268253Sgad
48368253Sgad	/* caller may not need a character-ized version */
48468253Sgad	if ((strp == NULL) || (strsize < 1))
48568253Sgad		return;
48668253Sgad
48768253Sgad	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
48868253Sgad		 localtime(&tsp->tv_sec));
48968253Sgad
49068253Sgad	/*
49168253Sgad	 * This check is for implementations of strftime which treat %z
49268253Sgad	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
49368253Sgad	 * completely ignore %z.  This section is not needed on freebsd.
49468253Sgad	 * I'm not sure this is completely right, but it should work OK
49568253Sgad	 * for EST and EDT...
49668253Sgad	 */
49768253Sgad#ifdef STRFTIME_WRONG_z
49868253Sgad	destp = strrchr(tempstr, ':');
49968253Sgad	if (destp != NULL) {
50068253Sgad		destp += 3;
50168253Sgad		if ((*destp != '+') && (*destp != '-')) {
50268253Sgad			char savday[6];
50368253Sgad			int tzmin = timezone / 60;
50468253Sgad			int tzhr = tzmin / 60;
50568253Sgad			if (daylight)
50668253Sgad				tzhr--;
50768253Sgad			strcpy(savday, destp + strlen(destp) - 4);
50868253Sgad			snprintf(destp, (destp - tempstr), "%+03d%02d",
50968739Sgad			    (-1*tzhr), tzmin % 60);
51068253Sgad			strcat(destp, savday);
51168253Sgad		}
51268253Sgad	}
51368253Sgad#endif
51468253Sgad
51568253Sgad	if (strsize > TIMESTR_SIZE) {
51668253Sgad		strsize = TIMESTR_SIZE;
51768253Sgad		strp[TIMESTR_SIZE+1] = '\0';
51868253Sgad	}
51979740Sgad	strlcpy(strp, tempstr, strsize);
52068253Sgad}
52168253Sgad
52268253Sgad/* routines for writing transfer-statistic records */
52368253Sgadvoid
52478146Sgadtrstat_init(struct printer *pp, const char *fname, int filenum)
52568253Sgad{
52668253Sgad	register const char *srcp;
52768253Sgad	register char *destp, *endp;
52868253Sgad
52968253Sgad	/*
53068253Sgad	 * Figure out the job id of this file.  The filename should be
53168253Sgad	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
53268253Sgad	 * two), followed by the jobnum, followed by a hostname.
53368253Sgad	 * The jobnum is usually 3 digits, but might be as many as 5.
53468253Sgad	 * Note that some care has to be taken parsing this, as the
53568253Sgad	 * filename could be coming from a remote-host, and thus might
53668253Sgad	 * not look anything like what is expected...
53768253Sgad	 */
53868253Sgad	memset(pp->jobnum, 0, sizeof(pp->jobnum));
53968253Sgad	pp->jobnum[0] = '0';
54068253Sgad	srcp = strchr(fname, '/');
54168253Sgad	if (srcp == NULL)
54268253Sgad		srcp = fname;
54368253Sgad	destp = &(pp->jobnum[0]);
54468253Sgad	endp = destp + 5;
54568253Sgad	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
54668253Sgad		srcp++;
54768253Sgad	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
54868253Sgad		*(destp++) = *(srcp++);
54968253Sgad
55068253Sgad	/* get the starting time in both numeric and string formats, and
55168253Sgad	 * save those away along with the file-number */
55268253Sgad	pp->jobdfnum = filenum;
55379740Sgad	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
55468253Sgad
55568253Sgad	return;
55668253Sgad}
55768253Sgad
55868253Sgadvoid
55978146Sgadtrstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
56078146Sgad    const char *userid, const char *otherhost, const char *orighost)
56168253Sgad{
56268253Sgad#define STATLINE_SIZE 1024
56368739Sgad	double trtime;
56480172Sgad	size_t remspace;
56580172Sgad	int statfile;
56668739Sgad	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
56768739Sgad	char *eostat;
56868739Sgad	const char *lprhost, *recvdev, *recvhost, *rectype;
56968739Sgad	const char *sendhost, *statfname;
57068253Sgad#define UPD_EOSTAT(xStr) do {         \
57168253Sgad	eostat = strchr(xStr, '\0');  \
57268253Sgad	remspace = eostat - xStr;     \
57368253Sgad} while(0)
57480172Sgad
57579740Sgad	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
57668253Sgad	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
57768253Sgad
57868253Sgad	gethostname(thishost, sizeof(thishost));
57968253Sgad	lprhost = sendhost = recvhost = recvdev = NULL;
58068253Sgad	switch (sendrecv) {
58168253Sgad	    case TR_SENDING:
58268253Sgad		rectype = "send";
58368253Sgad		statfname = pp->stat_send;
58468253Sgad		sendhost = thishost;
58568253Sgad		recvhost = otherhost;
58668253Sgad		break;
58768253Sgad	    case TR_RECVING:
58868253Sgad		rectype = "recv";
58968253Sgad		statfname = pp->stat_recv;
59068253Sgad		sendhost = otherhost;
59168253Sgad		recvhost = thishost;
59268253Sgad		break;
59368253Sgad	    case TR_PRINTING:
59468739Sgad		/*
59568739Sgad		 * This case is for copying to a device (presumably local,
59668739Sgad		 * though filters using things like 'net/CAP' can confuse
59768739Sgad		 * this assumption...).
59868739Sgad		 */
59968253Sgad		rectype = "prnt";
60068253Sgad		statfname = pp->stat_send;
60168253Sgad		sendhost = thishost;
60268253Sgad		recvdev = _PATH_DEFDEVLP;
60368253Sgad		if (pp->lp) recvdev = pp->lp;
60468253Sgad		break;
60568253Sgad	    default:
60668253Sgad		/* internal error...  should we syslog/printf an error? */
60768253Sgad		return;
60868253Sgad	}
60968739Sgad	if (statfname == NULL)
61068739Sgad		return;
61168253Sgad
61268253Sgad	/*
61368253Sgad	 * the original-host and userid are found out by reading thru the
61468253Sgad	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
61568253Sgad	 * the df's (data-files) are sent before the matching cf, so the
61668253Sgad	 * orighost & userid are generally not-available for incoming jobs.
61768253Sgad	 *
61868253Sgad	 * (it would be nice to create a work-around for that..)
61968739Sgad	 */
62068253Sgad	if (orighost && (*orighost != '\0'))
62168253Sgad		lprhost = orighost;
62268253Sgad	else
62368253Sgad		lprhost = ".na.";
62468739Sgad	if (*userid == '\0')
62568739Sgad		userid = NULL;
62668253Sgad
62768253Sgad	/*
62868253Sgad	 * Format of statline.
62968253Sgad	 * Some of the keywords listed here are not implemented here, but
63068253Sgad	 * they are listed to reserve the meaning for a given keyword.
63168253Sgad	 * Fields are separated by a blank.  The fields in statline are:
63268253Sgad	 *   <tstamp>      - time the transfer started
63368253Sgad	 *   <ptrqueue>    - name of the printer queue (the short-name...)
63468253Sgad	 *   <hname>       - hostname the file originally came from (the
63568253Sgad	 *		     'lpr host'), if known, or  "_na_" if not known.
63668253Sgad	 *   <xxx>         - id of job from that host (generally three digits)
63768253Sgad	 *   <n>           - file count (# of file within job)
63868253Sgad	 *   <rectype>     - 4-byte field indicating the type of transfer
63968253Sgad	 *		     statistics record.  "send" means it's from the
64068253Sgad	 *		     host sending a datafile, "recv" means it's from
64168253Sgad	 *		     a host as it receives a datafile.
64268253Sgad	 *   user=<userid> - user who sent the job (if known)
64368253Sgad	 *   secs=<n>      - seconds it took to transfer the file
64468253Sgad	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
64568253Sgad	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
646240319Sjh	 *		     for this to be useful)
64768253Sgad	 * ! top=<str>     - type of printer (if the type is defined in
64868253Sgad	 *		     printcap, and if this statline is for sending
64968253Sgad	 *		     a file to that ptr)
65068253Sgad	 * ! qls=<n>       - queue-length at start of send/print-ing a job
65168253Sgad	 * ! qle=<n>       - queue-length at end of send/print-ing a job
65268253Sgad	 *   sip=<addr>    - IP address of sending host, only included when
65368253Sgad	 *		     receiving a job.
65468253Sgad	 *   shost=<hname> - sending host (if that does != the original host)
65568253Sgad	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
65668253Sgad	 *   rdev=<dev>    - device receiving the file, when the file is being
65768253Sgad	 *		     send to a device instead of a remote host.
65868253Sgad	 *
65968253Sgad	 * Note: A single print job may be transferred multiple times.  The
66068253Sgad	 * original 'lpr' occurs on one host, and that original host might
66168253Sgad	 * send to some interim host (or print server).  That interim host
66268253Sgad	 * might turn around and send the job to yet another host (most likely
66368253Sgad	 * the real printer).  The 'shost=' parameter is only included if the
66468253Sgad	 * sending host for this particular transfer is NOT the same as the
66568253Sgad	 * host which did the original 'lpr'.
66668253Sgad	 *
66768253Sgad	 * Many values have 'something=' tags before them, because they are
66868253Sgad	 * in some sense "optional", or their order may vary.  "Optional" may
66968253Sgad	 * mean in the sense that different SITES might choose to have other
67068253Sgad	 * fields in the record, or that some fields are only included under
67168253Sgad	 * some circumstances.  Programs processing these records should not
67268253Sgad	 * assume the order or existence of any of these keyword fields.
67368253Sgad	 */
67468253Sgad	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
67568739Sgad	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
67668739Sgad	    pp->jobdfnum, rectype);
67768253Sgad	UPD_EOSTAT(statline);
67868253Sgad
67968253Sgad	if (userid != NULL) {
68068253Sgad		snprintf(eostat, remspace, " user=%s", userid);
68168253Sgad		UPD_EOSTAT(statline);
68268253Sgad	}
68380172Sgad	snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
68480172Sgad	    (unsigned long)bytecnt);
68568253Sgad	UPD_EOSTAT(statline);
68680172Sgad
68768739Sgad	/*
68868739Sgad	 * The bps field duplicates info from bytes and secs, so do
68968739Sgad	 * not bother to include it for very small files.
69068739Sgad	 */
69168253Sgad	if ((bytecnt > 25000) && (trtime > 1.1)) {
69268253Sgad		snprintf(eostat, remspace, " bps=%#.2e",
69368739Sgad		    ((double)bytecnt/trtime));
69468253Sgad		UPD_EOSTAT(statline);
69568253Sgad	}
69668253Sgad
69768253Sgad	if (sendrecv == TR_RECVING) {
69868253Sgad		if (remspace > 5+strlen(from_ip) ) {
69968253Sgad			snprintf(eostat, remspace, " sip=%s", from_ip);
70068253Sgad			UPD_EOSTAT(statline);
70168253Sgad		}
70268253Sgad	}
70368253Sgad	if (0 != strcmp(lprhost, sendhost)) {
70468253Sgad		if (remspace > 7+strlen(sendhost) ) {
70568253Sgad			snprintf(eostat, remspace, " shost=%s", sendhost);
70668253Sgad			UPD_EOSTAT(statline);
70768253Sgad		}
70868253Sgad	}
70968253Sgad	if (recvhost) {
71068253Sgad		if (remspace > 7+strlen(recvhost) ) {
71168253Sgad			snprintf(eostat, remspace, " rhost=%s", recvhost);
71268253Sgad			UPD_EOSTAT(statline);
71368253Sgad		}
71468253Sgad	}
71568253Sgad	if (recvdev) {
71668253Sgad		if (remspace > 6+strlen(recvdev) ) {
71768253Sgad			snprintf(eostat, remspace, " rdev=%s", recvdev);
71868253Sgad			UPD_EOSTAT(statline);
71968253Sgad		}
72068253Sgad	}
72168253Sgad	if (remspace > 1) {
72268253Sgad		strcpy(eostat, "\n");
72368253Sgad	} else {
724240319Sjh		/* probably should back up to just before the final " x=".. */
72568253Sgad		strcpy(statline+STATLINE_SIZE-2, "\n");
72668253Sgad	}
72768253Sgad	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
72868253Sgad	if (statfile < 0) {
72968253Sgad		/* statfile was given, but we can't open it.  should we
73068253Sgad		 * syslog/printf this as an error? */
73168253Sgad		return;
73268253Sgad	}
73368253Sgad	write(statfile, statline, strlen(statline));
73468253Sgad	close(statfile);
73568253Sgad
73668253Sgad	return;
737240319Sjh#undef UPD_EOSTAT
73868253Sgad}
73968253Sgad
7401553Srgrimes#include <stdarg.h>
7411553Srgrimes
7421553Srgrimesvoid
74331492Swollmanfatal(const struct printer *pp, const char *msg, ...)
7441553Srgrimes{
7451553Srgrimes	va_list ap;
7461553Srgrimes	va_start(ap, msg);
74778300Sgad	/* this error message is being sent to the 'from_host' */
74878300Sgad	if (from_host != local_host)
74978300Sgad		(void)printf("%s: ", local_host);
75078280Sgad	(void)printf("%s: ", progname);
75131492Swollman	if (pp && pp->printer)
75231492Swollman		(void)printf("%s: ", pp->printer);
7531553Srgrimes	(void)vprintf(msg, ap);
7541553Srgrimes	va_end(ap);
7551553Srgrimes	(void)putchar('\n');
7561553Srgrimes	exit(1);
7571553Srgrimes}
75831492Swollman
75931492Swollman/*
76031492Swollman * Close all file descriptors from START on up.
76131492Swollman * This is a horrific kluge, since getdtablesize() might return
76231492Swollman * ``infinity'', in which case we will be spending a long time
76331492Swollman * closing ``files'' which were never open.  Perhaps it would
76431492Swollman * be better to close the first N fds, for some small value of N.
76531492Swollman */
76631492Swollmanvoid
76778146Sgadcloseallfds(int start)
76831492Swollman{
76931492Swollman	int stop = getdtablesize();
77031492Swollman	for (; start < stop; start++)
77131492Swollman		close(start);
77231492Swollman}
77331492Swollman
774