displayq.c revision 80133
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35/*
36static char sccsid[] = "@(#)displayq.c	8.4 (Berkeley) 4/28/95";
37*/
38static const char rcsid[] =
39  "$FreeBSD: head/usr.sbin/lpr/common_source/displayq.c 80133 2001-07-22 07:25:27Z gad $";
40#endif /* not lint */
41
42#include <sys/param.h>
43#include <sys/stat.h>
44
45#include <ctype.h>
46#include <dirent.h>
47#include <errno.h>
48#include <fcntl.h>
49#include <signal.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <string.h>
53#define psignal foil_gcc_psignal
54#define	sys_siglist foil_gcc_siglist
55#include <unistd.h>
56#undef psignal
57#undef sys_siglist
58
59#include "lp.h"
60#include "lp.local.h"
61#include "pathnames.h"
62
63/*
64 * Routines to display the state of the queue.
65 */
66#define JOBCOL	40		/* column for job # in -l format */
67#define OWNCOL	7		/* start of Owner column in normal */
68#define SIZCOL	62		/* start of Size column in normal */
69
70/*
71 * Stuff for handling job specifications
72 */
73extern uid_t	uid, euid;
74
75static int	col;		/* column on screen */
76static char	current[40];	/* current file being printed */
77static char	file[132];	/* print file name */
78static int	first;		/* first file in ``files'' column? */
79static int	garbage;	/* # of garbage cf files */
80static int	lflag;		/* long output option */
81static int	rank;		/* order to be printed (-1=none, 0=active) */
82static long	totsize;	/* total print job size in bytes */
83
84static const char  *head0 = "Rank   Owner      Job  Files";
85static const char  *head1 = "Total Size\n";
86
87static void	alarmhandler(int _signo);
88static void	warn(const struct printer *_pp);
89
90/*
91 * Display the current state of the queue. Format = 1 if long format.
92 */
93void
94displayq(struct printer *pp, int format)
95{
96	register struct jobqueue *q;
97	register int i, nitems, fd, ret;
98	register char	*cp;
99	struct jobqueue **queue;
100	struct stat statb;
101	FILE *fp;
102	void (*savealrm)(int);
103
104	lflag = format;
105	totsize = 0;
106	rank = -1;
107
108	if ((cp = checkremote(pp))) {
109		printf("Warning: %s\n", cp);
110		free(cp);
111	}
112
113	/*
114	 * Print out local queue
115	 * Find all the control files in the spooling directory
116	 */
117	seteuid(euid);
118	if (chdir(pp->spool_dir) < 0)
119		fatal(pp, "cannot chdir to spooling directory: %s",
120		      strerror(errno));
121	seteuid(uid);
122	if ((nitems = getq(pp, &queue)) < 0)
123		fatal(pp, "cannot examine spooling area\n");
124	seteuid(euid);
125	ret = stat(pp->lock_file, &statb);
126	seteuid(uid);
127	if (ret >= 0) {
128		if (statb.st_mode & LFM_PRINT_DIS) {
129			if (pp->remote)
130				printf("%s: ", local_host);
131			printf("Warning: %s is down: ", pp->printer);
132			seteuid(euid);
133			fd = open(pp->status_file, O_RDONLY|O_SHLOCK);
134			seteuid(uid);
135			if (fd >= 0) {
136				while ((i = read(fd, line, sizeof(line))) > 0)
137					(void) fwrite(line, 1, i, stdout);
138				(void) close(fd);	/* unlocks as well */
139			} else
140				putchar('\n');
141		}
142		if (statb.st_mode & LFM_QUEUE_DIS) {
143			if (pp->remote)
144				printf("%s: ", local_host);
145			printf("Warning: %s queue is turned off\n",
146			       pp->printer);
147		}
148	}
149
150	if (nitems) {
151		seteuid(euid);
152		fp = fopen(pp->lock_file, "r");
153		seteuid(uid);
154		if (fp == NULL)
155			warn(pp);
156		else {
157			/* get daemon pid */
158			cp = current;
159			while ((i = getc(fp)) != EOF && i != '\n')
160				*cp++ = i;
161			*cp = '\0';
162			i = atoi(current);
163			if (i <= 0) {
164				ret = -1;
165			} else {
166				seteuid(euid);
167				ret = kill(i, 0);
168				seteuid(uid);
169			}
170			if (ret < 0) {
171				warn(pp);
172			} else {
173				/* read current file name */
174				cp = current;
175				while ((i = getc(fp)) != EOF && i != '\n')
176					*cp++ = i;
177				*cp = '\0';
178				/*
179				 * Print the status file.
180				 */
181				if (pp->remote)
182					printf("%s: ", local_host);
183				seteuid(euid);
184				fd = open(pp->status_file, O_RDONLY|O_SHLOCK);
185				seteuid(uid);
186				if (fd >= 0) {
187					while ((i = read(fd, line,
188							 sizeof(line))) > 0)
189						fwrite(line, 1, i, stdout);
190					close(fd);	/* unlocks as well */
191				} else
192					putchar('\n');
193			}
194			(void) fclose(fp);
195		}
196		/*
197		 * Now, examine the control files and print out the jobs to
198		 * be done for each user.
199		 */
200		if (!lflag)
201			header();
202		for (i = 0; i < nitems; i++) {
203			q = queue[i];
204			inform(pp, q->job_cfname);
205			free(q);
206		}
207		free(queue);
208	}
209	if (!pp->remote) {
210		if (nitems == 0)
211			puts("no entries");
212		return;
213	}
214
215	/*
216	 * Print foreign queue
217	 * Note that a file in transit may show up in either queue.
218	 */
219	if (nitems)
220		putchar('\n');
221	(void) snprintf(line, sizeof(line), "%c%s", format ? '\4' : '\3',
222			pp->remote_queue);
223	cp = line;
224	for (i = 0; i < requests && cp-line+10 < sizeof(line) - 1; i++) {
225		cp += strlen(cp);
226		(void) sprintf(cp, " %d", requ[i]);
227	}
228	for (i = 0; i < users && cp - line + 1 + strlen(user[i]) <
229		sizeof(line) - 1; i++) {
230		cp += strlen(cp);
231		*cp++ = ' ';
232		(void) strcpy(cp, user[i]);
233	}
234	strcat(line, "\n");
235	savealrm = signal(SIGALRM, alarmhandler);
236	alarm(pp->conn_timeout);
237	fd = getport(pp, pp->remote_host, 0);
238	alarm(0);
239	(void)signal(SIGALRM, savealrm);
240	if (fd < 0) {
241		if (from_host != local_host)
242			printf("%s: ", local_host);
243		printf("connection to %s is down\n", pp->remote_host);
244	}
245	else {
246		i = strlen(line);
247		if (write(fd, line, i) != i)
248			fatal(pp, "Lost connection");
249		while ((i = read(fd, line, sizeof(line))) > 0)
250			(void) fwrite(line, 1, i, stdout);
251		(void) close(fd);
252	}
253}
254
255/*
256 * Print a warning message if there is no daemon present.
257 */
258static void
259warn(const struct printer *pp)
260{
261	if (pp->remote)
262		printf("%s: ", local_host);
263	puts("Warning: no daemon present");
264	current[0] = '\0';
265}
266
267/*
268 * Print the header for the short listing format
269 */
270void
271header(void)
272{
273	printf("%s", head0);
274	col = strlen(head0)+1;
275	blankfill(SIZCOL);
276	printf("%s", head1);
277}
278
279void
280inform(const struct printer *pp, char *cf)
281{
282	register int copycnt;
283	char	 savedname[MAXPATHLEN+1];
284	FILE	*cfp;
285
286	/*
287	 * There's a chance the control file has gone away
288	 * in the meantime; if this is the case just keep going
289	 */
290	seteuid(euid);
291	if ((cfp = fopen(cf, "r")) == NULL)
292		return;
293	seteuid(uid);
294
295	if (rank < 0)
296		rank = 0;
297	if (pp->remote || garbage || strcmp(cf, current))
298		rank++;
299
300	/*
301	 * The cf-file may include commands to print more than one datafile
302	 * from the user.  For each datafile, the cf-file contains at least
303	 * one line which starts with some format-specifier ('a'-'z'), and
304	 * a second line ('N'ame) which indicates the original name the user
305	 * specified for that file.  There can be multiple format-spec lines
306	 * for a single Name-line, if the user requested multiple copies of
307	 * that file.  Standard lpr puts the format-spec line(s) before the
308	 * Name-line, while lprNG puts the Name-line before the format-spec
309	 * line(s).  This section needs to handle the lines in either order.
310	 */
311	copycnt = 0;
312	file[0] = '\0';
313	savedname[0] = '\0';
314	while (getline(cfp)) {
315		switch (line[0]) {
316		case 'P': /* Was this file specified in the user's list? */
317			if (!inlist(line+1, cf)) {
318				fclose(cfp);
319				return;
320			}
321			if (lflag) {
322				printf("\n%s: ", line+1);
323				col = strlen(line+1) + 2;
324				prank(rank);
325				blankfill(JOBCOL);
326				printf(" [job %s]\n", cf+3);
327			} else {
328				col = 0;
329				prank(rank);
330				blankfill(OWNCOL);
331				printf("%-10s %-3d  ", line+1, atoi(cf+3));
332				col += 16;
333				first = 1;
334			}
335			continue;
336		default: /* some format specifer and file name? */
337			if (line[0] < 'a' || line[0] > 'z')
338				break;
339			if (copycnt == 0 || strcmp(file, line+1) != 0) {
340				strlcpy(file, line + 1, sizeof(file));
341			}
342			copycnt++;
343			/*
344			 * deliberately 'continue' to another getline(), so
345			 * all format-spec lines for this datafile are read
346			 * in and counted before calling show()
347			 */
348			continue;
349		case 'N':
350			strlcpy(savedname, line + 1, sizeof(savedname));
351			break;
352		}
353		if ((file[0] != '\0') && (savedname[0] != '\0')) {
354			show(savedname, file, copycnt);
355			copycnt = 0;
356			file[0] = '\0';
357			savedname[0] = '\0';
358		}
359	}
360	fclose(cfp);
361	/* check for a file which hasn't been shown yet */
362	if (file[0] != '\0') {
363		if (savedname[0] == '\0') {
364			/* a safeguard in case the N-ame line is missing */
365			strlcpy(savedname, file, sizeof(savedname));
366		}
367		show(savedname, file, copycnt);
368	}
369	if (!lflag) {
370		blankfill(SIZCOL);
371		printf("%ld bytes\n", totsize);
372		totsize = 0;
373	}
374}
375
376int
377inlist(char *uname, char *cfile)
378{
379	register int *r, n;
380	register char **u, *cp;
381
382	if (users == 0 && requests == 0)
383		return(1);
384	/*
385	 * Check to see if it's in the user list
386	 */
387	for (u = user; u < &user[users]; u++)
388		if (!strcmp(*u, uname))
389			return(1);
390	/*
391	 * Check the request list
392	 */
393	for (n = 0, cp = cfile+3; isdigit(*cp); )
394		n = n * 10 + (*cp++ - '0');
395	for (r = requ; r < &requ[requests]; r++)
396		if (*r == n && !strcmp(cp, from_host))
397			return(1);
398	return(0);
399}
400
401void
402show(const char *nfile, const char *datafile, int copies)
403{
404	if (strcmp(nfile, " ") == 0)
405		nfile = "(standard input)";
406	if (lflag)
407		ldump(nfile, datafile, copies);
408	else
409		dump(nfile, datafile, copies);
410}
411
412/*
413 * Fill the line with blanks to the specified column
414 */
415void
416blankfill(int tocol)
417{
418	while (col++ < tocol)
419		putchar(' ');
420}
421
422/*
423 * Give the abbreviated dump of the file names
424 */
425void
426dump(const char *nfile, const char *datafile, int copies)
427{
428	struct stat lbuf;
429	const char etctmpl[] = ", ...";
430	char	 etc[sizeof(etctmpl)];
431	char	*lastsep;
432	short	 fill, nlen;
433	short	 rem, remetc;
434
435	/*
436	 * Print as many filenames as will fit
437	 *      (leaving room for the 'total size' field)
438	 */
439	fill = first ? 0 : 2;	/* fill space for ``, '' */
440	nlen = strlen(nfile);
441	rem = SIZCOL - 1 - col;
442	if (nlen + fill > rem) {
443		if (first) {
444			/* print the right-most part of the name */
445			printf("...%s ", &nfile[3+nlen-rem]);
446			col = SIZCOL;
447		} else if (rem > 0) {
448			/* fit as much of the etc-string as we can */
449			remetc = rem;
450			if (rem > strlen(etctmpl))
451				remetc = strlen(etctmpl);
452			etc[0] = '\0';
453			strncat(etc, etctmpl, remetc);
454			printf("%s", etc);
455			col += remetc;
456			rem -= remetc;
457			/* room for the last segment of this filename? */
458			lastsep = strrchr(nfile, '/');
459			if ((lastsep != NULL) && (rem > strlen(lastsep))) {
460				/* print the right-most part of this name */
461				printf("%s", lastsep);
462				col += strlen(lastsep);
463			} else {
464				/* do not pack any more names in here */
465				blankfill(SIZCOL);
466			}
467		}
468	} else {
469		if (!first)
470			printf(", ");
471		printf("%s", nfile);
472		col += nlen + fill;
473	}
474	first = 0;
475
476	seteuid(euid);
477	if (*datafile && !stat(datafile, &lbuf))
478		totsize += copies * lbuf.st_size;
479	seteuid(uid);
480}
481
482/*
483 * Print the long info about the file
484 */
485void
486ldump(const char *nfile, const char *datafile, int copies)
487{
488	struct stat lbuf;
489
490	putchar('\t');
491	if (copies > 1)
492		printf("%-2d copies of %-19s", copies, nfile);
493	else
494		printf("%-32s", nfile);
495	if (*datafile && !stat(datafile, &lbuf))
496		printf(" %qd bytes", (long long) lbuf.st_size);
497	else
498		printf(" ??? bytes");
499	putchar('\n');
500}
501
502/*
503 * Print the job's rank in the queue,
504 *   update col for screen management
505 */
506void
507prank(int n)
508{
509	char rline[100];
510	static const char *r[] = {
511		"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"
512	};
513
514	if (n == 0) {
515		printf("active");
516		col += 6;
517		return;
518	}
519	if ((n/10)%10 == 1)
520		(void)snprintf(rline, sizeof(rline), "%dth", n);
521	else
522		(void)snprintf(rline, sizeof(rline), "%d%s", n, r[n%10]);
523	col += strlen(rline);
524	printf("%s", rline);
525}
526
527void
528alarmhandler(int signo __unused)
529{
530	/* the signal is ignored */
531	/* (the '__unused' is just to avoid a compile-time warning) */
532}
533