common.c revision 99845
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
391553Srgrimes#ifndef lint
4031492Swollman/*
4115648Sjoergstatic char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
4231492Swollman*/
4331492Swollmanstatic const char rcsid[] =
4450479Speter  "$FreeBSD: head/usr.sbin/lpr/common_source/common.c 99845 2002-07-12 01:37:06Z gad $";
451553Srgrimes#endif /* not lint */
461553Srgrimes
471553Srgrimes#include <sys/param.h>
481553Srgrimes#include <sys/stat.h>
4915648Sjoerg#include <sys/time.h>
5068253Sgad#include <sys/types.h>
511553Srgrimes
521553Srgrimes#include <dirent.h>
5398152Sgad#include <errno.h>
5468253Sgad#include <fcntl.h>
5531492Swollman#include <stdio.h>
561553Srgrimes#include <stdlib.h>
571553Srgrimes#include <string.h>
5831492Swollman#include <unistd.h>
5931492Swollman
601553Srgrimes#include "lp.h"
6131492Swollman#include "lp.local.h"
621553Srgrimes#include "pathnames.h"
631553Srgrimes
641553Srgrimes/*
651553Srgrimes * Routines and data common to all the line printer functions.
661553Srgrimes */
671553Srgrimeschar	line[BUFSIZ];
6878280Sgadconst char	*progname;		/* program name */
691553Srgrimes
7027618Simpextern uid_t	uid, euid;
7127618Simp
7278146Sgadstatic int compar(const void *_p1, const void *_p2);
731553Srgrimes
741553Srgrimes/*
751553Srgrimes * Getline reads a line from the control file cfp, removes tabs, converts
761553Srgrimes *  new-line to null and leaves it in line.
771553Srgrimes * Returns 0 at EOF or the number of characters read.
781553Srgrimes */
791553Srgrimesint
8078146Sgadgetline(FILE *cfp)
811553Srgrimes{
821553Srgrimes	register int linel = 0;
831553Srgrimes	register char *lp = line;
8439084Swollman	register int c;
851553Srgrimes
8680172Sgad	while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
871553Srgrimes		if (c == EOF)
881553Srgrimes			return(0);
891553Srgrimes		if (c == '\t') {
901553Srgrimes			do {
911553Srgrimes				*lp++ = ' ';
921553Srgrimes				linel++;
9380172Sgad			} while ((linel & 07) != 0 && (size_t)(linel+1) <
9480172Sgad			    sizeof(line));
951553Srgrimes			continue;
961553Srgrimes		}
971553Srgrimes		*lp++ = c;
981553Srgrimes		linel++;
991553Srgrimes	}
1001553Srgrimes	*lp++ = '\0';
1011553Srgrimes	return(linel);
1021553Srgrimes}
1031553Srgrimes
1041553Srgrimes/*
1051553Srgrimes * Scan the current directory and make a list of daemon files sorted by
1061553Srgrimes * creation time.
1071553Srgrimes * Return the number of entries and a pointer to the list.
1081553Srgrimes */
1091553Srgrimesint
11078146Sgadgetq(const struct printer *pp, struct jobqueue *(*namelist[]))
1111553Srgrimes{
1121553Srgrimes	register struct dirent *d;
11368401Sgad	register struct jobqueue *q, **queue;
11499842Sgad	size_t arraysz, entrysz, nitems;
1151553Srgrimes	struct stat stbuf;
1161553Srgrimes	DIR *dirp;
11780172Sgad	int statres;
1181553Srgrimes
11927618Simp	seteuid(euid);
12068740Sgad	if ((dirp = opendir(pp->spool_dir)) == NULL) {
12168740Sgad		seteuid(uid);
12268739Sgad		return (-1);
12368740Sgad	}
1241553Srgrimes	if (fstat(dirp->dd_fd, &stbuf) < 0)
1251553Srgrimes		goto errdone;
12627618Simp	seteuid(uid);
1271553Srgrimes
1281553Srgrimes	/*
1291553Srgrimes	 * Estimate the array size by taking the size of the directory file
13027618Simp	 * and dividing it by a multiple of the minimum size entry.
1311553Srgrimes	 */
1321553Srgrimes	arraysz = (stbuf.st_size / 24);
13368401Sgad	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
1341553Srgrimes	if (queue == NULL)
1351553Srgrimes		goto errdone;
1361553Srgrimes
1371553Srgrimes	nitems = 0;
1381553Srgrimes	while ((d = readdir(dirp)) != NULL) {
1391553Srgrimes		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
1401553Srgrimes			continue;	/* daemon control files only */
14127618Simp		seteuid(euid);
14275253Sgad		statres = stat(d->d_name, &stbuf);
14375253Sgad		seteuid(uid);
14475253Sgad		if (statres < 0)
1451553Srgrimes			continue;	/* Doesn't exist */
14699842Sgad		entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
14799842Sgad		    strlen(d->d_name) + 1;
14899842Sgad		q = (struct jobqueue *)malloc(entrysz);
1491553Srgrimes		if (q == NULL)
1501553Srgrimes			goto errdone;
15199842Sgad		q->job_matched = 0;
15299842Sgad		q->job_processed = 0;
15368401Sgad		q->job_time = stbuf.st_mtime;
15468401Sgad		strcpy(q->job_cfname, d->d_name);
1551553Srgrimes		/*
1561553Srgrimes		 * Check to make sure the array has space left and
1571553Srgrimes		 * realloc the maximum size.
1581553Srgrimes		 */
1591553Srgrimes		if (++nitems > arraysz) {
16015648Sjoerg			arraysz *= 2;
16168401Sgad			queue = (struct jobqueue **)realloc((char *)queue,
16268739Sgad			    arraysz * sizeof(struct jobqueue *));
1631553Srgrimes			if (queue == NULL)
1641553Srgrimes				goto errdone;
1651553Srgrimes		}
1661553Srgrimes		queue[nitems-1] = q;
1671553Srgrimes	}
1681553Srgrimes	closedir(dirp);
1691553Srgrimes	if (nitems)
17068401Sgad		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
1711553Srgrimes	*namelist = queue;
1721553Srgrimes	return(nitems);
1731553Srgrimes
1741553Srgrimeserrdone:
1751553Srgrimes	closedir(dirp);
17668740Sgad	seteuid(uid);
17768739Sgad	return (-1);
1781553Srgrimes}
1791553Srgrimes
1801553Srgrimes/*
1811553Srgrimes * Compare modification times.
1821553Srgrimes */
1831553Srgrimesstatic int
18478146Sgadcompar(const void *p1, const void *p2)
1851553Srgrimes{
18668401Sgad	const struct jobqueue *qe1, *qe2;
18768739Sgad
18895290Sgad	qe1 = *(const struct jobqueue * const *)p1;
18995290Sgad	qe2 = *(const struct jobqueue * const *)p2;
19059920Swollman
19168401Sgad	if (qe1->job_time < qe2->job_time)
19259920Swollman		return (-1);
19368401Sgad	if (qe1->job_time > qe2->job_time)
19459920Swollman		return (1);
19559920Swollman	/*
19659920Swollman	 * At this point, the two files have the same last-modification time.
19759920Swollman	 * return a result based on filenames, so that 'cfA001some.host' will
19859920Swollman	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
19959920Swollman	 * around when it gets to '999', we also assume that '9xx' jobs are
20059920Swollman	 * older than '0xx' jobs.
20159920Swollman	*/
20268401Sgad	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
20359920Swollman		return (-1);
20468401Sgad	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
20559920Swollman		return (1);
20668401Sgad	return (strcmp(qe1->job_cfname, qe2->job_cfname));
2071553Srgrimes}
2081553Srgrimes
20915648Sjoerg/* sleep n milliseconds */
21015648Sjoergvoid
21178146Sgaddelay(int millisec)
21215648Sjoerg{
21315648Sjoerg	struct timeval tdelay;
21415648Sjoerg
21578146Sgad	if (millisec <= 0 || millisec > 10000)
21631492Swollman		fatal((struct printer *)0, /* fatal() knows how to deal */
21778146Sgad		    "unreasonable delay period (%d)", millisec);
21878146Sgad	tdelay.tv_sec = millisec / 1000;
21978146Sgad	tdelay.tv_usec = millisec * 1000 % 1000000;
22015648Sjoerg	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
22115648Sjoerg}
22215648Sjoerg
22331492Swollmanchar *
22478146Sgadlock_file_name(const struct printer *pp, char *buf, size_t len)
22531492Swollman{
22631492Swollman	static char staticbuf[MAXPATHLEN];
22731492Swollman
22831492Swollman	if (buf == 0)
22931492Swollman		buf = staticbuf;
23031492Swollman	if (len == 0)
23131492Swollman		len = MAXPATHLEN;
23231492Swollman
23379740Sgad	if (pp->lock_file[0] == '/')
23479740Sgad		strlcpy(buf, pp->lock_file, len);
23579740Sgad	else
23631492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
23779740Sgad
23831492Swollman	return buf;
23931492Swollman}
24031492Swollman
24131492Swollmanchar *
24278146Sgadstatus_file_name(const struct printer *pp, char *buf, size_t len)
24331492Swollman{
24431492Swollman	static char staticbuf[MAXPATHLEN];
24531492Swollman
24631492Swollman	if (buf == 0)
24731492Swollman		buf = staticbuf;
24831492Swollman	if (len == 0)
24931492Swollman		len = MAXPATHLEN;
25031492Swollman
25179740Sgad	if (pp->status_file[0] == '/')
25279740Sgad		strlcpy(buf, pp->status_file, len);
25379740Sgad	else
25431492Swollman		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
25579740Sgad
25631492Swollman	return buf;
25731492Swollman}
25831492Swollman
25998152Sgad/*
26098152Sgad * Routine to change operational state of a print queue.  The operational
26198154Sgad * state is indicated by the access bits on the lock file for the queue.
26298152Sgad * At present, this is only called from various routines in lpc/cmds.c.
26398152Sgad *
26498152Sgad *  XXX - Note that this works by changing access-bits on the
26598152Sgad *	file, and you can only do that if you are the owner of
26698152Sgad *	the file, or root.  Thus, this won't really work for
26798152Sgad *	userids in the "LPR_OPER" group, unless lpc is running
26898152Sgad *	setuid to root (or maybe setuid to daemon).
26998152Sgad *	Generally lpc is installed setgid to daemon, but does
27098152Sgad *	not run setuid.
27198152Sgad */
27298152Sgadint
27398152Sgadset_qstate(int action, const char *lfname)
27498152Sgad{
27598152Sgad	struct stat stbuf;
27698152Sgad	mode_t chgbits, newbits, oldmask;
27798152Sgad	const char *failmsg, *okmsg;
27899844Sgad	static const char *nomsg = "no state msg";
27998152Sgad	int chres, errsav, fd, res, statres;
28098152Sgad
28198152Sgad	/*
28298152Sgad	 * Find what the current access-bits are.
28398152Sgad	 */
28498152Sgad	memset(&stbuf, 0, sizeof(stbuf));
28598152Sgad	seteuid(euid);
28698152Sgad	statres = stat(lfname, &stbuf);
28798152Sgad	errsav = errno;
28898152Sgad	seteuid(uid);
28998152Sgad	if ((statres < 0) && (errsav != ENOENT)) {
29098152Sgad		printf("\tcannot stat() lock file\n");
29198152Sgad		return (SQS_STATFAIL);
29298152Sgad		/* NOTREACHED */
29398152Sgad	}
29498152Sgad
29598152Sgad	/*
29698152Sgad	 * Determine which bit(s) should change for the requested action.
29798152Sgad	 */
29898152Sgad	chgbits = stbuf.st_mode;
29998152Sgad	newbits = LOCK_FILE_MODE;
30098152Sgad	okmsg = NULL;
30198152Sgad	failmsg = NULL;
30299844Sgad	if (action & SQS_QCHANGED) {
30399844Sgad		chgbits |= LFM_RESET_QUE;
30499844Sgad		newbits |= LFM_RESET_QUE;
30599844Sgad		/* The okmsg is not actually printed for this case. */
30699844Sgad		okmsg = nomsg;
30799844Sgad		failmsg = "set queue-changed";
30899844Sgad	}
30998152Sgad	if (action & SQS_DISABLEQ) {
31098152Sgad		chgbits |= LFM_QUEUE_DIS;
31198152Sgad		newbits |= LFM_QUEUE_DIS;
31298152Sgad		okmsg = "queuing disabled";
31398152Sgad		failmsg = "disable queuing";
31498152Sgad	}
31598152Sgad	if (action & SQS_STOPP) {
31698152Sgad		chgbits |= LFM_PRINT_DIS;
31798152Sgad		newbits |= LFM_PRINT_DIS;
31898152Sgad		okmsg = "printing disabled";
31998152Sgad		failmsg = "disable printing";
32098152Sgad		if (action & SQS_DISABLEQ) {
32198152Sgad			okmsg = "printer and queuing disabled";
32298152Sgad			failmsg = "disable queuing and printing";
32398152Sgad		}
32498152Sgad	}
32598152Sgad	if (action & SQS_ENABLEQ) {
32698152Sgad		chgbits &= ~LFM_QUEUE_DIS;
32798152Sgad		newbits &= ~LFM_QUEUE_DIS;
32898152Sgad		okmsg = "queuing enabled";
32998152Sgad		failmsg = "enable queuing";
33098152Sgad	}
33198152Sgad	if (action & SQS_STARTP) {
33298152Sgad		chgbits &= ~LFM_PRINT_DIS;
33398152Sgad		newbits &= ~LFM_PRINT_DIS;
33498152Sgad		okmsg = "printing enabled";
33598152Sgad		failmsg = "enable printing";
33698152Sgad	}
33798152Sgad	if (okmsg == NULL) {
33898152Sgad		/* This routine was called with an invalid action. */
33998152Sgad		printf("\t<error in set_qstate!>\n");
34098152Sgad		return (SQS_PARMERR);
34198152Sgad		/* NOTREACHED */
34298152Sgad	}
34398152Sgad
34498152Sgad	res = 0;
34598152Sgad	if (statres >= 0) {
34698152Sgad		/* The file already exists, so change the access. */
34798152Sgad		seteuid(euid);
34898152Sgad		chres = chmod(lfname, chgbits);
34998152Sgad		errsav = errno;
35098152Sgad		seteuid(uid);
35198152Sgad		res = SQS_CHGOK;
35299845Sgad		if (chres < 0)
35398152Sgad			res = SQS_CHGFAIL;
35498152Sgad	} else if (newbits == LOCK_FILE_MODE) {
35598152Sgad		/*
35698152Sgad		 * The file does not exist, but the state requested is
35798152Sgad		 * the same as the default state when no file exists.
35898152Sgad		 * Thus, there is no need to create the file.
35998152Sgad		 */
36098152Sgad		res = SQS_SKIPCREOK;
36198152Sgad	} else {
36298152Sgad		/*
36398152Sgad		 * The file did not exist, so create it with the
36498152Sgad		 * appropriate access bits for the requested action.
36598152Sgad		 * Push a new umask around that create, to make sure
36698152Sgad		 * all the read/write bits are set as desired.
36798152Sgad		 */
36898152Sgad		oldmask = umask(S_IWOTH);
36998152Sgad		seteuid(euid);
37098152Sgad		fd = open(lfname, O_WRONLY|O_CREAT, newbits);
37198152Sgad		errsav = errno;
37298152Sgad		seteuid(uid);
37398152Sgad		umask(oldmask);
37498152Sgad		res = SQS_CREFAIL;
37598152Sgad		if (fd >= 0) {
37698152Sgad			res = SQS_CREOK;
37798152Sgad			close(fd);
37898152Sgad		}
37998152Sgad	}
38098152Sgad
38198152Sgad	switch (res) {
38298152Sgad	case SQS_CHGOK:
38398152Sgad	case SQS_CREOK:
38498152Sgad	case SQS_SKIPCREOK:
38599844Sgad		if (okmsg != nomsg)
38699844Sgad			printf("\t%s\n", okmsg);
38798152Sgad		break;
38898152Sgad	case SQS_CREFAIL:
38998152Sgad		printf("\tcannot create lock file: %s\n",
39098152Sgad		    strerror(errsav));
39198152Sgad		break;
39298152Sgad	default:
39398152Sgad		printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
39498152Sgad		break;
39598152Sgad	}
39698152Sgad
39798152Sgad	return (res);
39898152Sgad}
39998152Sgad
40068253Sgad/* routine to get a current timestamp, optionally in a standard-fmt string */
40168253Sgadvoid
40279740Sgadlpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
40368253Sgad{
40468253Sgad	struct timespec local_ts;
40568253Sgad	struct timeval btime;
40680172Sgad	char tempstr[TIMESTR_SIZE];
40780172Sgad#ifdef STRFTIME_WRONG_z
40868739Sgad	char *destp;
40980172Sgad#endif
41080172Sgad
41168253Sgad	if (tsp == NULL)
41268253Sgad		tsp = &local_ts;
41368253Sgad
41468253Sgad	/* some platforms have a routine called clock_gettime, but the
41568253Sgad	 * routine does nothing but return "not implemented". */
41668253Sgad	memset(tsp, 0, sizeof(struct timespec));
41768253Sgad	if (clock_gettime(CLOCK_REALTIME, tsp)) {
41868253Sgad		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
41968253Sgad		memset(tsp, 0, sizeof(struct timespec));
42068253Sgad		gettimeofday(&btime, NULL);
42168253Sgad		tsp->tv_sec = btime.tv_sec;
42268253Sgad		tsp->tv_nsec = btime.tv_usec * 1000;
42368253Sgad	}
42468253Sgad
42568253Sgad	/* caller may not need a character-ized version */
42668253Sgad	if ((strp == NULL) || (strsize < 1))
42768253Sgad		return;
42868253Sgad
42968253Sgad	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
43068253Sgad		 localtime(&tsp->tv_sec));
43168253Sgad
43268253Sgad	/*
43368253Sgad	 * This check is for implementations of strftime which treat %z
43468253Sgad	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
43568253Sgad	 * completely ignore %z.  This section is not needed on freebsd.
43668253Sgad	 * I'm not sure this is completely right, but it should work OK
43768253Sgad	 * for EST and EDT...
43868253Sgad	 */
43968253Sgad#ifdef STRFTIME_WRONG_z
44068253Sgad	destp = strrchr(tempstr, ':');
44168253Sgad	if (destp != NULL) {
44268253Sgad		destp += 3;
44368253Sgad		if ((*destp != '+') && (*destp != '-')) {
44468253Sgad			char savday[6];
44568253Sgad			int tzmin = timezone / 60;
44668253Sgad			int tzhr = tzmin / 60;
44768253Sgad			if (daylight)
44868253Sgad				tzhr--;
44968253Sgad			strcpy(savday, destp + strlen(destp) - 4);
45068253Sgad			snprintf(destp, (destp - tempstr), "%+03d%02d",
45168739Sgad			    (-1*tzhr), tzmin % 60);
45268253Sgad			strcat(destp, savday);
45368253Sgad		}
45468253Sgad	}
45568253Sgad#endif
45668253Sgad
45768253Sgad	if (strsize > TIMESTR_SIZE) {
45868253Sgad		strsize = TIMESTR_SIZE;
45968253Sgad		strp[TIMESTR_SIZE+1] = '\0';
46068253Sgad	}
46179740Sgad	strlcpy(strp, tempstr, strsize);
46268253Sgad}
46368253Sgad
46468253Sgad/* routines for writing transfer-statistic records */
46568253Sgadvoid
46678146Sgadtrstat_init(struct printer *pp, const char *fname, int filenum)
46768253Sgad{
46868253Sgad	register const char *srcp;
46968253Sgad	register char *destp, *endp;
47068253Sgad
47168253Sgad	/*
47268253Sgad	 * Figure out the job id of this file.  The filename should be
47368253Sgad	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
47468253Sgad	 * two), followed by the jobnum, followed by a hostname.
47568253Sgad	 * The jobnum is usually 3 digits, but might be as many as 5.
47668253Sgad	 * Note that some care has to be taken parsing this, as the
47768253Sgad	 * filename could be coming from a remote-host, and thus might
47868253Sgad	 * not look anything like what is expected...
47968253Sgad	 */
48068253Sgad	memset(pp->jobnum, 0, sizeof(pp->jobnum));
48168253Sgad	pp->jobnum[0] = '0';
48268253Sgad	srcp = strchr(fname, '/');
48368253Sgad	if (srcp == NULL)
48468253Sgad		srcp = fname;
48568253Sgad	destp = &(pp->jobnum[0]);
48668253Sgad	endp = destp + 5;
48768253Sgad	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
48868253Sgad		srcp++;
48968253Sgad	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
49068253Sgad		*(destp++) = *(srcp++);
49168253Sgad
49268253Sgad	/* get the starting time in both numeric and string formats, and
49368253Sgad	 * save those away along with the file-number */
49468253Sgad	pp->jobdfnum = filenum;
49579740Sgad	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
49668253Sgad
49768253Sgad	return;
49868253Sgad}
49968253Sgad
50068253Sgadvoid
50178146Sgadtrstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
50278146Sgad    const char *userid, const char *otherhost, const char *orighost)
50368253Sgad{
50468253Sgad#define STATLINE_SIZE 1024
50568739Sgad	double trtime;
50680172Sgad	size_t remspace;
50780172Sgad	int statfile;
50868739Sgad	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
50968739Sgad	char *eostat;
51068739Sgad	const char *lprhost, *recvdev, *recvhost, *rectype;
51168739Sgad	const char *sendhost, *statfname;
51268253Sgad#define UPD_EOSTAT(xStr) do {         \
51368253Sgad	eostat = strchr(xStr, '\0');  \
51468253Sgad	remspace = eostat - xStr;     \
51568253Sgad} while(0)
51680172Sgad
51779740Sgad	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
51868253Sgad	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
51968253Sgad
52068253Sgad	gethostname(thishost, sizeof(thishost));
52168253Sgad	lprhost = sendhost = recvhost = recvdev = NULL;
52268253Sgad	switch (sendrecv) {
52368253Sgad	    case TR_SENDING:
52468253Sgad		rectype = "send";
52568253Sgad		statfname = pp->stat_send;
52668253Sgad		sendhost = thishost;
52768253Sgad		recvhost = otherhost;
52868253Sgad		break;
52968253Sgad	    case TR_RECVING:
53068253Sgad		rectype = "recv";
53168253Sgad		statfname = pp->stat_recv;
53268253Sgad		sendhost = otherhost;
53368253Sgad		recvhost = thishost;
53468253Sgad		break;
53568253Sgad	    case TR_PRINTING:
53668739Sgad		/*
53768739Sgad		 * This case is for copying to a device (presumably local,
53868739Sgad		 * though filters using things like 'net/CAP' can confuse
53968739Sgad		 * this assumption...).
54068739Sgad		 */
54168253Sgad		rectype = "prnt";
54268253Sgad		statfname = pp->stat_send;
54368253Sgad		sendhost = thishost;
54468253Sgad		recvdev = _PATH_DEFDEVLP;
54568253Sgad		if (pp->lp) recvdev = pp->lp;
54668253Sgad		break;
54768253Sgad	    default:
54868253Sgad		/* internal error...  should we syslog/printf an error? */
54968253Sgad		return;
55068253Sgad	}
55168739Sgad	if (statfname == NULL)
55268739Sgad		return;
55368253Sgad
55468253Sgad	/*
55568253Sgad	 * the original-host and userid are found out by reading thru the
55668253Sgad	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
55768253Sgad	 * the df's (data-files) are sent before the matching cf, so the
55868253Sgad	 * orighost & userid are generally not-available for incoming jobs.
55968253Sgad	 *
56068253Sgad	 * (it would be nice to create a work-around for that..)
56168739Sgad	 */
56268253Sgad	if (orighost && (*orighost != '\0'))
56368253Sgad		lprhost = orighost;
56468253Sgad	else
56568253Sgad		lprhost = ".na.";
56668739Sgad	if (*userid == '\0')
56768739Sgad		userid = NULL;
56868253Sgad
56968253Sgad	/*
57068253Sgad	 * Format of statline.
57168253Sgad	 * Some of the keywords listed here are not implemented here, but
57268253Sgad	 * they are listed to reserve the meaning for a given keyword.
57368253Sgad	 * Fields are separated by a blank.  The fields in statline are:
57468253Sgad	 *   <tstamp>      - time the transfer started
57568253Sgad	 *   <ptrqueue>    - name of the printer queue (the short-name...)
57668253Sgad	 *   <hname>       - hostname the file originally came from (the
57768253Sgad	 *		     'lpr host'), if known, or  "_na_" if not known.
57868253Sgad	 *   <xxx>         - id of job from that host (generally three digits)
57968253Sgad	 *   <n>           - file count (# of file within job)
58068253Sgad	 *   <rectype>     - 4-byte field indicating the type of transfer
58168253Sgad	 *		     statistics record.  "send" means it's from the
58268253Sgad	 *		     host sending a datafile, "recv" means it's from
58368253Sgad	 *		     a host as it receives a datafile.
58468253Sgad	 *   user=<userid> - user who sent the job (if known)
58568253Sgad	 *   secs=<n>      - seconds it took to transfer the file
58668253Sgad	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
58768253Sgad	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
58868253Sgad	 *		     for this to be useful)
58968253Sgad	 * ! top=<str>     - type of printer (if the type is defined in
59068253Sgad	 *		     printcap, and if this statline is for sending
59168253Sgad	 *		     a file to that ptr)
59268253Sgad	 * ! qls=<n>       - queue-length at start of send/print-ing a job
59368253Sgad	 * ! qle=<n>       - queue-length at end of send/print-ing a job
59468253Sgad	 *   sip=<addr>    - IP address of sending host, only included when
59568253Sgad	 *		     receiving a job.
59668253Sgad	 *   shost=<hname> - sending host (if that does != the original host)
59768253Sgad	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
59868253Sgad	 *   rdev=<dev>    - device receiving the file, when the file is being
59968253Sgad	 *		     send to a device instead of a remote host.
60068253Sgad	 *
60168253Sgad	 * Note: A single print job may be transferred multiple times.  The
60268253Sgad	 * original 'lpr' occurs on one host, and that original host might
60368253Sgad	 * send to some interim host (or print server).  That interim host
60468253Sgad	 * might turn around and send the job to yet another host (most likely
60568253Sgad	 * the real printer).  The 'shost=' parameter is only included if the
60668253Sgad	 * sending host for this particular transfer is NOT the same as the
60768253Sgad	 * host which did the original 'lpr'.
60868253Sgad	 *
60968253Sgad	 * Many values have 'something=' tags before them, because they are
61068253Sgad	 * in some sense "optional", or their order may vary.  "Optional" may
61168253Sgad	 * mean in the sense that different SITES might choose to have other
61268253Sgad	 * fields in the record, or that some fields are only included under
61368253Sgad	 * some circumstances.  Programs processing these records should not
61468253Sgad	 * assume the order or existence of any of these keyword fields.
61568253Sgad	 */
61668253Sgad	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
61768739Sgad	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
61868739Sgad	    pp->jobdfnum, rectype);
61968253Sgad	UPD_EOSTAT(statline);
62068253Sgad
62168253Sgad	if (userid != NULL) {
62268253Sgad		snprintf(eostat, remspace, " user=%s", userid);
62368253Sgad		UPD_EOSTAT(statline);
62468253Sgad	}
62580172Sgad	snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
62680172Sgad	    (unsigned long)bytecnt);
62768253Sgad	UPD_EOSTAT(statline);
62880172Sgad
62968739Sgad	/*
63068739Sgad	 * The bps field duplicates info from bytes and secs, so do
63168739Sgad	 * not bother to include it for very small files.
63268739Sgad	 */
63368253Sgad	if ((bytecnt > 25000) && (trtime > 1.1)) {
63468253Sgad		snprintf(eostat, remspace, " bps=%#.2e",
63568739Sgad		    ((double)bytecnt/trtime));
63668253Sgad		UPD_EOSTAT(statline);
63768253Sgad	}
63868253Sgad
63968253Sgad	if (sendrecv == TR_RECVING) {
64068253Sgad		if (remspace > 5+strlen(from_ip) ) {
64168253Sgad			snprintf(eostat, remspace, " sip=%s", from_ip);
64268253Sgad			UPD_EOSTAT(statline);
64368253Sgad		}
64468253Sgad	}
64568253Sgad	if (0 != strcmp(lprhost, sendhost)) {
64668253Sgad		if (remspace > 7+strlen(sendhost) ) {
64768253Sgad			snprintf(eostat, remspace, " shost=%s", sendhost);
64868253Sgad			UPD_EOSTAT(statline);
64968253Sgad		}
65068253Sgad	}
65168253Sgad	if (recvhost) {
65268253Sgad		if (remspace > 7+strlen(recvhost) ) {
65368253Sgad			snprintf(eostat, remspace, " rhost=%s", recvhost);
65468253Sgad			UPD_EOSTAT(statline);
65568253Sgad		}
65668253Sgad	}
65768253Sgad	if (recvdev) {
65868253Sgad		if (remspace > 6+strlen(recvdev) ) {
65968253Sgad			snprintf(eostat, remspace, " rdev=%s", recvdev);
66068253Sgad			UPD_EOSTAT(statline);
66168253Sgad		}
66268253Sgad	}
66368253Sgad	if (remspace > 1) {
66468253Sgad		strcpy(eostat, "\n");
66568253Sgad	} else {
66668253Sgad		/* probably should back up to just before the final " x=".. */
66768253Sgad		strcpy(statline+STATLINE_SIZE-2, "\n");
66868253Sgad	}
66968253Sgad	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
67068253Sgad	if (statfile < 0) {
67168253Sgad		/* statfile was given, but we can't open it.  should we
67268253Sgad		 * syslog/printf this as an error? */
67368253Sgad		return;
67468253Sgad	}
67568253Sgad	write(statfile, statline, strlen(statline));
67668253Sgad	close(statfile);
67768253Sgad
67868253Sgad	return;
67968253Sgad#undef UPD_EOSTAT
68068253Sgad}
68168253Sgad
6821553Srgrimes#include <stdarg.h>
6831553Srgrimes
6841553Srgrimesvoid
68531492Swollmanfatal(const struct printer *pp, const char *msg, ...)
6861553Srgrimes{
6871553Srgrimes	va_list ap;
6881553Srgrimes	va_start(ap, msg);
68978300Sgad	/* this error message is being sent to the 'from_host' */
69078300Sgad	if (from_host != local_host)
69178300Sgad		(void)printf("%s: ", local_host);
69278280Sgad	(void)printf("%s: ", progname);
69331492Swollman	if (pp && pp->printer)
69431492Swollman		(void)printf("%s: ", pp->printer);
6951553Srgrimes	(void)vprintf(msg, ap);
6961553Srgrimes	va_end(ap);
6971553Srgrimes	(void)putchar('\n');
6981553Srgrimes	exit(1);
6991553Srgrimes}
70031492Swollman
70131492Swollman/*
70231492Swollman * Close all file descriptors from START on up.
70331492Swollman * This is a horrific kluge, since getdtablesize() might return
70431492Swollman * ``infinity'', in which case we will be spending a long time
70531492Swollman * closing ``files'' which were never open.  Perhaps it would
70631492Swollman * be better to close the first N fds, for some small value of N.
70731492Swollman */
70831492Swollmanvoid
70978146Sgadcloseallfds(int start)
71031492Swollman{
71131492Swollman	int stop = getdtablesize();
71231492Swollman	for (; start < stop; start++)
71331492Swollman		close(start);
71431492Swollman}
71531492Swollman
716