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
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
34 * @(#) Copyright (c) 1983, 1993 The Regents of the University of California. All rights reserved.
35 * @(#)printjob.c 8.7 (Berkeley) 5/10/95
36 * $FreeBSD: src/usr.sbin/lpr/lpd/printjob.c,v 1.22.2.32 2002/06/19 23:58:16 gad Exp $
37 * $DragonFly: src/usr.sbin/lpr/lpd/printjob.c,v 1.3 2004/03/22 22:32:50 cpressey Exp $
41 * printjob -- print jobs in the queue.
43 * NOTE: the lock file is used to pass information to lpq and lprm.
44 * it does not need to be removed because file locks are dynamic.
47 #include <sys/param.h>
50 #include <sys/types.h>
62 #include <sys/ioctl.h>
67 #include "pathnames.h"
70 #define DORETURN 0 /* dofork should return "can't fork" error */
71 #define DOABORT 1 /* dofork should just die if fork() fails */
84 static dev_t fdev; /* device of file pointed to by symlink */
85 static ino_t fino; /* inode of file pointed to by symlink */
86 static FILE *cfp; /* control file */
87 static pid_t of_pid; /* process id of output filter, if any */
88 static int child; /* id of any filters */
89 static int job_dfcnt; /* count of datafiles in current user job */
90 static int lfd; /* lock file descriptor */
91 static int ofd; /* output filter file descriptor */
92 static int tfd = -1; /* output filter temp file output */
93 static int pfd; /* prstatic inter file descriptor */
94 static int prchild; /* id of pr process */
95 static char title[80]; /* ``pr'' title */
96 static char locale[80]; /* ``pr'' locale */
98 /* these two are set from pp->daemon_user, but only if they are needed */
99 static char *daemon_uname; /* set from pwd->pw_name */
100 static int daemon_defgid;
102 static char class[32]; /* classification field */
103 static char origin_host[MAXHOSTNAMELEN]; /* user's host machine */
104 /* indentation size in static characters */
105 static char indent[10] = "-i0";
106 static char jobname[100]; /* job or file name */
107 static char length[10] = "-l"; /* page length in lines */
108 static char logname[32]; /* user's login name */
109 static char pxlength[10] = "-y"; /* page length in pixels */
110 static char pxwidth[10] = "-x"; /* page width in pixels */
111 /* tempstderr is the filename used to catch stderr from exec-ing filters */
112 static char tempstderr[] = "errs.XXXXXXX";
113 static char width[10] = "-w"; /* page width in static characters */
114 #define TFILENAME "fltXXXXXX"
115 static char tfile[] = TFILENAME; /* file name for filter output */
117 static void abortpr(int _signo);
118 static void alarmhandler(int _signo);
119 static void banner(struct printer *_pp, char *_name1, char *_name2);
120 static int dofork(const struct printer *_pp, int _action);
121 static int dropit(int _c);
122 static int execfilter(struct printer *_pp, char *_f_cmd, char **_f_av,
123 int _infd, int _outfd);
124 static void init(struct printer *_pp);
125 static void openpr(const struct printer *_pp);
126 static void opennet(const struct printer *_pp);
127 static void opentty(const struct printer *_pp);
128 static void openrem(const struct printer *pp);
129 static int print(struct printer *_pp, int _format, char *_file);
130 static int printit(struct printer *_pp, char *_file);
131 static void pstatus(const struct printer *_pp, const char *_msg, ...)
133 static char response(const struct printer *_pp);
134 static void scan_out(struct printer *_pp, int _scfd, char *_scsp,
136 static char *scnline(int _key, char *_p, int _c);
137 static int sendfile(struct printer *_pp, int _type, char *_file,
138 char _format, int _copyreq);
139 static int sendit(struct printer *_pp, char *_file);
140 static void sendmail(struct printer *_pp, char *_userid, int _bombed);
141 static void setty(const struct printer *_pp);
144 printjob(struct printer *pp)
147 struct jobqueue *q, **qp;
148 struct jobqueue **queue;
152 int errcnt, jobcount, tempfd;
155 init(pp); /* set up capabilities */
156 (void) write(1, "", 1); /* ack that daemon is started */
157 (void) close(2); /* set up log file */
158 if (open(pp->log_file, O_WRONLY|O_APPEND, LOG_FILE_MODE) < 0) {
159 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
161 (void) open(_PATH_DEVNULL, O_WRONLY);
164 printpid = getpid(); /* for use with lprm */
165 setpgrp(0, printpid);
168 * At initial lpd startup, printjob may be called with various
169 * signal handlers in effect. After that initial startup, any
170 * calls to printjob will have a *different* set of signal-handlers
171 * in effect. Make sure all handlers are the ones we want.
173 signal(SIGCHLD, SIG_DFL);
174 signal(SIGHUP, abortpr);
175 signal(SIGINT, abortpr);
176 signal(SIGQUIT, abortpr);
177 signal(SIGTERM, abortpr);
180 * uses short form file names
182 if (chdir(pp->spool_dir) < 0) {
183 syslog(LOG_ERR, "%s: chdir(%s): %m", pp->printer,
187 if (stat(pp->lock_file, &stb) == 0 && (stb.st_mode & LFM_PRINT_DIS))
188 exit(0); /* printing disabled */
189 lfd = open(pp->lock_file, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
192 if (errno == EWOULDBLOCK) /* active daemon present */
194 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
198 /* turn off non-blocking mode (was turned on for lock effects only) */
199 if (fcntl(lfd, F_SETFL, 0) < 0) {
200 syslog(LOG_ERR, "%s: fcntl(%s): %m", pp->printer,
206 * write process id for others to know
208 sprintf(line, "%u\n", printpid);
209 pidoff = i = strlen(line);
210 if (write(lfd, line, i) != i) {
211 syslog(LOG_ERR, "%s: write(%s): %m", pp->printer,
216 * search the spool directory for work and sort by queue order.
218 if ((nitems = getq(pp, &queue)) < 0) {
219 syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
223 if (nitems == 0) /* no work to do */
225 if (stb.st_mode & LFM_RESET_QUE) { /* reset queue flag */
226 if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE) < 0)
227 syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
231 /* create a file which will be used to hold stderr from filters */
232 if ((tempfd = mkstemp(tempstderr)) == -1) {
233 syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
237 if ((i = fchmod(tempfd, 0664)) == -1) {
238 syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
242 /* lpd doesn't need it to be open, it just needs it to exist */
245 openpr(pp); /* open printer or remote */
248 * we found something to do now do it --
249 * write the name of the current control file into the lock file
250 * so the spool queue program can tell what we're working on
252 for (qp = queue; nitems--; free((char *) q)) {
254 if (stat(q->job_cfname, &stb) < 0)
258 (void) lseek(lfd, pidoff, 0);
259 (void) snprintf(line, sizeof(line), "%s\n", q->job_cfname);
261 if (write(lfd, line, i) != i)
262 syslog(LOG_ERR, "%s: write(%s): %m", pp->printer,
265 i = printit(pp, q->job_cfname);
267 i = sendit(pp, q->job_cfname);
269 * Check to see if we are supposed to stop printing or
270 * if we are to rebuild the queue.
272 if (fstat(lfd, &stb) == 0) {
273 /* stop printing before starting next job? */
274 if (stb.st_mode & LFM_PRINT_DIS)
276 /* rebuild queue (after lpc topq) */
277 if (stb.st_mode & LFM_RESET_QUE) {
278 for (free(q); nitems--; free(q))
280 if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE)
283 "%s: fchmod(%s): %m",
284 pp->printer, pp->lock_file);
288 if (i == OK) /* all files of this job printed */
290 else if (i == REPRINT && ++errcnt < 5) {
291 /* try reprinting the job */
292 syslog(LOG_INFO, "restarting %s", pp->printer);
294 kill(of_pid, SIGCONT); /* to be sure */
296 while ((i = wait(NULL)) > 0 && i != of_pid)
299 syslog(LOG_WARNING, "%s: after kill(of=%d), wait() returned: %m",
300 pp->printer, of_pid);
303 (void) close(pfd); /* close printer */
304 if (ftruncate(lfd, pidoff) < 0)
305 syslog(LOG_WARNING, "%s: ftruncate(%s): %m",
306 pp->printer, pp->lock_file);
307 openpr(pp); /* try to reopen printer */
310 syslog(LOG_WARNING, "%s: job could not be %s (%s)",
312 pp->remote ? "sent to remote host" : "printed",
315 /* ensure we don't attempt this job again */
316 (void) unlink(q->job_cfname);
317 q->job_cfname[0] = 'd';
318 (void) unlink(q->job_cfname);
320 sendmail(pp, logname, FATALERR);
326 * search the spool directory for more work.
328 if ((nitems = getq(pp, &queue)) < 0) {
329 syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
333 if (nitems == 0) { /* no more work to do */
335 if (jobcount > 0) { /* jobs actually printed */
336 if (!pp->no_formfeed && !pp->tof)
337 (void) write(ofd, pp->form_feed,
338 strlen(pp->form_feed));
339 if (pp->trailer != NULL) /* output trailer */
340 (void) write(ofd, pp->trailer,
341 strlen(pp->trailer));
345 (void) unlink(tempstderr);
351 char fonts[4][50]; /* fonts for troff */
353 char ifonts[4][40] = {
361 * The remaining part is the reading of the control file (cf)
362 * and performing the various actions.
365 printit(struct printer *pp, char *file)
369 int bombed, didignorehdr;
374 * open control file; ignore if no longer there.
376 if ((cfp = fopen(file, "r")) == NULL) {
377 syslog(LOG_INFO, "%s: fopen(%s): %m", pp->printer, file);
383 for (i = 0; i < 4; i++)
384 strcpy(fonts[i], ifonts[i]);
385 sprintf(&width[2], "%ld", pp->page_width);
386 strcpy(indent+2, "0");
388 /* initialize job-specific count of datafiles processed */
392 * read the control file for work to do
394 * file format -- first character in the line is a command
395 * rest of the line is the argument.
396 * valid commands are:
398 * S -- "stat info" for symbolic link protection
399 * J -- "job name" on banner page
400 * C -- "class name" on banner page
401 * L -- "literal" user's name to print on banner
402 * T -- "title" for pr
403 * H -- "host name" of machine where lpr was done
404 * P -- "person" user's login name
405 * I -- "indent" amount to indent output
406 * R -- laser dpi "resolution"
407 * f -- "file name" name of text file to print
408 * l -- "file name" text file with control chars
409 * o -- "file name" postscript file, according to
410 * the RFC. Here it is treated like an 'f'.
411 * p -- "file name" text file to print with pr(1)
412 * t -- "file name" troff(1) file to print
413 * n -- "file name" ditroff(1) file to print
414 * d -- "file name" dvi file to print
415 * g -- "file name" plot(1G) file to print
416 * v -- "file name" plain raster file to print
417 * c -- "file name" cifplot file to print
418 * 1 -- "R font file" for troff
419 * 2 -- "I font file" for troff
420 * 3 -- "B font file" for troff
421 * 4 -- "S font file" for troff
422 * N -- "name" of file (used by lpq)
423 * U -- "unlink" name of file to remove
424 * (after we print it. (Pass 2 only)).
425 * M -- "mail" to user when done printing
426 * Z -- "locale" for pr
428 * getline reads a line and expands tabs to blanks
436 strlcpy(origin_host, line + 1, sizeof(origin_host));
437 if (class[0] == '\0') {
438 strlcpy(class, line+1, sizeof(class));
443 strlcpy(logname, line + 1, sizeof(logname));
444 if (pp->restricted) { /* restricted */
445 if (getpwnam(logname) == NULL) {
447 sendmail(pp, line+1, bombed);
456 while (*cp >= '0' && *cp <= '9')
457 i = i * 10 + (*cp++ - '0');
461 while (*cp >= '0' && *cp <= '9')
462 i = i * 10 + (*cp++ - '0');
467 if (line[1] != '\0') {
468 strlcpy(jobname, line + 1, sizeof(jobname));
470 strcpy(jobname, " ");
475 strlcpy(class, line + 1, sizeof(class));
476 else if (class[0] == '\0') {
477 /* XXX - why call gethostname instead of
478 * just strlcpy'ing local_host? */
479 gethostname(class, sizeof(class));
480 class[sizeof(class) - 1] = '\0';
484 case 'T': /* header title for pr */
485 strlcpy(title, line + 1, sizeof(title));
488 case 'L': /* identification line */
489 if (!pp->no_header && !pp->header_last)
490 banner(pp, line+1, jobname);
493 case '1': /* troff fonts */
497 if (line[1] != '\0') {
498 strlcpy(fonts[line[0]-'1'], line + 1,
503 case 'W': /* page width */
504 strlcpy(width+2, line + 1, sizeof(width) - 2);
507 case 'I': /* indent amount */
508 strlcpy(indent+2, line + 1, sizeof(indent) - 2);
511 case 'Z': /* locale for pr */
512 strlcpy(locale, line + 1, sizeof(locale));
515 default: /* some file to print */
516 /* only lowercase cmd-codes include a file-to-print */
517 if ((line[0] < 'a') || (line[0] > 'z')) {
518 /* ignore any other lines */
522 syslog(LOG_INFO, "%s: in %s :",
526 syslog(LOG_INFO, "%s: ignoring line: '%c' %s",
527 pp->printer, line[0], &line[1]);
530 i = print(pp, line[0], line+1);
542 sendmail(pp, logname, bombed);
560 case 'L': /* identification line */
561 if (!pp->no_header && pp->header_last)
562 banner(pp, line+1, jobname);
566 if (bombed < NOACCT) /* already sent if >= NOACCT */
567 sendmail(pp, line+1, bombed);
571 if (strchr(line+1, '/'))
573 (void) unlink(line+1);
576 * clean-up in case another control file exists
580 return (bombed == OK ? OK : ERROR);
585 * Set up the chain [ PR [ | {IF, OF} ] ] or {IF, RF, TF, NF, DF, CF, VF}.
586 * Return -1 if a non-recoverable error occured,
587 * 2 if the filter detected some errors (but printed the job anyway),
588 * 1 if we should try to reprint this job and
590 * Note: all filters take stdin as the file, stdout as the printer,
591 * stderr as the log file, and must not ignore SIGINT.
594 print(struct printer *pp, int format, char *file)
600 char *av[15], buf[BUFSIZ];
602 int p[2], retcode, stopped, wstatus, wstatus_set;
605 if (lstat(file, &stb) < 0 || (fi = open(file, O_RDONLY)) < 0) {
606 syslog(LOG_INFO, "%s: unable to open %s ('%c' line)",
607 pp->printer, file, format);
611 * Check to see if data file is a symbolic link. If so, it should
612 * still point to the same file or someone is trying to print
613 * something he shouldn't.
615 if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(fi, &stb) == 0 &&
616 (stb.st_dev != fdev || stb.st_ino != fino))
619 job_dfcnt++; /* increment datafile counter for this job */
620 stopped = 0; /* output filter is not stopped */
622 /* everything seems OK, start it up */
623 if (!pp->no_formfeed && !pp->tof) { /* start on a fresh page */
624 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
627 if (pp->filters[LPF_INPUT] == NULL
628 && (format == 'f' || format == 'l' || format == 'o')) {
630 while ((n = read(fi, buf, BUFSIZ)) > 0)
631 if (write(ofd, buf, n) != n) {
639 case 'p': /* print file using 'pr' */
640 if (pp->filters[LPF_INPUT] == NULL) { /* use output filter */
647 av[i++] = *title ? title : " ";
649 av[i++] = *locale ? locale : "C";
656 if ((prchild = dofork(pp, DORETURN)) == 0) { /* child */
657 dup2(fi, 0); /* file is stdin */
658 dup2(p[1], 1); /* pipe is stdout */
661 execl(_PATH_PR, "pr", width, length,
662 "-h", *title ? title : " ",
663 "-L", *locale ? locale : "C",
665 syslog(LOG_ERR, "cannot execl %s", _PATH_PR);
668 (void) close(p[1]); /* close output side */
675 fi = p[0]; /* use pipe for input */
676 case 'f': /* print plain text file */
677 prog = pp->filters[LPF_INPUT];
683 case 'o': /* print postscript file */
685 * Treat this as a "plain file with control characters", and
686 * assume the standard LPF_INPUT filter will recognize that
687 * the data is postscript and know what to do with it. These
688 * 'o'-file requests could come from MacOS 10.1 systems.
689 * (later versions of MacOS 10 will explicitly use 'l')
690 * A postscript file can contain binary data, which is why 'l'
691 * is somewhat more appropriate than 'f'.
694 case 'l': /* like 'f' but pass control characters */
695 prog = pp->filters[LPF_INPUT];
702 case 'r': /* print a fortran text file */
703 prog = pp->filters[LPF_FORTRAN];
708 case 't': /* print troff output */
709 case 'n': /* print ditroff output */
710 case 'd': /* print tex output */
711 (void) unlink(".railmag");
712 if ((fo = creat(".railmag", FILMOD)) < 0) {
713 syslog(LOG_ERR, "%s: cannot create .railmag",
715 (void) unlink(".railmag");
717 for (n = 0; n < 4; n++) {
718 if (fonts[n][0] != '/')
719 (void) write(fo, _PATH_VFONT,
720 sizeof(_PATH_VFONT) - 1);
721 (void) write(fo, fonts[n], strlen(fonts[n]));
722 (void) write(fo, "\n", 1);
726 prog = (format == 't') ? pp->filters[LPF_TROFF]
727 : ((format == 'n') ? pp->filters[LPF_DITROFF]
728 : pp->filters[LPF_DVI]);
733 case 'c': /* print cifplot output */
734 prog = pp->filters[LPF_CIFPLOT];
739 case 'g': /* print plot(1G) output */
740 prog = pp->filters[LPF_GRAPH];
745 case 'v': /* print raster output */
746 prog = pp->filters[LPF_RASTER];
753 syslog(LOG_ERR, "%s: illegal format character '%c'",
754 pp->printer, format);
760 "%s: no filter found in printcap for format character '%c'",
761 pp->printer, format);
764 if ((av[0] = strrchr(prog, '/')) != NULL)
771 av[n++] = origin_host;
772 av[n++] = pp->acct_file;
775 if (of_pid > 0) { /* stop output filter */
776 write(ofd, "\031\1", 2);
778 wait3(&wstatus, WUNTRACED, 0)) > 0 && wpid != of_pid)
782 "%s: after stopping 'of', wait3() returned: %m",
784 else if (!WIFSTOPPED(wstatus)) {
786 syslog(LOG_WARNING, "%s: output filter died "
787 "(pid=%d retcode=%d termsig=%d)",
788 pp->printer, of_pid, WEXITSTATUS(wstatus),
795 if ((child = dofork(pp, DORETURN)) == 0) { /* child */
798 /* setup stderr for the filter (child process)
799 * so it goes to our temporary errors file */
800 n = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
806 syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer,
815 while ((wpid = wait(&wstatus)) > 0 && wpid != child)
820 "%s: after execv(%s), wait() returned: %m",
824 retcode = WEXITSTATUS(wstatus);
829 if (stopped) { /* restart output filter */
830 if (kill(of_pid, SIGCONT) < 0) {
831 syslog(LOG_ERR, "cannot restart output filter");
837 /* Copy the filter's output to "lf" logfile */
838 if ((fp = fopen(tempstderr, "r"))) {
839 while (fgets(buf, sizeof(buf), fp))
844 if (wstatus_set && !WIFEXITED(wstatus)) {
845 syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d)",
846 pp->printer, format, WTERMSIG(wstatus));
858 syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d)",
859 pp->printer, format, retcode);
865 * Send the daemon control file (cf) and any data files.
866 * Return -1 if a non-recoverable error occured, 1 if a recoverable error and
870 sendit(struct printer *pp, char *file)
872 int dfcopies, err, i;
873 char *cp, last[BUFSIZ];
878 if ((cfp = fopen(file, "r")) == NULL)
881 /* initialize job-specific count of datafiles processed */
885 * read the control file for work to do
887 * file format -- first character in the line is a command
888 * rest of the line is the argument.
889 * commands of interest are:
891 * a-z -- "file name" name of file to print
892 * U -- "unlink" name of file to remove
893 * (after we print it. (Pass 2 only)).
900 while (getline(cfp)) {
902 if (line[0] == 'S') {
905 while (*cp >= '0' && *cp <= '9')
906 i = i * 10 + (*cp++ - '0');
910 while (*cp >= '0' && *cp <= '9')
911 i = i * 10 + (*cp++ - '0');
913 } else if (line[0] == 'H') {
914 strlcpy(origin_host, line + 1, sizeof(origin_host));
915 if (class[0] == '\0') {
916 strlcpy(class, line + 1, sizeof(class));
918 } else if (line[0] == 'P') {
919 strlcpy(logname, line + 1, sizeof(logname));
920 if (pp->restricted) { /* restricted */
921 if (getpwnam(logname) == NULL) {
922 sendmail(pp, line+1, NOACCT);
927 } else if (line[0] == 'I') {
928 strlcpy(indent+2, line + 1, sizeof(indent) - 2);
929 } else if (line[0] >= 'a' && line[0] <= 'z') {
932 while ((i = getline(cfp)) != 0) {
933 if (strcmp(last, line) != 0)
937 switch (sendfile(pp, '\3', last+1, *last, dfcopies)) {
946 sendmail(pp, logname, ACCESS);
953 if (err == OK && sendfile(pp, '\2', file, '\0', 1) > 0) {
962 if (line[0] == 'U' && !strchr(line+1, '/'))
963 (void) unlink(line+1);
965 * clean-up in case another control file exists
973 * Send a data file to the remote machine and spool it.
974 * Return positive if we should try resending.
977 sendfile(struct printer *pp, int type, char *file, char format, int copyreq)
981 char *av[15], *filtcmd;
982 char buf[BUFSIZ], opt_c[4], opt_h[4], opt_n[4];
983 int copycnt, filtstat, narg, resp, sfd, sfres, sizerr, statrc;
985 statrc = lstat(file, &stb);
987 syslog(LOG_ERR, "%s: error from lstat(%s): %m",
991 sfd = open(file, O_RDONLY);
993 syslog(LOG_ERR, "%s: error from open(%s,O_RDONLY): %m",
998 * Check to see if data file is a symbolic link. If so, it should
999 * still point to the same file or someone is trying to print something
1002 if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(sfd, &stb) == 0 &&
1003 (stb.st_dev != fdev || stb.st_ino != fino)) {
1008 /* Everything seems OK for reading the file, now to send it */
1014 * Type == 3 means this is a datafile, not a control file.
1015 * Increment the counter of data-files in this job, and
1016 * then check for input or output filters (which are only
1017 * applied to datafiles, not control files).
1022 * Note that here we are filtering datafiles, one at a time,
1023 * as they are sent to the remote machine. Here, the *only*
1024 * difference between an input filter (`if=') and an output
1025 * filter (`of=') is the argument list that the filter is
1026 * started up with. Here, the output filter is executed
1027 * for each individual file as it is sent. This is not the
1028 * same as local print queues, where the output filter is
1029 * started up once, and then all jobs are passed thru that
1030 * single invocation of the output filter.
1032 * Also note that a queue for a remote-machine can have an
1033 * input filter or an output filter, but not both.
1035 if (pp->filters[LPF_INPUT]) {
1036 filtcmd = pp->filters[LPF_INPUT];
1039 strcpy(opt_c, "-c");
1040 strcpy(opt_h, "-h");
1041 strcpy(opt_n, "-n");
1045 av[++narg] = length;
1046 av[++narg] = indent;
1048 av[++narg] = logname;
1050 av[++narg] = origin_host;
1051 av[++narg] = pp->acct_file;
1053 } else if (pp->filters[LPF_OUTPUT]) {
1054 filtcmd = pp->filters[LPF_OUTPUT];
1058 av[++narg] = length;
1064 * If there is an input or output filter, we have to run
1065 * the datafile thru that filter and store the result as
1066 * a temporary spool file, because the protocol requires
1067 * that we send the remote host the file-size before we
1068 * start to send any of the data.
1070 strcpy(tfile, TFILENAME);
1071 tfd = mkstemp(tfile);
1073 syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
1078 filtstat = execfilter(pp, filtcmd, av, sfd, tfd);
1080 /* process the return-code from the filter */
1092 "%s: filter '%c' exited (retcode=%d)",
1093 pp->printer, format, filtstat);
1097 statrc = fstat(tfd, &stb); /* to find size of tfile */
1100 "%s: error processing 'if', fstat(%s): %m",
1101 pp->printer, tfile);
1107 lseek(sfd, 0, SEEK_SET);
1115 (void) sprintf(buf, "%c%qd %s\n", type, stb.st_size, file);
1117 (void) sprintf(buf, "%c%qd %s_c%d\n", type, stb.st_size,
1120 for (i = 0; ; i++) {
1121 if (write(pfd, buf, amt) != amt ||
1122 (resp = response(pp)) < 0 || resp == '\1') {
1125 } else if (resp == '\0')
1129 "no space on remote; waiting for queue to drain");
1131 syslog(LOG_ALERT, "%s: can't send to %s; queue full",
1132 pp->printer, pp->remote_host);
1136 pstatus(pp, "sending to %s", pp->remote_host);
1138 * XXX - we should change trstat_init()/trstat_write() to include
1139 * the copycnt in the statistics record it may write.
1142 trstat_init(pp, file, job_dfcnt);
1143 for (i = 0; i < stb.st_size; i += BUFSIZ) {
1145 if (i + amt > stb.st_size)
1146 amt = stb.st_size - i;
1147 if (sizerr == 0 && read(sfd, buf, amt) != amt)
1149 if (write(pfd, buf, amt) != amt) {
1156 syslog(LOG_INFO, "%s: %s: changed size", pp->printer, file);
1157 /* tell recvjob to ignore this file */
1158 (void) write(pfd, "\1", 1);
1162 if (write(pfd, "", 1) != 1 || response(pp)) {
1167 trstat_write(pp, TR_SENDING, stb.st_size, logname,
1168 pp->remote_host, origin_host);
1170 * Usually we only need to send one copy of a datafile,
1171 * because the control-file will simply print the same
1172 * file multiple times. However, some printers ignore
1173 * the control file, and simply print each data file as
1174 * it arrives. For such "remote hosts", we need to
1175 * transfer the same data file multiple times. Such a
1176 * a host is indicated by adding 'rc' to the printcap
1178 * XXX - Right now this ONLY works for remote hosts which
1179 * do ignore the name of the data file, because
1180 * this sends the file multiple times with slight
1181 * changes to the filename. To do this right would
1182 * require that we also rewrite the control file
1183 * to match those filenames.
1185 if (pp->resend_copies && (copycnt < copyreq)) {
1186 lseek(sfd, 0, SEEK_SET);
1196 * If tfd is set, then it is the same value as sfd, and
1197 * therefore it is already closed at this point. All
1198 * we need to do is remove the temporary file.
1207 * This routine is called to execute one of the filters as was
1208 * specified in a printcap entry. While the child-process will read
1209 * all of 'infd', it is up to the caller to close that file descriptor
1210 * in the parent process.
1213 execfilter(struct printer *pp, char *f_cmd, char *f_av[], int infd, int outfd)
1216 int errfd, retcode, wstatus;
1218 char buf[BUFSIZ], *slash;
1220 fpid = dofork(pp, DORETURN);
1223 * This is the parent process, which just waits for the child
1224 * to complete and then returns the result. Note that it is
1225 * the child process which reads the input stream.
1230 while ((wpid = wait(&wstatus)) > 0 &&
1236 "%s: after execv(%s), wait() returned: %m",
1237 pp->printer, f_cmd);
1239 retcode = WEXITSTATUS(wstatus);
1243 * Copy everything the filter wrote to stderr from our
1244 * temporary errors file to the "lf=" logfile.
1246 errfp = fopen(tempstderr, "r");
1248 while (fgets(buf, sizeof(buf), errfp))
1257 * This is the child process, which is the one that executes the
1261 * If the first parameter has any slashes in it, then change it
1262 * to point to the first character after the last slash.
1264 slash = strrchr(f_av[0], '/');
1266 f_av[0] = slash + 1;
1268 * XXX - in the future, this should setup an explicit list of
1269 * environment variables and use execve()!
1273 * Setup stdin, stdout, and stderr as we want them when the filter
1274 * is running. Stderr is setup so it points to a temporary errors
1275 * file, and the parent process will copy that temporary file to
1276 * the real logfile after the filter completes.
1280 errfd = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
1286 syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer, f_cmd);
1292 * Check to make sure there have been no errors and that both programs
1293 * are in sync with eachother.
1294 * Return non-zero if the connection was lost.
1297 response(const struct printer *pp)
1301 if (read(pfd, &resp, 1) != 1) {
1302 syslog(LOG_INFO, "%s: lost connection", pp->printer);
1309 * Banner printing stuff
1312 banner(struct printer *pp, char *name1, char *name2)
1317 if (!pp->no_formfeed && !pp->tof)
1318 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1319 if (pp->short_banner) { /* short banner only */
1321 (void) write(ofd, class, strlen(class));
1322 (void) write(ofd, ":", 1);
1324 (void) write(ofd, name1, strlen(name1));
1325 (void) write(ofd, " Job: ", 7);
1326 (void) write(ofd, name2, strlen(name2));
1327 (void) write(ofd, " Date: ", 8);
1328 (void) write(ofd, ctime(&tvec), 24);
1329 (void) write(ofd, "\n", 1);
1330 } else { /* normal banner */
1331 (void) write(ofd, "\n\n\n", 3);
1332 scan_out(pp, ofd, name1, '\0');
1333 (void) write(ofd, "\n\n", 2);
1334 scan_out(pp, ofd, name2, '\0');
1336 (void) write(ofd,"\n\n\n",3);
1337 scan_out(pp, ofd, class, '\0');
1339 (void) write(ofd, "\n\n\n\n\t\t\t\t\tJob: ", 15);
1340 (void) write(ofd, name2, strlen(name2));
1341 (void) write(ofd, "\n\t\t\t\t\tDate: ", 12);
1342 (void) write(ofd, ctime(&tvec), 24);
1343 (void) write(ofd, "\n", 1);
1345 if (!pp->no_formfeed)
1346 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1351 scnline(int key, char *p, int c)
1355 for (scnwidth = WIDTH; --scnwidth;) {
1357 *p++ = key & 0200 ? c : BACKGND;
1362 #define TRC(q) (((q)-' ')&0177)
1365 scan_out(struct printer *pp, int scfd, char *scsp, int dlm)
1369 char outbuf[LINELEN+1], *sp, c, cc;
1372 for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) {
1375 for (nchrs = 0; ; ) {
1376 d = dropit(c = TRC(cc = *sp++));
1377 if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d))
1378 for (j = WIDTH; --j;)
1381 strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc);
1382 if (*sp == dlm || *sp == '\0' ||
1383 nchrs++ >= pp->page_width/(WIDTH+1)-1)
1388 while (*--strp == BACKGND && strp >= outbuf)
1392 (void) write(scfd, outbuf, strp-outbuf);
1418 * tell people about job completion
1421 sendmail(struct printer *pp, char *userid, int bombed)
1430 if ((s = dofork(pp, DORETURN)) == 0) { /* child */
1434 if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL)
1437 cp = _PATH_SENDMAIL;
1438 execl(_PATH_SENDMAIL, cp, "-t", (char *)0);
1440 } else if (s > 0) { /* parent */
1442 printf("To: %s@%s\n", userid, origin_host);
1443 printf("Subject: %s printer job \"%s\"\n", pp->printer,
1444 *jobname ? jobname : "<unknown>");
1445 printf("Reply-To: root@%s\n\n", local_host);
1446 printf("Your printer job ");
1448 printf("(%s) ", jobname);
1453 printf("\ncompleted successfully\n");
1458 printf("\ncould not be printed\n");
1462 printf("\ncould not be printed without an account on %s\n",
1467 if (stat(tempstderr, &stb) < 0 || stb.st_size == 0
1468 || (fp = fopen(tempstderr, "r")) == NULL) {
1469 printf("\nhad some errors and may not have printed\n");
1472 printf("\nhad the following errors and may not have printed:\n");
1473 while ((i = getc(fp)) != EOF)
1479 printf("\nwas not printed because it was not linked to the original file\n");
1484 syslog(LOG_WARNING, "unable to send mail to %s: %m", userid);
1490 syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)",
1491 userid, *jobname ? jobname : "<unknown>", pp->printer, cp);
1495 * dofork - fork with retries on failure
1498 dofork(const struct printer *pp, int action)
1505 if (daemon_uname == NULL) {
1506 pwd = getpwuid(pp->daemon_user);
1508 syslog(LOG_ERR, "%s: Can't lookup default daemon uid (%ld) in password file",
1509 pp->printer, pp->daemon_user);
1512 daemon_uname = strdup(pwd->pw_name);
1513 daemon_defgid = pwd->pw_gid;
1516 for (i = 0; i < 20; i++) {
1519 sleep((unsigned)(i*i));
1523 * Child should run as daemon instead of root
1527 fail = initgroups(daemon_uname, daemon_defgid);
1529 syslog(LOG_ERR, "%s: initgroups(%s,%u): %m",
1530 pp->printer, daemon_uname, daemon_defgid);
1533 fail = setgid(daemon_defgid);
1535 syslog(LOG_ERR, "%s: setgid(%u): %m",
1536 pp->printer, daemon_defgid);
1539 fail = setuid(pp->daemon_user);
1541 syslog(LOG_ERR, "%s: setuid(%ld): %m",
1542 pp->printer, pp->daemon_user);
1550 * An error occurred. If the error is in the child process, then
1551 * this routine MUST always exit(). DORETURN only effects how
1552 * errors should be handled in the parent process.
1556 syslog(LOG_ERR, "%s: dofork(): aborting child process...",
1560 syslog(LOG_ERR, "%s: dofork(): failure in fork", pp->printer);
1562 sleep(1); /* throttle errors, as a safety measure */
1567 syslog(LOG_ERR, "bad action (%d) to dofork", action);
1576 * Kill child processes to abort current job.
1579 abortpr(int signo __unused)
1582 (void) unlink(tempstderr);
1585 kill(of_pid, SIGCONT);
1586 while (wait(NULL) > 0)
1588 if (of_pid > 0 && tfd != -1)
1594 init(struct printer *pp)
1598 sprintf(&width[2], "%ld", pp->page_width);
1599 sprintf(&length[2], "%ld", pp->page_length);
1600 sprintf(&pxwidth[2], "%ld", pp->page_pwidth);
1601 sprintf(&pxlength[2], "%ld", pp->page_plength);
1602 if ((s = checkremote(pp)) != 0) {
1603 syslog(LOG_WARNING, "%s", s);
1609 startprinting(const char *printer)
1611 struct printer myprinter, *pp = &myprinter;
1615 status = getprintcap(printer, pp);
1618 syslog(LOG_ERR, "can't open printer description file: %m");
1620 case PCAPERR_NOTFOUND:
1621 syslog(LOG_ERR, "unknown printer: %s", printer);
1623 case PCAPERR_TCLOOP:
1624 fatal(pp, "potential reference loop detected in printcap file");
1632 * Acquire line printer or remote connection.
1635 openpr(const struct printer *pp)
1643 * Lpd does support the setting of 'of=' filters for
1644 * jobs going to remote machines, but that does not
1645 * have the same meaning as 'of=' does when handling
1646 * local print queues. For remote machines, all 'of='
1647 * filter processing is handled in sendfile(), and that
1648 * does not use these global "output filter" variables.
1653 } else if (*pp->lp) {
1654 if ((cp = strchr(pp->lp, '@')) != NULL)
1659 syslog(LOG_ERR, "%s: no line printer device or host name",
1665 * Start up an output filter, if needed.
1667 if (pp->filters[LPF_OUTPUT] && !pp->filters[LPF_INPUT] && !of_pid) {
1670 strcpy(tfile, TFILENAME);
1671 tfd = mkstemp(tfile);
1673 if ((of_pid = dofork(pp, DOABORT)) == 0) { /* child */
1674 dup2(p[0], 0); /* pipe is std in */
1675 /* tfile/printer is stdout */
1676 dup2(pp->remote ? tfd : pfd, 1);
1679 if ((cp = strrchr(pp->filters[LPF_OUTPUT], '/')) == NULL)
1680 cp = pp->filters[LPF_OUTPUT];
1683 execl(pp->filters[LPF_OUTPUT], cp, width, length,
1685 syslog(LOG_ERR, "%s: execl(%s): %m", pp->printer,
1686 pp->filters[LPF_OUTPUT]);
1689 (void) close(p[0]); /* close input side */
1690 ofd = p[1]; /* use pipe for output */
1698 * Printer connected directly to the network
1699 * or to a terminal server on the net
1702 opennet(const struct printer *pp)
1708 void (*savealrm)(int);
1710 port = strtoul(pp->lp, &ep, 0);
1711 if (*ep != '@' || port > 65535) {
1712 syslog(LOG_ERR, "%s: bad port number: %s", pp->printer,
1718 for (i = 1; ; i = i < 256 ? i << 1 : i) {
1720 savealrm = signal(SIGALRM, alarmhandler);
1721 alarm(pp->conn_timeout);
1722 pfd = getport(pp, ep, port);
1724 (void)signal(SIGALRM, savealrm);
1725 if (pfd < 0 && errno == ECONNREFUSED)
1727 else if (pfd >= 0) {
1729 * need to delay a bit for rs232 lines
1730 * to stabilize in case printer is
1731 * connected via a terminal server
1738 pstatus(pp, "waiting for %s to come up",
1742 "waiting for access to printer on %s",
1747 pstatus(pp, "sending to %s port %lu", ep, port);
1751 * Printer is connected to an RS232 port on this host
1754 opentty(const struct printer *pp)
1758 for (i = 1; ; i = i < 32 ? i << 1 : i) {
1759 pfd = open(pp->lp, pp->rw ? O_RDWR : O_WRONLY);
1764 if (errno == ENOENT) {
1765 syslog(LOG_ERR, "%s: %m", pp->lp);
1770 "waiting for %s to become ready (offline?)",
1776 pstatus(pp, "%s is ready and printing", pp->printer);
1780 * Printer is on a remote host
1783 openrem(const struct printer *pp)
1787 void (*savealrm)(int);
1789 for (i = 1; ; i = i < 256 ? i << 1 : i) {
1791 savealrm = signal(SIGALRM, alarmhandler);
1792 alarm(pp->conn_timeout);
1793 pfd = getport(pp, pp->remote_host, 0);
1795 (void)signal(SIGALRM, savealrm);
1797 if ((writel(pfd, "\2", pp->remote_queue, "\n",
1799 == 2 + strlen(pp->remote_queue))
1800 && (resp = response(pp)) == 0)
1806 pstatus(pp, "waiting for %s to come up",
1810 "waiting for queue to be enabled on %s",
1817 pstatus(pp, "sending to %s", pp->remote_host);
1824 setty(const struct printer *pp)
1826 struct termios ttybuf;
1828 if (ioctl(pfd, TIOCEXCL, (char *)0) < 0) {
1829 syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", pp->printer);
1832 if (tcgetattr(pfd, &ttybuf) < 0) {
1833 syslog(LOG_ERR, "%s: tcgetattr: %m", pp->printer);
1836 if (pp->baud_rate > 0)
1837 cfsetspeed(&ttybuf, pp->baud_rate);
1839 char *s = strdup(pp->mode_set), *tmp;
1841 while ((tmp = strsep(&s, ",")) != NULL) {
1842 (void) msearch(tmp, &ttybuf);
1845 if (pp->mode_set != 0 || pp->baud_rate > 0) {
1846 if (tcsetattr(pfd, TCSAFLUSH, &ttybuf) == -1) {
1847 syslog(LOG_ERR, "%s: tcsetattr: %m", pp->printer);
1855 pstatus(const struct printer *pp, const char *msg, ...)
1863 fd = open(pp->status_file, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
1865 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
1870 vasprintf(&buf, msg, ap);
1872 writel(fd, buf, "\n", (char *)0);
1878 alarmhandler(int signo __unused)
1880 /* the signal is ignored */
1881 /* (the '__unused' is just to avoid a compile-time warning) */