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