xref: /freebsd/usr.sbin/lpr/lpc/cmds.c (revision 42249ef2)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1983, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)cmds.c	8.2 (Berkeley) 4/28/95";
42 #endif /* not lint */
43 #endif
44 
45 #include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
46 __FBSDID("$FreeBSD$");
47 
48 /*
49  * lpc -- line printer control program -- commands:
50  */
51 
52 #include <sys/param.h>
53 #include <sys/time.h>
54 #include <sys/stat.h>
55 #include <sys/file.h>
56 
57 #include <signal.h>
58 #include <fcntl.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <dirent.h>
62 #include <unistd.h>
63 #include <stdlib.h>
64 #include <stdio.h>
65 #include <ctype.h>
66 #include <string.h>
67 #include "lp.h"
68 #include "lp.local.h"
69 #include "lpc.h"
70 #include "extern.h"
71 #include "pathnames.h"
72 
73 /*
74  * Return values from kill_qtask().
75  */
76 #define KQT_LFERROR	-2
77 #define KQT_KILLFAIL	-1
78 #define KQT_NODAEMON	0
79 #define KQT_KILLOK	1
80 
81 static char	*args2line(int argc, char **argv);
82 static int	 doarg(char *_job);
83 static int	 doselect(const struct dirent *_d);
84 static int	 kill_qtask(const char *lf);
85 static int	 sortq(const struct dirent **a, const struct dirent **b);
86 static int	 touch(struct jobqueue *_jq);
87 static void	 unlinkf(char *_name);
88 static void	 upstat(struct printer *_pp, const char *_msg, int _notify);
89 static void	 wrapup_clean(int _laststatus);
90 
91 /*
92  * generic framework for commands which operate on all or a specified
93  * set of printers
94  */
95 enum	qsel_val {			/* how a given ptr was selected */
96 	QSEL_UNKNOWN = -1,		/* ... not selected yet */
97 	QSEL_BYNAME = 0,		/* ... user specifed it by name */
98 	QSEL_ALL = 1			/* ... user wants "all" printers */
99 					/*     (with more to come)    */
100 };
101 
102 static enum qsel_val generic_qselect;	/* indicates how ptr was selected */
103 static int generic_initerr;		/* result of initrtn processing */
104 static char *generic_cmdname;
105 static char *generic_msg;		/* if a -msg was specified */
106 static char *generic_nullarg;
107 static void (*generic_wrapup)(int _last_status);   /* perform rtn wrap-up */
108 
109 void
110 generic(void (*specificrtn)(struct printer *_pp), int cmdopts,
111     void (*initrtn)(int _argc, char *_argv[]), int argc, char *argv[])
112 {
113 	int cmdstatus, more, targc;
114 	struct printer myprinter, *pp;
115 	char **margv, **targv;
116 
117 	if (argc == 1) {
118 		/*
119 		 * Usage needs a special case for 'down': The user must
120 		 * either include `-msg', or only the first parameter
121 		 * that they give will be processed as a printer name.
122 		 */
123 		printf("usage: %s  {all | printer ...}", argv[0]);
124 		if (strcmp(argv[0], "down") == 0) {
125 			printf(" -msg [<text> ...]\n");
126 			printf("   or: down  {all | printer} [<text> ...]");
127 		} else if (cmdopts & LPC_MSGOPT)
128 			printf(" [-msg <text> ...]");
129 		printf("\n");
130 		return;
131 	}
132 
133 	/* The first argument is the command name. */
134 	generic_cmdname = *argv++;
135 	argc--;
136 
137 	/*
138 	 * The initialization routine for a command might set a generic
139 	 * "wrapup" routine, which should be called after processing all
140 	 * the printers in the command.  This might print summary info.
141 	 *
142 	 * Note that the initialization routine may also parse (and
143 	 * nullify) some of the parameters given on the command, leaving
144 	 * only the parameters which have to do with printer names.
145 	 */
146 	pp = &myprinter;
147 	generic_wrapup = NULL;
148 	generic_qselect = QSEL_UNKNOWN;
149 	cmdstatus = 0;
150 	/* this just needs to be a distinct value of type 'char *' */
151 	if (generic_nullarg == NULL)
152 		generic_nullarg = strdup("");
153 
154 	/*
155 	 * Some commands accept a -msg argument, which indicates that
156 	 * all remaining arguments should be combined into a string.
157 	 */
158 	generic_msg = NULL;
159 	if (cmdopts & LPC_MSGOPT) {
160 		targc = argc;
161 		targv = argv;
162 		for (; targc > 0; targc--, targv++) {
163 			if (strcmp(*targv, "-msg") == 0) {
164 				argc -= targc;
165 				generic_msg = args2line(targc - 1, targv + 1);
166 				break;
167 			}
168 		}
169 		if (argc < 1) {
170 			printf("error: No printer name(s) specified before"
171 			    " '-msg'.\n");
172 			printf("usage: %s  {all | printer ...}",
173 			    generic_cmdname);
174 			printf(" [-msg <text> ...]\n");
175 			return;
176 		}
177 	}
178 
179 	/* call initialization routine, if there is one for this cmd */
180 	if (initrtn != NULL) {
181 		generic_initerr = 0;
182 		(*initrtn)(argc, argv);
183 		if (generic_initerr)
184 			return;
185 		/*
186 		 * The initrtn may have null'ed out some of the parameters.
187 		 * Compact the parameter list to remove those nulls, and
188 		 * correct the arg-count.
189 		 */
190 		targc = argc;
191 		targv = argv;
192 		margv = argv;
193 		argc = 0;
194 		for (; targc > 0; targc--, targv++) {
195 			if (*targv != generic_nullarg) {
196 				if (targv != margv)
197 					*margv = *targv;
198 				margv++;
199 				argc++;
200 			}
201 		}
202 	}
203 
204 	if (argc == 1 && strcmp(*argv, "all") == 0) {
205 		generic_qselect = QSEL_ALL;
206 		more = firstprinter(pp, &cmdstatus);
207 		if (cmdstatus)
208 			goto looperr;
209 		while (more) {
210 			(*specificrtn)(pp);
211 			do {
212 				more = nextprinter(pp, &cmdstatus);
213 looperr:
214 				switch (cmdstatus) {
215 				case PCAPERR_TCOPEN:
216 					printf("warning: %s: unresolved "
217 					       "tc= reference(s) ",
218 					       pp->printer);
219 				case PCAPERR_SUCCESS:
220 					break;
221 				default:
222 					fatal(pp, "%s", pcaperr(cmdstatus));
223 				}
224 			} while (more && cmdstatus);
225 		}
226 		goto wrapup;
227 	}
228 
229 	generic_qselect = QSEL_BYNAME;		/* specifically-named ptrs */
230 	for (; argc > 0; argc--, argv++) {
231 		init_printer(pp);
232 		cmdstatus = getprintcap(*argv, pp);
233 		switch (cmdstatus) {
234 		default:
235 			fatal(pp, "%s", pcaperr(cmdstatus));
236 		case PCAPERR_NOTFOUND:
237 			printf("unknown printer %s\n", *argv);
238 			continue;
239 		case PCAPERR_TCOPEN:
240 			printf("warning: %s: unresolved tc= reference(s)\n",
241 			       *argv);
242 			break;
243 		case PCAPERR_SUCCESS:
244 			break;
245 		}
246 		(*specificrtn)(pp);
247 	}
248 
249 wrapup:
250 	if (generic_wrapup) {
251 		(*generic_wrapup)(cmdstatus);
252 	}
253 	free_printer(pp);
254 	if (generic_msg)
255 		free(generic_msg);
256 }
257 
258 /*
259  * Convert an argv-array of character strings into a single string.
260  */
261 static char *
262 args2line(int argc, char **argv)
263 {
264 	char *cp1, *cend;
265 	const char *cp2;
266 	char buf[1024];
267 
268 	if (argc <= 0)
269 		return strdup("\n");
270 
271 	cp1 = buf;
272 	cend = buf + sizeof(buf) - 1;		/* save room for '\0' */
273 	while (--argc >= 0) {
274 		cp2 = *argv++;
275 		while ((cp1 < cend) && (*cp1++ = *cp2++))
276 			;
277 		cp1[-1] = ' ';
278 	}
279 	cp1[-1] = '\n';
280 	*cp1 = '\0';
281 	return strdup(buf);
282 }
283 
284 /*
285  * Kill the current daemon, to stop printing of the active job.
286  */
287 static int
288 kill_qtask(const char *lf)
289 {
290 	FILE *fp;
291 	pid_t pid;
292 	int errsav, killres, lockres, res;
293 
294 	PRIV_START
295 	fp = fopen(lf, "r");
296 	errsav = errno;
297 	PRIV_END
298 	res = KQT_NODAEMON;
299 	if (fp == NULL) {
300 		/*
301 		 * If there is no lock file, then there is no daemon to
302 		 * kill.  Any other error return means there is some
303 		 * kind of problem with the lock file.
304 		 */
305 		if (errsav != ENOENT)
306 			res = KQT_LFERROR;
307 		goto killdone;
308 	}
309 
310 	/* If the lock file is empty, then there is no daemon to kill */
311 	if (get_line(fp) == 0)
312 		goto killdone;
313 
314 	/*
315 	 * If the file can be locked without blocking, then there
316 	 * no daemon to kill, or we should not try to kill it.
317 	 *
318 	 * XXX - not sure I understand the reasoning behind this...
319 	 */
320 	lockres = flock(fileno(fp), LOCK_SH|LOCK_NB);
321 	(void) fclose(fp);
322 	if (lockres == 0)
323 		goto killdone;
324 
325 	pid = atoi(line);
326 	if (pid < 0) {
327 		/*
328 		 * If we got a negative pid, then the contents of the
329 		 * lock file is not valid.
330 		 */
331 		res = KQT_LFERROR;
332 		goto killdone;
333 	}
334 
335 	PRIV_END
336 	killres = kill(pid, SIGTERM);
337 	errsav = errno;
338 	PRIV_END
339 	if (killres == 0) {
340 		res = KQT_KILLOK;
341 		printf("\tdaemon (pid %d) killed\n", pid);
342 	} else if (errno == ESRCH) {
343 		res = KQT_NODAEMON;
344 	} else {
345 		res = KQT_KILLFAIL;
346 		printf("\tWarning: daemon (pid %d) not killed:\n", pid);
347 		printf("\t    %s\n", strerror(errsav));
348 	}
349 
350 killdone:
351 	switch (res) {
352 	case KQT_LFERROR:
353 		printf("\tcannot open lock file: %s\n",
354 		    strerror(errsav));
355 		break;
356 	case KQT_NODAEMON:
357 		printf("\tno daemon to abort\n");
358 		break;
359 	case KQT_KILLFAIL:
360 	case KQT_KILLOK:
361 		/* These two already printed messages to the user. */
362 		break;
363 	default:
364 		printf("\t<internal error in kill_qtask>\n");
365 		break;
366 	}
367 
368 	return (res);
369 }
370 
371 /*
372  * Write a message into the status file.
373  */
374 static void
375 upstat(struct printer *pp, const char *msg, int notifyuser)
376 {
377 	int fd;
378 	char statfile[MAXPATHLEN];
379 
380 	status_file_name(pp, statfile, sizeof statfile);
381 	umask(0);
382 	PRIV_START
383 	fd = open(statfile, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
384 	PRIV_END
385 	if (fd < 0) {
386 		printf("\tcannot create status file: %s\n", strerror(errno));
387 		return;
388 	}
389 	(void) ftruncate(fd, 0);
390 	if (msg == NULL)
391 		(void) write(fd, "\n", 1);
392 	else
393 		(void) write(fd, msg, strlen(msg));
394 	(void) close(fd);
395 	if (notifyuser) {
396 		if ((msg == (char *)NULL) || (strcmp(msg, "\n") == 0))
397 			printf("\tstatus message is now set to nothing.\n");
398 		else
399 			printf("\tstatus message is now: %s", msg);
400 	}
401 }
402 
403 /*
404  * kill an existing daemon and disable printing.
405  */
406 void
407 abort_q(struct printer *pp)
408 {
409 	int killres, setres;
410 	char lf[MAXPATHLEN];
411 
412 	lock_file_name(pp, lf, sizeof lf);
413 	printf("%s:\n", pp->printer);
414 
415 	/*
416 	 * Turn on the owner execute bit of the lock file to disable printing.
417 	 */
418 	setres = set_qstate(SQS_STOPP, lf);
419 
420 	/*
421 	 * If set_qstate found that there already was a lock file, then
422 	 * call a routine which will read that lock file and kill the
423 	 * lpd-process which is listed in that lock file.  If the lock
424 	 * file did not exist, then either there is no daemon running
425 	 * for this queue, or there is one running but *it* could not
426 	 * write a lock file (which means we can not determine the
427 	 * process id of that lpd-process).
428 	 */
429 	switch (setres) {
430 	case SQS_CHGOK:
431 	case SQS_CHGFAIL:
432 		/* Kill the process */
433 		killres = kill_qtask(lf);
434 		break;
435 	case SQS_CREOK:
436 	case SQS_CREFAIL:
437 		printf("\tno daemon to abort\n");
438 		break;
439 	case SQS_STATFAIL:
440 		printf("\tassuming no daemon to abort\n");
441 		break;
442 	default:
443 		printf("\t<unexpected result (%d) from set_qstate>\n",
444 		    setres);
445 		break;
446 	}
447 
448 	if (setres >= 0)
449 		upstat(pp, "printing disabled\n", 0);
450 }
451 
452 /*
453  * "global" variables for all the routines related to 'clean' and 'tclean'
454  */
455 static time_t	 cln_now;		/* current time */
456 static double	 cln_minage;		/* minimum age before file is removed */
457 static long	 cln_sizecnt;		/* amount of space freed up */
458 static int 	 cln_debug;		/* print extra debugging msgs */
459 static int	 cln_filecnt;		/* number of files destroyed */
460 static int	 cln_foundcore;		/* found a core file! */
461 static int	 cln_queuecnt;		/* number of queues checked */
462 static int 	 cln_testonly;		/* remove-files vs just-print-info */
463 
464 static int
465 doselect(const struct dirent *d)
466 {
467 	int c = d->d_name[0];
468 
469 	if ((c == 'c' || c == 'd' || c == 'r' || c == 't') &&
470 	    d->d_name[1] == 'f')
471 		return 1;
472 	if (c == 'c') {
473 		if (!strcmp(d->d_name, "core"))
474 			cln_foundcore = 1;
475 	}
476 	if (c == 'e') {
477 		if (!strncmp(d->d_name, "errs.", 5))
478 			return 1;
479 	}
480 	return 0;
481 }
482 
483 /*
484  * Comparison routine that clean_q() uses for scandir.
485  *
486  * The purpose of this sort is to have all `df' files end up immediately
487  * after the matching `cf' file.  For files matching `cf', `df', `rf', or
488  * `tf', it sorts by job number and machine, then by `cf', `df', `rf', or
489  * `tf', and then by the sequence letter (which is A-Z, or a-z).    This
490  * routine may also see filenames which do not start with `cf', `df', `rf',
491  * or `tf' (such as `errs.*'), and those are simply sorted by the full
492  * filename.
493  *
494  * XXX
495  *   This assumes that all control files start with `cfA*', and it turns
496  *   out there are a few implementations of lpr which will create `cfB*'
497  *   filenames (they will have datafile names which start with `dfB*').
498  */
499 static int
500 sortq(const struct dirent **a, const struct dirent **b)
501 {
502 	const int a_lt_b = -1, a_gt_b = 1, cat_other = 10;
503 	const char *fname_a, *fname_b, *jnum_a, *jnum_b;
504 	int cat_a, cat_b, ch, res, seq_a, seq_b;
505 
506 	fname_a = (*a)->d_name;
507 	fname_b = (*b)->d_name;
508 
509 	/*
510 	 * First separate filenames into categories.  Categories are
511 	 * legitimate `cf', `df', `rf' & `tf' filenames, and "other" - in
512 	 * that order.  It is critical that the mapping be exactly the
513 	 * same for 'a' vs 'b', so define a macro for the job.
514 	 *
515 	 * [aside: the standard `cf' file has the jobnumber start in
516 	 * position 4, but some implementations have that as an extra
517 	 * file-sequence letter, and start the job number in position 5.]
518 	 */
519 #define MAP_TO_CAT(fname_X,cat_X,jnum_X,seq_X) do { \
520 	cat_X = cat_other;    \
521 	ch = *(fname_X + 2);  \
522 	jnum_X = fname_X + 3; \
523 	seq_X = 0;            \
524 	if ((*(fname_X + 1) == 'f') && (isalpha(ch))) { \
525 		seq_X = ch; \
526 		if (*fname_X == 'c') \
527 			cat_X = 1; \
528 		else if (*fname_X == 'd') \
529 			cat_X = 2; \
530 		else if (*fname_X == 'r') \
531 			cat_X = 3; \
532 		else if (*fname_X == 't') \
533 			cat_X = 4; \
534 		if (cat_X != cat_other) { \
535 			ch = *jnum_X; \
536 			if (!isdigit(ch)) { \
537 				if (isalpha(ch)) { \
538 					jnum_X++; \
539 					ch = *jnum_X; \
540 					seq_X = (seq_X << 8) + ch; \
541 				} \
542 				if (!isdigit(ch)) \
543 					cat_X = cat_other; \
544 			} \
545 		} \
546 	} \
547 } while (0)
548 
549 	MAP_TO_CAT(fname_a, cat_a, jnum_a, seq_a);
550 	MAP_TO_CAT(fname_b, cat_b, jnum_b, seq_b);
551 
552 #undef MAP_TO_CAT
553 
554 	/* First handle all cases which have "other" files */
555 	if ((cat_a >= cat_other) || (cat_b >= cat_other)) {
556 		/* for two "other" files, just compare the full name */
557 		if (cat_a == cat_b)
558 			res = strcmp(fname_a, fname_b);
559 		else if (cat_a < cat_b)
560 			res = a_lt_b;
561 		else
562 			res = a_gt_b;
563 		goto have_res;
564 	}
565 
566 	/*
567 	 * At this point, we know both files are legitimate `cf', `df', `rf',
568 	 * or `tf' files.  Compare them by job-number and machine name.
569 	 */
570 	res = strcmp(jnum_a, jnum_b);
571 	if (res != 0)
572 		goto have_res;
573 
574 	/*
575 	 * We have two files which belong to the same job.  Sort based
576 	 * on the category of file (`c' before `d', etc).
577 	 */
578 	if (cat_a < cat_b) {
579 		res = a_lt_b;
580 		goto have_res;
581 	} else if (cat_a > cat_b) {
582 		res = a_gt_b;
583 		goto have_res;
584 	}
585 
586 	/*
587 	 * Two files in the same category for a single job.  Sort based
588 	 * on the sequence letter(s).  (usually `A' through `Z', etc).
589 	 */
590 	if (seq_a < seq_b) {
591 		res = a_lt_b;
592 		goto have_res;
593 	} else if (seq_a > seq_b) {
594 		res = a_gt_b;
595 		goto have_res;
596 	}
597 
598 	/*
599 	 * Given that the filenames in a directory are unique, this SHOULD
600 	 * never happen (unless there are logic errors in this routine).
601 	 * But if it does happen, we must return "is equal" or the caller
602 	 * might see inconsistent results in the sorting order, and that
603 	 * can trigger other problems.
604 	 */
605 	printf("\t*** Error in sortq: %s == %s !\n", fname_a, fname_b);
606 	printf("\t***       cat %d == %d ; seq = %d %d\n", cat_a, cat_b,
607 	    seq_a, seq_b);
608 	res = 0;
609 
610 have_res:
611 	return res;
612 }
613 
614 /*
615  * Remove all spool files and temporaries from the spooling area.
616  * Or, perhaps:
617  * Remove incomplete jobs from spooling area.
618  */
619 
620 void
621 clean_gi(int argc, char *argv[])
622 {
623 
624 	/* init some fields before 'clean' is called for each queue */
625 	cln_queuecnt = 0;
626 	cln_now = time(NULL);
627 	cln_minage = 3600.0;		/* only delete files >1h old */
628 	cln_filecnt = 0;
629 	cln_sizecnt = 0;
630 	cln_debug = 0;
631 	cln_testonly = 0;
632 	generic_wrapup = &wrapup_clean;
633 
634 	/* see if there are any options specified before the ptr list */
635 	for (; argc > 0; argc--, argv++) {
636 		if (**argv != '-')
637 			break;
638 		if (strcmp(*argv, "-d") == 0) {
639 			/* just an example of an option... */
640 			cln_debug++;
641 			*argv = generic_nullarg;	/* "erase" it */
642 		} else {
643 			printf("Invalid option '%s'\n", *argv);
644 			generic_initerr = 1;
645 		}
646 	}
647 
648 	return;
649 }
650 
651 void
652 tclean_gi(int argc, char *argv[])
653 {
654 
655 	/* only difference between 'clean' and 'tclean' is one value */
656 	/* (...and the fact that 'clean' is priv and 'tclean' is not) */
657 	clean_gi(argc, argv);
658 	cln_testonly = 1;
659 
660 	return;
661 }
662 
663 void
664 clean_q(struct printer *pp)
665 {
666 	char *cp, *cp1, *lp;
667 	struct dirent **queue;
668 	size_t linerem;
669 	int didhead, i, n, nitems, rmcp;
670 
671 	cln_queuecnt++;
672 
673 	didhead = 0;
674 	if (generic_qselect == QSEL_BYNAME) {
675 		printf("%s:\n", pp->printer);
676 		didhead = 1;
677 	}
678 
679 	lp = line;
680 	cp = pp->spool_dir;
681 	while (lp < &line[sizeof(line) - 1]) {
682 		if ((*lp++ = *cp++) == 0)
683 			break;
684 	}
685 	lp[-1] = '/';
686 	linerem = sizeof(line) - (lp - line);
687 
688 	cln_foundcore = 0;
689 	PRIV_START
690 	nitems = scandir(pp->spool_dir, &queue, doselect, sortq);
691 	PRIV_END
692 	if (nitems < 0) {
693 		if (!didhead) {
694 			printf("%s:\n", pp->printer);
695 			didhead = 1;
696 		}
697 		printf("\tcannot examine spool directory\n");
698 		return;
699 	}
700 	if (cln_foundcore) {
701 		if (!didhead) {
702 			printf("%s:\n", pp->printer);
703 			didhead = 1;
704 		}
705 		printf("\t** found a core file in %s !\n", pp->spool_dir);
706 	}
707 	if (nitems == 0)
708 		return;
709 	if (!didhead)
710 		printf("%s:\n", pp->printer);
711 	if (cln_debug) {
712 		printf("\t** ----- Sorted list of files being checked:\n");
713 		i = 0;
714 		do {
715 			cp = queue[i]->d_name;
716 			printf("\t** [%3d] = %s\n", i, cp);
717 		} while (++i < nitems);
718 		printf("\t** ----- end of sorted list\n");
719 	}
720 	i = 0;
721 	do {
722 		cp = queue[i]->d_name;
723 		rmcp = 0;
724 		if (*cp == 'c') {
725 			/*
726 			 * A control file.  Look for matching data-files.
727 			 */
728 			/* XXX
729 			 *  Note the logic here assumes that the hostname
730 			 *  part of cf-filenames match the hostname part
731 			 *  in df-filenames, and that is not necessarily
732 			 *  true (eg: for multi-homed hosts).  This needs
733 			 *  some further thought...
734 			 */
735 			n = 0;
736 			while (i + 1 < nitems) {
737 				cp1 = queue[i + 1]->d_name;
738 				if (*cp1 != 'd' || strcmp(cp + 3, cp1 + 3))
739 					break;
740 				i++;
741 				n++;
742 			}
743 			if (n == 0) {
744 				rmcp = 1;
745 			}
746 		} else if (*cp == 'e') {
747 			/*
748 			 * Must be an errrs or email temp file.
749 			 */
750 			rmcp = 1;
751 		} else {
752 			/*
753 			 * Must be a df with no cf (otherwise, it would have
754 			 * been skipped above) or an rf or tf file (which can
755 			 * always be removed if it is old enough).
756 			 */
757 			rmcp = 1;
758 		}
759 		if (rmcp) {
760 			if (strlen(cp) >= linerem) {
761 				printf("\t** internal error: 'line' overflow!\n");
762 				printf("\t**   spooldir = %s\n", pp->spool_dir);
763 				printf("\t**   cp = %s\n", cp);
764 				return;
765 			}
766 			strlcpy(lp, cp, linerem);
767 			unlinkf(line);
768 		}
769      	} while (++i < nitems);
770 }
771 
772 static void
773 wrapup_clean(int laststatus __unused)
774 {
775 
776 	printf("Checked %d queues, and ", cln_queuecnt);
777 	if (cln_filecnt < 1) {
778 		printf("no cruft was found\n");
779 		return;
780 	}
781 	if (cln_testonly) {
782 		printf("would have ");
783 	}
784 	printf("removed %d files (%ld bytes).\n", cln_filecnt, cln_sizecnt);
785 }
786 
787 static void
788 unlinkf(char *name)
789 {
790 	struct stat stbuf;
791 	double agemod, agestat;
792 	int res;
793 	char linkbuf[BUFSIZ];
794 
795 	/*
796 	 * We have to use lstat() instead of stat(), in case this is a df*
797 	 * "file" which is really a symlink due to 'lpr -s' processing.  In
798 	 * that case, we need to check the last-mod time of the symlink, and
799 	 * not the file that the symlink is pointed at.
800 	 */
801 	PRIV_START
802 	res = lstat(name, &stbuf);
803 	PRIV_END
804 	if (res < 0) {
805 		printf("\terror return from stat(%s):\n", name);
806 		printf("\t      %s\n", strerror(errno));
807 		return;
808 	}
809 
810 	agemod = difftime(cln_now, stbuf.st_mtime);
811 	agestat = difftime(cln_now,  stbuf.st_ctime);
812 	if (cln_debug > 1) {
813 		/* this debugging-aid probably is not needed any more... */
814 		printf("\t\t  modify age=%g secs, stat age=%g secs\n",
815 		    agemod, agestat);
816 	}
817 	if ((agemod <= cln_minage) && (agestat <= cln_minage))
818 		return;
819 
820 	/*
821 	 * if this file is a symlink, then find out the target of the
822 	 * symlink before unlink-ing the file itself
823 	 */
824 	if (S_ISLNK(stbuf.st_mode)) {
825 		PRIV_START
826 		res = readlink(name, linkbuf, sizeof(linkbuf));
827 		PRIV_END
828 		if (res < 0) {
829 			printf("\terror return from readlink(%s):\n", name);
830 			printf("\t      %s\n", strerror(errno));
831 			return;
832 		}
833 		if (res == sizeof(linkbuf))
834 			res--;
835 		linkbuf[res] = '\0';
836 	}
837 
838 	cln_filecnt++;
839 	cln_sizecnt += stbuf.st_size;
840 
841 	if (cln_testonly) {
842 		printf("\twould remove %s\n", name);
843 		if (S_ISLNK(stbuf.st_mode)) {
844 			printf("\t    (which is a symlink to %s)\n", linkbuf);
845 		}
846 	} else {
847 		PRIV_START
848 		res = unlink(name);
849 		PRIV_END
850 		if (res < 0)
851 			printf("\tcannot remove %s (!)\n", name);
852 		else
853 			printf("\tremoved %s\n", name);
854 		/* XXX
855 		 *  Note that for a df* file, this code should also check to see
856 		 *  if it is a symlink to some other file, and if the original
857 		 *  lpr command included '-r' ("remove file").  Of course, this
858 		 *  code would not be removing the df* file unless there was no
859 		 *  matching cf* file, and without the cf* file it is currently
860 		 *  impossible to determine if '-r' had been specified...
861 		 *
862 		 *  As a result of this quandry, we may be leaving behind a
863 		 *  user's file that was supposed to have been removed after
864 		 *  being printed.  This may effect services such as CAP or
865 		 *  samba, if they were configured to use 'lpr -r', and if
866 		 *  datafiles are not being properly removed.
867 		*/
868 		if (S_ISLNK(stbuf.st_mode)) {
869 			printf("\t    (which was a symlink to %s)\n", linkbuf);
870 		}
871 	}
872 }
873 
874 /*
875  * Enable queuing to the printer (allow lpr to add new jobs to the queue).
876  */
877 void
878 enable_q(struct printer *pp)
879 {
880 	int setres;
881 	char lf[MAXPATHLEN];
882 
883 	lock_file_name(pp, lf, sizeof lf);
884 	printf("%s:\n", pp->printer);
885 
886 	setres = set_qstate(SQS_ENABLEQ, lf);
887 }
888 
889 /*
890  * Disable queuing.
891  */
892 void
893 disable_q(struct printer *pp)
894 {
895 	int setres;
896 	char lf[MAXPATHLEN];
897 
898 	lock_file_name(pp, lf, sizeof lf);
899 	printf("%s:\n", pp->printer);
900 
901 	setres = set_qstate(SQS_DISABLEQ, lf);
902 }
903 
904 /*
905  * Disable queuing and printing and put a message into the status file
906  * (reason for being down).  If the user specified `-msg', then use
907  * everything after that as the message for the status file.  If the
908  * user did NOT specify `-msg', then the command should take the first
909  * parameter as the printer name, and all remaining parameters as the
910  * message for the status file.  (This is to be compatible with the
911  * original definition of 'down', which was implemented long before
912  * `-msg' was around).
913  */
914 void
915 down_gi(int argc, char *argv[])
916 {
917 
918 	/* If `-msg' was specified, then this routine has nothing to do. */
919 	if (generic_msg != NULL)
920 		return;
921 
922 	/*
923 	 * If the user only gave one parameter, then use a default msg.
924 	 * (if argc == 1 at this point, then *argv == name of printer).
925 	 */
926 	if (argc == 1) {
927 		generic_msg = strdup("printing disabled\n");
928 		return;
929 	}
930 
931 	/*
932 	 * The user specified multiple parameters, and did not specify
933 	 * `-msg'.  Build a message from all the parameters after the
934 	 * first one (and nullify those parameters so generic-processing
935 	 * will not process them as printer-queue names).
936 	 */
937 	argc--;
938 	argv++;
939 	generic_msg = args2line(argc, argv);
940 	for (; argc > 0; argc--, argv++)
941 		*argv = generic_nullarg;	/* "erase" it */
942 }
943 
944 void
945 down_q(struct printer *pp)
946 {
947 	int setres;
948 	char lf[MAXPATHLEN];
949 
950 	lock_file_name(pp, lf, sizeof lf);
951 	printf("%s:\n", pp->printer);
952 
953 	setres = set_qstate(SQS_DISABLEQ+SQS_STOPP, lf);
954 	if (setres >= 0)
955 		upstat(pp, generic_msg, 1);
956 }
957 
958 /*
959  * Exit lpc
960  */
961 void
962 quit(int argc __unused, char *argv[] __unused)
963 {
964 	exit(0);
965 }
966 
967 /*
968  * Kill and restart the daemon.
969  */
970 void
971 restart_q(struct printer *pp)
972 {
973 	int killres, setres, startok;
974 	char lf[MAXPATHLEN];
975 
976 	lock_file_name(pp, lf, sizeof lf);
977 	printf("%s:\n", pp->printer);
978 
979 	killres = kill_qtask(lf);
980 
981 	/*
982 	 * XXX - if the kill worked, we should probably sleep for
983 	 *      a second or so before trying to restart the queue.
984 	 */
985 
986 	/* make sure the queue is set to print jobs */
987 	setres = set_qstate(SQS_STARTP, lf);
988 
989 	PRIV_START
990 	startok = startdaemon(pp);
991 	PRIV_END
992 	if (!startok)
993 		printf("\tcouldn't restart daemon\n");
994 	else
995 		printf("\tdaemon restarted\n");
996 }
997 
998 /*
999  * Set the status message of each queue listed.  Requires a "-msg"
1000  * parameter to indicate the end of the queue list and start of msg text.
1001  */
1002 void
1003 setstatus_gi(int argc __unused, char *argv[] __unused)
1004 {
1005 
1006 	if (generic_msg == NULL) {
1007 		printf("You must specify '-msg' before the text of the new status message.\n");
1008 		generic_initerr = 1;
1009 	}
1010 }
1011 
1012 void
1013 setstatus_q(struct printer *pp)
1014 {
1015 	struct stat stbuf;
1016 	int not_shown;
1017 	char lf[MAXPATHLEN];
1018 
1019 	lock_file_name(pp, lf, sizeof lf);
1020 	printf("%s:\n", pp->printer);
1021 
1022 	upstat(pp, generic_msg, 1);
1023 
1024 	/*
1025 	 * Warn the user if 'lpq' will not display this new status-message.
1026 	 * Note that if lock file does not exist, then the queue is enabled
1027 	 * for both queuing and printing.
1028 	 */
1029 	not_shown = 1;
1030 	if (stat(lf, &stbuf) >= 0) {
1031 		if (stbuf.st_mode & LFM_PRINT_DIS)
1032 			not_shown = 0;
1033 	}
1034 	if (not_shown) {
1035 		printf("\tnote: This queue currently has printing enabled,\n");
1036 		printf("\t    so this -msg will only be shown by 'lpq' if\n");
1037 		printf("\t    a job is actively printing on it.\n");
1038 	}
1039 }
1040 
1041 /*
1042  * Enable printing on the specified printer and startup the daemon.
1043  */
1044 void
1045 start_q(struct printer *pp)
1046 {
1047 	int setres, startok;
1048 	char lf[MAXPATHLEN];
1049 
1050 	lock_file_name(pp, lf, sizeof lf);
1051 	printf("%s:\n", pp->printer);
1052 
1053 	setres = set_qstate(SQS_STARTP, lf);
1054 
1055 	PRIV_START
1056 	startok = startdaemon(pp);
1057 	PRIV_END
1058 	if (!startok)
1059 		printf("\tcouldn't start daemon\n");
1060 	else
1061 		printf("\tdaemon started\n");
1062 	PRIV_END
1063 }
1064 
1065 /*
1066  * Print the status of the printer queue.
1067  */
1068 void
1069 status(struct printer *pp)
1070 {
1071 	struct stat stbuf;
1072 	register int fd, i;
1073 	register struct dirent *dp;
1074 	DIR *dirp;
1075 	char file[MAXPATHLEN];
1076 
1077 	printf("%s:\n", pp->printer);
1078 	lock_file_name(pp, file, sizeof file);
1079 	if (stat(file, &stbuf) >= 0) {
1080 		printf("\tqueuing is %s\n",
1081 		       ((stbuf.st_mode & LFM_QUEUE_DIS) ? "disabled"
1082 			: "enabled"));
1083 		printf("\tprinting is %s\n",
1084 		       ((stbuf.st_mode & LFM_PRINT_DIS) ? "disabled"
1085 			: "enabled"));
1086 	} else {
1087 		printf("\tqueuing is enabled\n");
1088 		printf("\tprinting is enabled\n");
1089 	}
1090 	if ((dirp = opendir(pp->spool_dir)) == NULL) {
1091 		printf("\tcannot examine spool directory\n");
1092 		return;
1093 	}
1094 	i = 0;
1095 	while ((dp = readdir(dirp)) != NULL) {
1096 		if (*dp->d_name == 'c' && dp->d_name[1] == 'f')
1097 			i++;
1098 	}
1099 	closedir(dirp);
1100 	if (i == 0)
1101 		printf("\tno entries in spool area\n");
1102 	else if (i == 1)
1103 		printf("\t1 entry in spool area\n");
1104 	else
1105 		printf("\t%d entries in spool area\n", i);
1106 	fd = open(file, O_RDONLY);
1107 	if (fd < 0 || flock(fd, LOCK_SH|LOCK_NB) == 0) {
1108 		(void) close(fd);	/* unlocks as well */
1109 		printf("\tprinter idle\n");
1110 		return;
1111 	}
1112 	(void) close(fd);
1113 	/* print out the contents of the status file, if it exists */
1114 	status_file_name(pp, file, sizeof file);
1115 	fd = open(file, O_RDONLY|O_SHLOCK);
1116 	if (fd >= 0) {
1117 		(void) fstat(fd, &stbuf);
1118 		if (stbuf.st_size > 0) {
1119 			putchar('\t');
1120 			while ((i = read(fd, line, sizeof(line))) > 0)
1121 				(void) fwrite(line, 1, i, stdout);
1122 		}
1123 		(void) close(fd);	/* unlocks as well */
1124 	}
1125 }
1126 
1127 /*
1128  * Stop the specified daemon after completing the current job and disable
1129  * printing.
1130  */
1131 void
1132 stop_q(struct printer *pp)
1133 {
1134 	int setres;
1135 	char lf[MAXPATHLEN];
1136 
1137 	lock_file_name(pp, lf, sizeof lf);
1138 	printf("%s:\n", pp->printer);
1139 
1140 	setres = set_qstate(SQS_STOPP, lf);
1141 
1142 	if (setres >= 0)
1143 		upstat(pp, "printing disabled\n", 0);
1144 }
1145 
1146 struct	jobqueue **queue;
1147 int	nitems;
1148 time_t	mtime;
1149 
1150 /*
1151  * Put the specified jobs at the top of printer queue.
1152  */
1153 void
1154 topq(int argc, char *argv[])
1155 {
1156 	register int i;
1157 	struct stat stbuf;
1158 	int cmdstatus, changed;
1159 	struct printer myprinter, *pp = &myprinter;
1160 
1161 	if (argc < 3) {
1162 		printf("usage: topq printer [jobnum ...] [user ...]\n");
1163 		return;
1164 	}
1165 
1166 	--argc;
1167 	++argv;
1168 	init_printer(pp);
1169 	cmdstatus = getprintcap(*argv, pp);
1170 	switch(cmdstatus) {
1171 	default:
1172 		fatal(pp, "%s", pcaperr(cmdstatus));
1173 	case PCAPERR_NOTFOUND:
1174 		printf("unknown printer %s\n", *argv);
1175 		return;
1176 	case PCAPERR_TCOPEN:
1177 		printf("warning: %s: unresolved tc= reference(s)", *argv);
1178 		break;
1179 	case PCAPERR_SUCCESS:
1180 		break;
1181 	}
1182 	printf("%s:\n", pp->printer);
1183 
1184 	PRIV_START
1185 	if (chdir(pp->spool_dir) < 0) {
1186 		printf("\tcannot chdir to %s\n", pp->spool_dir);
1187 		goto out;
1188 	}
1189 	PRIV_END
1190 	nitems = getq(pp, &queue);
1191 	if (nitems == 0)
1192 		return;
1193 	changed = 0;
1194 	mtime = queue[0]->job_time;
1195 	for (i = argc; --i; ) {
1196 		if (doarg(argv[i]) == 0) {
1197 			printf("\tjob %s is not in the queue\n", argv[i]);
1198 			continue;
1199 		} else
1200 			changed++;
1201 	}
1202 	for (i = 0; i < nitems; i++)
1203 		free(queue[i]);
1204 	free(queue);
1205 	if (!changed) {
1206 		printf("\tqueue order unchanged\n");
1207 		return;
1208 	}
1209 	/*
1210 	 * Turn on the public execute bit of the lock file to
1211 	 * get lpd to rebuild the queue after the current job.
1212 	 */
1213 	PRIV_START
1214 	if (changed && stat(pp->lock_file, &stbuf) >= 0)
1215 		(void) chmod(pp->lock_file, stbuf.st_mode | LFM_RESET_QUE);
1216 
1217 out:
1218 	PRIV_END
1219 }
1220 
1221 /*
1222  * Reposition the job by changing the modification time of
1223  * the control file.
1224  */
1225 static int
1226 touch(struct jobqueue *jq)
1227 {
1228 	struct timeval tvp[2];
1229 	int ret;
1230 
1231 	tvp[0].tv_sec = tvp[1].tv_sec = --mtime;
1232 	tvp[0].tv_usec = tvp[1].tv_usec = 0;
1233 	PRIV_START
1234 	ret = utimes(jq->job_cfname, tvp);
1235 	PRIV_END
1236 	return (ret);
1237 }
1238 
1239 /*
1240  * Checks if specified job name is in the printer's queue.
1241  * Returns:  negative (-1) if argument name is not in the queue.
1242  */
1243 static int
1244 doarg(char *job)
1245 {
1246 	register struct jobqueue **qq;
1247 	register int jobnum, n;
1248 	register char *cp, *machine;
1249 	int cnt = 0;
1250 	FILE *fp;
1251 
1252 	/*
1253 	 * Look for a job item consisting of system name, colon, number
1254 	 * (example: ucbarpa:114)
1255 	 */
1256 	if ((cp = strchr(job, ':')) != NULL) {
1257 		machine = job;
1258 		*cp++ = '\0';
1259 		job = cp;
1260 	} else
1261 		machine = NULL;
1262 
1263 	/*
1264 	 * Check for job specified by number (example: 112 or 235ucbarpa).
1265 	 */
1266 	if (isdigit(*job)) {
1267 		jobnum = 0;
1268 		do
1269 			jobnum = jobnum * 10 + (*job++ - '0');
1270 		while (isdigit(*job));
1271 		for (qq = queue + nitems; --qq >= queue; ) {
1272 			n = 0;
1273 			for (cp = (*qq)->job_cfname+3; isdigit(*cp); )
1274 				n = n * 10 + (*cp++ - '0');
1275 			if (jobnum != n)
1276 				continue;
1277 			if (*job && strcmp(job, cp) != 0)
1278 				continue;
1279 			if (machine != NULL && strcmp(machine, cp) != 0)
1280 				continue;
1281 			if (touch(*qq) == 0) {
1282 				printf("\tmoved %s\n", (*qq)->job_cfname);
1283 				cnt++;
1284 			}
1285 		}
1286 		return(cnt);
1287 	}
1288 	/*
1289 	 * Process item consisting of owner's name (example: henry).
1290 	 */
1291 	for (qq = queue + nitems; --qq >= queue; ) {
1292 		PRIV_START
1293 		fp = fopen((*qq)->job_cfname, "r");
1294 		PRIV_END
1295 		if (fp == NULL)
1296 			continue;
1297 		while (get_line(fp) > 0)
1298 			if (line[0] == 'P')
1299 				break;
1300 		(void) fclose(fp);
1301 		if (line[0] != 'P' || strcmp(job, line+1) != 0)
1302 			continue;
1303 		if (touch(*qq) == 0) {
1304 			printf("\tmoved %s\n", (*qq)->job_cfname);
1305 			cnt++;
1306 		}
1307 	}
1308 	return(cnt);
1309 }
1310 
1311 /*
1312  * Enable both queuing & printing, and start printer (undo `down').
1313  */
1314 void
1315 up_q(struct printer *pp)
1316 {
1317 	int setres, startok;
1318 	char lf[MAXPATHLEN];
1319 
1320 	lock_file_name(pp, lf, sizeof lf);
1321 	printf("%s:\n", pp->printer);
1322 
1323 	setres = set_qstate(SQS_ENABLEQ+SQS_STARTP, lf);
1324 
1325 	PRIV_START
1326 	startok = startdaemon(pp);
1327 	PRIV_END
1328 	if (!startok)
1329 		printf("\tcouldn't start daemon\n");
1330 	else
1331 		printf("\tdaemon started\n");
1332 }
1333