get mxge to build, stage 29/many
[dragonfly.git] / usr.sbin / lpr / lpc / cmds.c
blob471c83ee49a41bb32dcca6f9da7662f0162ca991
1 /*
2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
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.
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.
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.4 2004/12/18 22:48:03 swildner Exp $
41 * lpc -- line printer control program -- commands:
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/stat.h>
47 #include <sys/file.h>
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"
65 * Return values from kill_qtask().
67 #define KQT_LFERROR -2
68 #define KQT_KILLFAIL -1
69 #define KQT_NODAEMON 0
70 #define KQT_KILLOK 1
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);
83 * generic framework for commands which operate on all or a specified
84 * set of printers
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) */
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 */
100 void
101 generic(void (*specificrtn)(struct printer *_pp), int cmdopts,
102 void (*initrtn)(int _argc, char **_argv), int argc, char **argv)
104 int cmdstatus, more, targc;
105 struct printer myprinter, *pp;
106 char **margv, **targv;
108 if (argc == 1) {
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.
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;
124 /* The first argument is the command name. */
125 generic_cmdname = *argv++;
126 argc--;
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.
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.
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("");
146 * Some commands accept a -msg argument, which indicates that
147 * all remaining arguments should be combined into a string.
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;
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;
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.
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++;
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));
207 } while (more && cmdstatus);
209 goto wrapup;
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;
229 (*specificrtn)(pp);
232 wrapup:
233 if (generic_wrapup) {
234 (*generic_wrapup)(cmdstatus);
236 free_printer(pp);
237 if (generic_msg)
238 free(generic_msg);
242 * Convert an argv-array of character strings into a single string.
244 static char *
245 args2line(int argc, char **argv)
247 char *cp1, *cend;
248 const char *cp2;
249 char buf[1024];
251 if (argc <= 0)
252 return strdup("\n");
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++))
260 cp1[-1] = ' ';
262 cp1[-1] = '\n';
263 *cp1 = '\0';
264 return strdup(buf);
268 * Kill the current daemon, to stop printing of the active job.
270 static int
271 kill_qtask(const char *lf)
273 FILE *fp;
274 pid_t pid;
275 int errsav, killres, lockres, res;
277 seteuid(euid);
278 fp = fopen(lf, "r");
279 errsav = errno;
280 seteuid(uid);
281 res = KQT_NODAEMON;
282 if (fp == NULL) {
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.
288 if (errsav != ENOENT)
289 res = KQT_LFERROR;
290 goto killdone;
293 /* If the lock file is empty, then there is no daemon to kill */
294 if (getline(fp) == 0)
295 goto killdone;
298 * If the file can be locked without blocking, then there
299 * no daemon to kill, or we should not try to kill it.
301 * XXX - not sure I understand the reasoning behind this...
303 lockres = flock(fileno(fp), LOCK_SH|LOCK_NB);
304 fclose(fp);
305 if (lockres == 0)
306 goto killdone;
308 pid = atoi(line);
309 if (pid < 0) {
311 * If we got a negative pid, then the contents of the
312 * lock file is not valid.
314 res = KQT_LFERROR;
315 goto killdone;
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));
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;
351 return (res);
355 * Write a message into the status file.
357 static void
358 upstat(struct printer *pp, const char *msg, int notifyuser)
360 int fd;
361 char statfile[MAXPATHLEN];
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;
372 ftruncate(fd, 0);
373 if (msg == NULL)
374 write(fd, "\n", 1);
375 else
376 write(fd, msg, strlen(msg));
377 close(fd);
378 if (notifyuser) {
379 if ((msg == 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);
387 * kill an existing daemon and disable printing.
389 void
390 abort_q(struct printer *pp)
392 int killres, setres;
393 char lf[MAXPATHLEN];
395 lock_file_name(pp, lf, sizeof lf);
396 printf("%s:\n", pp->printer);
399 * Turn on the owner execute bit of the lock file to disable printing.
401 setres = set_qstate(SQS_STOPP, lf);
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).
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;
431 if (setres >= 0)
432 upstat(pp, "printing disabled\n", 0);
436 * "global" variables for all the routines related to 'clean' and 'tclean'
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 */
447 static int
448 doselect(struct dirent *d)
450 int c = d->d_name[0];
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;
459 if (c == 'e') {
460 if (!strncmp(d->d_name, "errs.", 5))
461 return 1;
463 return 0;
467 * Comparison routine that clean_q() uses for scandir.
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.
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*').
482 static int
483 sortq(const void *a, const void *b)
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;
489 fname_a = (*(const struct dirent * const *)a)->d_name;
490 fname_b = (*(const struct dirent * const *)b)->d_name;
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.
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.]
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; \
525 if (!isdigit(ch)) \
526 cat_X = cat_other; \
530 } while (0)
532 MAP_TO_CAT(fname_a, cat_a, jnum_a, seq_a);
533 MAP_TO_CAT(fname_b, cat_b, jnum_b, seq_b);
535 #undef MAP_TO_CAT
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;
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.
553 res = strcmp(jnum_a, jnum_b);
554 if (res != 0)
555 goto have_res;
558 * We have two files which belong to the same job. Sort based
559 * on the catagory of file (`c' before `d', etc).
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;
570 * Two files in the same catagory for a single job. Sort based
571 * on the sequence letter(s). (usually `A' thru `Z', etc).
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;
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.
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;
593 have_res:
594 return res;
598 * Remove all spool files and temporaries from the spooling area.
599 * Or, perhaps:
600 * Remove incomplete jobs from spooling area.
603 void
604 clean_gi(int argc, char **argv)
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;
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;
631 return;
634 void
635 tclean_gi(int argc, char **argv)
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;
643 return;
646 void
647 clean_q(struct printer *pp)
649 char *cp, *cp1, *lp;
650 struct dirent **queue;
651 size_t linerem;
652 int didhead, i, n, nitems, rmcp;
654 cln_queuecnt++;
656 didhead = 0;
657 if (generic_qselect == QSEL_BYNAME) {
658 printf("%s:\n", pp->printer);
659 didhead = 1;
662 lp = line;
663 cp = pp->spool_dir;
664 while (lp < &line[sizeof(line) - 1]) {
665 if ((*lp++ = *cp++) == 0)
666 break;
668 lp[-1] = '/';
669 linerem = sizeof(line) - (lp - line);
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;
680 printf("\tcannot examine spool directory\n");
681 return;
683 if (cln_foundcore) {
684 if (!didhead) {
685 printf("%s:\n", pp->printer);
686 didhead = 1;
688 printf("\t** found a core file in %s !\n", pp->spool_dir);
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");
703 i = 0;
704 do {
705 cp = queue[i]->d_name;
706 rmcp = 0;
707 if (*cp == 'c') {
709 * A control file. Look for matching data-files.
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...
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++;
726 if (n == 0) {
727 rmcp = 1;
729 } else if (*cp == 'e') {
731 * Must be an errrs or email temp file.
733 rmcp = 1;
734 } else {
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).
740 rmcp = 1;
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;
749 strlcpy(lp, cp, linerem);
750 unlinkf(line);
752 } while (++i < nitems);
755 static void
756 wrapup_clean(int laststatus __unused)
759 printf("Checked %d queues, and ", cln_queuecnt);
760 if (cln_filecnt < 1) {
761 printf("no cruft was found\n");
762 return;
764 if (cln_testonly) {
765 printf("would have ");
767 printf("removed %d files (%ld bytes).\n", cln_filecnt, cln_sizecnt);
770 static void
771 unlinkf(char *name)
773 struct stat stbuf;
774 double agemod, agestat;
775 int res;
776 char linkbuf[BUFSIZ];
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.
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;
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);
800 if ((agemod <= cln_minage) && (agestat <= cln_minage))
801 return;
804 * if this file is a symlink, then find out the target of the
805 * symlink before unlink-ing the file itself
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;
816 if (res == sizeof(linkbuf))
817 res--;
818 linkbuf[res] = '\0';
821 cln_filecnt++;
822 cln_sizecnt += stbuf.st_size;
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);
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...
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.
851 if (S_ISLNK(stbuf.st_mode)) {
852 printf("\t (which was a symlink to %s)\n", linkbuf);
858 * Enable queuing to the printer (allow lpr to add new jobs to the queue).
860 void
861 enable_q(struct printer *pp)
863 int setres;
864 char lf[MAXPATHLEN];
866 lock_file_name(pp, lf, sizeof lf);
867 printf("%s:\n", pp->printer);
869 setres = set_qstate(SQS_ENABLEQ, lf);
873 * Disable queuing.
875 void
876 disable_q(struct printer *pp)
878 int setres;
879 char lf[MAXPATHLEN];
881 lock_file_name(pp, lf, sizeof lf);
882 printf("%s:\n", pp->printer);
884 setres = set_qstate(SQS_DISABLEQ, lf);
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).
897 void
898 down_gi(int argc, char **argv)
901 /* If `-msg' was specified, then this routine has nothing to do. */
902 if (generic_msg != NULL)
903 return;
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).
909 if (argc == 1) {
910 generic_msg = strdup("printing disabled\n");
911 return;
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).
920 argc--;
921 argv++;
922 generic_msg = args2line(argc, argv);
923 for (; argc > 0; argc--, argv++)
924 *argv = generic_nullarg; /* "erase" it */
927 void
928 down_q(struct printer *pp)
930 int setres;
931 char lf[MAXPATHLEN];
933 lock_file_name(pp, lf, sizeof lf);
934 printf("%s:\n", pp->printer);
936 setres = set_qstate(SQS_DISABLEQ+SQS_STOPP, lf);
937 if (setres >= 0)
938 upstat(pp, generic_msg, 1);
942 * Exit lpc
944 void
945 quit(int argc __unused, char **argv __unused)
947 exit(0);
951 * Kill and restart the daemon.
953 void
954 restart_q(struct printer *pp)
956 int killres, setres, startok;
957 char lf[MAXPATHLEN];
959 lock_file_name(pp, lf, sizeof lf);
960 printf("%s:\n", pp->printer);
962 killres = kill_qtask(lf);
965 * XXX - if the kill worked, we should probably sleep for
966 * a second or so before trying to restart the queue.
969 /* make sure the queue is set to print jobs */
970 setres = set_qstate(SQS_STARTP, lf);
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");
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.
985 void
986 setstatus_gi(int argc __unused, char **argv __unused)
989 if (generic_msg == NULL) {
990 printf("You must specify '-msg' before the text of the new status message.\n");
991 generic_initerr = 1;
995 void
996 setstatus_q(struct printer *pp)
998 char lf[MAXPATHLEN];
1000 lock_file_name(pp, lf, sizeof lf);
1001 printf("%s:\n", pp->printer);
1003 upstat(pp, generic_msg, 1);
1007 * Enable printing on the specified printer and startup the daemon.
1009 void
1010 start_q(struct printer *pp)
1012 int setres, startok;
1013 char lf[MAXPATHLEN];
1015 lock_file_name(pp, lf, sizeof lf);
1016 printf("%s:\n", pp->printer);
1018 setres = set_qstate(SQS_STARTP, lf);
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);
1031 * Print the status of the printer queue.
1033 void
1034 status(struct printer *pp)
1036 struct stat stbuf;
1037 int fd, i;
1038 struct dirent *dp;
1039 DIR *dirp;
1040 char file[MAXPATHLEN];
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");
1055 if ((dirp = opendir(pp->spool_dir)) == NULL) {
1056 printf("\tcannot examine spool directory\n");
1057 return;
1059 i = 0;
1060 while ((dp = readdir(dirp)) != NULL) {
1061 if (*dp->d_name == 'c' && dp->d_name[1] == 'f')
1062 i++;
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 close(fd); /* unlocks as well */
1074 printf("\tprinter idle\n");
1075 return;
1077 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 fstat(fd, &stbuf);
1083 if (stbuf.st_size > 0) {
1084 putchar('\t');
1085 while ((i = read(fd, line, sizeof(line))) > 0)
1086 fwrite(line, 1, i, stdout);
1088 close(fd); /* unlocks as well */
1093 * Stop the specified daemon after completing the current job and disable
1094 * printing.
1096 void
1097 stop_q(struct printer *pp)
1099 int setres;
1100 char lf[MAXPATHLEN];
1102 lock_file_name(pp, lf, sizeof lf);
1103 printf("%s:\n", pp->printer);
1105 setres = set_qstate(SQS_STOPP, lf);
1107 if (setres >= 0)
1108 upstat(pp, "printing disabled\n", 0);
1111 struct jobqueue **queue;
1112 int nitems;
1113 time_t mtime;
1116 * Put the specified jobs at the top of printer queue.
1118 void
1119 topq(int argc, char **argv)
1121 int i;
1122 struct stat stbuf;
1123 int cmdstatus, changed;
1124 struct printer myprinter, *pp = &myprinter;
1126 if (argc < 3) {
1127 printf("usage: topq printer [jobnum ...] [user ...]\n");
1128 return;
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;
1147 printf("%s:\n", pp->printer);
1149 seteuid(euid);
1150 if (chdir(pp->spool_dir) < 0) {
1151 printf("\tcannot chdir to %s\n", pp->spool_dir);
1152 goto out;
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++;
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;
1175 * Turn on the public execute bit of the lock file to
1176 * get lpd to rebuild the queue after the current job.
1178 seteuid(euid);
1179 if (changed && stat(pp->lock_file, &stbuf) >= 0)
1180 chmod(pp->lock_file, stbuf.st_mode | LFM_RESET_QUE);
1182 out:
1183 seteuid(uid);
1187 * Reposition the job by changing the modification time of
1188 * the control file.
1190 static int
1191 touch(struct jobqueue *jq)
1193 struct timeval tvp[2];
1194 int ret;
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);
1205 * Checks if specified job name is in the printer's queue.
1206 * Returns: negative (-1) if argument name is not in the queue.
1208 static int
1209 doarg(char *job)
1211 struct jobqueue **qq;
1212 int jobnum, n;
1213 char *cp, *machine;
1214 int cnt = 0;
1215 FILE *fp;
1218 * Look for a job item consisting of system name, colon, number
1219 * (example: ucbarpa:114)
1221 if ((cp = strchr(job, ':')) != NULL) {
1222 machine = job;
1223 *cp++ = '\0';
1224 job = cp;
1225 } else
1226 machine = NULL;
1229 * Check for job specified by number (example: 112 or 235ucbarpa).
1231 if (isdigit(*job)) {
1232 jobnum = 0;
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++;
1251 return(cnt);
1254 * Process item consisting of owner's name (example: henry).
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 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++;
1273 return(cnt);
1277 * Enable both queuing & printing, and start printer (undo `down').
1279 void
1280 up_q(struct printer *pp)
1282 int setres, startok;
1283 char lf[MAXPATHLEN];
1285 lock_file_name(pp, lf, sizeof lf);
1286 printf("%s:\n", pp->printer);
1288 setres = set_qstate(SQS_ENABLEQ+SQS_STARTP, lf);
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");