xref: /freebsd/usr.sbin/lpr/common_source/displayq.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
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 /*
36 static char sccsid[] = "@(#)displayq.c	8.4 (Berkeley) 4/28/95";
37 */
38 static const char rcsid[] =
39   "$FreeBSD$";
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  */
73 extern uid_t	uid, euid;
74 
75 static int	col;		/* column on screen */
76 static char	current[40];	/* current file being printed */
77 static char	file[132];	/* print file name */
78 static int	first;		/* first file in ``files'' column? */
79 static int	garbage;	/* # of garbage cf files */
80 static int	lflag;		/* long output option */
81 static int	rank;		/* order to be printed (-1=none, 0=active) */
82 static long	totsize;	/* total print job size in bytes */
83 
84 static const char  *head0 = "Rank   Owner      Job  Files";
85 static const char  *head1 = "Total Size\n";
86 
87 static void	alarmhandler(int _signo);
88 static void	warn(const struct printer *_pp);
89 
90 /*
91  * Display the current state of the queue. Format = 1 if long format.
92  */
93 void
94 displayq(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  */
258 static void
259 warn(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  */
270 void
271 header(void)
272 {
273 	printf(head0);
274 	col = strlen(head0)+1;
275 	blankfill(SIZCOL);
276 	printf(head1);
277 }
278 
279 void
280 inform(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 				strncpy(file, line + 1, sizeof(file) - 1);
341 				file[sizeof(file) - 1] = '\0';
342 			}
343 			copycnt++;
344 			/*
345 			 * deliberately 'continue' to another getline(), so
346 			 * all format-spec lines for this datafile are read
347 			 * in and counted before calling show()
348 			 */
349 			continue;
350 		case 'N':
351 			strncpy(savedname, line + 1, sizeof(savedname) - 1);
352 			savedname[sizeof(savedname) - 1] = '\0';
353 			break;
354 		}
355 		if ((file[0] != '\0') && (savedname[0] != '\0')) {
356 			show(savedname, file, copycnt);
357 			copycnt = 0;
358 			file[0] = '\0';
359 			savedname[0] = '\0';
360 		}
361 	}
362 	fclose(cfp);
363 	/* check for a file which hasn't been shown yet */
364 	if (file[0] != '\0') {
365 		if (savedname[0] == '\0') {
366 			/* a safeguard in case the N-ame line is missing */
367 			strncpy(savedname, file, sizeof(savedname) - 1);
368 			savedname[sizeof(savedname) - 1] = '\0';
369 		}
370 		show(savedname, file, copycnt);
371 	}
372 	if (!lflag) {
373 		blankfill(SIZCOL);
374 		printf("%ld bytes\n", totsize);
375 		totsize = 0;
376 	}
377 }
378 
379 int
380 inlist(char *uname, char *cfile)
381 {
382 	register int *r, n;
383 	register char **u, *cp;
384 
385 	if (users == 0 && requests == 0)
386 		return(1);
387 	/*
388 	 * Check to see if it's in the user list
389 	 */
390 	for (u = user; u < &user[users]; u++)
391 		if (!strcmp(*u, uname))
392 			return(1);
393 	/*
394 	 * Check the request list
395 	 */
396 	for (n = 0, cp = cfile+3; isdigit(*cp); )
397 		n = n * 10 + (*cp++ - '0');
398 	for (r = requ; r < &requ[requests]; r++)
399 		if (*r == n && !strcmp(cp, from_host))
400 			return(1);
401 	return(0);
402 }
403 
404 void
405 show(const char *nfile, const char *datafile, int copies)
406 {
407 	if (strcmp(nfile, " ") == 0)
408 		nfile = "(standard input)";
409 	if (lflag)
410 		ldump(nfile, datafile, copies);
411 	else
412 		dump(nfile, datafile, copies);
413 }
414 
415 /*
416  * Fill the line with blanks to the specified column
417  */
418 void
419 blankfill(int tocol)
420 {
421 	while (col++ < tocol)
422 		putchar(' ');
423 }
424 
425 /*
426  * Give the abbreviated dump of the file names
427  */
428 void
429 dump(const char *nfile, const char *datafile, int copies)
430 {
431 	struct stat lbuf;
432 	const char etctmpl[] = ", ...";
433 	char	 etc[sizeof(etctmpl)];
434 	char	*lastsep;
435 	short	 fill, nlen;
436 	short	 rem, remetc;
437 
438 	/*
439 	 * Print as many filenames as will fit
440 	 *      (leaving room for the 'total size' field)
441 	 */
442 	fill = first ? 0 : 2;	/* fill space for ``, '' */
443 	nlen = strlen(nfile);
444 	rem = SIZCOL - 1 - col;
445 	if (nlen + fill > rem) {
446 		if (first) {
447 			/* print the right-most part of the name */
448 			printf("...%s ", &nfile[3+nlen-rem]);
449 			col = SIZCOL;
450 		} else if (rem > 0) {
451 			/* fit as much of the etc-string as we can */
452 			remetc = rem;
453 			if (rem > strlen(etctmpl))
454 				remetc = strlen(etctmpl);
455 			etc[0] = '\0';
456 			strncat(etc, etctmpl, remetc);
457 			printf(etc);
458 			col += remetc;
459 			rem -= remetc;
460 			/* room for the last segment of this filename? */
461 			lastsep = strrchr(nfile, '/');
462 			if ((lastsep != NULL) && (rem > strlen(lastsep))) {
463 				/* print the right-most part of this name */
464 				printf("%s", lastsep);
465 				col += strlen(lastsep);
466 			} else {
467 				/* do not pack any more names in here */
468 				blankfill(SIZCOL);
469 			}
470 		}
471 	} else {
472 		if (!first)
473 			printf(", ");
474 		printf("%s", nfile);
475 		col += nlen + fill;
476 	}
477 	first = 0;
478 
479 	seteuid(euid);
480 	if (*datafile && !stat(datafile, &lbuf))
481 		totsize += copies * lbuf.st_size;
482 	seteuid(uid);
483 }
484 
485 /*
486  * Print the long info about the file
487  */
488 void
489 ldump(const char *nfile, const char *datafile, int copies)
490 {
491 	struct stat lbuf;
492 
493 	putchar('\t');
494 	if (copies > 1)
495 		printf("%-2d copies of %-19s", copies, nfile);
496 	else
497 		printf("%-32s", nfile);
498 	if (*datafile && !stat(datafile, &lbuf))
499 		printf(" %qd bytes", (long long) lbuf.st_size);
500 	else
501 		printf(" ??? bytes");
502 	putchar('\n');
503 }
504 
505 /*
506  * Print the job's rank in the queue,
507  *   update col for screen management
508  */
509 void
510 prank(int n)
511 {
512 	char rline[100];
513 	static const char *r[] = {
514 		"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"
515 	};
516 
517 	if (n == 0) {
518 		printf("active");
519 		col += 6;
520 		return;
521 	}
522 	if ((n/10)%10 == 1)
523 		(void)snprintf(rline, sizeof(rline), "%dth", n);
524 	else
525 		(void)snprintf(rline, sizeof(rline), "%d%s", n, r[n%10]);
526 	col += strlen(rline);
527 	printf("%s", rline);
528 }
529 
530 void
531 alarmhandler(int signo __unused)
532 {
533 	/* the signal is ignored */
534 	/* (the '__unused' is just to avoid a compile-time warning) */
535 }
536