common.c revision 139464
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: head/usr.sbin/lpr/common_source/common.c 139464 2004-12-31 00:36:28Z gad $");
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
13927618Simp	 * and dividing it by a multiple of the minimum size entry.
1401553Srgrimes	 */
1411553Srgrimes	arraysz = (stbuf.st_size / 24);
14268401Sgad	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
1431553Srgrimes	if (queue == NULL)
1441553Srgrimes		goto errdone;
1451553Srgrimes
1461553Srgrimes	nitems = 0;
1471553Srgrimes	while ((d = readdir(dirp)) != NULL) {
1481553Srgrimes		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
1491553Srgrimes			continue;	/* daemon control files only */
15027618Simp		seteuid(euid);
15175253Sgad		statres = stat(d->d_name, &stbuf);
15275253Sgad		seteuid(uid);
15375253Sgad		if (statres < 0)
1541553Srgrimes			continue;	/* Doesn't exist */
15599842Sgad		entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
15699842Sgad		    strlen(d->d_name) + 1;
15799842Sgad		q = (struct jobqueue *)malloc(entrysz);
1581553Srgrimes		if (q == NULL)
1591553Srgrimes			goto errdone;
16099842Sgad		q->job_matched = 0;
16199842Sgad		q->job_processed = 0;
16268401Sgad		q->job_time = stbuf.st_mtime;
16368401Sgad		strcpy(q->job_cfname, d->d_name);
1641553Srgrimes		/*
1651553Srgrimes		 * Check to make sure the array has space left and
1661553Srgrimes		 * realloc the maximum size.
1671553Srgrimes		 */
1681553Srgrimes		if (++nitems > arraysz) {
16915648Sjoerg			arraysz *= 2;
17068401Sgad			queue = (struct jobqueue **)realloc((char *)queue,
17168739Sgad			    arraysz * sizeof(struct jobqueue *));
1721553Srgrimes			if (queue == NULL)
1731553Srgrimes				goto errdone;
1741553Srgrimes		}
1751553Srgrimes		queue[nitems-1] = q;
1761553Srgrimes	}
1771553Srgrimes	closedir(dirp);
1781553Srgrimes	if (nitems)
17968401Sgad		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
1801553Srgrimes	*namelist = queue;
1811553Srgrimes	return(nitems);
1821553Srgrimes
1831553Srgrimeserrdone:
1841553Srgrimes	closedir(dirp);
18568740Sgad	seteuid(uid);
18668739Sgad	return (-1);
1871553Srgrimes}
1881553Srgrimes
1891553Srgrimes/*
1901553Srgrimes * Compare modification times.
1911553Srgrimes */
1921553Srgrimesstatic int
19378146Sgadcompar(const void *p1, const void *p2)
1941553Srgrimes{
19568401Sgad	const struct jobqueue *qe1, *qe2;
19668739Sgad
19795290Sgad	qe1 = *(const struct jobqueue * const *)p1;
19895290Sgad	qe2 = *(const struct jobqueue * const *)p2;
19959920Swollman
20068401Sgad	if (qe1->job_time < qe2->job_time)
20159920Swollman		return (-1);
20268401Sgad	if (qe1->job_time > qe2->job_time)
20359920Swollman		return (1);
20459920Swollman	/*
20559920Swollman	 * At this point, the two files have the same last-modification time.
20659920Swollman	 * return a result based on filenames, so that 'cfA001some.host' will
20759920Swollman	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
20859920Swollman	 * around when it gets to '999', we also assume that '9xx' jobs are
20959920Swollman	 * older than '0xx' jobs.
21059920Swollman	*/
21168401Sgad	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
21259920Swollman		return (-1);
21368401Sgad	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
21459920Swollman		return (1);
21568401Sgad	return (strcmp(qe1->job_cfname, qe2->job_cfname));
2161553Srgrimes}
2171553Srgrimes
218139464Sgad/*
219139464Sgad * A simple routine to determine the job number for a print job based on
220139464Sgad * the name of its control file.  The algorithm used here may look odd, but
221139464Sgad * the main issue is that all parts of `lpd', `lpc', `lpq' & `lprm' must be
222139464Sgad * using the same algorithm, whatever that algorithm may be.  If the caller
223139464Sgad * provides a non-null value for ''hostpp', then this returns a pointer to
224139464Sgad * the start of the hostname (or IP address?) as found in the filename.
225139464Sgad *
226139464Sgad * Algorithm: The standard `cf' file has the job number start in position 4,
227139464Sgad * but some implementations have that as an extra file-sequence letter, and
228139464Sgad * start the job number in position 5.  The job number is usually three bytes,
229139464Sgad * but may be as many as five.  Confusing matters still more, some Windows
230139464Sgad * print servers will append an IP address to the job number, instead of
231139464Sgad * the expected hostname.  So, if the job number ends with a '.', then
232139464Sgad * assume the correct jobnum value is the first three digits.
233139464Sgad */
234139464Sgadint
235139464Sgadcalc_jobnum(const char *cfname, const char **hostpp)
236139464Sgad{
237139464Sgad	int jnum;
238139464Sgad	const char *cp, *numstr, *hoststr;
239139464Sgad
240139464Sgad	numstr = cfname + 3;
241139464Sgad	if (!isdigitch(*numstr))
242139464Sgad		numstr++;
243139464Sgad	jnum = 0;
244139464Sgad	for (cp = numstr; (cp < numstr + 5) && isdigitch(*cp); cp++)
245139464Sgad		jnum = jnum * 10 + (*cp - '0');
246139464Sgad	hoststr = cp;
247139464Sgad
248139464Sgad	/*
249139464Sgad	 * If the filename was built with an IP number instead of a hostname,
250139464Sgad	 * then recalculate using only the first three digits found.
251139464Sgad	 */
252139464Sgad	while(isdigitch(*cp))
253139464Sgad		cp++;
254139464Sgad	if (*cp == '.') {
255139464Sgad		jnum = 0;
256139464Sgad		for (cp = numstr; (cp < numstr + 3) && isdigitch(*cp); cp++)
257139464Sgad			jnum = jnum * 10 + (*cp - '0');
258139464Sgad		hoststr = cp;
259139464Sgad	}
260139464Sgad	if (hostpp != NULL)
261139464Sgad		*hostpp = hoststr;
262139464Sgad	return (jnum);
263139464Sgad}
264139464Sgad
26515648Sjoerg/* sleep n milliseconds */
26615648Sjoergvoid
26778146Sgaddelay(int millisec)
26815648Sjoerg{
26915648Sjoerg	struct timeval tdelay;
27015648Sjoerg
27178146Sgad	if (millisec <= 0 || millisec > 10000)
27231492Swollman		fatal((struct printer *)0, /* fatal() knows how to deal */
27378146Sgad		    "unreasonable delay period (%d)", millisec);
27478146Sgad	tdelay.tv_sec = millisec / 1000;
27578146Sgad	tdelay.tv_usec = millisec * 1000 % 1000000;
27615648Sjoerg	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
27715648Sjoerg}
27815648Sjoerg
27931492Swollmanchar *
28078146Sgadlock_file_name(const struct printer *pp, char *buf, size_t len)
28131492Swollman{
28231492Swollman	static char staticbuf[MAXPATHLEN];
28331492Swollman
28431492Swollman	if (buf == 0)
28531492Swollman		buf = staticbuf;
28631492Swollman	if (len == 0)
28731492Swollman		len = MAXPATHLEN;
28831492Swollman
28979740Sgad	if (pp->lock_file[0] == '/')
29079740Sgad		strlcpy(buf, pp->lock_file, len);
29179740Sgad	else
29231492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
29379740Sgad
29431492Swollman	return buf;
29531492Swollman}
29631492Swollman
29731492Swollmanchar *
29878146Sgadstatus_file_name(const struct printer *pp, char *buf, size_t len)
29931492Swollman{
30031492Swollman	static char staticbuf[MAXPATHLEN];
30131492Swollman
30231492Swollman	if (buf == 0)
30331492Swollman		buf = staticbuf;
30431492Swollman	if (len == 0)
30531492Swollman		len = MAXPATHLEN;
30631492Swollman
30779740Sgad	if (pp->status_file[0] == '/')
30879740Sgad		strlcpy(buf, pp->status_file, len);
30979740Sgad	else
31031492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
31179740Sgad
31231492Swollman	return buf;
31331492Swollman}
31431492Swollman
31598152Sgad/*
31698152Sgad * Routine to change operational state of a print queue.  The operational
31798154Sgad * state is indicated by the access bits on the lock file for the queue.
31898152Sgad * At present, this is only called from various routines in lpc/cmds.c.
31998152Sgad *
32098152Sgad *  XXX - Note that this works by changing access-bits on the
32198152Sgad *	file, and you can only do that if you are the owner of
32298152Sgad *	the file, or root.  Thus, this won't really work for
32398152Sgad *	userids in the "LPR_OPER" group, unless lpc is running
32498152Sgad *	setuid to root (or maybe setuid to daemon).
32598152Sgad *	Generally lpc is installed setgid to daemon, but does
32698152Sgad *	not run setuid.
32798152Sgad */
32898152Sgadint
32998152Sgadset_qstate(int action, const char *lfname)
33098152Sgad{
33198152Sgad	struct stat stbuf;
33298152Sgad	mode_t chgbits, newbits, oldmask;
33398152Sgad	const char *failmsg, *okmsg;
33499844Sgad	static const char *nomsg = "no state msg";
33598152Sgad	int chres, errsav, fd, res, statres;
33698152Sgad
33798152Sgad	/*
33898152Sgad	 * Find what the current access-bits are.
33998152Sgad	 */
34098152Sgad	memset(&stbuf, 0, sizeof(stbuf));
34198152Sgad	seteuid(euid);
34298152Sgad	statres = stat(lfname, &stbuf);
34398152Sgad	errsav = errno;
34498152Sgad	seteuid(uid);
34598152Sgad	if ((statres < 0) && (errsav != ENOENT)) {
34698152Sgad		printf("\tcannot stat() lock file\n");
34798152Sgad		return (SQS_STATFAIL);
34898152Sgad		/* NOTREACHED */
34998152Sgad	}
35098152Sgad
35198152Sgad	/*
35298152Sgad	 * Determine which bit(s) should change for the requested action.
35398152Sgad	 */
35498152Sgad	chgbits = stbuf.st_mode;
35598152Sgad	newbits = LOCK_FILE_MODE;
35698152Sgad	okmsg = NULL;
35798152Sgad	failmsg = NULL;
35899844Sgad	if (action & SQS_QCHANGED) {
35999844Sgad		chgbits |= LFM_RESET_QUE;
36099844Sgad		newbits |= LFM_RESET_QUE;
36199844Sgad		/* The okmsg is not actually printed for this case. */
36299844Sgad		okmsg = nomsg;
36399844Sgad		failmsg = "set queue-changed";
36499844Sgad	}
36598152Sgad	if (action & SQS_DISABLEQ) {
36698152Sgad		chgbits |= LFM_QUEUE_DIS;
36798152Sgad		newbits |= LFM_QUEUE_DIS;
36898152Sgad		okmsg = "queuing disabled";
36998152Sgad		failmsg = "disable queuing";
37098152Sgad	}
37198152Sgad	if (action & SQS_STOPP) {
37298152Sgad		chgbits |= LFM_PRINT_DIS;
37398152Sgad		newbits |= LFM_PRINT_DIS;
37498152Sgad		okmsg = "printing disabled";
37598152Sgad		failmsg = "disable printing";
37698152Sgad		if (action & SQS_DISABLEQ) {
37798152Sgad			okmsg = "printer and queuing disabled";
37898152Sgad			failmsg = "disable queuing and printing";
37998152Sgad		}
38098152Sgad	}
38198152Sgad	if (action & SQS_ENABLEQ) {
38298152Sgad		chgbits &= ~LFM_QUEUE_DIS;
38398152Sgad		newbits &= ~LFM_QUEUE_DIS;
38498152Sgad		okmsg = "queuing enabled";
38598152Sgad		failmsg = "enable queuing";
38698152Sgad	}
38798152Sgad	if (action & SQS_STARTP) {
38898152Sgad		chgbits &= ~LFM_PRINT_DIS;
38998152Sgad		newbits &= ~LFM_PRINT_DIS;
39098152Sgad		okmsg = "printing enabled";
39198152Sgad		failmsg = "enable printing";
39298152Sgad	}
39398152Sgad	if (okmsg == NULL) {
39498152Sgad		/* This routine was called with an invalid action. */
39598152Sgad		printf("\t<error in set_qstate!>\n");
39698152Sgad		return (SQS_PARMERR);
39798152Sgad		/* NOTREACHED */
39898152Sgad	}
39998152Sgad
40098152Sgad	res = 0;
40198152Sgad	if (statres >= 0) {
40298152Sgad		/* The file already exists, so change the access. */
40398152Sgad		seteuid(euid);
40498152Sgad		chres = chmod(lfname, chgbits);
40598152Sgad		errsav = errno;
40698152Sgad		seteuid(uid);
40798152Sgad		res = SQS_CHGOK;
40899845Sgad		if (chres < 0)
40998152Sgad			res = SQS_CHGFAIL;
41098152Sgad	} else if (newbits == LOCK_FILE_MODE) {
41198152Sgad		/*
41298152Sgad		 * The file does not exist, but the state requested is
41398152Sgad		 * the same as the default state when no file exists.
41498152Sgad		 * Thus, there is no need to create the file.
41598152Sgad		 */
41698152Sgad		res = SQS_SKIPCREOK;
41798152Sgad	} else {
41898152Sgad		/*
41998152Sgad		 * The file did not exist, so create it with the
42098152Sgad		 * appropriate access bits for the requested action.
42198152Sgad		 * Push a new umask around that create, to make sure
42298152Sgad		 * all the read/write bits are set as desired.
42398152Sgad		 */
42498152Sgad		oldmask = umask(S_IWOTH);
42598152Sgad		seteuid(euid);
42698152Sgad		fd = open(lfname, O_WRONLY|O_CREAT, newbits);
42798152Sgad		errsav = errno;
42898152Sgad		seteuid(uid);
42998152Sgad		umask(oldmask);
43098152Sgad		res = SQS_CREFAIL;
43198152Sgad		if (fd >= 0) {
43298152Sgad			res = SQS_CREOK;
43398152Sgad			close(fd);
43498152Sgad		}
43598152Sgad	}
43698152Sgad
43798152Sgad	switch (res) {
43898152Sgad	case SQS_CHGOK:
43998152Sgad	case SQS_CREOK:
44098152Sgad	case SQS_SKIPCREOK:
44199844Sgad		if (okmsg != nomsg)
44299844Sgad			printf("\t%s\n", okmsg);
44398152Sgad		break;
44498152Sgad	case SQS_CREFAIL:
44598152Sgad		printf("\tcannot create lock file: %s\n",
44698152Sgad		    strerror(errsav));
44798152Sgad		break;
44898152Sgad	default:
44998152Sgad		printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
45098152Sgad		break;
45198152Sgad	}
45298152Sgad
45398152Sgad	return (res);
45498152Sgad}
45598152Sgad
45668253Sgad/* routine to get a current timestamp, optionally in a standard-fmt string */
45768253Sgadvoid
45879740Sgadlpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
45968253Sgad{
46068253Sgad	struct timespec local_ts;
46168253Sgad	struct timeval btime;
46280172Sgad	char tempstr[TIMESTR_SIZE];
46380172Sgad#ifdef STRFTIME_WRONG_z
46468739Sgad	char *destp;
46580172Sgad#endif
46680172Sgad
46768253Sgad	if (tsp == NULL)
46868253Sgad		tsp = &local_ts;
46968253Sgad
47068253Sgad	/* some platforms have a routine called clock_gettime, but the
47168253Sgad	 * routine does nothing but return "not implemented". */
47268253Sgad	memset(tsp, 0, sizeof(struct timespec));
47368253Sgad	if (clock_gettime(CLOCK_REALTIME, tsp)) {
47468253Sgad		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
47568253Sgad		memset(tsp, 0, sizeof(struct timespec));
47668253Sgad		gettimeofday(&btime, NULL);
47768253Sgad		tsp->tv_sec = btime.tv_sec;
47868253Sgad		tsp->tv_nsec = btime.tv_usec * 1000;
47968253Sgad	}
48068253Sgad
48168253Sgad	/* caller may not need a character-ized version */
48268253Sgad	if ((strp == NULL) || (strsize < 1))
48368253Sgad		return;
48468253Sgad
48568253Sgad	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
48668253Sgad		 localtime(&tsp->tv_sec));
48768253Sgad
48868253Sgad	/*
48968253Sgad	 * This check is for implementations of strftime which treat %z
49068253Sgad	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
49168253Sgad	 * completely ignore %z.  This section is not needed on freebsd.
49268253Sgad	 * I'm not sure this is completely right, but it should work OK
49368253Sgad	 * for EST and EDT...
49468253Sgad	 */
49568253Sgad#ifdef STRFTIME_WRONG_z
49668253Sgad	destp = strrchr(tempstr, ':');
49768253Sgad	if (destp != NULL) {
49868253Sgad		destp += 3;
49968253Sgad		if ((*destp != '+') && (*destp != '-')) {
50068253Sgad			char savday[6];
50168253Sgad			int tzmin = timezone / 60;
50268253Sgad			int tzhr = tzmin / 60;
50368253Sgad			if (daylight)
50468253Sgad				tzhr--;
50568253Sgad			strcpy(savday, destp + strlen(destp) - 4);
50668253Sgad			snprintf(destp, (destp - tempstr), "%+03d%02d",
50768739Sgad			    (-1*tzhr), tzmin % 60);
50868253Sgad			strcat(destp, savday);
50968253Sgad		}
51068253Sgad	}
51168253Sgad#endif
51268253Sgad
51368253Sgad	if (strsize > TIMESTR_SIZE) {
51468253Sgad		strsize = TIMESTR_SIZE;
51568253Sgad		strp[TIMESTR_SIZE+1] = '\0';
51668253Sgad	}
51779740Sgad	strlcpy(strp, tempstr, strsize);
51868253Sgad}
51968253Sgad
52068253Sgad/* routines for writing transfer-statistic records */
52168253Sgadvoid
52278146Sgadtrstat_init(struct printer *pp, const char *fname, int filenum)
52368253Sgad{
52468253Sgad	register const char *srcp;
52568253Sgad	register char *destp, *endp;
52668253Sgad
52768253Sgad	/*
52868253Sgad	 * Figure out the job id of this file.  The filename should be
52968253Sgad	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
53068253Sgad	 * two), followed by the jobnum, followed by a hostname.
53168253Sgad	 * The jobnum is usually 3 digits, but might be as many as 5.
53268253Sgad	 * Note that some care has to be taken parsing this, as the
53368253Sgad	 * filename could be coming from a remote-host, and thus might
53468253Sgad	 * not look anything like what is expected...
53568253Sgad	 */
53668253Sgad	memset(pp->jobnum, 0, sizeof(pp->jobnum));
53768253Sgad	pp->jobnum[0] = '0';
53868253Sgad	srcp = strchr(fname, '/');
53968253Sgad	if (srcp == NULL)
54068253Sgad		srcp = fname;
54168253Sgad	destp = &(pp->jobnum[0]);
54268253Sgad	endp = destp + 5;
54368253Sgad	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
54468253Sgad		srcp++;
54568253Sgad	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
54668253Sgad		*(destp++) = *(srcp++);
54768253Sgad
54868253Sgad	/* get the starting time in both numeric and string formats, and
54968253Sgad	 * save those away along with the file-number */
55068253Sgad	pp->jobdfnum = filenum;
55179740Sgad	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
55268253Sgad
55368253Sgad	return;
55468253Sgad}
55568253Sgad
55668253Sgadvoid
55778146Sgadtrstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
55878146Sgad    const char *userid, const char *otherhost, const char *orighost)
55968253Sgad{
56068253Sgad#define STATLINE_SIZE 1024
56168739Sgad	double trtime;
56280172Sgad	size_t remspace;
56380172Sgad	int statfile;
56468739Sgad	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
56568739Sgad	char *eostat;
56668739Sgad	const char *lprhost, *recvdev, *recvhost, *rectype;
56768739Sgad	const char *sendhost, *statfname;
56868253Sgad#define UPD_EOSTAT(xStr) do {         \
56968253Sgad	eostat = strchr(xStr, '\0');  \
57068253Sgad	remspace = eostat - xStr;     \
57168253Sgad} while(0)
57280172Sgad
57379740Sgad	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
57468253Sgad	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
57568253Sgad
57668253Sgad	gethostname(thishost, sizeof(thishost));
57768253Sgad	lprhost = sendhost = recvhost = recvdev = NULL;
57868253Sgad	switch (sendrecv) {
57968253Sgad	    case TR_SENDING:
58068253Sgad		rectype = "send";
58168253Sgad		statfname = pp->stat_send;
58268253Sgad		sendhost = thishost;
58368253Sgad		recvhost = otherhost;
58468253Sgad		break;
58568253Sgad	    case TR_RECVING:
58668253Sgad		rectype = "recv";
58768253Sgad		statfname = pp->stat_recv;
58868253Sgad		sendhost = otherhost;
58968253Sgad		recvhost = thishost;
59068253Sgad		break;
59168253Sgad	    case TR_PRINTING:
59268739Sgad		/*
59368739Sgad		 * This case is for copying to a device (presumably local,
59468739Sgad		 * though filters using things like 'net/CAP' can confuse
59568739Sgad		 * this assumption...).
59668739Sgad		 */
59768253Sgad		rectype = "prnt";
59868253Sgad		statfname = pp->stat_send;
59968253Sgad		sendhost = thishost;
60068253Sgad		recvdev = _PATH_DEFDEVLP;
60168253Sgad		if (pp->lp) recvdev = pp->lp;
60268253Sgad		break;
60368253Sgad	    default:
60468253Sgad		/* internal error...  should we syslog/printf an error? */
60568253Sgad		return;
60668253Sgad	}
60768739Sgad	if (statfname == NULL)
60868739Sgad		return;
60968253Sgad
61068253Sgad	/*
61168253Sgad	 * the original-host and userid are found out by reading thru the
61268253Sgad	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
61368253Sgad	 * the df's (data-files) are sent before the matching cf, so the
61468253Sgad	 * orighost & userid are generally not-available for incoming jobs.
61568253Sgad	 *
61668253Sgad	 * (it would be nice to create a work-around for that..)
61768739Sgad	 */
61868253Sgad	if (orighost && (*orighost != '\0'))
61968253Sgad		lprhost = orighost;
62068253Sgad	else
62168253Sgad		lprhost = ".na.";
62268739Sgad	if (*userid == '\0')
62368739Sgad		userid = NULL;
62468253Sgad
62568253Sgad	/*
62668253Sgad	 * Format of statline.
62768253Sgad	 * Some of the keywords listed here are not implemented here, but
62868253Sgad	 * they are listed to reserve the meaning for a given keyword.
62968253Sgad	 * Fields are separated by a blank.  The fields in statline are:
63068253Sgad	 *   <tstamp>      - time the transfer started
63168253Sgad	 *   <ptrqueue>    - name of the printer queue (the short-name...)
63268253Sgad	 *   <hname>       - hostname the file originally came from (the
63368253Sgad	 *		     'lpr host'), if known, or  "_na_" if not known.
63468253Sgad	 *   <xxx>         - id of job from that host (generally three digits)
63568253Sgad	 *   <n>           - file count (# of file within job)
63668253Sgad	 *   <rectype>     - 4-byte field indicating the type of transfer
63768253Sgad	 *		     statistics record.  "send" means it's from the
63868253Sgad	 *		     host sending a datafile, "recv" means it's from
63968253Sgad	 *		     a host as it receives a datafile.
64068253Sgad	 *   user=<userid> - user who sent the job (if known)
64168253Sgad	 *   secs=<n>      - seconds it took to transfer the file
64268253Sgad	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
64368253Sgad	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
64468253Sgad	 *		     for this to be useful)
64568253Sgad	 * ! top=<str>     - type of printer (if the type is defined in
64668253Sgad	 *		     printcap, and if this statline is for sending
64768253Sgad	 *		     a file to that ptr)
64868253Sgad	 * ! qls=<n>       - queue-length at start of send/print-ing a job
64968253Sgad	 * ! qle=<n>       - queue-length at end of send/print-ing a job
65068253Sgad	 *   sip=<addr>    - IP address of sending host, only included when
65168253Sgad	 *		     receiving a job.
65268253Sgad	 *   shost=<hname> - sending host (if that does != the original host)
65368253Sgad	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
65468253Sgad	 *   rdev=<dev>    - device receiving the file, when the file is being
65568253Sgad	 *		     send to a device instead of a remote host.
65668253Sgad	 *
65768253Sgad	 * Note: A single print job may be transferred multiple times.  The
65868253Sgad	 * original 'lpr' occurs on one host, and that original host might
65968253Sgad	 * send to some interim host (or print server).  That interim host
66068253Sgad	 * might turn around and send the job to yet another host (most likely
66168253Sgad	 * the real printer).  The 'shost=' parameter is only included if the
66268253Sgad	 * sending host for this particular transfer is NOT the same as the
66368253Sgad	 * host which did the original 'lpr'.
66468253Sgad	 *
66568253Sgad	 * Many values have 'something=' tags before them, because they are
66668253Sgad	 * in some sense "optional", or their order may vary.  "Optional" may
66768253Sgad	 * mean in the sense that different SITES might choose to have other
66868253Sgad	 * fields in the record, or that some fields are only included under
66968253Sgad	 * some circumstances.  Programs processing these records should not
67068253Sgad	 * assume the order or existence of any of these keyword fields.
67168253Sgad	 */
67268253Sgad	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
67368739Sgad	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
67468739Sgad	    pp->jobdfnum, rectype);
67568253Sgad	UPD_EOSTAT(statline);
67668253Sgad
67768253Sgad	if (userid != NULL) {
67868253Sgad		snprintf(eostat, remspace, " user=%s", userid);
67968253Sgad		UPD_EOSTAT(statline);
68068253Sgad	}
68180172Sgad	snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
68280172Sgad	    (unsigned long)bytecnt);
68368253Sgad	UPD_EOSTAT(statline);
68480172Sgad
68568739Sgad	/*
68668739Sgad	 * The bps field duplicates info from bytes and secs, so do
68768739Sgad	 * not bother to include it for very small files.
68868739Sgad	 */
68968253Sgad	if ((bytecnt > 25000) && (trtime > 1.1)) {
69068253Sgad		snprintf(eostat, remspace, " bps=%#.2e",
69168739Sgad		    ((double)bytecnt/trtime));
69268253Sgad		UPD_EOSTAT(statline);
69368253Sgad	}
69468253Sgad
69568253Sgad	if (sendrecv == TR_RECVING) {
69668253Sgad		if (remspace > 5+strlen(from_ip) ) {
69768253Sgad			snprintf(eostat, remspace, " sip=%s", from_ip);
69868253Sgad			UPD_EOSTAT(statline);
69968253Sgad		}
70068253Sgad	}
70168253Sgad	if (0 != strcmp(lprhost, sendhost)) {
70268253Sgad		if (remspace > 7+strlen(sendhost) ) {
70368253Sgad			snprintf(eostat, remspace, " shost=%s", sendhost);
70468253Sgad			UPD_EOSTAT(statline);
70568253Sgad		}
70668253Sgad	}
70768253Sgad	if (recvhost) {
70868253Sgad		if (remspace > 7+strlen(recvhost) ) {
70968253Sgad			snprintf(eostat, remspace, " rhost=%s", recvhost);
71068253Sgad			UPD_EOSTAT(statline);
71168253Sgad		}
71268253Sgad	}
71368253Sgad	if (recvdev) {
71468253Sgad		if (remspace > 6+strlen(recvdev) ) {
71568253Sgad			snprintf(eostat, remspace, " rdev=%s", recvdev);
71668253Sgad			UPD_EOSTAT(statline);
71768253Sgad		}
71868253Sgad	}
71968253Sgad	if (remspace > 1) {
72068253Sgad		strcpy(eostat, "\n");
72168253Sgad	} else {
72268253Sgad		/* probably should back up to just before the final " x=".. */
72368253Sgad		strcpy(statline+STATLINE_SIZE-2, "\n");
72468253Sgad	}
72568253Sgad	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
72668253Sgad	if (statfile < 0) {
72768253Sgad		/* statfile was given, but we can't open it.  should we
72868253Sgad		 * syslog/printf this as an error? */
72968253Sgad		return;
73068253Sgad	}
73168253Sgad	write(statfile, statline, strlen(statline));
73268253Sgad	close(statfile);
73368253Sgad
73468253Sgad	return;
73568253Sgad#undef UPD_EOSTAT
73668253Sgad}
73768253Sgad
7381553Srgrimes#include <stdarg.h>
7391553Srgrimes
7401553Srgrimesvoid
74131492Swollmanfatal(const struct printer *pp, const char *msg, ...)
7421553Srgrimes{
7431553Srgrimes	va_list ap;
7441553Srgrimes	va_start(ap, msg);
74578300Sgad	/* this error message is being sent to the 'from_host' */
74678300Sgad	if (from_host != local_host)
74778300Sgad		(void)printf("%s: ", local_host);
74878280Sgad	(void)printf("%s: ", progname);
74931492Swollman	if (pp && pp->printer)
75031492Swollman		(void)printf("%s: ", pp->printer);
7511553Srgrimes	(void)vprintf(msg, ap);
7521553Srgrimes	va_end(ap);
7531553Srgrimes	(void)putchar('\n');
7541553Srgrimes	exit(1);
7551553Srgrimes}
75631492Swollman
75731492Swollman/*
75831492Swollman * Close all file descriptors from START on up.
75931492Swollman * This is a horrific kluge, since getdtablesize() might return
76031492Swollman * ``infinity'', in which case we will be spending a long time
76131492Swollman * closing ``files'' which were never open.  Perhaps it would
76231492Swollman * be better to close the first N fds, for some small value of N.
76331492Swollman */
76431492Swollmanvoid
76578146Sgadcloseallfds(int start)
76631492Swollman{
76731492Swollman	int stop = getdtablesize();
76831492Swollman	for (; start < stop; start++)
76931492Swollman		close(start);
77031492Swollman}
77131492Swollman
772