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