printjob.c revision 94032
11553Srgrimes/*
21553Srgrimes * Copyright (c) 1983, 1993
31553Srgrimes *	The Regents of the University of California.  All rights reserved.
41553Srgrimes *
51553Srgrimes *
61553Srgrimes * Redistribution and use in source and binary forms, with or without
71553Srgrimes * modification, are permitted provided that the following conditions
81553Srgrimes * are met:
91553Srgrimes * 1. Redistributions of source code must retain the above copyright
101553Srgrimes *    notice, this list of conditions and the following disclaimer.
111553Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121553Srgrimes *    notice, this list of conditions and the following disclaimer in the
131553Srgrimes *    documentation and/or other materials provided with the distribution.
141553Srgrimes * 3. All advertising materials mentioning features or use of this software
151553Srgrimes *    must display the following acknowledgement:
161553Srgrimes *	This product includes software developed by the University of
171553Srgrimes *	California, Berkeley and its contributors.
181553Srgrimes * 4. Neither the name of the University nor the names of its contributors
191553Srgrimes *    may be used to endorse or promote products derived from this software
201553Srgrimes *    without specific prior written permission.
211553Srgrimes *
221553Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
231553Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
241553Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
251553Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
261553Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
271553Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
281553Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
291553Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
301553Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
311553Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
321553Srgrimes * SUCH DAMAGE.
331553Srgrimes */
341553Srgrimes
351553Srgrimes#ifndef lint
3631492Swollmanstatic const char copyright[] =
371553Srgrimes"@(#) Copyright (c) 1983, 1993\n\
381553Srgrimes	The Regents of the University of California.  All rights reserved.\n";
391553Srgrimes#endif /* not lint */
401553Srgrimes
411553Srgrimes#ifndef lint
4231492Swollman/*
4315648Sjoergstatic char sccsid[] = "@(#)printjob.c	8.7 (Berkeley) 5/10/95";
4431492Swollman*/
4531492Swollmanstatic const char rcsid[] =
4650479Speter  "$FreeBSD: head/usr.sbin/lpr/lpd/printjob.c 94032 2002-04-07 05:37:27Z gad $";
471553Srgrimes#endif /* not lint */
481553Srgrimes
491553Srgrimes
501553Srgrimes/*
511553Srgrimes * printjob -- print jobs in the queue.
521553Srgrimes *
531553Srgrimes *	NOTE: the lock file is used to pass information to lpq and lprm.
541553Srgrimes *	it does not need to be removed because file locks are dynamic.
551553Srgrimes */
561553Srgrimes
571553Srgrimes#include <sys/param.h>
581553Srgrimes#include <sys/wait.h>
591553Srgrimes#include <sys/stat.h>
601553Srgrimes#include <sys/types.h>
611553Srgrimes
621553Srgrimes#include <pwd.h>
631553Srgrimes#include <unistd.h>
641553Srgrimes#include <signal.h>
651553Srgrimes#include <syslog.h>
661553Srgrimes#include <fcntl.h>
671553Srgrimes#include <dirent.h>
681553Srgrimes#include <errno.h>
691553Srgrimes#include <stdio.h>
701553Srgrimes#include <string.h>
711553Srgrimes#include <stdlib.h>
7215032Ssef#include <sys/ioctl.h>
7315032Ssef#include <termios.h>
7415703Sjoerg#include <time.h>
751553Srgrimes#include "lp.h"
761553Srgrimes#include "lp.local.h"
771553Srgrimes#include "pathnames.h"
781553Srgrimes#include "extern.h"
791553Srgrimes
8080230Sgad#define DORETURN	0	/* dofork should return "can't fork" error */
8180230Sgad#define DOABORT		1	/* dofork should just die if fork() fails */
821553Srgrimes
831553Srgrimes/*
841553Srgrimes * Error tokens
851553Srgrimes */
861553Srgrimes#define REPRINT		-2
871553Srgrimes#define ERROR		-1
881553Srgrimes#define	OK		0
891553Srgrimes#define	FATALERR	1
901553Srgrimes#define	NOACCT		2
911553Srgrimes#define	FILTERERR	3
921553Srgrimes#define	ACCESS		4
931553Srgrimes
941553Srgrimesstatic dev_t	 fdev;		/* device of file pointed to by symlink */
951553Srgrimesstatic ino_t	 fino;		/* inode of file pointed to by symlink */
961553Srgrimesstatic FILE	*cfp;		/* control file */
971553Srgrimesstatic int	 child;		/* id of any filters */
9868253Sgadstatic int	 job_dfcnt;	/* count of datafiles in current user job */
991553Srgrimesstatic int	 lfd;		/* lock file descriptor */
1001553Srgrimesstatic int	 ofd;		/* output filter file descriptor */
1011553Srgrimesstatic int	 ofilter;	/* id of output filter, if any */
10224831Sbrianstatic int	 tfd = -1;	/* output filter temp file output */
1031553Srgrimesstatic int	 pfd;		/* prstatic inter file descriptor */
1041553Srgrimesstatic int	 pid;		/* pid of lpd process */
1051553Srgrimesstatic int	 prchild;	/* id of pr process */
1061553Srgrimesstatic char	 title[80];	/* ``pr'' title */
10753956Sachestatic char      locale[80];    /* ``pr'' locale */
1081553Srgrimes
10980230Sgad/* these two are set from pp->daemon_user, but only if they are needed */
11080230Sgadstatic char	*daemon_uname;	/* set from pwd->pw_name */
11180230Sgadstatic int	 daemon_defgid;
11280230Sgad
1131553Srgrimesstatic char	class[32];		/* classification field */
11478300Sgadstatic char	origin_host[MAXHOSTNAMELEN];	/* user's host machine */
1151553Srgrimes				/* indentation size in static characters */
1168857Srgrimesstatic char	indent[10] = "-i0";
1171553Srgrimesstatic char	jobname[100];		/* job or file name */
1181553Srgrimesstatic char	length[10] = "-l";	/* page length in lines */
1191553Srgrimesstatic char	logname[32];		/* user's login name */
1201553Srgrimesstatic char	pxlength[10] = "-y";	/* page length in pixels */
1211553Srgrimesstatic char	pxwidth[10] = "-x";	/* page width in pixels */
12268664Sgad/* tempstderr is the filename used to catch stderr from exec-ing filters */
12368664Sgadstatic char	tempstderr[] = "errs.XXXXXXX";
1241553Srgrimesstatic char	width[10] = "-w";	/* page width in static characters */
12524831Sbrian#define TFILENAME "fltXXXXXX"
12624831Sbrianstatic char	tfile[] = TFILENAME;	/* file name for filter output */
1271553Srgrimes
12878146Sgadstatic void	 abortpr(int _signo);
12978146Sgadstatic void	 alarmhandler(int _signo);
13078146Sgadstatic void	 banner(struct printer *_pp, char *_name1, char *_name2);
13178146Sgadstatic int	 dofork(const struct printer *_pp, int _action);
13278146Sgadstatic int	 dropit(int _c);
13394032Sgadstatic int	 execfilter(struct printer *_pp, char *_f_cmd, char **_f_av,
13494032Sgad		    int _infd, int _outfd);
13578146Sgadstatic void	 init(struct printer *_pp);
13678146Sgadstatic void	 openpr(const struct printer *_pp);
13778146Sgadstatic void	 opennet(const struct printer *_pp);
13878146Sgadstatic void	 opentty(const struct printer *_pp);
13978146Sgadstatic void	 openrem(const struct printer *pp);
14078146Sgadstatic int	 print(struct printer *_pp, int _format, char *_file);
14178146Sgadstatic int	 printit(struct printer *_pp, char *_file);
14279739Sgadstatic void	 pstatus(const struct printer *_pp, const char *_msg, ...)
14379739Sgad		    __printflike(2, 3);
14478146Sgadstatic char	 response(const struct printer *_pp);
14578146Sgadstatic void	 scan_out(struct printer *_pp, int _scfd, char *_scsp,
14678146Sgad		    int _dlm);
14778146Sgadstatic char	*scnline(int _key, char *_p, int _c);
14878146Sgadstatic int	 sendfile(struct printer *_pp, int _type, char *_file,
14978146Sgad		    char _format);
15078146Sgadstatic int	 sendit(struct printer *_pp, char *_file);
15178146Sgadstatic void	 sendmail(struct printer *_pp, char *_user, int _bombed);
15278146Sgadstatic void	 setty(const struct printer *_pp);
1531553Srgrimes
1541553Srgrimesvoid
15578146Sgadprintjob(struct printer *pp)
1561553Srgrimes{
1571553Srgrimes	struct stat stb;
15868401Sgad	register struct jobqueue *q, **qp;
15968401Sgad	struct jobqueue **queue;
1601553Srgrimes	register int i, nitems;
16168733Sgad	off_t pidoff;
16268733Sgad	int errcnt, jobcount, tempfd;
1631553Srgrimes
16468733Sgad	jobcount = 0;
16531492Swollman	init(pp); /* set up capabilities */
16631492Swollman	(void) write(1, "", 1);	/* ack that daemon is started */
1671553Srgrimes	(void) close(2);			/* set up log file */
16831492Swollman	if (open(pp->log_file, O_WRONLY|O_APPEND, LOG_FILE_MODE) < 0) {
16931492Swollman		syslog(LOG_ERR, "%s: %m", pp->log_file);
1701553Srgrimes		(void) open(_PATH_DEVNULL, O_WRONLY);
1711553Srgrimes	}
1721553Srgrimes	setgid(getegid());
1731553Srgrimes	pid = getpid();				/* for use with lprm */
1741553Srgrimes	setpgrp(0, pid);
17579735Sgad
17679735Sgad	/*
17779735Sgad	 * At initial lpd startup, printjob may be called with various
17879735Sgad	 * signal handlers in effect.  After that initial startup, any
17979735Sgad	 * calls to printjob will have a *different* set of signal-handlers
18079735Sgad	 * in effect.  Make sure all handlers are the ones we want.
18179735Sgad	 */
18279735Sgad	signal(SIGCHLD, SIG_DFL);
1831553Srgrimes	signal(SIGHUP, abortpr);
1841553Srgrimes	signal(SIGINT, abortpr);
1851553Srgrimes	signal(SIGQUIT, abortpr);
1861553Srgrimes	signal(SIGTERM, abortpr);
1871553Srgrimes
1881553Srgrimes	/*
1891553Srgrimes	 * uses short form file names
1901553Srgrimes	 */
19131492Swollman	if (chdir(pp->spool_dir) < 0) {
19231492Swollman		syslog(LOG_ERR, "%s: %m", pp->spool_dir);
1931553Srgrimes		exit(1);
1941553Srgrimes	}
19531492Swollman	if (stat(pp->lock_file, &stb) == 0 && (stb.st_mode & LFM_PRINT_DIS))
1961553Srgrimes		exit(0);		/* printing disabled */
19731492Swollman	lfd = open(pp->lock_file, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
19831492Swollman		   LOCK_FILE_MODE);
1991553Srgrimes	if (lfd < 0) {
20031492Swollman		if (errno == EWOULDBLOCK)	/* active daemon present */
20131492Swollman			exit(0);
20231492Swollman		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
2031553Srgrimes		exit(1);
2041553Srgrimes	}
20531492Swollman	/* turn off non-blocking mode (was turned on for lock effects only) */
20631492Swollman	if (fcntl(lfd, F_SETFL, 0) < 0) {
20731492Swollman		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
2081553Srgrimes		exit(1);
2091553Srgrimes	}
2101553Srgrimes	ftruncate(lfd, 0);
2111553Srgrimes	/*
2121553Srgrimes	 * write process id for others to know
2131553Srgrimes	 */
2141553Srgrimes	sprintf(line, "%u\n", pid);
2151553Srgrimes	pidoff = i = strlen(line);
2161553Srgrimes	if (write(lfd, line, i) != i) {
21731492Swollman		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
2181553Srgrimes		exit(1);
2191553Srgrimes	}
2201553Srgrimes	/*
2211553Srgrimes	 * search the spool directory for work and sort by queue order.
2221553Srgrimes	 */
22331492Swollman	if ((nitems = getq(pp, &queue)) < 0) {
22431492Swollman		syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
22531492Swollman		       pp->spool_dir);
2261553Srgrimes		exit(1);
2271553Srgrimes	}
2281553Srgrimes	if (nitems == 0)		/* no work to do */
2291553Srgrimes		exit(0);
23031492Swollman	if (stb.st_mode & LFM_RESET_QUE) { /* reset queue flag */
23131492Swollman		if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE) < 0)
23231492Swollman			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
23331492Swollman			       pp->lock_file);
2341553Srgrimes	}
23568664Sgad
23668664Sgad	/* create a file which will be used to hold stderr from filters */
23768664Sgad	if ((tempfd = mkstemp(tempstderr)) == -1) {
23868664Sgad		syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
23968664Sgad		       tempstderr);
24068732Sgad		exit(1);
24168664Sgad	}
24268664Sgad	if ((i = fchmod(tempfd, 0664)) == -1) {
24368664Sgad		syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
24468664Sgad		       tempstderr);
24568732Sgad		exit(1);
24668664Sgad	}
24768664Sgad	/* lpd doesn't need it to be open, it just needs it to exist */
24868664Sgad	close(tempfd);
24968664Sgad
25031492Swollman	openpr(pp);			/* open printer or remote */
2511553Srgrimesagain:
2521553Srgrimes	/*
2531553Srgrimes	 * we found something to do now do it --
2541553Srgrimes	 *    write the name of the current control file into the lock file
2551553Srgrimes	 *    so the spool queue program can tell what we're working on
2561553Srgrimes	 */
2571553Srgrimes	for (qp = queue; nitems--; free((char *) q)) {
2581553Srgrimes		q = *qp++;
25968401Sgad		if (stat(q->job_cfname, &stb) < 0)
2601553Srgrimes			continue;
26115648Sjoerg		errcnt = 0;
2621553Srgrimes	restart:
26315648Sjoerg		(void) lseek(lfd, pidoff, 0);
26468401Sgad		(void) snprintf(line, sizeof(line), "%s\n", q->job_cfname);
2651553Srgrimes		i = strlen(line);
2661553Srgrimes		if (write(lfd, line, i) != i)
26731492Swollman			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
26831492Swollman			       pp->lock_file);
26931492Swollman		if (!pp->remote)
27068401Sgad			i = printit(pp, q->job_cfname);
2711553Srgrimes		else
27268401Sgad			i = sendit(pp, q->job_cfname);
2731553Srgrimes		/*
2741553Srgrimes		 * Check to see if we are supposed to stop printing or
2751553Srgrimes		 * if we are to rebuild the queue.
2761553Srgrimes		 */
2771553Srgrimes		if (fstat(lfd, &stb) == 0) {
2781553Srgrimes			/* stop printing before starting next job? */
27931492Swollman			if (stb.st_mode & LFM_PRINT_DIS)
2801553Srgrimes				goto done;
2811553Srgrimes			/* rebuild queue (after lpc topq) */
28231492Swollman			if (stb.st_mode & LFM_RESET_QUE) {
28331492Swollman				for (free(q); nitems--; free(q))
2841553Srgrimes					q = *qp++;
28531492Swollman				if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE)
28631492Swollman				    < 0)
2871553Srgrimes					syslog(LOG_WARNING, "%s: %s: %m",
28831492Swollman					       pp->printer, pp->lock_file);
2891553Srgrimes				break;
2901553Srgrimes			}
2911553Srgrimes		}
29268733Sgad		if (i == OK)		/* all files of this job printed */
29368733Sgad			jobcount++;
29415648Sjoerg		else if (i == REPRINT && ++errcnt < 5) {
29515648Sjoerg			/* try reprinting the job */
29631492Swollman			syslog(LOG_INFO, "restarting %s", pp->printer);
2971553Srgrimes			if (ofilter > 0) {
2981553Srgrimes				kill(ofilter, SIGCONT);	/* to be sure */
2991553Srgrimes				(void) close(ofd);
30015648Sjoerg				while ((i = wait(NULL)) > 0 && i != ofilter)
3011553Srgrimes					;
30279735Sgad				if (i < 0)
30379735Sgad					syslog(LOG_WARNING, "%s: after kill(of=%d), wait() returned: %m",
30479735Sgad					    pp->printer, ofilter);
3051553Srgrimes				ofilter = 0;
3061553Srgrimes			}
3071553Srgrimes			(void) close(pfd);	/* close printer */
3081553Srgrimes			if (ftruncate(lfd, pidoff) < 0)
30931492Swollman				syslog(LOG_WARNING, "%s: %s: %m",
31031492Swollman				       pp->printer, pp->lock_file);
31131492Swollman			openpr(pp);		/* try to reopen printer */
3121553Srgrimes			goto restart;
31315648Sjoerg		} else {
31431492Swollman			syslog(LOG_WARNING, "%s: job could not be %s (%s)",
31531492Swollman			       pp->printer,
31631492Swollman			       pp->remote ? "sent to remote host" : "printed",
31768401Sgad			       q->job_cfname);
31815648Sjoerg			if (i == REPRINT) {
31927748Simp				/* ensure we don't attempt this job again */
32068401Sgad				(void) unlink(q->job_cfname);
32168401Sgad				q->job_cfname[0] = 'd';
32268401Sgad				(void) unlink(q->job_cfname);
32315648Sjoerg				if (logname[0])
32431492Swollman					sendmail(pp, logname, FATALERR);
32515648Sjoerg			}
3261553Srgrimes		}
3271553Srgrimes	}
32831492Swollman	free(queue);
3291553Srgrimes	/*
3301553Srgrimes	 * search the spool directory for more work.
3311553Srgrimes	 */
33231492Swollman	if ((nitems = getq(pp, &queue)) < 0) {
33331492Swollman		syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
33431492Swollman		       pp->spool_dir);
3351553Srgrimes		exit(1);
3361553Srgrimes	}
3371553Srgrimes	if (nitems == 0) {		/* no more work to do */
3381553Srgrimes	done:
33968733Sgad		if (jobcount > 0) {	/* jobs actually printed */
34031492Swollman			if (!pp->no_formfeed && !pp->tof)
34131492Swollman				(void) write(ofd, pp->form_feed,
34231492Swollman					     strlen(pp->form_feed));
34331492Swollman			if (pp->trailer != NULL) /* output trailer */
34431492Swollman				(void) write(ofd, pp->trailer,
34531492Swollman					     strlen(pp->trailer));
3461553Srgrimes		}
34719202Simp		(void) close(ofd);
34819202Simp		(void) wait(NULL);
34968664Sgad		(void) unlink(tempstderr);
3501553Srgrimes		exit(0);
3511553Srgrimes	}
3521553Srgrimes	goto again;
3531553Srgrimes}
3541553Srgrimes
3551553Srgrimeschar	fonts[4][50];	/* fonts for troff */
3561553Srgrimes
3571553Srgrimeschar ifonts[4][40] = {
3581553Srgrimes	_PATH_VFONTR,
3591553Srgrimes	_PATH_VFONTI,
3601553Srgrimes	_PATH_VFONTB,
3611553Srgrimes	_PATH_VFONTS,
3621553Srgrimes};
3631553Srgrimes
3641553Srgrimes/*
3651553Srgrimes * The remaining part is the reading of the control file (cf)
3661553Srgrimes * and performing the various actions.
3671553Srgrimes */
3681553Srgrimesstatic int
36978146Sgadprintit(struct printer *pp, char *file)
3701553Srgrimes{
3711553Srgrimes	register int i;
37268734Sgad	char *cp;
37368734Sgad	int bombed, didignorehdr;
3741553Srgrimes
37568734Sgad	bombed = OK;
37668734Sgad	didignorehdr = 0;
3771553Srgrimes	/*
3781553Srgrimes	 * open control file; ignore if no longer there.
3791553Srgrimes	 */
3801553Srgrimes	if ((cfp = fopen(file, "r")) == NULL) {
38131492Swollman		syslog(LOG_INFO, "%s: %s: %m", pp->printer, file);
3821553Srgrimes		return(OK);
3831553Srgrimes	}
3841553Srgrimes	/*
3851553Srgrimes	 * Reset troff fonts.
3861553Srgrimes	 */
3871553Srgrimes	for (i = 0; i < 4; i++)
3881553Srgrimes		strcpy(fonts[i], ifonts[i]);
38931492Swollman	sprintf(&width[2], "%ld", pp->page_width);
3901553Srgrimes	strcpy(indent+2, "0");
3911553Srgrimes
39268253Sgad	/* initialize job-specific count of datafiles processed */
39368253Sgad	job_dfcnt = 0;
39468253Sgad
3951553Srgrimes	/*
3961553Srgrimes	 *      read the control file for work to do
3971553Srgrimes	 *
3981553Srgrimes	 *      file format -- first character in the line is a command
3991553Srgrimes	 *      rest of the line is the argument.
4001553Srgrimes	 *      valid commands are:
4011553Srgrimes	 *
4021553Srgrimes	 *		S -- "stat info" for symbolic link protection
4031553Srgrimes	 *		J -- "job name" on banner page
4041553Srgrimes	 *		C -- "class name" on banner page
4051553Srgrimes	 *              L -- "literal" user's name to print on banner
4061553Srgrimes	 *		T -- "title" for pr
4071553Srgrimes	 *		H -- "host name" of machine where lpr was done
4081553Srgrimes	 *              P -- "person" user's login name
4091553Srgrimes	 *              I -- "indent" amount to indent output
41015648Sjoerg	 *		R -- laser dpi "resolution"
4111553Srgrimes	 *              f -- "file name" name of text file to print
4121553Srgrimes	 *		l -- "file name" text file with control chars
41383684Sgad	 *		o -- "file name" postscript file, according to
41483684Sgad	 *		     the RFC.  Here it is treated like an 'f'.
4151553Srgrimes	 *		p -- "file name" text file to print with pr(1)
4161553Srgrimes	 *		t -- "file name" troff(1) file to print
4171553Srgrimes	 *		n -- "file name" ditroff(1) file to print
4181553Srgrimes	 *		d -- "file name" dvi file to print
4191553Srgrimes	 *		g -- "file name" plot(1G) file to print
4201553Srgrimes	 *		v -- "file name" plain raster file to print
4211553Srgrimes	 *		c -- "file name" cifplot file to print
4221553Srgrimes	 *		1 -- "R font file" for troff
4231553Srgrimes	 *		2 -- "I font file" for troff
4241553Srgrimes	 *		3 -- "B font file" for troff
4251553Srgrimes	 *		4 -- "S font file" for troff
4261553Srgrimes	 *		N -- "name" of file (used by lpq)
4271553Srgrimes	 *              U -- "unlink" name of file to remove
4281553Srgrimes	 *                    (after we print it. (Pass 2 only)).
4291553Srgrimes	 *		M -- "mail" to user when done printing
43053956Sache	 *              Z -- "locale" for pr
4311553Srgrimes	 *
4321553Srgrimes	 *      getline reads a line and expands tabs to blanks
4331553Srgrimes	 */
4341553Srgrimes
4351553Srgrimes	/* pass 1 */
4361553Srgrimes
4371553Srgrimes	while (getline(cfp))
4381553Srgrimes		switch (line[0]) {
4391553Srgrimes		case 'H':
44078300Sgad			strlcpy(origin_host, line + 1, sizeof(origin_host));
44127748Simp			if (class[0] == '\0') {
44280133Sgad				strlcpy(class, line+1, sizeof(class));
44327748Simp			}
4441553Srgrimes			continue;
4451553Srgrimes
4461553Srgrimes		case 'P':
44780133Sgad			strlcpy(logname, line + 1, sizeof(logname));
44831492Swollman			if (pp->restricted) { /* restricted */
4491553Srgrimes				if (getpwnam(logname) == NULL) {
4501553Srgrimes					bombed = NOACCT;
45131492Swollman					sendmail(pp, line+1, bombed);
4521553Srgrimes					goto pass2;
4531553Srgrimes				}
4541553Srgrimes			}
4551553Srgrimes			continue;
4561553Srgrimes
4571553Srgrimes		case 'S':
4581553Srgrimes			cp = line+1;
4591553Srgrimes			i = 0;
4601553Srgrimes			while (*cp >= '0' && *cp <= '9')
4611553Srgrimes				i = i * 10 + (*cp++ - '0');
4621553Srgrimes			fdev = i;
4631553Srgrimes			cp++;
4641553Srgrimes			i = 0;
4651553Srgrimes			while (*cp >= '0' && *cp <= '9')
4661553Srgrimes				i = i * 10 + (*cp++ - '0');
4671553Srgrimes			fino = i;
4681553Srgrimes			continue;
4691553Srgrimes
4701553Srgrimes		case 'J':
47127748Simp			if (line[1] != '\0') {
47280133Sgad				strlcpy(jobname, line + 1, sizeof(jobname));
47327748Simp			} else
4741553Srgrimes				strcpy(jobname, " ");
4751553Srgrimes			continue;
4761553Srgrimes
4771553Srgrimes		case 'C':
4781553Srgrimes			if (line[1] != '\0')
47980133Sgad				strlcpy(class, line + 1, sizeof(class));
48080133Sgad			else if (class[0] == '\0') {
48180133Sgad				/* XXX - why call gethostname instead of
48280133Sgad				 *       just strlcpy'ing local_host? */
4831553Srgrimes				gethostname(class, sizeof(class));
48480133Sgad				class[sizeof(class) - 1] = '\0';
48580133Sgad			}
4861553Srgrimes			continue;
4871553Srgrimes
4881553Srgrimes		case 'T':	/* header title for pr */
48980133Sgad			strlcpy(title, line + 1, sizeof(title));
4901553Srgrimes			continue;
4911553Srgrimes
4921553Srgrimes		case 'L':	/* identification line */
49331492Swollman			if (!pp->no_header && !pp->header_last)
49431492Swollman				banner(pp, line+1, jobname);
4951553Srgrimes			continue;
4961553Srgrimes
4971553Srgrimes		case '1':	/* troff fonts */
4981553Srgrimes		case '2':
4991553Srgrimes		case '3':
5001553Srgrimes		case '4':
50127748Simp			if (line[1] != '\0') {
50280133Sgad				strlcpy(fonts[line[0]-'1'], line + 1,
50380133Sgad				    (size_t)50);
50427748Simp			}
5051553Srgrimes			continue;
5061553Srgrimes
5071553Srgrimes		case 'W':	/* page width */
50880133Sgad			strlcpy(width+2, line + 1, sizeof(width) - 2);
5091553Srgrimes			continue;
5101553Srgrimes
5111553Srgrimes		case 'I':	/* indent amount */
51280133Sgad			strlcpy(indent+2, line + 1, sizeof(indent) - 2);
5131553Srgrimes			continue;
5141553Srgrimes
51553956Sache		case 'Z':       /* locale for pr */
51680133Sgad			strlcpy(locale, line + 1, sizeof(locale));
51753956Sache			locale[sizeof(locale) - 1] = '\0';
51853956Sache			continue;
51953956Sache
5201553Srgrimes		default:	/* some file to print */
52168467Sgad			/* only lowercase cmd-codes include a file-to-print */
52268467Sgad			if ((line[0] < 'a') || (line[0] > 'z')) {
52368467Sgad				/* ignore any other lines */
52468467Sgad				if (lflag <= 1)
52568467Sgad					continue;
52668467Sgad				if (!didignorehdr) {
52768467Sgad					syslog(LOG_INFO, "%s: in %s :",
52868467Sgad					       pp->printer, file);
52968467Sgad					didignorehdr = 1;
53068467Sgad				}
53168467Sgad				syslog(LOG_INFO, "%s: ignoring line: '%c' %s",
53268467Sgad				       pp->printer, line[0], &line[1]);
53368467Sgad				continue;
53468467Sgad			}
53568467Sgad			i = print(pp, line[0], line+1);
53668467Sgad			switch (i) {
5371553Srgrimes			case ERROR:
5381553Srgrimes				if (bombed == OK)
5391553Srgrimes					bombed = FATALERR;
5401553Srgrimes				break;
5411553Srgrimes			case REPRINT:
5421553Srgrimes				(void) fclose(cfp);
5431553Srgrimes				return(REPRINT);
5441553Srgrimes			case FILTERERR:
5451553Srgrimes			case ACCESS:
5461553Srgrimes				bombed = i;
54731492Swollman				sendmail(pp, logname, bombed);
5481553Srgrimes			}
5491553Srgrimes			title[0] = '\0';
5501553Srgrimes			continue;
5511553Srgrimes
5521553Srgrimes		case 'N':
5531553Srgrimes		case 'U':
5541553Srgrimes		case 'M':
55515648Sjoerg		case 'R':
5561553Srgrimes			continue;
5571553Srgrimes		}
5581553Srgrimes
5591553Srgrimes	/* pass 2 */
5601553Srgrimes
5611553Srgrimespass2:
5621553Srgrimes	fseek(cfp, 0L, 0);
5631553Srgrimes	while (getline(cfp))
5641553Srgrimes		switch (line[0]) {
5651553Srgrimes		case 'L':	/* identification line */
56631492Swollman			if (!pp->no_header && pp->header_last)
56731492Swollman				banner(pp, line+1, jobname);
5681553Srgrimes			continue;
5691553Srgrimes
5701553Srgrimes		case 'M':
5711553Srgrimes			if (bombed < NOACCT)	/* already sent if >= NOACCT */
57231492Swollman				sendmail(pp, line+1, bombed);
5731553Srgrimes			continue;
5741553Srgrimes
5751553Srgrimes		case 'U':
57627748Simp			if (strchr(line+1, '/'))
57727748Simp				continue;
5781553Srgrimes			(void) unlink(line+1);
5791553Srgrimes		}
5801553Srgrimes	/*
5811553Srgrimes	 * clean-up in case another control file exists
5821553Srgrimes	 */
5831553Srgrimes	(void) fclose(cfp);
5841553Srgrimes	(void) unlink(file);
5851553Srgrimes	return(bombed == OK ? OK : ERROR);
5861553Srgrimes}
5871553Srgrimes
5881553Srgrimes/*
5891553Srgrimes * Print a file.
5901553Srgrimes * Set up the chain [ PR [ | {IF, OF} ] ] or {IF, RF, TF, NF, DF, CF, VF}.
5911553Srgrimes * Return -1 if a non-recoverable error occured,
5921553Srgrimes * 2 if the filter detected some errors (but printed the job anyway),
5931553Srgrimes * 1 if we should try to reprint this job and
5941553Srgrimes * 0 if all is well.
5951553Srgrimes * Note: all filters take stdin as the file, stdout as the printer,
5961553Srgrimes * stderr as the log file, and must not ignore SIGINT.
5971553Srgrimes */
5981553Srgrimesstatic int
59978146Sgadprint(struct printer *pp, int format, char *file)
6001553Srgrimes{
60153956Sache	register int n, i;
6021553Srgrimes	register char *prog;
60331492Swollman	int fi, fo;
6041553Srgrimes	FILE *fp;
6051553Srgrimes	char *av[15], buf[BUFSIZ];
60668734Sgad	int pid, p[2], stopped;
6071553Srgrimes	union wait status;
6081553Srgrimes	struct stat stb;
6091553Srgrimes
61068467Sgad	if (lstat(file, &stb) < 0 || (fi = open(file, O_RDONLY)) < 0) {
61168467Sgad		syslog(LOG_INFO, "%s: unable to open %s ('%c' line)",
61268467Sgad		       pp->printer, file, format);
6131553Srgrimes		return(ERROR);
61468467Sgad	}
6151553Srgrimes	/*
6161553Srgrimes	 * Check to see if data file is a symbolic link. If so, it should
6171553Srgrimes	 * still point to the same file or someone is trying to print
6181553Srgrimes	 * something he shouldn't.
6191553Srgrimes	 */
6201553Srgrimes	if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(fi, &stb) == 0 &&
6211553Srgrimes	    (stb.st_dev != fdev || stb.st_ino != fino))
6221553Srgrimes		return(ACCESS);
62368253Sgad
62468253Sgad	job_dfcnt++;		/* increment datafile counter for this job */
62568734Sgad	stopped = 0;		/* output filter is not stopped */
62668253Sgad
62768253Sgad	/* everything seems OK, start it up */
62831492Swollman	if (!pp->no_formfeed && !pp->tof) { /* start on a fresh page */
62931492Swollman		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
63031492Swollman		pp->tof = 1;
6311553Srgrimes	}
63231492Swollman	if (pp->filters[LPF_INPUT] == NULL
63383684Sgad	    && (format == 'f' || format == 'l' || format == 'o')) {
63431492Swollman		pp->tof = 0;
6351553Srgrimes		while ((n = read(fi, buf, BUFSIZ)) > 0)
6361553Srgrimes			if (write(ofd, buf, n) != n) {
6371553Srgrimes				(void) close(fi);
6381553Srgrimes				return(REPRINT);
6391553Srgrimes			}
6401553Srgrimes		(void) close(fi);
6411553Srgrimes		return(OK);
6421553Srgrimes	}
6431553Srgrimes	switch (format) {
6441553Srgrimes	case 'p':	/* print file using 'pr' */
64531492Swollman		if (pp->filters[LPF_INPUT] == NULL) {	/* use output filter */
6461553Srgrimes			prog = _PATH_PR;
64753956Sache			i = 0;
64853956Sache			av[i++] = "pr";
64953956Sache			av[i++] = width;
65053956Sache			av[i++] = length;
65153956Sache			av[i++] = "-h";
65253956Sache			av[i++] = *title ? title : " ";
65353956Sache			av[i++] = "-L";
65453956Sache			av[i++] = *locale ? locale : "C";
65553956Sache			av[i++] = "-F";
65653956Sache			av[i] = 0;
6571553Srgrimes			fo = ofd;
6581553Srgrimes			goto start;
6591553Srgrimes		}
6601553Srgrimes		pipe(p);
66131492Swollman		if ((prchild = dofork(pp, DORETURN)) == 0) {	/* child */
6621553Srgrimes			dup2(fi, 0);		/* file is stdin */
6631553Srgrimes			dup2(p[1], 1);		/* pipe is stdout */
6648094Sjkh			closelog();
66531492Swollman			closeallfds(3);
6661553Srgrimes			execl(_PATH_PR, "pr", width, length,
66753956Sache			    "-h", *title ? title : " ",
66853956Sache			    "-L", *locale ? locale : "C",
66979452Sbrian			    "-F", (char *)0);
6701553Srgrimes			syslog(LOG_ERR, "cannot execl %s", _PATH_PR);
6711553Srgrimes			exit(2);
6721553Srgrimes		}
6731553Srgrimes		(void) close(p[1]);		/* close output side */
6741553Srgrimes		(void) close(fi);
6751553Srgrimes		if (prchild < 0) {
6761553Srgrimes			prchild = 0;
6771553Srgrimes			(void) close(p[0]);
6781553Srgrimes			return(ERROR);
6791553Srgrimes		}
6801553Srgrimes		fi = p[0];			/* use pipe for input */
6811553Srgrimes	case 'f':	/* print plain text file */
68231492Swollman		prog = pp->filters[LPF_INPUT];
6831553Srgrimes		av[1] = width;
6841553Srgrimes		av[2] = length;
6851553Srgrimes		av[3] = indent;
6861553Srgrimes		n = 4;
6871553Srgrimes		break;
68886935Sgad	case 'o':	/* print postscript file */
68986935Sgad		/*
69086935Sgad		 * Treat this as a "plain file with control characters", and
69186935Sgad		 * assume the standard LPF_INPUT filter will recognize that
69286935Sgad		 * the data is postscript and know what to do with it.  These
69386935Sgad		 * 'o'-file requests could come from MacOS 10.1 systems.
69486935Sgad		 * (later versions of MacOS 10 will explicitly use 'l')
69586935Sgad		 * A postscript file can contain binary data, which is why 'l'
69686935Sgad		 * is somewhat more appropriate than 'f'.
69786935Sgad		 */
69886935Sgad		/* FALLTHROUGH */
6991553Srgrimes	case 'l':	/* like 'f' but pass control characters */
70031492Swollman		prog = pp->filters[LPF_INPUT];
7011553Srgrimes		av[1] = "-c";
7021553Srgrimes		av[2] = width;
7031553Srgrimes		av[3] = length;
7041553Srgrimes		av[4] = indent;
7051553Srgrimes		n = 5;
7061553Srgrimes		break;
7071553Srgrimes	case 'r':	/* print a fortran text file */
70831492Swollman		prog = pp->filters[LPF_FORTRAN];
7091553Srgrimes		av[1] = width;
7101553Srgrimes		av[2] = length;
7111553Srgrimes		n = 3;
7121553Srgrimes		break;
7131553Srgrimes	case 't':	/* print troff output */
7141553Srgrimes	case 'n':	/* print ditroff output */
7151553Srgrimes	case 'd':	/* print tex output */
7161553Srgrimes		(void) unlink(".railmag");
7171553Srgrimes		if ((fo = creat(".railmag", FILMOD)) < 0) {
71831492Swollman			syslog(LOG_ERR, "%s: cannot create .railmag",
71931492Swollman			       pp->printer);
7201553Srgrimes			(void) unlink(".railmag");
7211553Srgrimes		} else {
7221553Srgrimes			for (n = 0; n < 4; n++) {
7231553Srgrimes				if (fonts[n][0] != '/')
7241553Srgrimes					(void) write(fo, _PATH_VFONT,
7251553Srgrimes					    sizeof(_PATH_VFONT) - 1);
7261553Srgrimes				(void) write(fo, fonts[n], strlen(fonts[n]));
7271553Srgrimes				(void) write(fo, "\n", 1);
7281553Srgrimes			}
7291553Srgrimes			(void) close(fo);
7301553Srgrimes		}
73131492Swollman		prog = (format == 't') ? pp->filters[LPF_TROFF]
73231492Swollman			: ((format == 'n') ? pp->filters[LPF_DITROFF]
73331492Swollman			   : pp->filters[LPF_DVI]);
7341553Srgrimes		av[1] = pxwidth;
7351553Srgrimes		av[2] = pxlength;
7361553Srgrimes		n = 3;
7371553Srgrimes		break;
7381553Srgrimes	case 'c':	/* print cifplot output */
73931492Swollman		prog = pp->filters[LPF_CIFPLOT];
7401553Srgrimes		av[1] = pxwidth;
7411553Srgrimes		av[2] = pxlength;
7421553Srgrimes		n = 3;
7431553Srgrimes		break;
7441553Srgrimes	case 'g':	/* print plot(1G) output */
74531492Swollman		prog = pp->filters[LPF_GRAPH];
7461553Srgrimes		av[1] = pxwidth;
7471553Srgrimes		av[2] = pxlength;
7481553Srgrimes		n = 3;
7491553Srgrimes		break;
7501553Srgrimes	case 'v':	/* print raster output */
75131492Swollman		prog = pp->filters[LPF_RASTER];
7521553Srgrimes		av[1] = pxwidth;
7531553Srgrimes		av[2] = pxlength;
7541553Srgrimes		n = 3;
7551553Srgrimes		break;
7561553Srgrimes	default:
7571553Srgrimes		(void) close(fi);
7581553Srgrimes		syslog(LOG_ERR, "%s: illegal format character '%c'",
75931492Swollman			pp->printer, format);
7601553Srgrimes		return(ERROR);
7611553Srgrimes	}
76215648Sjoerg	if (prog == NULL) {
76315648Sjoerg		(void) close(fi);
76415648Sjoerg		syslog(LOG_ERR,
76515648Sjoerg		   "%s: no filter found in printcap for format character '%c'",
76631492Swollman		   pp->printer, format);
76715648Sjoerg		return(ERROR);
76815648Sjoerg	}
76927635Simp	if ((av[0] = strrchr(prog, '/')) != NULL)
7701553Srgrimes		av[0]++;
7711553Srgrimes	else
7721553Srgrimes		av[0] = prog;
7731553Srgrimes	av[n++] = "-n";
7741553Srgrimes	av[n++] = logname;
7751553Srgrimes	av[n++] = "-h";
77678300Sgad	av[n++] = origin_host;
77731492Swollman	av[n++] = pp->acct_file;
7781553Srgrimes	av[n] = 0;
7791553Srgrimes	fo = pfd;
7801553Srgrimes	if (ofilter > 0) {		/* stop output filter */
7811553Srgrimes		write(ofd, "\031\1", 2);
7821553Srgrimes		while ((pid =
7831553Srgrimes		    wait3((int *)&status, WUNTRACED, 0)) > 0 && pid != ofilter)
7841553Srgrimes			;
78579735Sgad		if (pid < 0)
78679735Sgad			syslog(LOG_WARNING, "%s: after stopping 'of', wait3() returned: %m",
78779735Sgad			    pp->printer);
78879735Sgad		else if (status.w_stopval != WSTOPPED) {
7891553Srgrimes			(void) close(fi);
79015648Sjoerg			syslog(LOG_WARNING,
79131492Swollman			       "%s: output filter died "
79279735Sgad			       "(pid=%d retcode=%d termsig=%d)",
79379735Sgad				pp->printer, ofilter, status.w_retcode,
79431492Swollman			       status.w_termsig);
7951553Srgrimes			return(REPRINT);
7961553Srgrimes		}
7971553Srgrimes		stopped++;
7981553Srgrimes	}
7991553Srgrimesstart:
80031492Swollman	if ((child = dofork(pp, DORETURN)) == 0) { /* child */
8011553Srgrimes		dup2(fi, 0);
8021553Srgrimes		dup2(fo, 1);
80368664Sgad		/* setup stderr for the filter (child process)
80468664Sgad		 * so it goes to our temporary errors file */
80568664Sgad		n = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
8061553Srgrimes		if (n >= 0)
8071553Srgrimes			dup2(n, 2);
8088094Sjkh		closelog();
80931492Swollman		closeallfds(3);
8101553Srgrimes		execv(prog, av);
8111553Srgrimes		syslog(LOG_ERR, "cannot execv %s", prog);
8121553Srgrimes		exit(2);
8131553Srgrimes	}
8141553Srgrimes	(void) close(fi);
8151553Srgrimes	if (child < 0)
8161553Srgrimes		status.w_retcode = 100;
81779735Sgad	else {
8181553Srgrimes		while ((pid = wait((int *)&status)) > 0 && pid != child)
8191553Srgrimes			;
82079735Sgad		if (pid < 0) {
82179735Sgad			status.w_retcode = 100;
82279735Sgad			syslog(LOG_WARNING, "%s: after execv(%s), wait() returned: %m",
82379735Sgad			    pp->printer, prog);
82479735Sgad		}
82579735Sgad	}
8261553Srgrimes	child = 0;
8271553Srgrimes	prchild = 0;
8281553Srgrimes	if (stopped) {		/* restart output filter */
8291553Srgrimes		if (kill(ofilter, SIGCONT) < 0) {
8301553Srgrimes			syslog(LOG_ERR, "cannot restart output filter");
8311553Srgrimes			exit(1);
8321553Srgrimes		}
8331553Srgrimes	}
83431492Swollman	pp->tof = 0;
8351553Srgrimes
83668664Sgad	/* Copy the filter's output to "lf" logfile */
83768664Sgad	if ((fp = fopen(tempstderr, "r"))) {
8381553Srgrimes		while (fgets(buf, sizeof(buf), fp))
8391553Srgrimes			fputs(buf, stderr);
8401553Srgrimes		fclose(fp);
8411553Srgrimes	}
8421553Srgrimes
8431553Srgrimes	if (!WIFEXITED(status)) {
84415648Sjoerg		syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d)",
84531492Swollman			pp->printer, format, status.w_termsig);
8461553Srgrimes		return(ERROR);
8471553Srgrimes	}
8481553Srgrimes	switch (status.w_retcode) {
8491553Srgrimes	case 0:
85031492Swollman		pp->tof = 1;
8511553Srgrimes		return(OK);
8521553Srgrimes	case 1:
8531553Srgrimes		return(REPRINT);
85415648Sjoerg	case 2:
85515648Sjoerg		return(ERROR);
8561553Srgrimes	default:
85715648Sjoerg		syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d)",
85831492Swollman			pp->printer, format, status.w_retcode);
85915648Sjoerg		return(FILTERERR);
8601553Srgrimes	}
8611553Srgrimes}
8621553Srgrimes
8631553Srgrimes/*
8641553Srgrimes * Send the daemon control file (cf) and any data files.
8651553Srgrimes * Return -1 if a non-recoverable error occured, 1 if a recoverable error and
8661553Srgrimes * 0 if all is well.
8671553Srgrimes */
8681553Srgrimesstatic int
86978146Sgadsendit(struct printer *pp, char *file)
8701553Srgrimes{
8711553Srgrimes	register int i, err = OK;
8721553Srgrimes	char *cp, last[BUFSIZ];
8731553Srgrimes
8741553Srgrimes	/*
8751553Srgrimes	 * open control file
8761553Srgrimes	 */
8771553Srgrimes	if ((cfp = fopen(file, "r")) == NULL)
8781553Srgrimes		return(OK);
87968253Sgad
88068253Sgad	/* initialize job-specific count of datafiles processed */
88168253Sgad	job_dfcnt = 0;
88268253Sgad
8831553Srgrimes	/*
8841553Srgrimes	 *      read the control file for work to do
8851553Srgrimes	 *
8861553Srgrimes	 *      file format -- first character in the line is a command
8871553Srgrimes	 *      rest of the line is the argument.
8881553Srgrimes	 *      commands of interest are:
8891553Srgrimes	 *
8901553Srgrimes	 *            a-z -- "file name" name of file to print
8911553Srgrimes	 *              U -- "unlink" name of file to remove
8921553Srgrimes	 *                    (after we print it. (Pass 2 only)).
8931553Srgrimes	 */
8941553Srgrimes
8951553Srgrimes	/*
8961553Srgrimes	 * pass 1
8971553Srgrimes	 */
8981553Srgrimes	while (getline(cfp)) {
8991553Srgrimes	again:
9001553Srgrimes		if (line[0] == 'S') {
9011553Srgrimes			cp = line+1;
9021553Srgrimes			i = 0;
9031553Srgrimes			while (*cp >= '0' && *cp <= '9')
9041553Srgrimes				i = i * 10 + (*cp++ - '0');
9051553Srgrimes			fdev = i;
9061553Srgrimes			cp++;
9071553Srgrimes			i = 0;
9081553Srgrimes			while (*cp >= '0' && *cp <= '9')
9091553Srgrimes				i = i * 10 + (*cp++ - '0');
9101553Srgrimes			fino = i;
91124831Sbrian		} else if (line[0] == 'H') {
91278300Sgad			strlcpy(origin_host, line + 1, sizeof(origin_host));
91368343Sgad			if (class[0] == '\0') {
91480133Sgad				strlcpy(class, line + 1, sizeof(class));
91568343Sgad			}
91624831Sbrian		} else if (line[0] == 'P') {
91780133Sgad			strlcpy(logname, line + 1, sizeof(logname));
91831492Swollman			if (pp->restricted) { /* restricted */
91924831Sbrian				if (getpwnam(logname) == NULL) {
92031492Swollman					sendmail(pp, line+1, NOACCT);
92124831Sbrian					err = ERROR;
92224831Sbrian					break;
92324831Sbrian				}
92424831Sbrian			}
92524831Sbrian		} else if (line[0] == 'I') {
92680133Sgad			strlcpy(indent+2, line + 1, sizeof(indent) - 2);
92724831Sbrian		} else if (line[0] >= 'a' && line[0] <= 'z') {
9281553Srgrimes			strcpy(last, line);
92931492Swollman			while ((i = getline(cfp)) != 0)
9301553Srgrimes				if (strcmp(last, line))
9311553Srgrimes					break;
93231492Swollman			switch (sendfile(pp, '\3', last+1, *last)) {
9331553Srgrimes			case OK:
9341553Srgrimes				if (i)
9351553Srgrimes					goto again;
9361553Srgrimes				break;
9371553Srgrimes			case REPRINT:
9381553Srgrimes				(void) fclose(cfp);
9391553Srgrimes				return(REPRINT);
9401553Srgrimes			case ACCESS:
94131492Swollman				sendmail(pp, logname, ACCESS);
9421553Srgrimes			case ERROR:
9431553Srgrimes				err = ERROR;
9441553Srgrimes			}
9451553Srgrimes			break;
9461553Srgrimes		}
9471553Srgrimes	}
94831492Swollman	if (err == OK && sendfile(pp, '\2', file, '\0') > 0) {
9491553Srgrimes		(void) fclose(cfp);
9501553Srgrimes		return(REPRINT);
9511553Srgrimes	}
9521553Srgrimes	/*
9531553Srgrimes	 * pass 2
9541553Srgrimes	 */
9551553Srgrimes	fseek(cfp, 0L, 0);
9561553Srgrimes	while (getline(cfp))
95727748Simp		if (line[0] == 'U' && !strchr(line+1, '/'))
9581553Srgrimes			(void) unlink(line+1);
9591553Srgrimes	/*
9601553Srgrimes	 * clean-up in case another control file exists
9611553Srgrimes	 */
9621553Srgrimes	(void) fclose(cfp);
9631553Srgrimes	(void) unlink(file);
9641553Srgrimes	return(err);
9651553Srgrimes}
9661553Srgrimes
9671553Srgrimes/*
9681553Srgrimes * Send a data file to the remote machine and spool it.
9691553Srgrimes * Return positive if we should try resending.
9701553Srgrimes */
9711553Srgrimesstatic int
97278146Sgadsendfile(struct printer *pp, int type, char *file, char format)
9731553Srgrimes{
9741553Srgrimes	register int f, i, amt;
9751553Srgrimes	struct stat stb;
97694032Sgad	char *av[15], *filtcmd;
97794032Sgad	char buf[BUFSIZ], opt_c[4], opt_h[4], opt_n[4];
97894032Sgad	int filtstat, narg, resp, sizerr, statrc;
9791553Srgrimes
98074124Sgad	statrc = lstat(file, &stb);
98174124Sgad	if (statrc < 0) {
98274124Sgad		syslog(LOG_ERR, "%s: error from lstat(%s): %m",
98374124Sgad		    pp->printer, file);
9841553Srgrimes		return(ERROR);
98574124Sgad	}
98674124Sgad	f = open(file, O_RDONLY);
98774124Sgad	if (f < 0) {
98874124Sgad		syslog(LOG_ERR, "%s: error from open(%s,O_RDONLY): %m",
98974124Sgad		    pp->printer, file);
99074124Sgad		return(ERROR);
99174124Sgad	}
9921553Srgrimes	/*
9931553Srgrimes	 * Check to see if data file is a symbolic link. If so, it should
9941553Srgrimes	 * still point to the same file or someone is trying to print something
9951553Srgrimes	 * he shouldn't.
9961553Srgrimes	 */
9971553Srgrimes	if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(f, &stb) == 0 &&
9981553Srgrimes	    (stb.st_dev != fdev || stb.st_ino != fino))
9991553Srgrimes		return(ACCESS);
100024831Sbrian
100194032Sgad	/* Everything seems OK for reading the file, now to send it */
100294032Sgad	filtcmd = NULL;
100324831Sbrian	sizerr = 0;
100494032Sgad	tfd = -1;
100524831Sbrian	if (type == '\3') {
100694032Sgad		/*
100794032Sgad		 * Type == 3 means this is a datafile, not a control file.
100894032Sgad		 * Increment the counter of data-files in this job, and
100994032Sgad		 * then check for input or output filters (which are only
101094032Sgad		 * applied to datafiles, not control files).
101194032Sgad		 */
101294032Sgad		job_dfcnt++;
101394032Sgad
101494032Sgad		/*
101594032Sgad		 * Note that here we are filtering datafiles, one at a time,
101694032Sgad		 * as they are sent to the remote machine.  Here, the *only*
101794032Sgad		 * difference between an input filter (`if=') and an output
101894032Sgad		 * filter (`of=') is the argument list that the filter is
101994032Sgad		 * started up with.  Here, the output filter is executed
102094032Sgad		 * for each individual file as it is sent.  This is not the
102194032Sgad		 * same as local print queues, where the output filter is
102294032Sgad		 * started up once, and then all jobs are passed thru that
102394032Sgad		 * single invocation of the output filter.
102494032Sgad		 *
102594032Sgad		 * Also note that a queue for a remote-machine can have an
102694032Sgad		 * input filter or an output filter, but not both.
102794032Sgad		 */
102831492Swollman		if (pp->filters[LPF_INPUT]) {
102994032Sgad			filtcmd = pp->filters[LPF_INPUT];
103094032Sgad			av[0] = filtcmd;
103194032Sgad			narg = 0;
103294032Sgad			strcpy(opt_c, "-c");
103394032Sgad			strcpy(opt_h, "-h");
103494032Sgad			strcpy(opt_n, "-n");
103524831Sbrian			if (format == 'l')
103694032Sgad				av[++narg] = opt_c;
103794032Sgad			av[++narg] = width;
103894032Sgad			av[++narg] = length;
103994032Sgad			av[++narg] = indent;
104094032Sgad			av[++narg] = opt_n;
104194032Sgad			av[++narg] = logname;
104294032Sgad			av[++narg] = opt_h;
104394032Sgad			av[++narg] = origin_host;
104494032Sgad			av[++narg] = pp->acct_file;
104594032Sgad			av[++narg] = NULL;
104694032Sgad		} else if (pp->filters[LPF_OUTPUT]) {
104794032Sgad			filtcmd = pp->filters[LPF_OUTPUT];
104894032Sgad			av[0] = filtcmd;
104994032Sgad			narg = 0;
105094032Sgad			av[++narg] = width;
105194032Sgad			av[++narg] = length;
105294032Sgad			av[++narg] = NULL;
105324831Sbrian		}
105424831Sbrian	}
105594032Sgad	if (filtcmd) {
105694032Sgad		/*
105794032Sgad		 * If there is an input or output filter, we have to run
105894032Sgad		 * the datafile thru that filter and store the result as
105994032Sgad		 * a temporary spool file, because the protocol requires
106094032Sgad		 * that we send the remote host the file-size before we
106194032Sgad		 * start to send any of the data.
106294032Sgad		 */
106394032Sgad		strcpy(tfile, TFILENAME);
106494032Sgad		tfd = mkstemp(tfile);
106594032Sgad		if (tfd == -1) {
106694032Sgad			syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
106794032Sgad			    TFILENAME);
106894032Sgad			return (ERROR);
106994032Sgad		}
107094032Sgad		filtstat = execfilter(pp, filtcmd, av, f, tfd);
107124831Sbrian
107294032Sgad		/* process the return-code from the filter */
107394032Sgad		switch (filtstat) {
107494032Sgad		case 0:
107594032Sgad			break;
107694032Sgad		case 1:
107794032Sgad			unlink(tfile);
107894032Sgad			return (REPRINT);
107994032Sgad		case 2:
108094032Sgad			unlink(tfile);
108194032Sgad			return (ERROR);
108294032Sgad		default:
108394032Sgad			syslog(LOG_WARNING,
108494032Sgad			    "%s: filter '%c' exited (retcode=%d)",
108594032Sgad			    pp->printer, format, filtstat);
108694032Sgad			unlink(tfile);
108794032Sgad			return (FILTERERR);
108894032Sgad		}
108994032Sgad		statrc = fstat(tfd, &stb);   /* to find size of tfile */
109094032Sgad		if (statrc < 0)	{
109194032Sgad			syslog(LOG_ERR,
109294032Sgad			    "%s: error processing 'if', fstat(%s): %m",
109394032Sgad			    pp->printer, tfile);
109494032Sgad			return (ERROR);
109594032Sgad		}
109694032Sgad		f = tfd;
109794032Sgad		lseek(f,0,SEEK_SET);
109894032Sgad	}
109994032Sgad
11001553Srgrimes	(void) sprintf(buf, "%c%qd %s\n", type, stb.st_size, file);
11011553Srgrimes	amt = strlen(buf);
11021553Srgrimes	for (i = 0;  ; i++) {
11031553Srgrimes		if (write(pfd, buf, amt) != amt ||
110431492Swollman		    (resp = response(pp)) < 0 || resp == '\1') {
11051553Srgrimes			(void) close(f);
110624831Sbrian			if (tfd != -1 && type == '\3') {
110724831Sbrian				tfd = -1;
110824831Sbrian				unlink(tfile);
110924831Sbrian			}
11101553Srgrimes			return(REPRINT);
11111553Srgrimes		} else if (resp == '\0')
11121553Srgrimes			break;
11131553Srgrimes		if (i == 0)
111431492Swollman			pstatus(pp,
111531492Swollman				"no space on remote; waiting for queue to drain");
11161553Srgrimes		if (i == 10)
11171553Srgrimes			syslog(LOG_ALERT, "%s: can't send to %s; queue full",
111831492Swollman				pp->printer, pp->remote_host);
11191553Srgrimes		sleep(5 * 60);
11201553Srgrimes	}
11211553Srgrimes	if (i)
112231492Swollman		pstatus(pp, "sending to %s", pp->remote_host);
112368253Sgad	if (type == '\3')
112468253Sgad		trstat_init(pp, file, job_dfcnt);
11251553Srgrimes	for (i = 0; i < stb.st_size; i += BUFSIZ) {
11261553Srgrimes		amt = BUFSIZ;
11271553Srgrimes		if (i + amt > stb.st_size)
11281553Srgrimes			amt = stb.st_size - i;
11291553Srgrimes		if (sizerr == 0 && read(f, buf, amt) != amt)
11301553Srgrimes			sizerr = 1;
11311553Srgrimes		if (write(pfd, buf, amt) != amt) {
11321553Srgrimes			(void) close(f);
113324831Sbrian			if (tfd != -1 && type == '\3') {
113424831Sbrian				tfd = -1;
113524831Sbrian				unlink(tfile);
113624831Sbrian			}
11371553Srgrimes			return(REPRINT);
11381553Srgrimes		}
11391553Srgrimes	}
11401553Srgrimes
11411553Srgrimes	(void) close(f);
114224831Sbrian	if (tfd != -1 && type == '\3') {
114324831Sbrian		tfd = -1;
114424831Sbrian		unlink(tfile);
114524831Sbrian	}
11461553Srgrimes	if (sizerr) {
114731492Swollman		syslog(LOG_INFO, "%s: %s: changed size", pp->printer, file);
11481553Srgrimes		/* tell recvjob to ignore this file */
11491553Srgrimes		(void) write(pfd, "\1", 1);
11501553Srgrimes		return(ERROR);
11511553Srgrimes	}
115231492Swollman	if (write(pfd, "", 1) != 1 || response(pp)) {
11531553Srgrimes		return(REPRINT);
115424831Sbrian	}
115568253Sgad	if (type == '\3')
115668253Sgad		trstat_write(pp, TR_SENDING, stb.st_size, logname,
115778300Sgad				 pp->remote_host, origin_host);
11581553Srgrimes	return(OK);
11591553Srgrimes}
11601553Srgrimes
11611553Srgrimes/*
116294032Sgad *  This routine is called to execute one of the filters as was
116394032Sgad *  specified in a printcap entry.
116494032Sgad */
116594032Sgadstatic int
116694032Sgadexecfilter(struct printer *pp, char *f_cmd, char *f_av[], int infd, int outfd)
116794032Sgad{
116894032Sgad	int errfd, fpid, wpid;
116994032Sgad	FILE *errfp;
117094032Sgad	union wait status; /* XXX */
117194032Sgad	char buf[BUFSIZ], *slash;
117294032Sgad
117394032Sgad	fpid = dofork(pp, DORETURN);
117494032Sgad	if (fpid != 0) {
117594032Sgad		/*
117694032Sgad		 * This is the parent process, which just waits for the child
117794032Sgad		 * to complete and then returns the result.  Note that it is
117894032Sgad		 * the child process which reads the input stream.
117994032Sgad		 */
118094032Sgad		(void) close(infd);
118194032Sgad		if (fpid < 0)
118294032Sgad			status.w_retcode = 100;
118394032Sgad		else {
118494032Sgad			while ((wpid = wait((int *)&status)) > 0 &&
118594032Sgad			    wpid != fpid)
118694032Sgad				;
118794032Sgad			if (wpid < 0) {
118894032Sgad				status.w_retcode = 100;
118994032Sgad				syslog(LOG_WARNING,
119094032Sgad				    "%s: after execv(%s), wait() returned: %m",
119194032Sgad				    pp->printer, f_cmd);
119294032Sgad			}
119394032Sgad		}
119494032Sgad
119594032Sgad		/*
119694032Sgad		 * Copy everything the filter wrote to stderr from our
119794032Sgad		 * temporary errors file to the "lf=" logfile.
119894032Sgad		 */
119994032Sgad		errfp = fopen(tempstderr, "r");
120094032Sgad		if (errfp) {
120194032Sgad			while (fgets(buf, sizeof(buf), errfp))
120294032Sgad				fputs(buf, stderr);
120394032Sgad			fclose(errfp);
120494032Sgad		}
120594032Sgad
120694032Sgad		return (status.w_retcode);
120794032Sgad	}
120894032Sgad
120994032Sgad	/*
121094032Sgad	 * This is the child process, which is the one that executes the
121194032Sgad	 * given filter.
121294032Sgad	 */
121394032Sgad	/*
121494032Sgad	 * If the first parameter has any slashes in it, then change it
121594032Sgad	 * to point to the first character after the last slash.
121694032Sgad	 */
121794032Sgad	slash = strrchr(f_av[0], '/');
121894032Sgad	if (slash != NULL)
121994032Sgad		f_av[0] = slash + 1;
122094032Sgad	/*
122194032Sgad	 * XXX - in the future, this should setup an explicit list of
122294032Sgad	 *       environment variables and use execve()!
122394032Sgad	 */
122494032Sgad
122594032Sgad	/*
122694032Sgad	 * Setup stdin, stdout, and stderr as we want them when the filter
122794032Sgad	 * is running.  Stderr is setup so it points to a temporary errors
122894032Sgad	 * file, and the parent process will copy that temporary file to
122994032Sgad	 * the real logfile after the filter completes.
123094032Sgad	 */
123194032Sgad	dup2(infd, 0);
123294032Sgad	dup2(outfd, 1);
123394032Sgad	errfd = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
123494032Sgad	if (errfd >= 0)
123594032Sgad		dup2(errfd, 2);
123694032Sgad	closelog();
123794032Sgad	closeallfds(3);
123894032Sgad	execv(f_cmd, f_av);
123994032Sgad	syslog(LOG_ERR, "%s: cannot execv %s", pp->printer, f_cmd);
124094032Sgad	exit(2);
124194032Sgad	/* NOTREACHED */
124294032Sgad}
124394032Sgad
124494032Sgad/*
12451553Srgrimes * Check to make sure there have been no errors and that both programs
12461553Srgrimes * are in sync with eachother.
12471553Srgrimes * Return non-zero if the connection was lost.
12481553Srgrimes */
12491553Srgrimesstatic char
125078146Sgadresponse(const struct printer *pp)
12511553Srgrimes{
12521553Srgrimes	char resp;
12531553Srgrimes
12541553Srgrimes	if (read(pfd, &resp, 1) != 1) {
125531492Swollman		syslog(LOG_INFO, "%s: lost connection", pp->printer);
12561553Srgrimes		return(-1);
12571553Srgrimes	}
12581553Srgrimes	return(resp);
12591553Srgrimes}
12601553Srgrimes
12611553Srgrimes/*
12621553Srgrimes * Banner printing stuff
12631553Srgrimes */
12641553Srgrimesstatic void
126578146Sgadbanner(struct printer *pp, char *name1, char *name2)
12661553Srgrimes{
12671553Srgrimes	time_t tvec;
12681553Srgrimes
12691553Srgrimes	time(&tvec);
127031492Swollman	if (!pp->no_formfeed && !pp->tof)
127131492Swollman		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
127231492Swollman	if (pp->short_banner) {	/* short banner only */
12731553Srgrimes		if (class[0]) {
12741553Srgrimes			(void) write(ofd, class, strlen(class));
12751553Srgrimes			(void) write(ofd, ":", 1);
12761553Srgrimes		}
12771553Srgrimes		(void) write(ofd, name1, strlen(name1));
12781553Srgrimes		(void) write(ofd, "  Job: ", 7);
12791553Srgrimes		(void) write(ofd, name2, strlen(name2));
12801553Srgrimes		(void) write(ofd, "  Date: ", 8);
12811553Srgrimes		(void) write(ofd, ctime(&tvec), 24);
12821553Srgrimes		(void) write(ofd, "\n", 1);
12831553Srgrimes	} else {	/* normal banner */
12841553Srgrimes		(void) write(ofd, "\n\n\n", 3);
128531492Swollman		scan_out(pp, ofd, name1, '\0');
12861553Srgrimes		(void) write(ofd, "\n\n", 2);
128731492Swollman		scan_out(pp, ofd, name2, '\0');
12881553Srgrimes		if (class[0]) {
12891553Srgrimes			(void) write(ofd,"\n\n\n",3);
129031492Swollman			scan_out(pp, ofd, class, '\0');
12911553Srgrimes		}
12921553Srgrimes		(void) write(ofd, "\n\n\n\n\t\t\t\t\tJob:  ", 15);
12931553Srgrimes		(void) write(ofd, name2, strlen(name2));
12941553Srgrimes		(void) write(ofd, "\n\t\t\t\t\tDate: ", 12);
12951553Srgrimes		(void) write(ofd, ctime(&tvec), 24);
12961553Srgrimes		(void) write(ofd, "\n", 1);
12971553Srgrimes	}
129831492Swollman	if (!pp->no_formfeed)
129931492Swollman		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
130031492Swollman	pp->tof = 1;
13011553Srgrimes}
13021553Srgrimes
13031553Srgrimesstatic char *
130478146Sgadscnline(int key, char *p, int c)
13051553Srgrimes{
130639084Swollman	register int scnwidth;
13071553Srgrimes
13081553Srgrimes	for (scnwidth = WIDTH; --scnwidth;) {
13091553Srgrimes		key <<= 1;
13101553Srgrimes		*p++ = key & 0200 ? c : BACKGND;
13111553Srgrimes	}
13121553Srgrimes	return (p);
13131553Srgrimes}
13141553Srgrimes
13151553Srgrimes#define TRC(q)	(((q)-' ')&0177)
13161553Srgrimes
13171553Srgrimesstatic void
131878146Sgadscan_out(struct printer *pp, int scfd, char *scsp, int dlm)
13191553Srgrimes{
13201553Srgrimes	register char *strp;
132139084Swollman	register int nchrs, j;
13221553Srgrimes	char outbuf[LINELEN+1], *sp, c, cc;
13231553Srgrimes	int d, scnhgt;
13241553Srgrimes
13251553Srgrimes	for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) {
13261553Srgrimes		strp = &outbuf[0];
13271553Srgrimes		sp = scsp;
13281553Srgrimes		for (nchrs = 0; ; ) {
13291553Srgrimes			d = dropit(c = TRC(cc = *sp++));
13301553Srgrimes			if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d))
13311553Srgrimes				for (j = WIDTH; --j;)
13321553Srgrimes					*strp++ = BACKGND;
13331553Srgrimes			else
133431492Swollman				strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc);
133531492Swollman			if (*sp == dlm || *sp == '\0' ||
133631492Swollman			    nchrs++ >= pp->page_width/(WIDTH+1)-1)
13371553Srgrimes				break;
13381553Srgrimes			*strp++ = BACKGND;
13391553Srgrimes			*strp++ = BACKGND;
13401553Srgrimes		}
13411553Srgrimes		while (*--strp == BACKGND && strp >= outbuf)
13421553Srgrimes			;
13431553Srgrimes		strp++;
13448857Srgrimes		*strp++ = '\n';
13451553Srgrimes		(void) write(scfd, outbuf, strp-outbuf);
13461553Srgrimes	}
13471553Srgrimes}
13481553Srgrimes
13491553Srgrimesstatic int
135078146Sgaddropit(int c)
13511553Srgrimes{
13521553Srgrimes	switch(c) {
13531553Srgrimes
13541553Srgrimes	case TRC('_'):
13551553Srgrimes	case TRC(';'):
13561553Srgrimes	case TRC(','):
13571553Srgrimes	case TRC('g'):
13581553Srgrimes	case TRC('j'):
13591553Srgrimes	case TRC('p'):
13601553Srgrimes	case TRC('q'):
13611553Srgrimes	case TRC('y'):
13621553Srgrimes		return (DROP);
13631553Srgrimes
13641553Srgrimes	default:
13651553Srgrimes		return (0);
13661553Srgrimes	}
13671553Srgrimes}
13681553Srgrimes
13691553Srgrimes/*
13701553Srgrimes * sendmail ---
13711553Srgrimes *   tell people about job completion
13721553Srgrimes */
13731553Srgrimesstatic void
137478146Sgadsendmail(struct printer *pp, char *user, int bombed)
13751553Srgrimes{
13761553Srgrimes	register int i;
13771553Srgrimes	int p[2], s;
137878146Sgad	register const char *cp;
13791553Srgrimes	struct stat stb;
13801553Srgrimes	FILE *fp;
13811553Srgrimes
13821553Srgrimes	pipe(p);
138331492Swollman	if ((s = dofork(pp, DORETURN)) == 0) {		/* child */
13841553Srgrimes		dup2(p[0], 0);
13858094Sjkh		closelog();
138631492Swollman		closeallfds(3);
138727635Simp		if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL)
13881553Srgrimes			cp++;
138931492Swollman		else
13901553Srgrimes			cp = _PATH_SENDMAIL;
139179452Sbrian		execl(_PATH_SENDMAIL, cp, "-t", (char *)0);
139231492Swollman		_exit(0);
13931553Srgrimes	} else if (s > 0) {				/* parent */
13941553Srgrimes		dup2(p[1], 1);
139578300Sgad		printf("To: %s@%s\n", user, origin_host);
139631492Swollman		printf("Subject: %s printer job \"%s\"\n", pp->printer,
139715648Sjoerg			*jobname ? jobname : "<unknown>");
139878300Sgad		printf("Reply-To: root@%s\n\n", local_host);
13991553Srgrimes		printf("Your printer job ");
14001553Srgrimes		if (*jobname)
14011553Srgrimes			printf("(%s) ", jobname);
140231492Swollman
140331492Swollman		cp = "XXX compiler confusion"; /* XXX shut GCC up */
14041553Srgrimes		switch (bombed) {
14051553Srgrimes		case OK:
14061553Srgrimes			printf("\ncompleted successfully\n");
140715648Sjoerg			cp = "OK";
14081553Srgrimes			break;
14091553Srgrimes		default:
14101553Srgrimes		case FATALERR:
14111553Srgrimes			printf("\ncould not be printed\n");
141215648Sjoerg			cp = "FATALERR";
14131553Srgrimes			break;
14141553Srgrimes		case NOACCT:
141578300Sgad			printf("\ncould not be printed without an account on %s\n",
141678300Sgad			    local_host);
141715648Sjoerg			cp = "NOACCT";
14181553Srgrimes			break;
14191553Srgrimes		case FILTERERR:
142068664Sgad			if (stat(tempstderr, &stb) < 0 || stb.st_size == 0
142168664Sgad			    || (fp = fopen(tempstderr, "r")) == NULL) {
142215648Sjoerg				printf("\nhad some errors and may not have printed\n");
14231553Srgrimes				break;
14241553Srgrimes			}
142515648Sjoerg			printf("\nhad the following errors and may not have printed:\n");
14261553Srgrimes			while ((i = getc(fp)) != EOF)
14271553Srgrimes				putchar(i);
14281553Srgrimes			(void) fclose(fp);
142915648Sjoerg			cp = "FILTERERR";
14301553Srgrimes			break;
14311553Srgrimes		case ACCESS:
14321553Srgrimes			printf("\nwas not printed because it was not linked to the original file\n");
143315648Sjoerg			cp = "ACCESS";
14341553Srgrimes		}
14351553Srgrimes		fflush(stdout);
14361553Srgrimes		(void) close(1);
143731492Swollman	} else {
143831492Swollman		syslog(LOG_WARNING, "unable to send mail to %s: %m", user);
143931492Swollman		return;
14401553Srgrimes	}
14411553Srgrimes	(void) close(p[0]);
14421553Srgrimes	(void) close(p[1]);
144315648Sjoerg	wait(NULL);
144415648Sjoerg	syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)",
144531492Swollman		user, *jobname ? jobname : "<unknown>", pp->printer, cp);
14461553Srgrimes}
14471553Srgrimes
14481553Srgrimes/*
14491553Srgrimes * dofork - fork with retries on failure
14501553Srgrimes */
14511553Srgrimesstatic int
145278146Sgaddofork(const struct printer *pp, int action)
14531553Srgrimes{
145480230Sgad	int i, fail, forkpid;
145560871Smpp	struct passwd *pwd;
14561553Srgrimes
145780230Sgad	forkpid = -1;
145880230Sgad	if (daemon_uname == NULL) {
145980230Sgad		pwd = getpwuid(pp->daemon_user);
146080230Sgad		if (pwd == NULL) {
146180230Sgad			syslog(LOG_ERR, "%s: Can't lookup default daemon uid (%ld) in password file",
146280230Sgad			    pp->printer, pp->daemon_user);
146380230Sgad			goto error_ret;
146480230Sgad		}
146580230Sgad		daemon_uname = strdup(pwd->pw_name);
146680230Sgad		daemon_defgid = pwd->pw_gid;
146780230Sgad	}
146880230Sgad
14691553Srgrimes	for (i = 0; i < 20; i++) {
147080230Sgad		forkpid = fork();
147180230Sgad		if (forkpid < 0) {
14721553Srgrimes			sleep((unsigned)(i*i));
14731553Srgrimes			continue;
14741553Srgrimes		}
14751553Srgrimes		/*
14761553Srgrimes		 * Child should run as daemon instead of root
14771553Srgrimes		 */
147878146Sgad		if (forkpid == 0) {
147980230Sgad			errno = 0;
148080230Sgad			fail = initgroups(daemon_uname, daemon_defgid);
148180230Sgad			if (fail) {
148280230Sgad				syslog(LOG_ERR, "%s: initgroups(%s,%u): %m",
148380230Sgad				    pp->printer, daemon_uname, daemon_defgid);
148460871Smpp				break;
148560871Smpp			}
148680230Sgad			fail = setgid(daemon_defgid);
148780230Sgad			if (fail) {
148880230Sgad				syslog(LOG_ERR, "%s: setgid(%u): %m",
148980230Sgad				    pp->printer, daemon_defgid);
149080230Sgad				break;
149180230Sgad			}
149280230Sgad			fail = setuid(pp->daemon_user);
149380230Sgad			if (fail) {
149480230Sgad				syslog(LOG_ERR, "%s: setuid(%ld): %m",
149580230Sgad				    pp->printer, pp->daemon_user);
149680230Sgad				break;
149780230Sgad			}
149860871Smpp		}
149980230Sgad		return forkpid;
15001553Srgrimes	}
15011553Srgrimes
150280230Sgad	/*
150380230Sgad	 * An error occurred.  If the error is in the child process, then
150480230Sgad	 * this routine MUST always exit().  DORETURN only effects how
150580230Sgad	 * errors should be handled in the parent process.
150680230Sgad	 */
150780230Sgaderror_ret:
150880230Sgad	if (forkpid == 0) {
150980230Sgad		syslog(LOG_ERR, "%s: dofork(): aborting child process...",
151080230Sgad		    pp->printer);
151180230Sgad		exit(1);
151280230Sgad	}
151380230Sgad	syslog(LOG_ERR, "%s: dofork(): failure in fork", pp->printer);
151480230Sgad
151580230Sgad	sleep(1);		/* throttle errors, as a safety measure */
15161553Srgrimes	switch (action) {
15171553Srgrimes	case DORETURN:
151880230Sgad		return -1;
15191553Srgrimes	default:
15201553Srgrimes		syslog(LOG_ERR, "bad action (%d) to dofork", action);
152180230Sgad		/* FALLTHROUGH */
15221553Srgrimes	case DOABORT:
15231553Srgrimes		exit(1);
15241553Srgrimes	}
15251553Srgrimes	/*NOTREACHED*/
15261553Srgrimes}
15271553Srgrimes
15281553Srgrimes/*
15291553Srgrimes * Kill child processes to abort current job.
15301553Srgrimes */
15311553Srgrimesstatic void
153278146Sgadabortpr(int signo __unused)
15331553Srgrimes{
153468664Sgad
153568664Sgad	(void) unlink(tempstderr);
15361553Srgrimes	kill(0, SIGINT);
15371553Srgrimes	if (ofilter > 0)
15381553Srgrimes		kill(ofilter, SIGCONT);
15391553Srgrimes	while (wait(NULL) > 0)
15401553Srgrimes		;
154124831Sbrian	if (ofilter > 0 && tfd != -1)
154224831Sbrian		unlink(tfile);
15431553Srgrimes	exit(0);
15441553Srgrimes}
15451553Srgrimes
15461553Srgrimesstatic void
154778146Sgadinit(struct printer *pp)
15481553Srgrimes{
15491553Srgrimes	char *s;
15501553Srgrimes
155131492Swollman	sprintf(&width[2], "%ld", pp->page_width);
155231492Swollman	sprintf(&length[2], "%ld", pp->page_length);
155331492Swollman	sprintf(&pxwidth[2], "%ld", pp->page_pwidth);
155431492Swollman	sprintf(&pxlength[2], "%ld", pp->page_plength);
155531492Swollman	if ((s = checkremote(pp)) != 0) {
155631492Swollman		syslog(LOG_WARNING, "%s", s);
155731492Swollman		free(s);
155831492Swollman	}
155931492Swollman}
156031492Swollman
156131492Swollmanvoid
156278146Sgadstartprinting(const char *printer)
156331492Swollman{
156431492Swollman	struct printer myprinter, *pp = &myprinter;
156531492Swollman	int status;
156631492Swollman
156731492Swollman	init_printer(pp);
156831492Swollman	status = getprintcap(printer, pp);
156931492Swollman	switch(status) {
157031492Swollman	case PCAPERR_OSERR:
157131492Swollman		syslog(LOG_ERR, "can't open printer description file: %m");
15721553Srgrimes		exit(1);
157331492Swollman	case PCAPERR_NOTFOUND:
15741553Srgrimes		syslog(LOG_ERR, "unknown printer: %s", printer);
15751553Srgrimes		exit(1);
157631492Swollman	case PCAPERR_TCLOOP:
157731492Swollman		fatal(pp, "potential reference loop detected in printcap file");
157831492Swollman	default:
157931492Swollman		break;
158031492Swollman	}
158131492Swollman	printjob(pp);
15821553Srgrimes}
15831553Srgrimes
15841553Srgrimes/*
15851553Srgrimes * Acquire line printer or remote connection.
15861553Srgrimes */
15871553Srgrimesstatic void
158878146Sgadopenpr(const struct printer *pp)
15891553Srgrimes{
159031492Swollman	int p[2];
159115648Sjoerg	char *cp;
15921553Srgrimes
159331492Swollman	if (pp->remote) {
159431492Swollman		openrem(pp);
159594032Sgad		/*
159694032Sgad		 * Lpd does support the setting of 'of=' filters for
159794032Sgad		 * jobs going to remote machines, but that does not
159894032Sgad		 * have the same meaning as 'of=' does when handling
159994032Sgad		 * local print queues.  For remote machines, all 'of='
160094032Sgad		 * filter processing is handled in sendfile(), and that
160194032Sgad		 * does not use these global "output filter" variables.
160294032Sgad		 */
160394032Sgad		ofd = -1;
160494032Sgad		ofilter = 0;
160594032Sgad		return;
160631492Swollman	} else if (*pp->lp) {
160731492Swollman		if ((cp = strchr(pp->lp, '@')) != NULL)
160831492Swollman			opennet(pp);
160915648Sjoerg		else
161031492Swollman			opentty(pp);
16111553Srgrimes	} else {
16121553Srgrimes		syslog(LOG_ERR, "%s: no line printer device or host name",
161331492Swollman			pp->printer);
16141553Srgrimes		exit(1);
16151553Srgrimes	}
161615648Sjoerg
16171553Srgrimes	/*
16181553Srgrimes	 * Start up an output filter, if needed.
16191553Srgrimes	 */
162031492Swollman	if (pp->filters[LPF_OUTPUT] && !pp->filters[LPF_INPUT] && !ofilter) {
16211553Srgrimes		pipe(p);
162231492Swollman		if (pp->remote) {
162331492Swollman			strcpy(tfile, TFILENAME);
162424831Sbrian			tfd = mkstemp(tfile);
162524831Sbrian		}
162631492Swollman		if ((ofilter = dofork(pp, DOABORT)) == 0) {	/* child */
16271553Srgrimes			dup2(p[0], 0);		/* pipe is std in */
162824831Sbrian			/* tfile/printer is stdout */
162931492Swollman			dup2(pp->remote ? tfd : pfd, 1);
16308094Sjkh			closelog();
163131492Swollman			closeallfds(3);
163231492Swollman			if ((cp = strrchr(pp->filters[LPF_OUTPUT], '/')) == NULL)
163331492Swollman				cp = pp->filters[LPF_OUTPUT];
16341553Srgrimes			else
16351553Srgrimes				cp++;
163679452Sbrian			execl(pp->filters[LPF_OUTPUT], cp, width, length,
163779452Sbrian			      (char *)0);
163831492Swollman			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
163931492Swollman			       pp->filters[LPF_OUTPUT]);
16401553Srgrimes			exit(1);
16411553Srgrimes		}
16421553Srgrimes		(void) close(p[0]);		/* close input side */
16431553Srgrimes		ofd = p[1];			/* use pipe for output */
16441553Srgrimes	} else {
16451553Srgrimes		ofd = pfd;
16461553Srgrimes		ofilter = 0;
16471553Srgrimes	}
16481553Srgrimes}
16491553Srgrimes
165015648Sjoerg/*
165115648Sjoerg * Printer connected directly to the network
165215648Sjoerg * or to a terminal server on the net
165315648Sjoerg */
165415648Sjoergstatic void
165578146Sgadopennet(const struct printer *pp)
165615648Sjoerg{
165715648Sjoerg	register int i;
165831492Swollman	int resp;
165931492Swollman	u_long port;
166031492Swollman	char *ep;
166130407Sjoerg	void (*savealrm)(int);
166215648Sjoerg
166331492Swollman	port = strtoul(pp->lp, &ep, 0);
166438470Sbrian	if (*ep != '@' || port > 65535) {
166531492Swollman		syslog(LOG_ERR, "%s: bad port number: %s", pp->printer,
166631492Swollman		       pp->lp);
166715648Sjoerg		exit(1);
166815648Sjoerg	}
166931492Swollman	ep++;
167015648Sjoerg
167115648Sjoerg	for (i = 1; ; i = i < 256 ? i << 1 : i) {
167215648Sjoerg		resp = -1;
167330407Sjoerg		savealrm = signal(SIGALRM, alarmhandler);
167431492Swollman		alarm(pp->conn_timeout);
167531492Swollman		pfd = getport(pp, ep, port);
167631020Sjoerg		alarm(0);
167730407Sjoerg		(void)signal(SIGALRM, savealrm);
167815648Sjoerg		if (pfd < 0 && errno == ECONNREFUSED)
167915648Sjoerg			resp = 1;
168015648Sjoerg		else if (pfd >= 0) {
168115648Sjoerg			/*
168215648Sjoerg			 * need to delay a bit for rs232 lines
168315648Sjoerg			 * to stabilize in case printer is
168415648Sjoerg			 * connected via a terminal server
168515648Sjoerg			 */
168615648Sjoerg			delay(500);
168715648Sjoerg			break;
168815648Sjoerg		}
168915648Sjoerg		if (i == 1) {
169031492Swollman			if (resp < 0)
169131492Swollman				pstatus(pp, "waiting for %s to come up",
169231492Swollman					pp->lp);
169331492Swollman			else
169431492Swollman				pstatus(pp,
169531492Swollman					"waiting for access to printer on %s",
169631492Swollman					pp->lp);
169715648Sjoerg		}
169815648Sjoerg		sleep(i);
169915648Sjoerg	}
170079739Sgad	pstatus(pp, "sending to %s port %lu", ep, port);
170115648Sjoerg}
170215648Sjoerg
170315648Sjoerg/*
170415648Sjoerg * Printer is connected to an RS232 port on this host
170515648Sjoerg */
170615648Sjoergstatic void
170778146Sgadopentty(const struct printer *pp)
170815648Sjoerg{
170915648Sjoerg	register int i;
171015648Sjoerg
171115648Sjoerg	for (i = 1; ; i = i < 32 ? i << 1 : i) {
171231492Swollman		pfd = open(pp->lp, pp->rw ? O_RDWR : O_WRONLY);
171315648Sjoerg		if (pfd >= 0) {
171415648Sjoerg			delay(500);
171515648Sjoerg			break;
171615648Sjoerg		}
171715648Sjoerg		if (errno == ENOENT) {
171831492Swollman			syslog(LOG_ERR, "%s: %m", pp->lp);
171915648Sjoerg			exit(1);
172015648Sjoerg		}
172115648Sjoerg		if (i == 1)
172231492Swollman			pstatus(pp,
172331492Swollman				"waiting for %s to become ready (offline?)",
172431492Swollman				pp->printer);
172515648Sjoerg		sleep(i);
172615648Sjoerg	}
172715648Sjoerg	if (isatty(pfd))
172831492Swollman		setty(pp);
172931492Swollman	pstatus(pp, "%s is ready and printing", pp->printer);
173015648Sjoerg}
173115648Sjoerg
173215648Sjoerg/*
173315648Sjoerg * Printer is on a remote host
173415648Sjoerg */
173515648Sjoergstatic void
173678146Sgadopenrem(const struct printer *pp)
173715648Sjoerg{
173831492Swollman	register int i;
173927748Simp	int resp;
174030407Sjoerg	void (*savealrm)(int);
174115648Sjoerg
174215648Sjoerg	for (i = 1; ; i = i < 256 ? i << 1 : i) {
174315648Sjoerg		resp = -1;
174430407Sjoerg		savealrm = signal(SIGALRM, alarmhandler);
174531492Swollman		alarm(pp->conn_timeout);
174631492Swollman		pfd = getport(pp, pp->remote_host, 0);
174731020Sjoerg		alarm(0);
174830407Sjoerg		(void)signal(SIGALRM, savealrm);
174915648Sjoerg		if (pfd >= 0) {
175031492Swollman			if ((writel(pfd, "\2", pp->remote_queue, "\n",
175131492Swollman				    (char *)0)
175231492Swollman			     == 2 + strlen(pp->remote_queue))
175331492Swollman			    && (resp = response(pp)) == 0)
175415648Sjoerg				break;
175515648Sjoerg			(void) close(pfd);
175615648Sjoerg		}
175715648Sjoerg		if (i == 1) {
175815648Sjoerg			if (resp < 0)
175931492Swollman				pstatus(pp, "waiting for %s to come up",
176031492Swollman					pp->remote_host);
176115648Sjoerg			else {
176231492Swollman				pstatus(pp,
176331492Swollman					"waiting for queue to be enabled on %s",
176431492Swollman					pp->remote_host);
176515648Sjoerg				i = 256;
176615648Sjoerg			}
176715648Sjoerg		}
176815648Sjoerg		sleep(i);
176915648Sjoerg	}
177031492Swollman	pstatus(pp, "sending to %s", pp->remote_host);
177115648Sjoerg}
177215648Sjoerg
17731553Srgrimes/*
17741553Srgrimes * setup tty lines.
17751553Srgrimes */
17761553Srgrimesstatic void
177778146Sgadsetty(const struct printer *pp)
17781553Srgrimes{
177915032Ssef	struct termios ttybuf;
17801553Srgrimes
17811553Srgrimes	if (ioctl(pfd, TIOCEXCL, (char *)0) < 0) {
178231492Swollman		syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", pp->printer);
17831553Srgrimes		exit(1);
17841553Srgrimes	}
178515032Ssef	if (tcgetattr(pfd, &ttybuf) < 0) {
178631492Swollman		syslog(LOG_ERR, "%s: tcgetattr: %m", pp->printer);
17871553Srgrimes		exit(1);
17881553Srgrimes	}
178931492Swollman	if (pp->baud_rate > 0)
179031492Swollman		cfsetspeed(&ttybuf, pp->baud_rate);
179131492Swollman	if (pp->mode_set) {
179231492Swollman		char *s = strdup(pp->mode_set), *tmp;
179315032Ssef
179431492Swollman		while ((tmp = strsep(&s, ",")) != NULL) {
179539084Swollman			(void) msearch(tmp, &ttybuf);
17961553Srgrimes		}
17971553Srgrimes	}
179831492Swollman	if (pp->mode_set != 0 || pp->baud_rate > 0) {
179915032Ssef		if (tcsetattr(pfd, TCSAFLUSH, &ttybuf) == -1) {
180031492Swollman			syslog(LOG_ERR, "%s: tcsetattr: %m", pp->printer);
18011553Srgrimes		}
18021553Srgrimes	}
18031553Srgrimes}
18041553Srgrimes
180527757Simp#ifdef __STDC__
18061553Srgrimes#include <stdarg.h>
18071553Srgrimes#else
18081553Srgrimes#include <varargs.h>
18091553Srgrimes#endif
18101553Srgrimes
181115648Sjoergstatic void
181227757Simp#ifdef __STDC__
181331492Swollmanpstatus(const struct printer *pp, const char *msg, ...)
18141553Srgrimes#else
181531492Swollmanpstatus(pp, msg, va_alist)
181631492Swollman	const struct printer *pp;
18171553Srgrimes	char *msg;
18181553Srgrimes        va_dcl
18191553Srgrimes#endif
18201553Srgrimes{
182131492Swollman	int fd;
182231492Swollman	char *buf;
18231553Srgrimes	va_list ap;
182427757Simp#ifdef __STDC__
18251553Srgrimes	va_start(ap, msg);
18261553Srgrimes#else
18271553Srgrimes	va_start(ap);
18281553Srgrimes#endif
18291553Srgrimes
18301553Srgrimes	umask(0);
183131492Swollman	fd = open(pp->status_file, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
183231492Swollman	if (fd < 0) {
183331492Swollman		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->status_file);
18341553Srgrimes		exit(1);
18351553Srgrimes	}
18361553Srgrimes	ftruncate(fd, 0);
183731492Swollman	vasprintf(&buf, msg, ap);
18381553Srgrimes	va_end(ap);
183931492Swollman	writel(fd, buf, "\n", (char *)0);
184031492Swollman	close(fd);
184131492Swollman	free(buf);
18421553Srgrimes}
184330407Sjoerg
184430407Sjoergvoid
184578146Sgadalarmhandler(int signo __unused)
184630407Sjoerg{
184778146Sgad	/* the signal is ignored */
184878146Sgad	/* (the '__unused' is just to avoid a compile-time warning) */
184930407Sjoerg}
1850