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