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>
55241852Seadler#include <err.h>
5698152Sgad#include <errno.h>
5768253Sgad#include <fcntl.h>
5831492Swollman#include <stdio.h>
591553Srgrimes#include <stdlib.h>
601553Srgrimes#include <string.h>
6131492Swollman#include <unistd.h>
6231492Swollman
631553Srgrimes#include "lp.h"
6431492Swollman#include "lp.local.h"
651553Srgrimes#include "pathnames.h"
661553Srgrimes
671553Srgrimes/*
681553Srgrimes * Routines and data common to all the line printer functions.
691553Srgrimes */
701553Srgrimeschar	line[BUFSIZ];
7178280Sgadconst char	*progname;		/* program name */
721553Srgrimes
7378146Sgadstatic int compar(const void *_p1, const void *_p2);
741553Srgrimes
751553Srgrimes/*
76139464Sgad * isdigit() takes a parameter of 'int', but expect values in the range
77139464Sgad * of unsigned char.  Define a wrapper which takes a value of type 'char',
78139464Sgad * whether signed or unsigned, and ensure it ends up in the right range.
79139464Sgad */
80139464Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
81139464Sgad
82139464Sgad/*
831553Srgrimes * Getline reads a line from the control file cfp, removes tabs, converts
841553Srgrimes *  new-line to null and leaves it in line.
851553Srgrimes * Returns 0 at EOF or the number of characters read.
861553Srgrimes */
871553Srgrimesint
8878146Sgadgetline(FILE *cfp)
891553Srgrimes{
901553Srgrimes	register int linel = 0;
911553Srgrimes	register char *lp = line;
9239084Swollman	register int c;
931553Srgrimes
9480172Sgad	while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
951553Srgrimes		if (c == EOF)
961553Srgrimes			return(0);
971553Srgrimes		if (c == '\t') {
981553Srgrimes			do {
991553Srgrimes				*lp++ = ' ';
1001553Srgrimes				linel++;
10180172Sgad			} while ((linel & 07) != 0 && (size_t)(linel+1) <
10280172Sgad			    sizeof(line));
1031553Srgrimes			continue;
1041553Srgrimes		}
1051553Srgrimes		*lp++ = c;
1061553Srgrimes		linel++;
1071553Srgrimes	}
1081553Srgrimes	*lp++ = '\0';
1091553Srgrimes	return(linel);
1101553Srgrimes}
1111553Srgrimes
1121553Srgrimes/*
1131553Srgrimes * Scan the current directory and make a list of daemon files sorted by
1141553Srgrimes * creation time.
1151553Srgrimes * Return the number of entries and a pointer to the list.
1161553Srgrimes */
1171553Srgrimesint
11878146Sgadgetq(const struct printer *pp, struct jobqueue *(*namelist[]))
1191553Srgrimes{
1201553Srgrimes	register struct dirent *d;
12168401Sgad	register struct jobqueue *q, **queue;
12299842Sgad	size_t arraysz, entrysz, nitems;
1231553Srgrimes	struct stat stbuf;
1241553Srgrimes	DIR *dirp;
12580172Sgad	int statres;
1261553Srgrimes
127241852Seadler	PRIV_START
12868740Sgad	if ((dirp = opendir(pp->spool_dir)) == NULL) {
129241852Seadler		PRIV_END
13068739Sgad		return (-1);
13168740Sgad	}
132235647Sgleb	if (fstat(dirfd(dirp), &stbuf) < 0)
1331553Srgrimes		goto errdone;
134241852Seadler	PRIV_END
1351553Srgrimes
1361553Srgrimes	/*
1371553Srgrimes	 * Estimate the array size by taking the size of the directory file
138238546Sjh	 * and dividing it by a multiple of the minimum size entry.
1391553Srgrimes	 */
1401553Srgrimes	arraysz = (stbuf.st_size / 24);
141238547Sjh	if (arraysz < 16)
142238547Sjh		arraysz = 16;
14368401Sgad	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
1441553Srgrimes	if (queue == NULL)
1451553Srgrimes		goto errdone;
1461553Srgrimes
1471553Srgrimes	nitems = 0;
1481553Srgrimes	while ((d = readdir(dirp)) != NULL) {
1491553Srgrimes		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
1501553Srgrimes			continue;	/* daemon control files only */
151241852Seadler		PRIV_START
15275253Sgad		statres = stat(d->d_name, &stbuf);
153241852Seadler		PRIV_END
15475253Sgad		if (statres < 0)
1551553Srgrimes			continue;	/* Doesn't exist */
15699842Sgad		entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
15799842Sgad		    strlen(d->d_name) + 1;
15899842Sgad		q = (struct jobqueue *)malloc(entrysz);
1591553Srgrimes		if (q == NULL)
1601553Srgrimes			goto errdone;
16199842Sgad		q->job_matched = 0;
16299842Sgad		q->job_processed = 0;
16368401Sgad		q->job_time = stbuf.st_mtime;
16468401Sgad		strcpy(q->job_cfname, d->d_name);
1651553Srgrimes		/*
1661553Srgrimes		 * Check to make sure the array has space left and
1671553Srgrimes		 * realloc the maximum size.
1681553Srgrimes		 */
1691553Srgrimes		if (++nitems > arraysz) {
17015648Sjoerg			arraysz *= 2;
17168401Sgad			queue = (struct jobqueue **)realloc((char *)queue,
17268739Sgad			    arraysz * sizeof(struct jobqueue *));
1731553Srgrimes			if (queue == NULL)
1741553Srgrimes				goto errdone;
1751553Srgrimes		}
1761553Srgrimes		queue[nitems-1] = q;
1771553Srgrimes	}
1781553Srgrimes	closedir(dirp);
1791553Srgrimes	if (nitems)
18068401Sgad		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
1811553Srgrimes	*namelist = queue;
1821553Srgrimes	return(nitems);
1831553Srgrimes
1841553Srgrimeserrdone:
1851553Srgrimes	closedir(dirp);
186241852Seadler	PRIV_END
18768739Sgad	return (-1);
1881553Srgrimes}
1891553Srgrimes
1901553Srgrimes/*
1911553Srgrimes * Compare modification times.
1921553Srgrimes */
1931553Srgrimesstatic int
19478146Sgadcompar(const void *p1, const void *p2)
1951553Srgrimes{
19668401Sgad	const struct jobqueue *qe1, *qe2;
19768739Sgad
19895290Sgad	qe1 = *(const struct jobqueue * const *)p1;
19995290Sgad	qe2 = *(const struct jobqueue * const *)p2;
20059920Swollman
20168401Sgad	if (qe1->job_time < qe2->job_time)
20259920Swollman		return (-1);
20368401Sgad	if (qe1->job_time > qe2->job_time)
20459920Swollman		return (1);
20559920Swollman	/*
20659920Swollman	 * At this point, the two files have the same last-modification time.
20759920Swollman	 * return a result based on filenames, so that 'cfA001some.host' will
20859920Swollman	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
20959920Swollman	 * around when it gets to '999', we also assume that '9xx' jobs are
21059920Swollman	 * older than '0xx' jobs.
21159920Swollman	*/
21268401Sgad	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
21359920Swollman		return (-1);
21468401Sgad	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
21559920Swollman		return (1);
21668401Sgad	return (strcmp(qe1->job_cfname, qe2->job_cfname));
2171553Srgrimes}
2181553Srgrimes
219139464Sgad/*
220139464Sgad * A simple routine to determine the job number for a print job based on
221139464Sgad * the name of its control file.  The algorithm used here may look odd, but
222139464Sgad * the main issue is that all parts of `lpd', `lpc', `lpq' & `lprm' must be
223139464Sgad * using the same algorithm, whatever that algorithm may be.  If the caller
224139464Sgad * provides a non-null value for ''hostpp', then this returns a pointer to
225139464Sgad * the start of the hostname (or IP address?) as found in the filename.
226139464Sgad *
227139464Sgad * Algorithm: The standard `cf' file has the job number start in position 4,
228139464Sgad * but some implementations have that as an extra file-sequence letter, and
229139464Sgad * start the job number in position 5.  The job number is usually three bytes,
230139464Sgad * but may be as many as five.  Confusing matters still more, some Windows
231139464Sgad * print servers will append an IP address to the job number, instead of
232139464Sgad * the expected hostname.  So, if the job number ends with a '.', then
233139464Sgad * assume the correct jobnum value is the first three digits.
234139464Sgad */
235139464Sgadint
236139464Sgadcalc_jobnum(const char *cfname, const char **hostpp)
237139464Sgad{
238139464Sgad	int jnum;
239139464Sgad	const char *cp, *numstr, *hoststr;
240139464Sgad
241139464Sgad	numstr = cfname + 3;
242139464Sgad	if (!isdigitch(*numstr))
243139464Sgad		numstr++;
244139464Sgad	jnum = 0;
245139464Sgad	for (cp = numstr; (cp < numstr + 5) && isdigitch(*cp); cp++)
246139464Sgad		jnum = jnum * 10 + (*cp - '0');
247139464Sgad	hoststr = cp;
248139464Sgad
249139464Sgad	/*
250139464Sgad	 * If the filename was built with an IP number instead of a hostname,
251139464Sgad	 * then recalculate using only the first three digits found.
252139464Sgad	 */
253139464Sgad	while(isdigitch(*cp))
254139464Sgad		cp++;
255139464Sgad	if (*cp == '.') {
256139464Sgad		jnum = 0;
257139464Sgad		for (cp = numstr; (cp < numstr + 3) && isdigitch(*cp); cp++)
258139464Sgad			jnum = jnum * 10 + (*cp - '0');
259139464Sgad		hoststr = cp;
260139464Sgad	}
261139464Sgad	if (hostpp != NULL)
262139464Sgad		*hostpp = hoststr;
263139464Sgad	return (jnum);
264139464Sgad}
265139464Sgad
26615648Sjoerg/* sleep n milliseconds */
26715648Sjoergvoid
26878146Sgaddelay(int millisec)
26915648Sjoerg{
27015648Sjoerg	struct timeval tdelay;
27115648Sjoerg
27278146Sgad	if (millisec <= 0 || millisec > 10000)
27331492Swollman		fatal((struct printer *)0, /* fatal() knows how to deal */
27478146Sgad		    "unreasonable delay period (%d)", millisec);
27578146Sgad	tdelay.tv_sec = millisec / 1000;
27678146Sgad	tdelay.tv_usec = millisec * 1000 % 1000000;
27715648Sjoerg	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
27815648Sjoerg}
27915648Sjoerg
28031492Swollmanchar *
28178146Sgadlock_file_name(const struct printer *pp, char *buf, size_t len)
28231492Swollman{
28331492Swollman	static char staticbuf[MAXPATHLEN];
28431492Swollman
28531492Swollman	if (buf == 0)
28631492Swollman		buf = staticbuf;
28731492Swollman	if (len == 0)
28831492Swollman		len = MAXPATHLEN;
28931492Swollman
29079740Sgad	if (pp->lock_file[0] == '/')
29179740Sgad		strlcpy(buf, pp->lock_file, len);
29279740Sgad	else
29331492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
29479740Sgad
29531492Swollman	return buf;
29631492Swollman}
29731492Swollman
29831492Swollmanchar *
29978146Sgadstatus_file_name(const struct printer *pp, char *buf, size_t len)
30031492Swollman{
30131492Swollman	static char staticbuf[MAXPATHLEN];
30231492Swollman
30331492Swollman	if (buf == 0)
30431492Swollman		buf = staticbuf;
30531492Swollman	if (len == 0)
30631492Swollman		len = MAXPATHLEN;
30731492Swollman
30879740Sgad	if (pp->status_file[0] == '/')
30979740Sgad		strlcpy(buf, pp->status_file, len);
31079740Sgad	else
31131492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
31279740Sgad
31331492Swollman	return buf;
31431492Swollman}
31531492Swollman
31698152Sgad/*
31798152Sgad * Routine to change operational state of a print queue.  The operational
31898154Sgad * state is indicated by the access bits on the lock file for the queue.
31998152Sgad * At present, this is only called from various routines in lpc/cmds.c.
32098152Sgad *
32198152Sgad *  XXX - Note that this works by changing access-bits on the
32298152Sgad *	file, and you can only do that if you are the owner of
32398152Sgad *	the file, or root.  Thus, this won't really work for
32498152Sgad *	userids in the "LPR_OPER" group, unless lpc is running
32598152Sgad *	setuid to root (or maybe setuid to daemon).
32698152Sgad *	Generally lpc is installed setgid to daemon, but does
32798152Sgad *	not run setuid.
32898152Sgad */
32998152Sgadint
33098152Sgadset_qstate(int action, const char *lfname)
33198152Sgad{
33298152Sgad	struct stat stbuf;
33398152Sgad	mode_t chgbits, newbits, oldmask;
33498152Sgad	const char *failmsg, *okmsg;
33599844Sgad	static const char *nomsg = "no state msg";
33698152Sgad	int chres, errsav, fd, res, statres;
33798152Sgad
33898152Sgad	/*
33998152Sgad	 * Find what the current access-bits are.
34098152Sgad	 */
34198152Sgad	memset(&stbuf, 0, sizeof(stbuf));
342241852Seadler	PRIV_START
34398152Sgad	statres = stat(lfname, &stbuf);
34498152Sgad	errsav = errno;
345241852Seadler	PRIV_END
34698152Sgad	if ((statres < 0) && (errsav != ENOENT)) {
34798152Sgad		printf("\tcannot stat() lock file\n");
34898152Sgad		return (SQS_STATFAIL);
34998152Sgad		/* NOTREACHED */
35098152Sgad	}
35198152Sgad
35298152Sgad	/*
35398152Sgad	 * Determine which bit(s) should change for the requested action.
35498152Sgad	 */
35598152Sgad	chgbits = stbuf.st_mode;
35698152Sgad	newbits = LOCK_FILE_MODE;
35798152Sgad	okmsg = NULL;
35898152Sgad	failmsg = NULL;
35999844Sgad	if (action & SQS_QCHANGED) {
36099844Sgad		chgbits |= LFM_RESET_QUE;
36199844Sgad		newbits |= LFM_RESET_QUE;
36299844Sgad		/* The okmsg is not actually printed for this case. */
36399844Sgad		okmsg = nomsg;
36499844Sgad		failmsg = "set queue-changed";
36599844Sgad	}
36698152Sgad	if (action & SQS_DISABLEQ) {
36798152Sgad		chgbits |= LFM_QUEUE_DIS;
36898152Sgad		newbits |= LFM_QUEUE_DIS;
36998152Sgad		okmsg = "queuing disabled";
37098152Sgad		failmsg = "disable queuing";
37198152Sgad	}
37298152Sgad	if (action & SQS_STOPP) {
37398152Sgad		chgbits |= LFM_PRINT_DIS;
37498152Sgad		newbits |= LFM_PRINT_DIS;
37598152Sgad		okmsg = "printing disabled";
37698152Sgad		failmsg = "disable printing";
37798152Sgad		if (action & SQS_DISABLEQ) {
37898152Sgad			okmsg = "printer and queuing disabled";
37998152Sgad			failmsg = "disable queuing and printing";
38098152Sgad		}
38198152Sgad	}
38298152Sgad	if (action & SQS_ENABLEQ) {
38398152Sgad		chgbits &= ~LFM_QUEUE_DIS;
38498152Sgad		newbits &= ~LFM_QUEUE_DIS;
38598152Sgad		okmsg = "queuing enabled";
38698152Sgad		failmsg = "enable queuing";
38798152Sgad	}
38898152Sgad	if (action & SQS_STARTP) {
38998152Sgad		chgbits &= ~LFM_PRINT_DIS;
39098152Sgad		newbits &= ~LFM_PRINT_DIS;
39198152Sgad		okmsg = "printing enabled";
39298152Sgad		failmsg = "enable printing";
39398152Sgad	}
39498152Sgad	if (okmsg == NULL) {
39598152Sgad		/* This routine was called with an invalid action. */
39698152Sgad		printf("\t<error in set_qstate!>\n");
39798152Sgad		return (SQS_PARMERR);
39898152Sgad		/* NOTREACHED */
39998152Sgad	}
40098152Sgad
40198152Sgad	res = 0;
40298152Sgad	if (statres >= 0) {
40398152Sgad		/* The file already exists, so change the access. */
404241852Seadler		PRIV_START
40598152Sgad		chres = chmod(lfname, chgbits);
40698152Sgad		errsav = errno;
407241852Seadler		PRIV_END
40898152Sgad		res = SQS_CHGOK;
40999845Sgad		if (chres < 0)
41098152Sgad			res = SQS_CHGFAIL;
41198152Sgad	} else if (newbits == LOCK_FILE_MODE) {
41298152Sgad		/*
41398152Sgad		 * The file does not exist, but the state requested is
41498152Sgad		 * the same as the default state when no file exists.
41598152Sgad		 * Thus, there is no need to create the file.
41698152Sgad		 */
41798152Sgad		res = SQS_SKIPCREOK;
41898152Sgad	} else {
41998152Sgad		/*
42098152Sgad		 * The file did not exist, so create it with the
42198152Sgad		 * appropriate access bits for the requested action.
42298152Sgad		 * Push a new umask around that create, to make sure
42398152Sgad		 * all the read/write bits are set as desired.
42498152Sgad		 */
42598152Sgad		oldmask = umask(S_IWOTH);
426241852Seadler		PRIV_START
42798152Sgad		fd = open(lfname, O_WRONLY|O_CREAT, newbits);
42898152Sgad		errsav = errno;
429241852Seadler		PRIV_END
43098152Sgad		umask(oldmask);
43198152Sgad		res = SQS_CREFAIL;
43298152Sgad		if (fd >= 0) {
43398152Sgad			res = SQS_CREOK;
43498152Sgad			close(fd);
43598152Sgad		}
43698152Sgad	}
43798152Sgad
43898152Sgad	switch (res) {
43998152Sgad	case SQS_CHGOK:
44098152Sgad	case SQS_CREOK:
44198152Sgad	case SQS_SKIPCREOK:
44299844Sgad		if (okmsg != nomsg)
44399844Sgad			printf("\t%s\n", okmsg);
44498152Sgad		break;
44598152Sgad	case SQS_CREFAIL:
44698152Sgad		printf("\tcannot create lock file: %s\n",
44798152Sgad		    strerror(errsav));
44898152Sgad		break;
44998152Sgad	default:
45098152Sgad		printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
45198152Sgad		break;
45298152Sgad	}
45398152Sgad
45498152Sgad	return (res);
45598152Sgad}
45698152Sgad
45768253Sgad/* routine to get a current timestamp, optionally in a standard-fmt string */
45868253Sgadvoid
45979740Sgadlpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
46068253Sgad{
46168253Sgad	struct timespec local_ts;
46268253Sgad	struct timeval btime;
46380172Sgad	char tempstr[TIMESTR_SIZE];
46480172Sgad#ifdef STRFTIME_WRONG_z
46568739Sgad	char *destp;
46680172Sgad#endif
46780172Sgad
46868253Sgad	if (tsp == NULL)
46968253Sgad		tsp = &local_ts;
47068253Sgad
47168253Sgad	/* some platforms have a routine called clock_gettime, but the
47268253Sgad	 * routine does nothing but return "not implemented". */
47368253Sgad	memset(tsp, 0, sizeof(struct timespec));
47468253Sgad	if (clock_gettime(CLOCK_REALTIME, tsp)) {
47568253Sgad		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
47668253Sgad		memset(tsp, 0, sizeof(struct timespec));
47768253Sgad		gettimeofday(&btime, NULL);
47868253Sgad		tsp->tv_sec = btime.tv_sec;
47968253Sgad		tsp->tv_nsec = btime.tv_usec * 1000;
48068253Sgad	}
48168253Sgad
48268253Sgad	/* caller may not need a character-ized version */
48368253Sgad	if ((strp == NULL) || (strsize < 1))
48468253Sgad		return;
48568253Sgad
48668253Sgad	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
48768253Sgad		 localtime(&tsp->tv_sec));
48868253Sgad
48968253Sgad	/*
49068253Sgad	 * This check is for implementations of strftime which treat %z
49168253Sgad	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
49268253Sgad	 * completely ignore %z.  This section is not needed on freebsd.
49368253Sgad	 * I'm not sure this is completely right, but it should work OK
49468253Sgad	 * for EST and EDT...
49568253Sgad	 */
49668253Sgad#ifdef STRFTIME_WRONG_z
49768253Sgad	destp = strrchr(tempstr, ':');
49868253Sgad	if (destp != NULL) {
49968253Sgad		destp += 3;
50068253Sgad		if ((*destp != '+') && (*destp != '-')) {
50168253Sgad			char savday[6];
50268253Sgad			int tzmin = timezone / 60;
50368253Sgad			int tzhr = tzmin / 60;
50468253Sgad			if (daylight)
50568253Sgad				tzhr--;
50668253Sgad			strcpy(savday, destp + strlen(destp) - 4);
50768253Sgad			snprintf(destp, (destp - tempstr), "%+03d%02d",
50868739Sgad			    (-1*tzhr), tzmin % 60);
50968253Sgad			strcat(destp, savday);
51068253Sgad		}
51168253Sgad	}
51268253Sgad#endif
51368253Sgad
51468253Sgad	if (strsize > TIMESTR_SIZE) {
51568253Sgad		strsize = TIMESTR_SIZE;
51668253Sgad		strp[TIMESTR_SIZE+1] = '\0';
51768253Sgad	}
51879740Sgad	strlcpy(strp, tempstr, strsize);
51968253Sgad}
52068253Sgad
52168253Sgad/* routines for writing transfer-statistic records */
52268253Sgadvoid
52378146Sgadtrstat_init(struct printer *pp, const char *fname, int filenum)
52468253Sgad{
52568253Sgad	register const char *srcp;
52668253Sgad	register char *destp, *endp;
52768253Sgad
52868253Sgad	/*
52968253Sgad	 * Figure out the job id of this file.  The filename should be
53068253Sgad	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
53168253Sgad	 * two), followed by the jobnum, followed by a hostname.
53268253Sgad	 * The jobnum is usually 3 digits, but might be as many as 5.
53368253Sgad	 * Note that some care has to be taken parsing this, as the
53468253Sgad	 * filename could be coming from a remote-host, and thus might
53568253Sgad	 * not look anything like what is expected...
53668253Sgad	 */
53768253Sgad	memset(pp->jobnum, 0, sizeof(pp->jobnum));
53868253Sgad	pp->jobnum[0] = '0';
53968253Sgad	srcp = strchr(fname, '/');
54068253Sgad	if (srcp == NULL)
54168253Sgad		srcp = fname;
54268253Sgad	destp = &(pp->jobnum[0]);
54368253Sgad	endp = destp + 5;
54468253Sgad	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
54568253Sgad		srcp++;
54668253Sgad	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
54768253Sgad		*(destp++) = *(srcp++);
54868253Sgad
54968253Sgad	/* get the starting time in both numeric and string formats, and
55068253Sgad	 * save those away along with the file-number */
55168253Sgad	pp->jobdfnum = filenum;
55279740Sgad	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
55368253Sgad
55468253Sgad	return;
55568253Sgad}
55668253Sgad
55768253Sgadvoid
55878146Sgadtrstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
55978146Sgad    const char *userid, const char *otherhost, const char *orighost)
56068253Sgad{
56168253Sgad#define STATLINE_SIZE 1024
56268739Sgad	double trtime;
56380172Sgad	size_t remspace;
56480172Sgad	int statfile;
56568739Sgad	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
56668739Sgad	char *eostat;
56768739Sgad	const char *lprhost, *recvdev, *recvhost, *rectype;
56868739Sgad	const char *sendhost, *statfname;
56968253Sgad#define UPD_EOSTAT(xStr) do {         \
57068253Sgad	eostat = strchr(xStr, '\0');  \
57168253Sgad	remspace = eostat - xStr;     \
57268253Sgad} while(0)
57380172Sgad
57479740Sgad	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
57568253Sgad	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
57668253Sgad
57768253Sgad	gethostname(thishost, sizeof(thishost));
57868253Sgad	lprhost = sendhost = recvhost = recvdev = NULL;
57968253Sgad	switch (sendrecv) {
58068253Sgad	    case TR_SENDING:
58168253Sgad		rectype = "send";
58268253Sgad		statfname = pp->stat_send;
58368253Sgad		sendhost = thishost;
58468253Sgad		recvhost = otherhost;
58568253Sgad		break;
58668253Sgad	    case TR_RECVING:
58768253Sgad		rectype = "recv";
58868253Sgad		statfname = pp->stat_recv;
58968253Sgad		sendhost = otherhost;
59068253Sgad		recvhost = thishost;
59168253Sgad		break;
59268253Sgad	    case TR_PRINTING:
59368739Sgad		/*
59468739Sgad		 * This case is for copying to a device (presumably local,
59568739Sgad		 * though filters using things like 'net/CAP' can confuse
59668739Sgad		 * this assumption...).
59768739Sgad		 */
59868253Sgad		rectype = "prnt";
59968253Sgad		statfname = pp->stat_send;
60068253Sgad		sendhost = thishost;
60168253Sgad		recvdev = _PATH_DEFDEVLP;
60268253Sgad		if (pp->lp) recvdev = pp->lp;
60368253Sgad		break;
60468253Sgad	    default:
60568253Sgad		/* internal error...  should we syslog/printf an error? */
60668253Sgad		return;
60768253Sgad	}
60868739Sgad	if (statfname == NULL)
60968739Sgad		return;
61068253Sgad
61168253Sgad	/*
61268253Sgad	 * the original-host and userid are found out by reading thru the
61368253Sgad	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
61468253Sgad	 * the df's (data-files) are sent before the matching cf, so the
61568253Sgad	 * orighost & userid are generally not-available for incoming jobs.
61668253Sgad	 *
61768253Sgad	 * (it would be nice to create a work-around for that..)
61868739Sgad	 */
61968253Sgad	if (orighost && (*orighost != '\0'))
62068253Sgad		lprhost = orighost;
62168253Sgad	else
62268253Sgad		lprhost = ".na.";
62368739Sgad	if (*userid == '\0')
62468739Sgad		userid = NULL;
62568253Sgad
62668253Sgad	/*
62768253Sgad	 * Format of statline.
62868253Sgad	 * Some of the keywords listed here are not implemented here, but
62968253Sgad	 * they are listed to reserve the meaning for a given keyword.
63068253Sgad	 * Fields are separated by a blank.  The fields in statline are:
63168253Sgad	 *   <tstamp>      - time the transfer started
63268253Sgad	 *   <ptrqueue>    - name of the printer queue (the short-name...)
63368253Sgad	 *   <hname>       - hostname the file originally came from (the
63468253Sgad	 *		     'lpr host'), if known, or  "_na_" if not known.
63568253Sgad	 *   <xxx>         - id of job from that host (generally three digits)
63668253Sgad	 *   <n>           - file count (# of file within job)
63768253Sgad	 *   <rectype>     - 4-byte field indicating the type of transfer
63868253Sgad	 *		     statistics record.  "send" means it's from the
63968253Sgad	 *		     host sending a datafile, "recv" means it's from
64068253Sgad	 *		     a host as it receives a datafile.
64168253Sgad	 *   user=<userid> - user who sent the job (if known)
64268253Sgad	 *   secs=<n>      - seconds it took to transfer the file
64368253Sgad	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
64468253Sgad	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
645238546Sjh	 *		     for this to be useful)
64668253Sgad	 * ! top=<str>     - type of printer (if the type is defined in
64768253Sgad	 *		     printcap, and if this statline is for sending
64868253Sgad	 *		     a file to that ptr)
64968253Sgad	 * ! qls=<n>       - queue-length at start of send/print-ing a job
65068253Sgad	 * ! qle=<n>       - queue-length at end of send/print-ing a job
65168253Sgad	 *   sip=<addr>    - IP address of sending host, only included when
65268253Sgad	 *		     receiving a job.
65368253Sgad	 *   shost=<hname> - sending host (if that does != the original host)
65468253Sgad	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
65568253Sgad	 *   rdev=<dev>    - device receiving the file, when the file is being
65668253Sgad	 *		     send to a device instead of a remote host.
65768253Sgad	 *
65868253Sgad	 * Note: A single print job may be transferred multiple times.  The
65968253Sgad	 * original 'lpr' occurs on one host, and that original host might
66068253Sgad	 * send to some interim host (or print server).  That interim host
66168253Sgad	 * might turn around and send the job to yet another host (most likely
66268253Sgad	 * the real printer).  The 'shost=' parameter is only included if the
66368253Sgad	 * sending host for this particular transfer is NOT the same as the
66468253Sgad	 * host which did the original 'lpr'.
66568253Sgad	 *
66668253Sgad	 * Many values have 'something=' tags before them, because they are
66768253Sgad	 * in some sense "optional", or their order may vary.  "Optional" may
66868253Sgad	 * mean in the sense that different SITES might choose to have other
66968253Sgad	 * fields in the record, or that some fields are only included under
67068253Sgad	 * some circumstances.  Programs processing these records should not
67168253Sgad	 * assume the order or existence of any of these keyword fields.
67268253Sgad	 */
67368253Sgad	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
67468739Sgad	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
67568739Sgad	    pp->jobdfnum, rectype);
67668253Sgad	UPD_EOSTAT(statline);
67768253Sgad
67868253Sgad	if (userid != NULL) {
67968253Sgad		snprintf(eostat, remspace, " user=%s", userid);
68068253Sgad		UPD_EOSTAT(statline);
68168253Sgad	}
68280172Sgad	snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
68380172Sgad	    (unsigned long)bytecnt);
68468253Sgad	UPD_EOSTAT(statline);
68580172Sgad
68668739Sgad	/*
68768739Sgad	 * The bps field duplicates info from bytes and secs, so do
68868739Sgad	 * not bother to include it for very small files.
68968739Sgad	 */
69068253Sgad	if ((bytecnt > 25000) && (trtime > 1.1)) {
69168253Sgad		snprintf(eostat, remspace, " bps=%#.2e",
69268739Sgad		    ((double)bytecnt/trtime));
69368253Sgad		UPD_EOSTAT(statline);
69468253Sgad	}
69568253Sgad
69668253Sgad	if (sendrecv == TR_RECVING) {
69768253Sgad		if (remspace > 5+strlen(from_ip) ) {
69868253Sgad			snprintf(eostat, remspace, " sip=%s", from_ip);
69968253Sgad			UPD_EOSTAT(statline);
70068253Sgad		}
70168253Sgad	}
70268253Sgad	if (0 != strcmp(lprhost, sendhost)) {
70368253Sgad		if (remspace > 7+strlen(sendhost) ) {
70468253Sgad			snprintf(eostat, remspace, " shost=%s", sendhost);
70568253Sgad			UPD_EOSTAT(statline);
70668253Sgad		}
70768253Sgad	}
70868253Sgad	if (recvhost) {
70968253Sgad		if (remspace > 7+strlen(recvhost) ) {
71068253Sgad			snprintf(eostat, remspace, " rhost=%s", recvhost);
71168253Sgad			UPD_EOSTAT(statline);
71268253Sgad		}
71368253Sgad	}
71468253Sgad	if (recvdev) {
71568253Sgad		if (remspace > 6+strlen(recvdev) ) {
71668253Sgad			snprintf(eostat, remspace, " rdev=%s", recvdev);
71768253Sgad			UPD_EOSTAT(statline);
71868253Sgad		}
71968253Sgad	}
72068253Sgad	if (remspace > 1) {
72168253Sgad		strcpy(eostat, "\n");
72268253Sgad	} else {
723238546Sjh		/* probably should back up to just before the final " x=".. */
72468253Sgad		strcpy(statline+STATLINE_SIZE-2, "\n");
72568253Sgad	}
72668253Sgad	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
72768253Sgad	if (statfile < 0) {
72868253Sgad		/* statfile was given, but we can't open it.  should we
72968253Sgad		 * syslog/printf this as an error? */
73068253Sgad		return;
73168253Sgad	}
73268253Sgad	write(statfile, statline, strlen(statline));
73368253Sgad	close(statfile);
73468253Sgad
73568253Sgad	return;
736238546Sjh#undef UPD_EOSTAT
73768253Sgad}
73868253Sgad
7391553Srgrimes#include <stdarg.h>
7401553Srgrimes
7411553Srgrimesvoid
74231492Swollmanfatal(const struct printer *pp, const char *msg, ...)
7431553Srgrimes{
7441553Srgrimes	va_list ap;
7451553Srgrimes	va_start(ap, msg);
74678300Sgad	/* this error message is being sent to the 'from_host' */
74778300Sgad	if (from_host != local_host)
74878300Sgad		(void)printf("%s: ", local_host);
74978280Sgad	(void)printf("%s: ", progname);
75031492Swollman	if (pp && pp->printer)
75131492Swollman		(void)printf("%s: ", pp->printer);
7521553Srgrimes	(void)vprintf(msg, ap);
7531553Srgrimes	va_end(ap);
7541553Srgrimes	(void)putchar('\n');
7551553Srgrimes	exit(1);
7561553Srgrimes}
75731492Swollman
75831492Swollman/*
75931492Swollman * Close all file descriptors from START on up.
76031492Swollman */
76131492Swollmanvoid
76278146Sgadcloseallfds(int start)
76331492Swollman{
764251044Sgad	int stop;
765251044Sgad
766251044Sgad	if (USE_CLOSEFROM)		/* The faster, modern solution */
767251044Sgad		closefrom(start);
768251044Sgad	else {
769251044Sgad		/* This older logic can be pretty awful on some OS's.  The
770251044Sgad		 * getdtablesize() might return ``infinity'', and then this
771251044Sgad		 * will waste a lot of time closing file descriptors which
772251044Sgad		 * had never been open()-ed. */
773251044Sgad		stop = getdtablesize();
774251044Sgad		for (; start < stop; start++)
775251044Sgad			close(start);
776251044Sgad	}
77731492Swollman}
77831492Swollman
779