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 * 4. Neither the name of the University nor the names of its contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static const char copyright[] =
33 "@(#) Copyright (c) 1983, 1993\n\
34 The Regents of the University of California. All rights reserved.\n";
39 static char sccsid[] = "@(#)printjob.c 8.7 (Berkeley) 5/10/95";
43 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
44 __FBSDID("$FreeBSD$");
47 * printjob -- print jobs in the queue.
49 * NOTE: the lock file is used to pass information to lpq and lprm.
50 * it does not need to be removed because file locks are dynamic.
53 #include <sys/param.h>
56 #include <sys/types.h>
69 #include <sys/ioctl.h>
74 #include "pathnames.h"
77 #define DORETURN 0 /* dofork should return "can't fork" error */
78 #define DOABORT 1 /* dofork should just die if fork() fails */
81 * The buffer size to use when reading/writing spool files.
83 #define SPL_BUFSIZ BUFSIZ
96 static dev_t fdev; /* device of file pointed to by symlink */
97 static ino_t fino; /* inode of file pointed to by symlink */
98 static FILE *cfp; /* control file */
99 static pid_t of_pid; /* process id of output filter, if any */
100 static int child; /* id of any filters */
101 static int job_dfcnt; /* count of datafiles in current user job */
102 static int lfd; /* lock file descriptor */
103 static int ofd; /* output filter file descriptor */
104 static int tfd = -1; /* output filter temp file output */
105 static int pfd; /* prstatic inter file descriptor */
106 static int prchild; /* id of pr process */
107 static char title[80]; /* ``pr'' title */
108 static char locale[80]; /* ``pr'' locale */
110 /* these two are set from pp->daemon_user, but only if they are needed */
111 static char *daemon_uname; /* set from pwd->pw_name */
112 static int daemon_defgid;
114 static char class[32]; /* classification field */
115 static char origin_host[MAXHOSTNAMELEN]; /* user's host machine */
116 /* indentation size in static characters */
117 static char indent[10] = "-i0";
118 static char jobname[100]; /* job or file name */
119 static char length[10] = "-l"; /* page length in lines */
120 static char logname[32]; /* user's login name */
121 static char pxlength[10] = "-y"; /* page length in pixels */
122 static char pxwidth[10] = "-x"; /* page width in pixels */
123 /* tempstderr is the filename used to catch stderr from exec-ing filters */
124 static char tempstderr[] = "errs.XXXXXXX";
125 static char width[10] = "-w"; /* page width in static characters */
126 #define TFILENAME "fltXXXXXX"
127 static char tfile[] = TFILENAME; /* file name for filter output */
129 static void abortpr(int _signo);
130 static void alarmhandler(int _signo);
131 static void banner(struct printer *_pp, char *_name1, char *_name2);
132 static int dofork(const struct printer *_pp, int _action);
133 static int dropit(int _c);
134 static int execfilter(struct printer *_pp, char *_f_cmd, char **_f_av,
135 int _infd, int _outfd);
136 static void init(struct printer *_pp);
137 static void openpr(const struct printer *_pp);
138 static void opennet(const struct printer *_pp);
139 static void opentty(const struct printer *_pp);
140 static void openrem(const struct printer *pp);
141 static int print(struct printer *_pp, int _format, char *_file);
142 static int printit(struct printer *_pp, char *_file);
143 static void pstatus(const struct printer *_pp, const char *_msg, ...)
145 static char response(const struct printer *_pp);
146 static void scan_out(struct printer *_pp, int _scfd, char *_scsp,
148 static char *scnline(int _key, char *_p, int _c);
149 static int sendfile(struct printer *_pp, int _type, char *_file,
150 char _format, int _copyreq);
151 static int sendit(struct printer *_pp, char *_file);
152 static void sendmail(struct printer *_pp, char *_userid, int _bombed);
153 static void setty(const struct printer *_pp);
154 static void wait4data(struct printer *_pp, const char *_dfile);
157 printjob(struct printer *pp)
160 register struct jobqueue *q, **qp;
161 struct jobqueue **queue;
162 register int i, nitems;
165 int errcnt, jobcount, statok, tempfd;
168 init(pp); /* set up capabilities */
169 (void) write(STDOUT_FILENO, "", 1); /* ack that daemon is started */
170 (void) close(STDERR_FILENO); /* set up log file */
171 if (open(pp->log_file, O_WRONLY|O_APPEND, LOG_FILE_MODE) < 0) {
172 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
174 (void) open(_PATH_DEVNULL, O_WRONLY);
177 printpid = getpid(); /* for use with lprm */
178 setpgrp(0, printpid);
181 * At initial lpd startup, printjob may be called with various
182 * signal handlers in effect. After that initial startup, any
183 * calls to printjob will have a *different* set of signal-handlers
184 * in effect. Make sure all handlers are the ones we want.
186 signal(SIGCHLD, SIG_DFL);
187 signal(SIGHUP, abortpr);
188 signal(SIGINT, abortpr);
189 signal(SIGQUIT, abortpr);
190 signal(SIGTERM, abortpr);
193 * uses short form file names
195 if (chdir(pp->spool_dir) < 0) {
196 syslog(LOG_ERR, "%s: chdir(%s): %m", pp->printer,
200 statok = stat(pp->lock_file, &stb);
201 if (statok == 0 && (stb.st_mode & LFM_PRINT_DIS))
202 exit(0); /* printing disabled */
204 lfd = open(pp->lock_file, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
207 if (errno == EWOULDBLOCK) /* active daemon present */
209 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
214 * If the initial call to stat() failed, then lock_file will have
215 * been created by open(). Update &stb to match that new file.
218 statok = stat(pp->lock_file, &stb);
219 /* turn off non-blocking mode (was turned on for lock effects only) */
220 if (fcntl(lfd, F_SETFL, 0) < 0) {
221 syslog(LOG_ERR, "%s: fcntl(%s): %m", pp->printer,
227 * write process id for others to know
229 sprintf(line, "%u\n", printpid);
230 pidoff = i = strlen(line);
231 if (write(lfd, line, i) != i) {
232 syslog(LOG_ERR, "%s: write(%s): %m", pp->printer,
237 * search the spool directory for work and sort by queue order.
239 if ((nitems = getq(pp, &queue)) < 0) {
240 syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
244 if (nitems == 0) /* no work to do */
246 if (stb.st_mode & LFM_RESET_QUE) { /* reset queue flag */
247 if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE) < 0)
248 syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
252 /* create a file which will be used to hold stderr from filters */
253 if ((tempfd = mkstemp(tempstderr)) == -1) {
254 syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
258 if ((i = fchmod(tempfd, 0664)) == -1) {
259 syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
263 /* lpd doesn't need it to be open, it just needs it to exist */
266 openpr(pp); /* open printer or remote */
269 * we found something to do now do it --
270 * write the name of the current control file into the lock file
271 * so the spool queue program can tell what we're working on
273 for (qp = queue; nitems--; free((char *) q)) {
275 if (stat(q->job_cfname, &stb) < 0)
279 (void) lseek(lfd, pidoff, 0);
280 (void) snprintf(line, sizeof(line), "%s\n", q->job_cfname);
282 if (write(lfd, line, i) != i)
283 syslog(LOG_ERR, "%s: write(%s): %m", pp->printer,
286 i = printit(pp, q->job_cfname);
288 i = sendit(pp, q->job_cfname);
290 * Check to see if we are supposed to stop printing or
291 * if we are to rebuild the queue.
293 if (fstat(lfd, &stb) == 0) {
294 /* stop printing before starting next job? */
295 if (stb.st_mode & LFM_PRINT_DIS)
297 /* rebuild queue (after lpc topq) */
298 if (stb.st_mode & LFM_RESET_QUE) {
299 for (free(q); nitems--; free(q))
301 if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE)
304 "%s: fchmod(%s): %m",
305 pp->printer, pp->lock_file);
309 if (i == OK) /* all files of this job printed */
311 else if (i == REPRINT && ++errcnt < 5) {
312 /* try reprinting the job */
313 syslog(LOG_INFO, "restarting %s", pp->printer);
315 kill(of_pid, SIGCONT); /* to be sure */
317 while ((i = wait(NULL)) > 0 && i != of_pid)
320 syslog(LOG_WARNING, "%s: after kill(of=%d), wait() returned: %m",
321 pp->printer, of_pid);
324 (void) close(pfd); /* close printer */
325 if (ftruncate(lfd, pidoff) < 0)
326 syslog(LOG_WARNING, "%s: ftruncate(%s): %m",
327 pp->printer, pp->lock_file);
328 openpr(pp); /* try to reopen printer */
331 syslog(LOG_WARNING, "%s: job could not be %s (%s)",
333 pp->remote ? "sent to remote host" : "printed",
336 /* ensure we don't attempt this job again */
337 (void) unlink(q->job_cfname);
338 q->job_cfname[0] = 'd';
339 (void) unlink(q->job_cfname);
341 sendmail(pp, logname, FATALERR);
347 * search the spool directory for more work.
349 if ((nitems = getq(pp, &queue)) < 0) {
350 syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
354 if (nitems == 0) { /* no more work to do */
356 if (jobcount > 0) { /* jobs actually printed */
357 if (!pp->no_formfeed && !pp->tof)
358 (void) write(ofd, pp->form_feed,
359 strlen(pp->form_feed));
360 if (pp->trailer != NULL) /* output trailer */
361 (void) write(ofd, pp->trailer,
362 strlen(pp->trailer));
366 (void) unlink(tempstderr);
372 char fonts[4][50]; /* fonts for troff */
374 char ifonts[4][40] = {
382 * The remaining part is the reading of the control file (cf)
383 * and performing the various actions.
386 printit(struct printer *pp, char *file)
390 int bombed, didignorehdr;
395 * open control file; ignore if no longer there.
397 if ((cfp = fopen(file, "r")) == NULL) {
398 syslog(LOG_INFO, "%s: fopen(%s): %m", pp->printer, file);
404 for (i = 0; i < 4; i++)
405 strcpy(fonts[i], ifonts[i]);
406 sprintf(&width[2], "%ld", pp->page_width);
407 strcpy(indent+2, "0");
409 /* initialize job-specific count of datafiles processed */
413 * read the control file for work to do
415 * file format -- first character in the line is a command
416 * rest of the line is the argument.
417 * valid commands are:
419 * S -- "stat info" for symbolic link protection
420 * J -- "job name" on banner page
421 * C -- "class name" on banner page
422 * L -- "literal" user's name to print on banner
423 * T -- "title" for pr
424 * H -- "host name" of machine where lpr was done
425 * P -- "person" user's login name
426 * I -- "indent" amount to indent output
427 * R -- laser dpi "resolution"
428 * f -- "file name" name of text file to print
429 * l -- "file name" text file with control chars
430 * o -- "file name" postscript file, according to
431 * the RFC. Here it is treated like an 'f'.
432 * p -- "file name" text file to print with pr(1)
433 * t -- "file name" troff(1) file to print
434 * n -- "file name" ditroff(1) file to print
435 * d -- "file name" dvi file to print
436 * g -- "file name" plot(1G) file to print
437 * v -- "file name" plain raster file to print
438 * c -- "file name" cifplot file to print
439 * 1 -- "R font file" for troff
440 * 2 -- "I font file" for troff
441 * 3 -- "B font file" for troff
442 * 4 -- "S font file" for troff
443 * N -- "name" of file (used by lpq)
444 * U -- "unlink" name of file to remove
445 * (after we print it. (Pass 2 only)).
446 * M -- "mail" to user when done printing
447 * Z -- "locale" for pr
449 * getline reads a line and expands tabs to blanks
457 strlcpy(origin_host, line + 1, sizeof(origin_host));
458 if (class[0] == '\0') {
459 strlcpy(class, line+1, sizeof(class));
464 strlcpy(logname, line + 1, sizeof(logname));
465 if (pp->restricted) { /* restricted */
466 if (getpwnam(logname) == NULL) {
468 sendmail(pp, line+1, bombed);
477 while (*cp >= '0' && *cp <= '9')
478 i = i * 10 + (*cp++ - '0');
482 while (*cp >= '0' && *cp <= '9')
483 i = i * 10 + (*cp++ - '0');
488 if (line[1] != '\0') {
489 strlcpy(jobname, line + 1, sizeof(jobname));
491 strcpy(jobname, " ");
496 strlcpy(class, line + 1, sizeof(class));
497 else if (class[0] == '\0') {
498 /* XXX - why call gethostname instead of
499 * just strlcpy'ing local_host? */
500 gethostname(class, sizeof(class));
501 class[sizeof(class) - 1] = '\0';
505 case 'T': /* header title for pr */
506 strlcpy(title, line + 1, sizeof(title));
509 case 'L': /* identification line */
510 if (!pp->no_header && !pp->header_last)
511 banner(pp, line+1, jobname);
514 case '1': /* troff fonts */
518 if (line[1] != '\0') {
519 strlcpy(fonts[line[0]-'1'], line + 1,
524 case 'W': /* page width */
525 strlcpy(width+2, line + 1, sizeof(width) - 2);
528 case 'I': /* indent amount */
529 strlcpy(indent+2, line + 1, sizeof(indent) - 2);
532 case 'Z': /* locale for pr */
533 strlcpy(locale, line + 1, sizeof(locale));
536 default: /* some file to print */
537 /* only lowercase cmd-codes include a file-to-print */
538 if ((line[0] < 'a') || (line[0] > 'z')) {
539 /* ignore any other lines */
543 syslog(LOG_INFO, "%s: in %s :",
547 syslog(LOG_INFO, "%s: ignoring line: '%c' %s",
548 pp->printer, line[0], &line[1]);
551 i = print(pp, line[0], line+1);
563 sendmail(pp, logname, bombed);
581 case 'L': /* identification line */
582 if (!pp->no_header && pp->header_last)
583 banner(pp, line+1, jobname);
587 if (bombed < NOACCT) /* already sent if >= NOACCT */
588 sendmail(pp, line+1, bombed);
592 if (strchr(line+1, '/'))
594 (void) unlink(line+1);
597 * clean-up in case another control file exists
601 return (bombed == OK ? OK : ERROR);
606 * Set up the chain [ PR [ | {IF, OF} ] ] or {IF, RF, TF, NF, DF, CF, VF}.
607 * Return -1 if a non-recoverable error occured,
608 * 2 if the filter detected some errors (but printed the job anyway),
609 * 1 if we should try to reprint this job and
611 * Note: all filters take stdin as the file, stdout as the printer,
612 * stderr as the log file, and must not ignore SIGINT.
615 print(struct printer *pp, int format, char *file)
621 char *av[15], buf[SPL_BUFSIZ];
623 int p[2], retcode, stopped, wstatus, wstatus_set;
626 /* Make sure the entire data file has arrived. */
629 if (lstat(file, &stb) < 0 || (fi = open(file, O_RDONLY)) < 0) {
630 syslog(LOG_INFO, "%s: unable to open %s ('%c' line)",
631 pp->printer, file, format);
635 * Check to see if data file is a symbolic link. If so, it should
636 * still point to the same file or someone is trying to print
637 * something he shouldn't.
639 if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(fi, &stb) == 0 &&
640 (stb.st_dev != fdev || stb.st_ino != fino))
643 job_dfcnt++; /* increment datafile counter for this job */
644 stopped = 0; /* output filter is not stopped */
646 /* everything seems OK, start it up */
647 if (!pp->no_formfeed && !pp->tof) { /* start on a fresh page */
648 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
651 if (pp->filters[LPF_INPUT] == NULL
652 && (format == 'f' || format == 'l' || format == 'o')) {
654 while ((n = read(fi, buf, SPL_BUFSIZ)) > 0)
655 if (write(ofd, buf, n) != n) {
663 case 'p': /* print file using 'pr' */
664 if (pp->filters[LPF_INPUT] == NULL) { /* use output filter */
671 av[i++] = *title ? title : " ";
673 av[i++] = *locale ? locale : "C";
680 if ((prchild = dofork(pp, DORETURN)) == 0) { /* child */
681 dup2(fi, STDIN_FILENO); /* file is stdin */
682 dup2(p[1], STDOUT_FILENO); /* pipe is stdout */
685 execl(_PATH_PR, "pr", width, length,
686 "-h", *title ? title : " ",
687 "-L", *locale ? locale : "C",
689 syslog(LOG_ERR, "cannot execl %s", _PATH_PR);
692 (void) close(p[1]); /* close output side */
699 fi = p[0]; /* use pipe for input */
700 case 'f': /* print plain text file */
701 prog = pp->filters[LPF_INPUT];
707 case 'o': /* print postscript file */
709 * Treat this as a "plain file with control characters", and
710 * assume the standard LPF_INPUT filter will recognize that
711 * the data is postscript and know what to do with it. These
712 * 'o'-file requests could come from MacOS 10.1 systems.
713 * (later versions of MacOS 10 will explicitly use 'l')
714 * A postscript file can contain binary data, which is why 'l'
715 * is somewhat more appropriate than 'f'.
718 case 'l': /* like 'f' but pass control characters */
719 prog = pp->filters[LPF_INPUT];
726 case 'r': /* print a fortran text file */
727 prog = pp->filters[LPF_FORTRAN];
732 case 't': /* print troff output */
733 case 'n': /* print ditroff output */
734 case 'd': /* print tex output */
735 (void) unlink(".railmag");
736 if ((fo = creat(".railmag", FILMOD)) < 0) {
737 syslog(LOG_ERR, "%s: cannot create .railmag",
739 (void) unlink(".railmag");
741 for (n = 0; n < 4; n++) {
742 if (fonts[n][0] != '/')
743 (void) write(fo, _PATH_VFONT,
744 sizeof(_PATH_VFONT) - 1);
745 (void) write(fo, fonts[n], strlen(fonts[n]));
746 (void) write(fo, "\n", 1);
750 prog = (format == 't') ? pp->filters[LPF_TROFF]
751 : ((format == 'n') ? pp->filters[LPF_DITROFF]
752 : pp->filters[LPF_DVI]);
757 case 'c': /* print cifplot output */
758 prog = pp->filters[LPF_CIFPLOT];
763 case 'g': /* print plot(1G) output */
764 prog = pp->filters[LPF_GRAPH];
769 case 'v': /* print raster output */
770 prog = pp->filters[LPF_RASTER];
777 syslog(LOG_ERR, "%s: illegal format character '%c'",
778 pp->printer, format);
784 "%s: no filter found in printcap for format character '%c'",
785 pp->printer, format);
788 if ((av[0] = strrchr(prog, '/')) != NULL)
795 av[n++] = origin_host;
796 av[n++] = pp->acct_file;
799 if (of_pid > 0) { /* stop output filter */
800 write(ofd, "\031\1", 2);
802 wait3(&wstatus, WUNTRACED, 0)) > 0 && wpid != of_pid)
806 "%s: after stopping 'of', wait3() returned: %m",
808 else if (!WIFSTOPPED(wstatus)) {
810 syslog(LOG_WARNING, "%s: output filter died "
811 "(pid=%d retcode=%d termsig=%d)",
812 pp->printer, of_pid, WEXITSTATUS(wstatus),
819 if ((child = dofork(pp, DORETURN)) == 0) { /* child */
820 dup2(fi, STDIN_FILENO);
821 dup2(fo, STDOUT_FILENO);
822 /* setup stderr for the filter (child process)
823 * so it goes to our temporary errors file */
824 n = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
826 dup2(n, STDERR_FILENO);
830 syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer,
839 while ((wpid = wait(&wstatus)) > 0 && wpid != child)
844 "%s: after execv(%s), wait() returned: %m",
848 retcode = WEXITSTATUS(wstatus);
853 if (stopped) { /* restart output filter */
854 if (kill(of_pid, SIGCONT) < 0) {
855 syslog(LOG_ERR, "cannot restart output filter");
861 /* Copy the filter's output to "lf" logfile */
862 if ((fp = fopen(tempstderr, "r"))) {
863 while (fgets(buf, sizeof(buf), fp))
868 if (wstatus_set && !WIFEXITED(wstatus)) {
869 syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d)",
870 pp->printer, format, WTERMSIG(wstatus));
882 syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d)",
883 pp->printer, format, retcode);
889 * Send the daemon control file (cf) and any data files.
890 * Return -1 if a non-recoverable error occured, 1 if a recoverable error and
894 sendit(struct printer *pp, char *file)
896 int dfcopies, err, i;
897 char *cp, last[sizeof(line)];
902 if ((cfp = fopen(file, "r")) == NULL)
905 /* initialize job-specific count of datafiles processed */
909 * read the control file for work to do
911 * file format -- first character in the line is a command
912 * rest of the line is the argument.
913 * commands of interest are:
915 * a-z -- "file name" name of file to print
916 * U -- "unlink" name of file to remove
917 * (after we print it. (Pass 2 only)).
924 while (getline(cfp)) {
926 if (line[0] == 'S') {
929 while (*cp >= '0' && *cp <= '9')
930 i = i * 10 + (*cp++ - '0');
934 while (*cp >= '0' && *cp <= '9')
935 i = i * 10 + (*cp++ - '0');
937 } else if (line[0] == 'H') {
938 strlcpy(origin_host, line + 1, sizeof(origin_host));
939 if (class[0] == '\0') {
940 strlcpy(class, line + 1, sizeof(class));
942 } else if (line[0] == 'P') {
943 strlcpy(logname, line + 1, sizeof(logname));
944 if (pp->restricted) { /* restricted */
945 if (getpwnam(logname) == NULL) {
946 sendmail(pp, line+1, NOACCT);
951 } else if (line[0] == 'I') {
952 strlcpy(indent+2, line + 1, sizeof(indent) - 2);
953 } else if (line[0] >= 'a' && line[0] <= 'z') {
956 while ((i = getline(cfp)) != 0) {
957 if (strcmp(last, line) != 0)
961 switch (sendfile(pp, '\3', last+1, *last, dfcopies)) {
970 sendmail(pp, logname, ACCESS);
977 if (err == OK && sendfile(pp, '\2', file, '\0', 1) > 0) {
986 if (line[0] == 'U' && !strchr(line+1, '/'))
987 (void) unlink(line+1);
989 * clean-up in case another control file exists
997 * Send a data file to the remote machine and spool it.
998 * Return positive if we should try resending.
1001 sendfile(struct printer *pp, int type, char *file, char format, int copyreq)
1005 char *av[15], *filtcmd;
1006 char buf[SPL_BUFSIZ], opt_c[4], opt_h[4], opt_n[4];
1007 int copycnt, filtstat, narg, resp, sfd, sfres, sizerr, statrc;
1009 /* Make sure the entire data file has arrived. */
1010 wait4data(pp, file);
1012 statrc = lstat(file, &stb);
1014 syslog(LOG_ERR, "%s: error from lstat(%s): %m",
1018 sfd = open(file, O_RDONLY);
1020 syslog(LOG_ERR, "%s: error from open(%s,O_RDONLY): %m",
1025 * Check to see if data file is a symbolic link. If so, it should
1026 * still point to the same file or someone is trying to print something
1029 if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(sfd, &stb) == 0 &&
1030 (stb.st_dev != fdev || stb.st_ino != fino)) {
1035 /* Everything seems OK for reading the file, now to send it */
1041 * Type == 3 means this is a datafile, not a control file.
1042 * Increment the counter of data-files in this job, and
1043 * then check for input or output filters (which are only
1044 * applied to datafiles, not control files).
1049 * Note that here we are filtering datafiles, one at a time,
1050 * as they are sent to the remote machine. Here, the *only*
1051 * difference between an input filter (`if=') and an output
1052 * filter (`of=') is the argument list that the filter is
1053 * started up with. Here, the output filter is executed
1054 * for each individual file as it is sent. This is not the
1055 * same as local print queues, where the output filter is
1056 * started up once, and then all jobs are passed thru that
1057 * single invocation of the output filter.
1059 * Also note that a queue for a remote-machine can have an
1060 * input filter or an output filter, but not both.
1062 if (pp->filters[LPF_INPUT]) {
1063 filtcmd = pp->filters[LPF_INPUT];
1066 strcpy(opt_c, "-c");
1067 strcpy(opt_h, "-h");
1068 strcpy(opt_n, "-n");
1072 av[++narg] = length;
1073 av[++narg] = indent;
1075 av[++narg] = logname;
1077 av[++narg] = origin_host;
1078 av[++narg] = pp->acct_file;
1080 } else if (pp->filters[LPF_OUTPUT]) {
1081 filtcmd = pp->filters[LPF_OUTPUT];
1085 av[++narg] = length;
1091 * If there is an input or output filter, we have to run
1092 * the datafile thru that filter and store the result as
1093 * a temporary spool file, because the protocol requires
1094 * that we send the remote host the file-size before we
1095 * start to send any of the data.
1097 strcpy(tfile, TFILENAME);
1098 tfd = mkstemp(tfile);
1100 syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
1105 filtstat = execfilter(pp, filtcmd, av, sfd, tfd);
1107 /* process the return-code from the filter */
1119 "%s: filter '%c' exited (retcode=%d)",
1120 pp->printer, format, filtstat);
1124 statrc = fstat(tfd, &stb); /* to find size of tfile */
1127 "%s: error processing 'if', fstat(%s): %m",
1128 pp->printer, tfile);
1134 lseek(sfd, 0, SEEK_SET);
1142 (void) sprintf(buf, "%c%" PRId64 " %s\n", type, stb.st_size,
1145 (void) sprintf(buf, "%c%" PRId64 " %s_c%d\n", type, stb.st_size,
1148 for (i = 0; ; i++) {
1149 if (write(pfd, buf, amt) != amt ||
1150 (resp = response(pp)) < 0 || resp == '\1') {
1153 } else if (resp == '\0')
1157 "no space on remote; waiting for queue to drain");
1159 syslog(LOG_ALERT, "%s: can't send to %s; queue full",
1160 pp->printer, pp->remote_host);
1164 pstatus(pp, "sending to %s", pp->remote_host);
1166 * XXX - we should change trstat_init()/trstat_write() to include
1167 * the copycnt in the statistics record it may write.
1170 trstat_init(pp, file, job_dfcnt);
1171 for (i = 0; i < stb.st_size; i += SPL_BUFSIZ) {
1173 if (i + amt > stb.st_size)
1174 amt = stb.st_size - i;
1175 if (sizerr == 0 && read(sfd, buf, amt) != amt)
1177 if (write(pfd, buf, amt) != amt) {
1184 syslog(LOG_INFO, "%s: %s: changed size", pp->printer, file);
1185 /* tell recvjob to ignore this file */
1186 (void) write(pfd, "\1", 1);
1190 if (write(pfd, "", 1) != 1 || response(pp)) {
1195 trstat_write(pp, TR_SENDING, stb.st_size, logname,
1196 pp->remote_host, origin_host);
1198 * Usually we only need to send one copy of a datafile,
1199 * because the control-file will simply print the same
1200 * file multiple times. However, some printers ignore
1201 * the control file, and simply print each data file as
1202 * it arrives. For such "remote hosts", we need to
1203 * transfer the same data file multiple times. Such a
1204 * a host is indicated by adding 'rc' to the printcap
1206 * XXX - Right now this ONLY works for remote hosts which
1207 * do ignore the name of the data file, because
1208 * this sends the file multiple times with slight
1209 * changes to the filename. To do this right would
1210 * require that we also rewrite the control file
1211 * to match those filenames.
1213 if (pp->resend_copies && (copycnt < copyreq)) {
1214 lseek(sfd, 0, SEEK_SET);
1224 * If tfd is set, then it is the same value as sfd, and
1225 * therefore it is already closed at this point. All
1226 * we need to do is remove the temporary file.
1235 * Some print servers send the control-file first, and then start sending the
1236 * matching data file(s). That is not the correct order. If some queue is
1237 * already printing an active job, then when that job is finished the queue
1238 * may proceed to the control file of any incoming print job. This turns
1239 * into a race between the process which is receiving the data file, and the
1240 * process which is actively printing the very same file. When the remote
1241 * server sends files in the wrong order, it is even possible that a queue
1242 * will start to print a data file before the file has been created!
1244 * So before we start to print() or send() a data file, we call this routine
1245 * to make sure the data file is not still changing in size. Note that this
1246 * problem will only happen for jobs arriving from a remote host, and that
1247 * the process which has decided to print this job (and is thus making this
1248 * check) is *not* the process which is receiving the job.
1250 * A second benefit of this is that any incoming job is guaranteed to appear
1251 * in a queue listing for at least a few seconds after it has arrived. Some
1252 * lpr implementations get confused if they send a job and it disappears
1253 * from the queue before they can check on it.
1255 #define MAXWAIT_ARRIVE 16 /* max to wait for the file to *exist* */
1256 #define MAXWAIT_4DATA (20*60) /* max to wait for it to stop changing */
1257 #define MINWAIT_4DATA 4 /* This value must be >= 1 */
1258 #define DEBUG_MINWAIT 1
1260 wait4data(struct printer *pp, const char *dfile)
1266 time_t amtslept, cur_time, prev_mtime;
1269 /* Skip these checks if the print job is from the local host. */
1270 dlen = strlen(dfile);
1271 hlen = strlen(local_host);
1273 cp = dfile + dlen - hlen;
1274 if (strcmp(cp, local_host) == 0)
1279 * If this data file does not exist, then wait up to MAXWAIT_ARRIVE
1280 * seconds for it to arrive.
1283 statres = stat(dfile, &statdf);
1284 while (statres < 0 && amtslept < MAXWAIT_ARRIVE) {
1286 pstatus(pp, "Waiting for data file from remote host");
1287 amtslept += MINWAIT_4DATA - sleep(MINWAIT_4DATA);
1288 statres = stat(dfile, &statdf);
1291 /* The file still does not exist, so just give up on it. */
1292 syslog(LOG_WARNING, "%s: wait4data() abandoned wait for %s",
1293 pp->printer, dfile);
1298 * The file exists, so keep waiting until the data file has not
1299 * changed for some reasonable amount of time. Extra care is
1300 * taken when computing wait-times, just in case there are data
1301 * files with a last-modify time in the future. While that is
1302 * very unlikely to happen, it can happen when the system has
1303 * a flakey time-of-day clock.
1305 prev_mtime = statdf.st_mtime;
1306 cur_time = time(NULL);
1307 if (statdf.st_mtime >= cur_time - MINWAIT_4DATA) {
1308 if (statdf.st_mtime >= cur_time) /* some TOD oddity */
1309 sleepreq = MINWAIT_4DATA;
1311 sleepreq = cur_time - statdf.st_mtime;
1313 pstatus(pp, "Waiting for data file from remote host");
1314 amtslept += sleepreq - sleep(sleepreq);
1315 statres = stat(dfile, &statdf);
1317 sleepreq = MINWAIT_4DATA;
1318 while (statres == 0 && amtslept < MAXWAIT_4DATA) {
1319 if (statdf.st_mtime == prev_mtime)
1321 prev_mtime = statdf.st_mtime;
1322 amtslept += sleepreq - sleep(sleepreq);
1323 statres = stat(dfile, &statdf);
1327 syslog(LOG_WARNING, "%s: %s disappeared during wait4data()",
1328 pp->printer, dfile);
1329 else if (amtslept > MAXWAIT_4DATA)
1331 "%s: %s still changing after %lu secs in wait4data()",
1332 pp->printer, dfile, (unsigned long)amtslept);
1334 else if (amtslept > MINWAIT_4DATA)
1335 syslog(LOG_INFO, "%s: slept %lu secs in wait4data(%s)",
1336 pp->printer, (unsigned long)amtslept, dfile);
1339 #undef MAXWAIT_ARRIVE
1340 #undef MAXWAIT_4DATA
1341 #undef MINWAIT_4DATA
1344 * This routine is called to execute one of the filters as was
1345 * specified in a printcap entry. While the child-process will read
1346 * all of 'infd', it is up to the caller to close that file descriptor
1347 * in the parent process.
1350 execfilter(struct printer *pp, char *f_cmd, char *f_av[], int infd, int outfd)
1353 int errfd, retcode, wstatus;
1355 char buf[BUFSIZ], *slash;
1357 fpid = dofork(pp, DORETURN);
1360 * This is the parent process, which just waits for the child
1361 * to complete and then returns the result. Note that it is
1362 * the child process which reads the input stream.
1367 while ((wpid = wait(&wstatus)) > 0 &&
1373 "%s: after execv(%s), wait() returned: %m",
1374 pp->printer, f_cmd);
1376 retcode = WEXITSTATUS(wstatus);
1380 * Copy everything the filter wrote to stderr from our
1381 * temporary errors file to the "lf=" logfile.
1383 errfp = fopen(tempstderr, "r");
1385 while (fgets(buf, sizeof(buf), errfp))
1394 * This is the child process, which is the one that executes the
1398 * If the first parameter has any slashes in it, then change it
1399 * to point to the first character after the last slash.
1401 slash = strrchr(f_av[0], '/');
1403 f_av[0] = slash + 1;
1405 * XXX - in the future, this should setup an explicit list of
1406 * environment variables and use execve()!
1410 * Setup stdin, stdout, and stderr as we want them when the filter
1411 * is running. Stderr is setup so it points to a temporary errors
1412 * file, and the parent process will copy that temporary file to
1413 * the real logfile after the filter completes.
1415 dup2(infd, STDIN_FILENO);
1416 dup2(outfd, STDOUT_FILENO);
1417 errfd = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
1419 dup2(errfd, STDERR_FILENO);
1423 syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer, f_cmd);
1429 * Check to make sure there have been no errors and that both programs
1430 * are in sync with eachother.
1431 * Return non-zero if the connection was lost.
1434 response(const struct printer *pp)
1438 if (read(pfd, &resp, 1) != 1) {
1439 syslog(LOG_INFO, "%s: lost connection", pp->printer);
1446 * Banner printing stuff
1449 banner(struct printer *pp, char *name1, char *name2)
1454 if (!pp->no_formfeed && !pp->tof)
1455 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1456 if (pp->short_banner) { /* short banner only */
1458 (void) write(ofd, class, strlen(class));
1459 (void) write(ofd, ":", 1);
1461 (void) write(ofd, name1, strlen(name1));
1462 (void) write(ofd, " Job: ", 7);
1463 (void) write(ofd, name2, strlen(name2));
1464 (void) write(ofd, " Date: ", 8);
1465 (void) write(ofd, ctime(&tvec), 24);
1466 (void) write(ofd, "\n", 1);
1467 } else { /* normal banner */
1468 (void) write(ofd, "\n\n\n", 3);
1469 scan_out(pp, ofd, name1, '\0');
1470 (void) write(ofd, "\n\n", 2);
1471 scan_out(pp, ofd, name2, '\0');
1473 (void) write(ofd,"\n\n\n",3);
1474 scan_out(pp, ofd, class, '\0');
1476 (void) write(ofd, "\n\n\n\n\t\t\t\t\tJob: ", 15);
1477 (void) write(ofd, name2, strlen(name2));
1478 (void) write(ofd, "\n\t\t\t\t\tDate: ", 12);
1479 (void) write(ofd, ctime(&tvec), 24);
1480 (void) write(ofd, "\n", 1);
1482 if (!pp->no_formfeed)
1483 (void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1488 scnline(int key, char *p, int c)
1490 register int scnwidth;
1492 for (scnwidth = WIDTH; --scnwidth;) {
1494 *p++ = key & 0200 ? c : BACKGND;
1499 #define TRC(q) (((q)-' ')&0177)
1502 scan_out(struct printer *pp, int scfd, char *scsp, int dlm)
1504 register char *strp;
1505 register int nchrs, j;
1506 char outbuf[LINELEN+1], *sp, c, cc;
1509 for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) {
1512 for (nchrs = 0; ; ) {
1513 d = dropit(c = TRC(cc = *sp++));
1514 if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d))
1515 for (j = WIDTH; --j;)
1518 strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc);
1519 if (*sp == dlm || *sp == '\0' ||
1520 nchrs++ >= pp->page_width/(WIDTH+1)-1)
1525 while (*--strp == BACKGND && strp >= outbuf)
1529 (void) write(scfd, outbuf, strp-outbuf);
1555 * tell people about job completion
1558 sendmail(struct printer *pp, char *userid, int bombed)
1562 register const char *cp;
1567 if ((s = dofork(pp, DORETURN)) == 0) { /* child */
1568 dup2(p[0], STDIN_FILENO);
1571 if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL)
1574 cp = _PATH_SENDMAIL;
1575 execl(_PATH_SENDMAIL, cp, "-t", (char *)0);
1577 } else if (s > 0) { /* parent */
1578 dup2(p[1], STDOUT_FILENO);
1579 printf("To: %s@%s\n", userid, origin_host);
1580 printf("Subject: %s printer job \"%s\"\n", pp->printer,
1581 *jobname ? jobname : "<unknown>");
1582 printf("Reply-To: root@%s\n\n", local_host);
1583 printf("Your printer job ");
1585 printf("(%s) ", jobname);
1590 printf("\ncompleted successfully\n");
1595 printf("\ncould not be printed\n");
1599 printf("\ncould not be printed without an account on %s\n",
1604 if (stat(tempstderr, &stb) < 0 || stb.st_size == 0
1605 || (fp = fopen(tempstderr, "r")) == NULL) {
1606 printf("\nhad some errors and may not have printed\n");
1609 printf("\nhad the following errors and may not have printed:\n");
1610 while ((i = getc(fp)) != EOF)
1616 printf("\nwas not printed because it was not linked to the original file\n");
1619 (void) close(STDOUT_FILENO);
1621 syslog(LOG_WARNING, "unable to send mail to %s: %m", userid);
1627 syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)",
1628 userid, *jobname ? jobname : "<unknown>", pp->printer, cp);
1632 * dofork - fork with retries on failure
1635 dofork(const struct printer *pp, int action)
1642 if (daemon_uname == NULL) {
1643 pwd = getpwuid(pp->daemon_user);
1645 syslog(LOG_ERR, "%s: Can't lookup default daemon uid (%ld) in password file",
1646 pp->printer, pp->daemon_user);
1649 daemon_uname = strdup(pwd->pw_name);
1650 daemon_defgid = pwd->pw_gid;
1653 for (i = 0; i < 20; i++) {
1656 sleep((unsigned)(i*i));
1660 * Child should run as daemon instead of root
1664 fail = initgroups(daemon_uname, daemon_defgid);
1666 syslog(LOG_ERR, "%s: initgroups(%s,%u): %m",
1667 pp->printer, daemon_uname, daemon_defgid);
1670 fail = setgid(daemon_defgid);
1672 syslog(LOG_ERR, "%s: setgid(%u): %m",
1673 pp->printer, daemon_defgid);
1676 fail = setuid(pp->daemon_user);
1678 syslog(LOG_ERR, "%s: setuid(%ld): %m",
1679 pp->printer, pp->daemon_user);
1687 * An error occurred. If the error is in the child process, then
1688 * this routine MUST always exit(). DORETURN only effects how
1689 * errors should be handled in the parent process.
1693 syslog(LOG_ERR, "%s: dofork(): aborting child process...",
1697 syslog(LOG_ERR, "%s: dofork(): failure in fork", pp->printer);
1699 sleep(1); /* throttle errors, as a safety measure */
1704 syslog(LOG_ERR, "bad action (%d) to dofork", action);
1713 * Kill child processes to abort current job.
1716 abortpr(int signo __unused)
1719 (void) unlink(tempstderr);
1722 kill(of_pid, SIGCONT);
1723 while (wait(NULL) > 0)
1725 if (of_pid > 0 && tfd != -1)
1731 init(struct printer *pp)
1735 sprintf(&width[2], "%ld", pp->page_width);
1736 sprintf(&length[2], "%ld", pp->page_length);
1737 sprintf(&pxwidth[2], "%ld", pp->page_pwidth);
1738 sprintf(&pxlength[2], "%ld", pp->page_plength);
1739 if ((s = checkremote(pp)) != 0) {
1740 syslog(LOG_WARNING, "%s", s);
1746 startprinting(const char *printer)
1748 struct printer myprinter, *pp = &myprinter;
1752 status = getprintcap(printer, pp);
1755 syslog(LOG_ERR, "can't open printer description file: %m");
1757 case PCAPERR_NOTFOUND:
1758 syslog(LOG_ERR, "unknown printer: %s", printer);
1760 case PCAPERR_TCLOOP:
1761 fatal(pp, "potential reference loop detected in printcap file");
1769 * Acquire line printer or remote connection.
1772 openpr(const struct printer *pp)
1780 * Lpd does support the setting of 'of=' filters for
1781 * jobs going to remote machines, but that does not
1782 * have the same meaning as 'of=' does when handling
1783 * local print queues. For remote machines, all 'of='
1784 * filter processing is handled in sendfile(), and that
1785 * does not use these global "output filter" variables.
1790 } else if (*pp->lp) {
1791 if ((cp = strchr(pp->lp, '@')) != NULL)
1796 syslog(LOG_ERR, "%s: no line printer device or host name",
1802 * Start up an output filter, if needed.
1804 if (pp->filters[LPF_OUTPUT] && !pp->filters[LPF_INPUT] && !of_pid) {
1807 strcpy(tfile, TFILENAME);
1808 tfd = mkstemp(tfile);
1810 if ((of_pid = dofork(pp, DOABORT)) == 0) { /* child */
1811 dup2(p[0], STDIN_FILENO); /* pipe is std in */
1812 /* tfile/printer is stdout */
1813 dup2(pp->remote ? tfd : pfd, STDOUT_FILENO);
1816 if ((cp = strrchr(pp->filters[LPF_OUTPUT], '/')) == NULL)
1817 cp = pp->filters[LPF_OUTPUT];
1820 execl(pp->filters[LPF_OUTPUT], cp, width, length,
1822 syslog(LOG_ERR, "%s: execl(%s): %m", pp->printer,
1823 pp->filters[LPF_OUTPUT]);
1826 (void) close(p[0]); /* close input side */
1827 ofd = p[1]; /* use pipe for output */
1835 * Printer connected directly to the network
1836 * or to a terminal server on the net
1839 opennet(const struct printer *pp)
1845 void (*savealrm)(int);
1847 port = strtoul(pp->lp, &ep, 0);
1848 if (*ep != '@' || port > 65535) {
1849 syslog(LOG_ERR, "%s: bad port number: %s", pp->printer,
1855 for (i = 1; ; i = i < 256 ? i << 1 : i) {
1857 savealrm = signal(SIGALRM, alarmhandler);
1858 alarm(pp->conn_timeout);
1859 pfd = getport(pp, ep, port);
1861 (void)signal(SIGALRM, savealrm);
1862 if (pfd < 0 && errno == ECONNREFUSED)
1864 else if (pfd >= 0) {
1866 * need to delay a bit for rs232 lines
1867 * to stabilize in case printer is
1868 * connected via a terminal server
1875 pstatus(pp, "waiting for %s to come up",
1879 "waiting for access to printer on %s",
1884 pstatus(pp, "sending to %s port %lu", ep, port);
1888 * Printer is connected to an RS232 port on this host
1891 opentty(const struct printer *pp)
1895 for (i = 1; ; i = i < 32 ? i << 1 : i) {
1896 pfd = open(pp->lp, pp->rw ? O_RDWR : O_WRONLY);
1901 if (errno == ENOENT) {
1902 syslog(LOG_ERR, "%s: %m", pp->lp);
1907 "waiting for %s to become ready (offline?)",
1913 pstatus(pp, "%s is ready and printing", pp->printer);
1917 * Printer is on a remote host
1920 openrem(const struct printer *pp)
1924 void (*savealrm)(int);
1926 for (i = 1; ; i = i < 256 ? i << 1 : i) {
1928 savealrm = signal(SIGALRM, alarmhandler);
1929 alarm(pp->conn_timeout);
1930 pfd = getport(pp, pp->remote_host, 0);
1932 (void)signal(SIGALRM, savealrm);
1934 if ((writel(pfd, "\2", pp->remote_queue, "\n",
1936 == 2 + strlen(pp->remote_queue))
1937 && (resp = response(pp)) == 0)
1943 pstatus(pp, "waiting for %s to come up",
1947 "waiting for queue to be enabled on %s",
1954 pstatus(pp, "sending to %s", pp->remote_host);
1961 setty(const struct printer *pp)
1963 struct termios ttybuf;
1965 if (ioctl(pfd, TIOCEXCL, (char *)0) < 0) {
1966 syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", pp->printer);
1969 if (tcgetattr(pfd, &ttybuf) < 0) {
1970 syslog(LOG_ERR, "%s: tcgetattr: %m", pp->printer);
1973 if (pp->baud_rate > 0)
1974 cfsetspeed(&ttybuf, pp->baud_rate);
1976 char *s = strdup(pp->mode_set), *tmp;
1978 while ((tmp = strsep(&s, ",")) != NULL) {
1979 (void) msearch(tmp, &ttybuf);
1982 if (pp->mode_set != 0 || pp->baud_rate > 0) {
1983 if (tcsetattr(pfd, TCSAFLUSH, &ttybuf) == -1) {
1984 syslog(LOG_ERR, "%s: tcsetattr: %m", pp->printer);
1992 pstatus(const struct printer *pp, const char *msg, ...)
2000 fd = open(pp->status_file, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
2002 syslog(LOG_ERR, "%s: open(%s): %m", pp->printer,
2007 vasprintf(&buf, msg, ap);
2009 writel(fd, buf, "\n", (char *)0);
2015 alarmhandler(int signo __unused)
2017 /* the signal is ignored */
2018 /* (the '__unused' is just to avoid a compile-time warning) */