2 * Copyright (c) 1983, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 static const char copyright[] =
42 "@(#) Copyright (c) 1983, 1989, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
48 static char sccsid[] = "@(#)lpr.c 8.4 (Berkeley) 4/28/95";
52 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
53 __FBSDID("$FreeBSD$");
56 * lpr -- off line print
58 * Allows multiple printers and printers on remote machines by
59 * using information from a printer data base.
62 #include <sys/param.h>
65 #include <netinet/in.h> /* N_BADMAG uses ntohl() */
84 #include "pathnames.h"
86 static char *cfname; /* daemon control files, linked from tf's */
87 static char *class = local_host; /* class title on header page */
88 static char *dfname; /* data files */
89 static char *fonts[4]; /* troff font names */
90 static char format = 'f'; /* format char for printing files */
91 static int hdr = 1; /* print header or not (default is yes) */
92 static int iflag; /* indentation wanted */
93 static int inchar; /* location to increment char in file names */
94 static int indent; /* amount to indent */
95 static const char *jobname; /* job name on header page */
96 static int mailflg; /* send mail */
97 static int nact; /* number of jobs to act on */
98 static int ncopies = 1; /* # of copies to make */
99 static char *lpr_username; /* person sending the print job(s) */
100 static int qflag; /* q job, but don't exec daemon */
101 static int rflag; /* remove files upon completion */
102 static int sflag; /* symbolic link flag */
103 static int tfd; /* control file descriptor */
104 static char *tfname; /* tmp copy of cf before linking */
105 static char *title; /* pr'ing title */
106 static char *locale; /* pr'ing locale */
107 static int userid; /* user id */
108 static char *Uflag; /* user name specified with -U flag */
109 static char *width; /* width for versatec printing */
110 static char *Zflag; /* extra filter options for LPRng servers */
112 static struct stat statb;
114 static void card(int _c, const char *_p2);
115 static int checkwriteperm(const char *_file, const char *_directory);
116 static void chkprinter(const char *_ptrname, struct printer *_pp);
117 static void cleanup(int _signo);
118 static void copy(const struct printer *_pp, int _f, const char _n[]);
119 static char *itoa(int _i);
120 static const char *linked(const char *_file);
121 int main(int _argc, char *_argv[]);
122 static char *lmktemp(const struct printer *_pp, const char *_id,
124 static void mktemps(const struct printer *_pp);
125 static int nfile(char *_n);
126 static int test(const char *_file);
127 static void usage(void);
132 main(int argc, char *argv[])
136 const char *arg, *cp, *printer;
142 struct stat statb1, statb2;
143 struct printer myprinter, *pp = &myprinter;
149 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
150 signal(SIGHUP, cleanup);
151 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
152 signal(SIGINT, cleanup);
153 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
154 signal(SIGQUIT, cleanup);
155 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
156 signal(SIGTERM, cleanup);
159 gethostname(local_host, sizeof(local_host));
160 openlog("lpd", 0, LOG_LPR);
163 while ((c = getopt(argc, argv,
164 ":#:1:2:3:4:C:J:L:P:T:U:Z:cdfghi:lnmprstvw:"))
167 case '#': /* n copies */
168 i = strtol(optarg, &p, 10);
170 errx(1, "Bad argument to -#, number expected");
175 case '1': /* troff fonts */
179 fonts[optopt - '1'] = optarg;
182 case 'C': /* classification spec */
187 case 'J': /* job name */
192 case 'P': /* specifiy printer name */
196 case 'L': /* pr's locale */
200 case 'T': /* pr's title line */
204 case 'U': /* user name */
213 case 'c': /* print cifplot output */
214 case 'd': /* print tex output (dvi files) */
215 case 'g': /* print graph(1G) output */
216 case 'l': /* literal output */
217 case 'n': /* print ditroff output */
218 case 't': /* print troff output (cat files) */
219 case 'p': /* print using ``pr'' */
220 case 'v': /* print vplot output */
224 case 'f': /* print fortran output */
228 case 'h': /* nulifiy header page */
232 case 'i': /* indent output */
234 indent = strtol(optarg, &p, 10);
236 errx(1, "Bad argument to -i, number expected");
239 case 'm': /* send mail when done */
243 case 'q': /* just queue job */
247 case 'r': /* remove file when done */
251 case 's': /* try to link files */
255 case 'w': /* versatec page width */
259 case ':': /* catch "missing argument" error */
261 iflag++; /* -i without args is valid */
274 if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
276 chkprinter(printer, pp);
277 if (pp->no_copies && ncopies > 1)
278 errx(1, "multiple copies are not allowed");
279 if (pp->max_copies > 0 && ncopies > pp->max_copies)
280 errx(1, "only %ld copies are allowed", pp->max_copies);
282 * Get the identity of the person doing the lpr using the same
283 * algorithm as lprm. Actually, not quite -- lprm will override
284 * the login name with "root" if the user is running as root;
285 * the daemon actually checks for the string "root" in its
286 * permission checking. Sigh.
290 if (userid != 0 && userid != pp->daemon_user)
291 errx(1, "only privileged users may use the `-U' flag");
292 lpr_username = Uflag; /* -U person doing 'lpr' */
294 lpr_username = getlogin(); /* person doing 'lpr' */
295 if (userid != pp->daemon_user || lpr_username == 0) {
296 if ((pw = getpwuid(userid)) == NULL)
297 errx(1, "Who are you?");
298 lpr_username = pw->pw_name;
303 * Check for restricted group access.
305 if (pp->restrict_grp != NULL && userid != pp->daemon_user) {
306 if ((gptr = getgrnam(pp->restrict_grp)) == NULL)
307 errx(1, "Restricted group specified incorrectly");
308 if (gptr->gr_gid != getgid()) {
309 while (*gptr->gr_mem != NULL) {
310 if ((strcmp(lpr_username, *gptr->gr_mem)) == 0)
314 if (*gptr->gr_mem == NULL)
315 errx(1, "Not a member of the restricted group");
319 * Check to make sure queuing is enabled if userid is not root.
321 lock_file_name(pp, buf, sizeof buf);
322 if (userid && stat(buf, &stb) == 0 && (stb.st_mode & LFM_QUEUE_DIS))
323 errx(1, "Printer queue is disabled");
325 * Initialize the control file.
330 (void) fchown(tfd, pp->daemon_user, -1);
331 /* owned by daemon for protection */
333 card('H', local_host);
334 card('P', lpr_username);
336 if (hdr && !pp->no_header) {
337 if (jobname == NULL) {
341 jobname = ((arg = strrchr(argv[0], '/'))
342 ? arg + 1 : argv[0]);
345 card('L', lpr_username);
347 if (format != 'p' && Zflag != 0)
350 card('I', itoa(indent));
352 card('M', lpr_username);
353 if (format == 't' || format == 'n' || format == 'd')
354 for (i = 0; i < 4; i++)
355 if (fonts[i] != NULL)
356 card('1'+i, fonts[i]);
361 * Our use of `Z' here is incompatible with LPRng's
362 * use. We assume that the only use of our existing
363 * `Z' card is as shown for `p' format (pr) files.
370 else if ((s = setlocale(LC_TIME, "")) != NULL)
375 * Read the files and spool them.
379 else while (argc--) {
380 if (argv[0][0] == '-' && argv[0][1] == '\0') {
386 if ((f = test(arg = *argv++)) < 0)
387 continue; /* file unreasonable */
389 if (sflag && (cp = linked(arg)) != NULL) {
390 (void)snprintf(buf, sizeof(buf), "%u %ju",
391 statb.st_dev, (uintmax_t)statb.st_ino);
394 card('T', title ? title : arg);
395 for (i = 0; i < ncopies; i++)
396 card(format, &dfname[inchar-2]);
397 card('U', &dfname[inchar-2]);
406 printf("%s: %s: not linked, copying instead\n",
411 * The user wants the file removed after it is copied
412 * to the spool area, so see if the file can be moved
413 * instead of copy/unlink'ed. This is much faster and
414 * uses less spool space than copying the file. This
415 * can be very significant when running services like
416 * samba, pcnfs, CAP, et al.
421 * There are several things to check to avoid any
422 * security issues. Some of these are redundant
423 * under BSD's, but are necessary when lpr is built
424 * under some other OS's (which I do do...)
426 if (lstat(arg, &statb1) < 0)
428 if (S_ISLNK(statb1.st_mode))
430 if (link(arg, dfname) != 0)
434 * Make sure the user hasn't tried to trick us via
435 * any race conditions
437 if (lstat(dfname, &statb2) < 0)
439 if (statb1.st_dev != statb2.st_dev)
441 if (statb1.st_ino != statb2.st_ino)
444 * Skip if the file already had multiple hard links,
445 * because changing the owner and access-bits would
446 * change ALL versions of the file
448 if (statb2.st_nlink > 2)
451 * If we can access and remove the original file
452 * without special setuid-ness then this method is
453 * safe. Otherwise, abandon the move and fall back
454 * to the (usual) copy method.
457 ret = access(dfname, R_OK);
464 * Unlink of user file was successful. Change the
465 * owner and permissions, add entries to the control
466 * file, and skip the file copying step.
468 chown(dfname, pp->daemon_user, getegid());
469 chmod(dfname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
472 card('T', title ? title : arg);
473 for (i = 0; i < ncopies; i++)
474 card(format, &dfname[inchar-2]);
475 card('U', &dfname[inchar-2]);
482 PRIV_END /* restore old uid */
485 if ((i = open(arg, O_RDONLY)) < 0) {
486 printf("%s: cannot open %s\n", progname, arg);
490 if (f && unlink(arg) < 0)
491 printf("%s: %s: not removed\n", progname, arg);
499 * Touch the control file to fix position in the queue.
502 if ((tfd = open(tfname, O_RDWR)) >= 0) {
505 if (read(tfd, &touch_c, 1) == 1 &&
506 lseek(tfd, (off_t)0, 0) == 0 &&
507 write(tfd, &touch_c, 1) != 1) {
508 printf("%s: cannot touch %s\n", progname,
515 if (link(tfname, cfname) < 0) {
516 printf("%s: cannot rename %s\n", progname, cfname);
522 if (qflag) /* just q things up */
524 if (!startdaemon(pp))
525 printf("jobs queued, but cannot start daemon.\n");
534 * Create the file n and copy from file descriptor f.
537 copy(const struct printer *pp, int f, const char n[])
539 register int fd, i, nr, nc;
543 card('T', title ? title : n);
544 for (i = 0; i < ncopies; i++)
545 card(format, &dfname[inchar-2]);
546 card('U', &dfname[inchar-2]);
550 while ((i = read(f, buf, BUFSIZ)) > 0) {
551 if (write(fd, buf, i) != i) {
552 printf("%s: %s: temp file write error\n", progname, n);
559 if (pp->max_blocks > 0 && nr > pp->max_blocks) {
560 printf("%s: %s: copy file is too large\n",
568 printf("%s: %s: empty input file\n", progname,
575 * Try and link the file to dfname. Return a pointer to the full
576 * path name if successful.
579 linked(const char *file)
582 static char buf[MAXPATHLEN];
586 if (getcwd(buf, sizeof(buf)) == NULL)
588 while (file[0] == '.') {
594 if (file[2] == '/') {
595 if ((cp = strrchr(buf, '/')) != NULL)
603 strncat(buf, "/", sizeof(buf) - strlen(buf) - 1);
604 strncat(buf, file, sizeof(buf) - strlen(buf) - 1);
608 ret = symlink(file, dfname);
610 return(ret ? NULL : file);
614 * Put a line into the control file.
617 card(int c, const char *p2)
620 register char *p1 = buf;
624 while ((c = *p2++) != '\0' && len < sizeof(buf)) {
625 *p1++ = (c == '\n') ? ' ' : c;
629 write(tfd, buf, len);
633 * Create a new file in the spool directory.
639 int oldumask = umask(0); /* should block signals */
642 f = open(n, O_WRONLY | O_EXCL | O_CREAT, FILMOD);
643 (void) umask(oldumask);
645 printf("%s: cannot create %s\n", progname, n);
648 if (fchown(f, userid, -1) < 0) {
649 printf("%s: cannot chown %s\n", progname, n);
650 cleanup(0); /* cleanup does exit */
653 if (++n[inchar] > 'z') {
654 if (++n[inchar-2] == 't') {
655 printf("too many files - break up the job\n");
659 } else if (n[inchar] == '[')
665 * Cleanup after interrupts and errors.
668 cleanup(int signo __unused)
672 signal(SIGHUP, SIG_IGN);
673 signal(SIGINT, SIG_IGN);
674 signal(SIGQUIT, SIG_IGN);
675 signal(SIGTERM, SIG_IGN);
681 while (tfname[i]-- != 'A');
685 while (cfname[i]-- != 'A');
690 while (dfname[i]-- != 'A');
692 } while (dfname[i-2]-- != 'd');
697 * Test to see if this is a printable file.
698 * Return -1 if it is not, 0 if its printable, and 1 if
699 * we should remove it after printing.
702 test(const char *file)
709 if (access(file, 4) < 0) {
710 printf("%s: cannot access %s\n", progname, file);
713 if (stat(file, &statb) < 0) {
714 printf("%s: cannot stat %s\n", progname, file);
717 if ((statb.st_mode & S_IFMT) == S_IFDIR) {
718 printf("%s: %s is a directory\n", progname, file);
721 if (statb.st_size == 0) {
722 printf("%s: %s is an empty file\n", progname, file);
725 if ((fd = open(file, O_RDONLY)) < 0) {
726 printf("%s: cannot open %s\n", progname, file);
730 * XXX Shall we add a similar test for ELF?
732 if (read(fd, &execb, sizeof(execb)) == sizeof(execb) &&
734 printf("%s: %s is an executable program", progname, file);
740 * aside: note that 'cp' is technically a 'const char *'
741 * (because it points into 'file'), even though strrchr
742 * returns a value of type 'char *'.
744 if ((cp = strrchr(file, '/')) == NULL) {
745 if (checkwriteperm(file,".") == 0)
749 fd = checkwriteperm(file,"/");
751 /* strlcpy will change the '/' to '\0' */
752 dlen = cp - file + 1;
753 dirpath = malloc(dlen);
754 strlcpy(dirpath, file, dlen);
755 fd = checkwriteperm(file, dirpath);
761 printf("%s: %s: is not removable by you\n", progname, file);
766 printf(" and is unprintable\n");
772 checkwriteperm(const char *file, const char *directory)
775 if (access(directory, W_OK) == 0) {
776 stat(directory, &stats);
777 if (stats.st_mode & S_ISVTX) {
779 if(stats.st_uid == userid) {
788 * itoa - integer to string conversion
793 static char b[10] = "########";
804 * Perform lookup for printer name or abbreviation --
807 chkprinter(const char *ptrname, struct printer *pp)
812 status = getprintcap(ptrname, pp);
816 errx(1, "%s: %s", ptrname, pcaperr(status));
817 case PCAPERR_NOTFOUND:
818 errx(1, "%s: unknown printer", ptrname);
820 warnx("%s: unresolved tc= reference(s)", ptrname);
825 * Tell the user what we wanna get.
830 fprintf(stderr, "%s\n",
831 "usage: lpr [-Pprinter] [-#num] [-C class] [-J job] [-T title] [-U user]\n"
832 "\t[-Z daemon-options] [-i[numcols]] [-i[numcols]] [-1234 font]\n"
833 "\t[-L locale] [-wnum] [-cdfghlnmprstv] [name ...]");
839 * Make the temp files.
842 mktemps(const struct printer *pp)
844 register int len, fd, n;
848 (void) snprintf(buf, sizeof(buf), "%s/.seq", pp->spool_dir);
850 if ((fd = open(buf, O_RDWR|O_CREAT, 0664)) < 0) {
851 printf("%s: cannot create %s\n", progname, buf);
854 if (flock(fd, LOCK_EX)) {
855 printf("%s: cannot lock %s\n", progname, buf);
860 if ((len = read(fd, buf, sizeof(buf))) > 0) {
861 for (cp = buf; len--; ) {
862 if (*cp < '0' || *cp > '9')
864 n = n * 10 + (*cp++ - '0');
867 len = strlen(pp->spool_dir) + strlen(local_host) + 8;
868 tfname = lmktemp(pp, "tf", n, len);
869 cfname = lmktemp(pp, "cf", n, len);
870 dfname = lmktemp(pp, "df", n, len);
871 inchar = strlen(pp->spool_dir) + 3;
873 (void) lseek(fd, (off_t)0, 0);
874 snprintf(buf, sizeof(buf), "%03d\n", n);
875 (void) write(fd, buf, strlen(buf));
876 (void) close(fd); /* unlocks as well */
880 * Make a temp file name.
883 lmktemp(const struct printer *pp, const char *id, int num, int len)
887 if ((s = malloc(len)) == NULL)
888 errx(1, "out of memory");
889 (void) snprintf(s, len, "%s/%sA%03d%s", pp->spool_dir, id, num,