xref: /freebsd/usr.sbin/lpr/common_source/common.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
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 const char	*progname;		/* program name */
68 
69 extern uid_t	uid, euid;
70 
71 static 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  */
78 int
79 getline(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  */
107 int
108 getq(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 
169 errdone:
170 	closedir(dirp);
171 	seteuid(uid);
172 	return (-1);
173 }
174 
175 /*
176  * Compare modification times.
177  */
178 static int
179 compar(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 */
205 void
206 delay(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 
218 char *
219 lock_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 		buf[0] = '\0';
230 		strncpy(buf, pp->lock_file, len);
231 	} else {
232 		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
233 	}
234 	return buf;
235 }
236 
237 char *
238 status_file_name(const struct printer *pp, char *buf, size_t len)
239 {
240 	static char staticbuf[MAXPATHLEN];
241 
242 	if (buf == 0)
243 		buf = staticbuf;
244 	if (len == 0)
245 		len = MAXPATHLEN;
246 
247 	if (pp->status_file[0] == '/') {
248 		buf[0] = '\0';
249 		strncpy(buf, pp->status_file, len);
250 	} else {
251 		snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
252 	}
253 	return buf;
254 }
255 
256 /* routine to get a current timestamp, optionally in a standard-fmt string */
257 void
258 lpd_gettime(struct timespec *tsp, char *strp, int strsize)
259 {
260 	struct timespec local_ts;
261 	struct timeval btime;
262 	char *destp;
263 	char tempstr[TIMESTR_SIZE];
264 
265 	if (tsp == NULL)
266 		tsp = &local_ts;
267 
268 	/* some platforms have a routine called clock_gettime, but the
269 	 * routine does nothing but return "not implemented". */
270 	memset(tsp, 0, sizeof(struct timespec));
271 	if (clock_gettime(CLOCK_REALTIME, tsp)) {
272 		/* nanosec-aware rtn failed, fall back to microsec-aware rtn */
273 		memset(tsp, 0, sizeof(struct timespec));
274 		gettimeofday(&btime, NULL);
275 		tsp->tv_sec = btime.tv_sec;
276 		tsp->tv_nsec = btime.tv_usec * 1000;
277 	}
278 
279 	/* caller may not need a character-ized version */
280 	if ((strp == NULL) || (strsize < 1))
281 		return;
282 
283 	strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
284 		 localtime(&tsp->tv_sec));
285 
286 	/*
287 	 * This check is for implementations of strftime which treat %z
288 	 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
289 	 * completely ignore %z.  This section is not needed on freebsd.
290 	 * I'm not sure this is completely right, but it should work OK
291 	 * for EST and EDT...
292 	 */
293 #ifdef STRFTIME_WRONG_z
294 	destp = strrchr(tempstr, ':');
295 	if (destp != NULL) {
296 		destp += 3;
297 		if ((*destp != '+') && (*destp != '-')) {
298 			char savday[6];
299 			int tzmin = timezone / 60;
300 			int tzhr = tzmin / 60;
301 			if (daylight)
302 				tzhr--;
303 			strcpy(savday, destp + strlen(destp) - 4);
304 			snprintf(destp, (destp - tempstr), "%+03d%02d",
305 			    (-1*tzhr), tzmin % 60);
306 			strcat(destp, savday);
307 		}
308 	}
309 #endif
310 
311 	if (strsize > TIMESTR_SIZE) {
312 		strsize = TIMESTR_SIZE;
313 		strp[TIMESTR_SIZE+1] = '\0';
314 	}
315 	strncpy(strp, tempstr, strsize);
316 }
317 
318 /* routines for writing transfer-statistic records */
319 void
320 trstat_init(struct printer *pp, const char *fname, int filenum)
321 {
322 	register const char *srcp;
323 	register char *destp, *endp;
324 
325 	/*
326 	 * Figure out the job id of this file.  The filename should be
327 	 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
328 	 * two), followed by the jobnum, followed by a hostname.
329 	 * The jobnum is usually 3 digits, but might be as many as 5.
330 	 * Note that some care has to be taken parsing this, as the
331 	 * filename could be coming from a remote-host, and thus might
332 	 * not look anything like what is expected...
333 	 */
334 	memset(pp->jobnum, 0, sizeof(pp->jobnum));
335 	pp->jobnum[0] = '0';
336 	srcp = strchr(fname, '/');
337 	if (srcp == NULL)
338 		srcp = fname;
339 	destp = &(pp->jobnum[0]);
340 	endp = destp + 5;
341 	while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
342 		srcp++;
343 	while (*srcp >= '0' && *srcp <= '9' && destp < endp)
344 		*(destp++) = *(srcp++);
345 
346 	/* get the starting time in both numeric and string formats, and
347 	 * save those away along with the file-number */
348 	pp->jobdfnum = filenum;
349 	lpd_gettime(&pp->tr_start, pp->tr_timestr, TIMESTR_SIZE);
350 
351 	return;
352 }
353 
354 void
355 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
356     const char *userid, const char *otherhost, const char *orighost)
357 {
358 #define STATLINE_SIZE 1024
359 	double trtime;
360 	int remspace, statfile;
361 	char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
362 	char *eostat;
363 	const char *lprhost, *recvdev, *recvhost, *rectype;
364 	const char *sendhost, *statfname;
365 #define UPD_EOSTAT(xStr) do {         \
366 	eostat = strchr(xStr, '\0');  \
367 	remspace = eostat - xStr;     \
368 } while(0)
369 
370 	lpd_gettime(&pp->tr_done, NULL, 0);
371 	trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
372 
373 	gethostname(thishost, sizeof(thishost));
374 	lprhost = sendhost = recvhost = recvdev = NULL;
375 	switch (sendrecv) {
376 	    case TR_SENDING:
377 		rectype = "send";
378 		statfname = pp->stat_send;
379 		sendhost = thishost;
380 		recvhost = otherhost;
381 		break;
382 	    case TR_RECVING:
383 		rectype = "recv";
384 		statfname = pp->stat_recv;
385 		sendhost = otherhost;
386 		recvhost = thishost;
387 		break;
388 	    case TR_PRINTING:
389 		/*
390 		 * This case is for copying to a device (presumably local,
391 		 * though filters using things like 'net/CAP' can confuse
392 		 * this assumption...).
393 		 */
394 		rectype = "prnt";
395 		statfname = pp->stat_send;
396 		sendhost = thishost;
397 		recvdev = _PATH_DEFDEVLP;
398 		if (pp->lp) recvdev = pp->lp;
399 		break;
400 	    default:
401 		/* internal error...  should we syslog/printf an error? */
402 		return;
403 	}
404 	if (statfname == NULL)
405 		return;
406 
407 	/*
408 	 * the original-host and userid are found out by reading thru the
409 	 * cf (control-file) for the job.  Unfortunately, on incoming jobs
410 	 * the df's (data-files) are sent before the matching cf, so the
411 	 * orighost & userid are generally not-available for incoming jobs.
412 	 *
413 	 * (it would be nice to create a work-around for that..)
414 	 */
415 	if (orighost && (*orighost != '\0'))
416 		lprhost = orighost;
417 	else
418 		lprhost = ".na.";
419 	if (*userid == '\0')
420 		userid = NULL;
421 
422 	/*
423 	 * Format of statline.
424 	 * Some of the keywords listed here are not implemented here, but
425 	 * they are listed to reserve the meaning for a given keyword.
426 	 * Fields are separated by a blank.  The fields in statline are:
427 	 *   <tstamp>      - time the transfer started
428 	 *   <ptrqueue>    - name of the printer queue (the short-name...)
429 	 *   <hname>       - hostname the file originally came from (the
430 	 *		     'lpr host'), if known, or  "_na_" if not known.
431 	 *   <xxx>         - id of job from that host (generally three digits)
432 	 *   <n>           - file count (# of file within job)
433 	 *   <rectype>     - 4-byte field indicating the type of transfer
434 	 *		     statistics record.  "send" means it's from the
435 	 *		     host sending a datafile, "recv" means it's from
436 	 *		     a host as it receives a datafile.
437 	 *   user=<userid> - user who sent the job (if known)
438 	 *   secs=<n>      - seconds it took to transfer the file
439 	 *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
440 	 *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
441 	 *		     for this to be useful)
442 	 * ! top=<str>     - type of printer (if the type is defined in
443 	 *		     printcap, and if this statline is for sending
444 	 *		     a file to that ptr)
445 	 * ! qls=<n>       - queue-length at start of send/print-ing a job
446 	 * ! qle=<n>       - queue-length at end of send/print-ing a job
447 	 *   sip=<addr>    - IP address of sending host, only included when
448 	 *		     receiving a job.
449 	 *   shost=<hname> - sending host (if that does != the original host)
450 	 *   rhost=<hname> - hostname receiving the file (ie, "destination")
451 	 *   rdev=<dev>    - device receiving the file, when the file is being
452 	 *		     send to a device instead of a remote host.
453 	 *
454 	 * Note: A single print job may be transferred multiple times.  The
455 	 * original 'lpr' occurs on one host, and that original host might
456 	 * send to some interim host (or print server).  That interim host
457 	 * might turn around and send the job to yet another host (most likely
458 	 * the real printer).  The 'shost=' parameter is only included if the
459 	 * sending host for this particular transfer is NOT the same as the
460 	 * host which did the original 'lpr'.
461 	 *
462 	 * Many values have 'something=' tags before them, because they are
463 	 * in some sense "optional", or their order may vary.  "Optional" may
464 	 * mean in the sense that different SITES might choose to have other
465 	 * fields in the record, or that some fields are only included under
466 	 * some circumstances.  Programs processing these records should not
467 	 * assume the order or existence of any of these keyword fields.
468 	 */
469 	snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
470 	    pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
471 	    pp->jobdfnum, rectype);
472 	UPD_EOSTAT(statline);
473 
474 	if (userid != NULL) {
475 		snprintf(eostat, remspace, " user=%s", userid);
476 		UPD_EOSTAT(statline);
477 	}
478 	snprintf(eostat, remspace, " secs=%#.2f bytes=%u", trtime, bytecnt);
479 	UPD_EOSTAT(statline);
480 
481 	/*
482 	 * The bps field duplicates info from bytes and secs, so do
483 	 * not bother to include it for very small files.
484 	 */
485 	if ((bytecnt > 25000) && (trtime > 1.1)) {
486 		snprintf(eostat, remspace, " bps=%#.2e",
487 		    ((double)bytecnt/trtime));
488 		UPD_EOSTAT(statline);
489 	}
490 
491 	if (sendrecv == TR_RECVING) {
492 		if (remspace > 5+strlen(from_ip) ) {
493 			snprintf(eostat, remspace, " sip=%s", from_ip);
494 			UPD_EOSTAT(statline);
495 		}
496 	}
497 	if (0 != strcmp(lprhost, sendhost)) {
498 		if (remspace > 7+strlen(sendhost) ) {
499 			snprintf(eostat, remspace, " shost=%s", sendhost);
500 			UPD_EOSTAT(statline);
501 		}
502 	}
503 	if (recvhost) {
504 		if (remspace > 7+strlen(recvhost) ) {
505 			snprintf(eostat, remspace, " rhost=%s", recvhost);
506 			UPD_EOSTAT(statline);
507 		}
508 	}
509 	if (recvdev) {
510 		if (remspace > 6+strlen(recvdev) ) {
511 			snprintf(eostat, remspace, " rdev=%s", recvdev);
512 			UPD_EOSTAT(statline);
513 		}
514 	}
515 	if (remspace > 1) {
516 		strcpy(eostat, "\n");
517 	} else {
518 		/* probably should back up to just before the final " x=".. */
519 		strcpy(statline+STATLINE_SIZE-2, "\n");
520 	}
521 	statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
522 	if (statfile < 0) {
523 		/* statfile was given, but we can't open it.  should we
524 		 * syslog/printf this as an error? */
525 		return;
526 	}
527 	write(statfile, statline, strlen(statline));
528 	close(statfile);
529 
530 	return;
531 #undef UPD_EOSTAT
532 }
533 
534 #ifdef __STDC__
535 #include <stdarg.h>
536 #else
537 #include <varargs.h>
538 #endif
539 
540 void
541 #ifdef __STDC__
542 fatal(const struct printer *pp, const char *msg, ...)
543 #else
544 fatal(pp, msg, va_alist)
545 	const struct printer *pp;
546 	char *msg;
547         va_dcl
548 #endif
549 {
550 	va_list ap;
551 #ifdef __STDC__
552 	va_start(ap, msg);
553 #else
554 	va_start(ap);
555 #endif
556 	/* this error message is being sent to the 'from_host' */
557 	if (from_host != local_host)
558 		(void)printf("%s: ", local_host);
559 	(void)printf("%s: ", progname);
560 	if (pp && pp->printer)
561 		(void)printf("%s: ", pp->printer);
562 	(void)vprintf(msg, ap);
563 	va_end(ap);
564 	(void)putchar('\n');
565 	exit(1);
566 }
567 
568 /*
569  * Close all file descriptors from START on up.
570  * This is a horrific kluge, since getdtablesize() might return
571  * ``infinity'', in which case we will be spending a long time
572  * closing ``files'' which were never open.  Perhaps it would
573  * be better to close the first N fds, for some small value of N.
574  */
575 void
576 closeallfds(int start)
577 {
578 	int stop = getdtablesize();
579 	for (; start < stop; start++)
580 		close(start);
581 }
582 
583