common.c revision 79740
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39#ifndef lint
40/*
41static char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
42*/
43static const char rcsid[] =
44  "$FreeBSD: head/usr.sbin/lpr/common_source/common.c 79740 2001-07-15 00:57:18Z gad $";
45#endif /* not lint */
46
47#include <sys/param.h>
48#include <sys/stat.h>
49#include <sys/time.h>
50#include <sys/types.h>
51
52#include <dirent.h>
53#include <fcntl.h>
54#include <stdio.h>
55#include <stdlib.h>
56#include <string.h>
57#include <unistd.h>
58
59#include "lp.h"
60#include "lp.local.h"
61#include "pathnames.h"
62
63/*
64 * Routines and data common to all the line printer functions.
65 */
66char	line[BUFSIZ];
67const char	*progname;		/* program name */
68
69extern uid_t	uid, euid;
70
71static int compar(const void *_p1, const void *_p2);
72
73/*
74 * Getline reads a line from the control file cfp, removes tabs, converts
75 *  new-line to null and leaves it in line.
76 * Returns 0 at EOF or the number of characters read.
77 */
78int
79getline(FILE *cfp)
80{
81	register int linel = 0;
82	register char *lp = line;
83	register int c;
84
85	while ((c = getc(cfp)) != '\n' && linel+1 < sizeof(line)) {
86		if (c == EOF)
87			return(0);
88		if (c == '\t') {
89			do {
90				*lp++ = ' ';
91				linel++;
92			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
93			continue;
94		}
95		*lp++ = c;
96		linel++;
97	}
98	*lp++ = '\0';
99	return(linel);
100}
101
102/*
103 * Scan the current directory and make a list of daemon files sorted by
104 * creation time.
105 * Return the number of entries and a pointer to the list.
106 */
107int
108getq(const struct printer *pp, struct jobqueue *(*namelist[]))
109{
110	register struct dirent *d;
111	register struct jobqueue *q, **queue;
112	register int nitems;
113	struct stat stbuf;
114	DIR *dirp;
115	int arraysz, statres;
116
117	seteuid(euid);
118	if ((dirp = opendir(pp->spool_dir)) == NULL) {
119		seteuid(uid);
120		return (-1);
121	}
122	if (fstat(dirp->dd_fd, &stbuf) < 0)
123		goto errdone;
124	seteuid(uid);
125
126	/*
127	 * Estimate the array size by taking the size of the directory file
128	 * and dividing it by a multiple of the minimum size entry.
129	 */
130	arraysz = (stbuf.st_size / 24);
131	queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
132	if (queue == NULL)
133		goto errdone;
134
135	nitems = 0;
136	while ((d = readdir(dirp)) != NULL) {
137		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
138			continue;	/* daemon control files only */
139		seteuid(euid);
140		statres = stat(d->d_name, &stbuf);
141		seteuid(uid);
142		if (statres < 0)
143			continue;	/* Doesn't exist */
144		q = (struct jobqueue *)malloc(sizeof(time_t) + strlen(d->d_name)
145		    + 1);
146		if (q == NULL)
147			goto errdone;
148		q->job_time = stbuf.st_mtime;
149		strcpy(q->job_cfname, d->d_name);
150		/*
151		 * Check to make sure the array has space left and
152		 * realloc the maximum size.
153		 */
154		if (++nitems > arraysz) {
155			arraysz *= 2;
156			queue = (struct jobqueue **)realloc((char *)queue,
157			    arraysz * sizeof(struct jobqueue *));
158			if (queue == NULL)
159				goto errdone;
160		}
161		queue[nitems-1] = q;
162	}
163	closedir(dirp);
164	if (nitems)
165		qsort(queue, nitems, sizeof(struct jobqueue *), compar);
166	*namelist = queue;
167	return(nitems);
168
169errdone:
170	closedir(dirp);
171	seteuid(uid);
172	return (-1);
173}
174
175/*
176 * Compare modification times.
177 */
178static int
179compar(const void *p1, const void *p2)
180{
181	const struct jobqueue *qe1, *qe2;
182
183	qe1 = *(const struct jobqueue **)p1;
184	qe2 = *(const struct jobqueue **)p2;
185
186	if (qe1->job_time < qe2->job_time)
187		return (-1);
188	if (qe1->job_time > qe2->job_time)
189		return (1);
190	/*
191	 * At this point, the two files have the same last-modification time.
192	 * return a result based on filenames, so that 'cfA001some.host' will
193	 * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
194	 * around when it gets to '999', we also assume that '9xx' jobs are
195	 * older than '0xx' jobs.
196	*/
197	if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
198		return (-1);
199	if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
200		return (1);
201	return (strcmp(qe1->job_cfname, qe2->job_cfname));
202}
203
204/* sleep n milliseconds */
205void
206delay(int millisec)
207{
208	struct timeval tdelay;
209
210	if (millisec <= 0 || millisec > 10000)
211		fatal((struct printer *)0, /* fatal() knows how to deal */
212		    "unreasonable delay period (%d)", millisec);
213	tdelay.tv_sec = millisec / 1000;
214	tdelay.tv_usec = millisec * 1000 % 1000000;
215	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
216}
217
218char *
219lock_file_name(const struct printer *pp, char *buf, size_t len)
220{
221	static char staticbuf[MAXPATHLEN];
222
223	if (buf == 0)
224		buf = staticbuf;
225	if (len == 0)
226		len = MAXPATHLEN;
227
228	if (pp->lock_file[0] == '/')
229		strlcpy(buf, pp->lock_file, len);
230	else
231		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
232
233	return buf;
234}
235
236char *
237status_file_name(const struct printer *pp, char *buf, size_t len)
238{
239	static char staticbuf[MAXPATHLEN];
240
241	if (buf == 0)
242		buf = staticbuf;
243	if (len == 0)
244		len = MAXPATHLEN;
245
246	if (pp->status_file[0] == '/')
247		strlcpy(buf, pp->status_file, len);
248	else
249		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
250
251	return buf;
252}
253
254/* routine to get a current timestamp, optionally in a standard-fmt string */
255void
256lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
257{
258	struct timespec local_ts;
259	struct timeval btime;
260	char *destp;
261	char tempstr[TIMESTR_SIZE];
262
263	if (tsp == NULL)
264		tsp = &local_ts;
265
266	/* some platforms have a routine called clock_gettime, but the
267	 * routine does nothing but return "not implemented". */
268	memset(tsp, 0, sizeof(struct timespec));
269	if (clock_gettime(CLOCK_REALTIME, tsp)) {
270		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
271		memset(tsp, 0, sizeof(struct timespec));
272		gettimeofday(&btime, NULL);
273		tsp->tv_sec = btime.tv_sec;
274		tsp->tv_nsec = btime.tv_usec * 1000;
275	}
276
277	/* caller may not need a character-ized version */
278	if ((strp == NULL) || (strsize < 1))
279		return;
280
281	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
282		 localtime(&tsp->tv_sec));
283
284	/*
285	 * This check is for implementations of strftime which treat %z
286	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
287	 * completely ignore %z.  This section is not needed on freebsd.
288	 * I'm not sure this is completely right, but it should work OK
289	 * for EST and EDT...
290	 */
291#ifdef STRFTIME_WRONG_z
292	destp = strrchr(tempstr, ':');
293	if (destp != NULL) {
294		destp += 3;
295		if ((*destp != '+') && (*destp != '-')) {
296			char savday[6];
297			int tzmin = timezone / 60;
298			int tzhr = tzmin / 60;
299			if (daylight)
300				tzhr--;
301			strcpy(savday, destp + strlen(destp) - 4);
302			snprintf(destp, (destp - tempstr), "%+03d%02d",
303			    (-1*tzhr), tzmin % 60);
304			strcat(destp, savday);
305		}
306	}
307#endif
308
309	if (strsize > TIMESTR_SIZE) {
310		strsize = TIMESTR_SIZE;
311		strp[TIMESTR_SIZE+1] = '\0';
312	}
313	strlcpy(strp, tempstr, strsize);
314}
315
316/* routines for writing transfer-statistic records */
317void
318trstat_init(struct printer *pp, const char *fname, int filenum)
319{
320	register const char *srcp;
321	register char *destp, *endp;
322
323	/*
324	 * Figure out the job id of this file.  The filename should be
325	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
326	 * two), followed by the jobnum, followed by a hostname.
327	 * The jobnum is usually 3 digits, but might be as many as 5.
328	 * Note that some care has to be taken parsing this, as the
329	 * filename could be coming from a remote-host, and thus might
330	 * not look anything like what is expected...
331	 */
332	memset(pp->jobnum, 0, sizeof(pp->jobnum));
333	pp->jobnum[0] = '0';
334	srcp = strchr(fname, '/');
335	if (srcp == NULL)
336		srcp = fname;
337	destp = &(pp->jobnum[0]);
338	endp = destp + 5;
339	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
340		srcp++;
341	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
342		*(destp++) = *(srcp++);
343
344	/* get the starting time in both numeric and string formats, and
345	 * save those away along with the file-number */
346	pp->jobdfnum = filenum;
347	lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
348
349	return;
350}
351
352void
353trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
354    const char *userid, const char *otherhost, const char *orighost)
355{
356#define STATLINE_SIZE 1024
357	double trtime;
358	int remspace, statfile;
359	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
360	char *eostat;
361	const char *lprhost, *recvdev, *recvhost, *rectype;
362	const char *sendhost, *statfname;
363#define UPD_EOSTAT(xStr) do {         \
364	eostat = strchr(xStr, '\0');  \
365	remspace = eostat - xStr;     \
366} while(0)
367
368	lpd_gettime(&pp->tr_done, NULL, (size_t)0);
369	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
370
371	gethostname(thishost, sizeof(thishost));
372	lprhost = sendhost = recvhost = recvdev = NULL;
373	switch (sendrecv) {
374	    case TR_SENDING:
375		rectype = "send";
376		statfname = pp->stat_send;
377		sendhost = thishost;
378		recvhost = otherhost;
379		break;
380	    case TR_RECVING:
381		rectype = "recv";
382		statfname = pp->stat_recv;
383		sendhost = otherhost;
384		recvhost = thishost;
385		break;
386	    case TR_PRINTING:
387		/*
388		 * This case is for copying to a device (presumably local,
389		 * though filters using things like 'net/CAP' can confuse
390		 * this assumption...).
391		 */
392		rectype = "prnt";
393		statfname = pp->stat_send;
394		sendhost = thishost;
395		recvdev = _PATH_DEFDEVLP;
396		if (pp->lp) recvdev = pp->lp;
397		break;
398	    default:
399		/* internal error...  should we syslog/printf an error? */
400		return;
401	}
402	if (statfname == NULL)
403		return;
404
405	/*
406	 * the original-host and userid are found out by reading thru the
407	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
408	 * the df's (data-files) are sent before the matching cf, so the
409	 * orighost & userid are generally not-available for incoming jobs.
410	 *
411	 * (it would be nice to create a work-around for that..)
412	 */
413	if (orighost && (*orighost != '\0'))
414		lprhost = orighost;
415	else
416		lprhost = ".na.";
417	if (*userid == '\0')
418		userid = NULL;
419
420	/*
421	 * Format of statline.
422	 * Some of the keywords listed here are not implemented here, but
423	 * they are listed to reserve the meaning for a given keyword.
424	 * Fields are separated by a blank.  The fields in statline are:
425	 *   <tstamp>      - time the transfer started
426	 *   <ptrqueue>    - name of the printer queue (the short-name...)
427	 *   <hname>       - hostname the file originally came from (the
428	 *		     'lpr host'), if known, or  "_na_" if not known.
429	 *   <xxx>         - id of job from that host (generally three digits)
430	 *   <n>           - file count (# of file within job)
431	 *   <rectype>     - 4-byte field indicating the type of transfer
432	 *		     statistics record.  "send" means it's from the
433	 *		     host sending a datafile, "recv" means it's from
434	 *		     a host as it receives a datafile.
435	 *   user=<userid> - user who sent the job (if known)
436	 *   secs=<n>      - seconds it took to transfer the file
437	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
438	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
439	 *		     for this to be useful)
440	 * ! top=<str>     - type of printer (if the type is defined in
441	 *		     printcap, and if this statline is for sending
442	 *		     a file to that ptr)
443	 * ! qls=<n>       - queue-length at start of send/print-ing a job
444	 * ! qle=<n>       - queue-length at end of send/print-ing a job
445	 *   sip=<addr>    - IP address of sending host, only included when
446	 *		     receiving a job.
447	 *   shost=<hname> - sending host (if that does != the original host)
448	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
449	 *   rdev=<dev>    - device receiving the file, when the file is being
450	 *		     send to a device instead of a remote host.
451	 *
452	 * Note: A single print job may be transferred multiple times.  The
453	 * original 'lpr' occurs on one host, and that original host might
454	 * send to some interim host (or print server).  That interim host
455	 * might turn around and send the job to yet another host (most likely
456	 * the real printer).  The 'shost=' parameter is only included if the
457	 * sending host for this particular transfer is NOT the same as the
458	 * host which did the original 'lpr'.
459	 *
460	 * Many values have 'something=' tags before them, because they are
461	 * in some sense "optional", or their order may vary.  "Optional" may
462	 * mean in the sense that different SITES might choose to have other
463	 * fields in the record, or that some fields are only included under
464	 * some circumstances.  Programs processing these records should not
465	 * assume the order or existence of any of these keyword fields.
466	 */
467	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
468	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
469	    pp->jobdfnum, rectype);
470	UPD_EOSTAT(statline);
471
472	if (userid != NULL) {
473		snprintf(eostat, remspace, " user=%s", userid);
474		UPD_EOSTAT(statline);
475	}
476	snprintf(eostat, remspace, " secs=%#.2f bytes=%u", trtime, bytecnt);
477	UPD_EOSTAT(statline);
478
479	/*
480	 * The bps field duplicates info from bytes and secs, so do
481	 * not bother to include it for very small files.
482	 */
483	if ((bytecnt > 25000) && (trtime > 1.1)) {
484		snprintf(eostat, remspace, " bps=%#.2e",
485		    ((double)bytecnt/trtime));
486		UPD_EOSTAT(statline);
487	}
488
489	if (sendrecv == TR_RECVING) {
490		if (remspace > 5+strlen(from_ip) ) {
491			snprintf(eostat, remspace, " sip=%s", from_ip);
492			UPD_EOSTAT(statline);
493		}
494	}
495	if (0 != strcmp(lprhost, sendhost)) {
496		if (remspace > 7+strlen(sendhost) ) {
497			snprintf(eostat, remspace, " shost=%s", sendhost);
498			UPD_EOSTAT(statline);
499		}
500	}
501	if (recvhost) {
502		if (remspace > 7+strlen(recvhost) ) {
503			snprintf(eostat, remspace, " rhost=%s", recvhost);
504			UPD_EOSTAT(statline);
505		}
506	}
507	if (recvdev) {
508		if (remspace > 6+strlen(recvdev) ) {
509			snprintf(eostat, remspace, " rdev=%s", recvdev);
510			UPD_EOSTAT(statline);
511		}
512	}
513	if (remspace > 1) {
514		strcpy(eostat, "\n");
515	} else {
516		/* probably should back up to just before the final " x=".. */
517		strcpy(statline+STATLINE_SIZE-2, "\n");
518	}
519	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
520	if (statfile < 0) {
521		/* statfile was given, but we can't open it.  should we
522		 * syslog/printf this as an error? */
523		return;
524	}
525	write(statfile, statline, strlen(statline));
526	close(statfile);
527
528	return;
529#undef UPD_EOSTAT
530}
531
532#ifdef __STDC__
533#include <stdarg.h>
534#else
535#include <varargs.h>
536#endif
537
538void
539#ifdef __STDC__
540fatal(const struct printer *pp, const char *msg, ...)
541#else
542fatal(pp, msg, va_alist)
543	const struct printer *pp;
544	char *msg;
545        va_dcl
546#endif
547{
548	va_list ap;
549#ifdef __STDC__
550	va_start(ap, msg);
551#else
552	va_start(ap);
553#endif
554	/* this error message is being sent to the 'from_host' */
555	if (from_host != local_host)
556		(void)printf("%s: ", local_host);
557	(void)printf("%s: ", progname);
558	if (pp && pp->printer)
559		(void)printf("%s: ", pp->printer);
560	(void)vprintf(msg, ap);
561	va_end(ap);
562	(void)putchar('\n');
563	exit(1);
564}
565
566/*
567 * Close all file descriptors from START on up.
568 * This is a horrific kluge, since getdtablesize() might return
569 * ``infinity'', in which case we will be spending a long time
570 * closing ``files'' which were never open.  Perhaps it would
571 * be better to close the first N fds, for some small value of N.
572 */
573void
574closeallfds(int start)
575{
576	int stop = getdtablesize();
577	for (; start < stop; start++)
578		close(start);
579}
580
581