printjob.c revision 95067
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 95067 2002-04-19 18:28:35Z 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);
15194038Sgadstatic void	 sendmail(struct printer *_pp, char *_userid, 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);
81195067Sgad		syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer,
81295067Sgad		    prog);
8131553Srgrimes		exit(2);
8141553Srgrimes	}
8151553Srgrimes	(void) close(fi);
8161553Srgrimes	if (child < 0)
8171553Srgrimes		status.w_retcode = 100;
81879735Sgad	else {
8191553Srgrimes		while ((pid = wait((int *)&status)) > 0 && pid != child)
8201553Srgrimes			;
82179735Sgad		if (pid < 0) {
82279735Sgad			status.w_retcode = 100;
82379735Sgad			syslog(LOG_WARNING, "%s: after execv(%s), wait() returned: %m",
82479735Sgad			    pp->printer, prog);
82579735Sgad		}
82679735Sgad	}
8271553Srgrimes	child = 0;
8281553Srgrimes	prchild = 0;
8291553Srgrimes	if (stopped) {		/* restart output filter */
8301553Srgrimes		if (kill(ofilter, SIGCONT) < 0) {
8311553Srgrimes			syslog(LOG_ERR, "cannot restart output filter");
8321553Srgrimes			exit(1);
8331553Srgrimes		}
8341553Srgrimes	}
83531492Swollman	pp->tof = 0;
8361553Srgrimes
83768664Sgad	/* Copy the filter's output to "lf" logfile */
83868664Sgad	if ((fp = fopen(tempstderr, "r"))) {
8391553Srgrimes		while (fgets(buf, sizeof(buf), fp))
8401553Srgrimes			fputs(buf, stderr);
8411553Srgrimes		fclose(fp);
8421553Srgrimes	}
8431553Srgrimes
8441553Srgrimes	if (!WIFEXITED(status)) {
84515648Sjoerg		syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d)",
84631492Swollman			pp->printer, format, status.w_termsig);
8471553Srgrimes		return(ERROR);
8481553Srgrimes	}
8491553Srgrimes	switch (status.w_retcode) {
8501553Srgrimes	case 0:
85131492Swollman		pp->tof = 1;
8521553Srgrimes		return(OK);
8531553Srgrimes	case 1:
8541553Srgrimes		return(REPRINT);
85515648Sjoerg	case 2:
85615648Sjoerg		return(ERROR);
8571553Srgrimes	default:
85815648Sjoerg		syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d)",
85931492Swollman			pp->printer, format, status.w_retcode);
86015648Sjoerg		return(FILTERERR);
8611553Srgrimes	}
8621553Srgrimes}
8631553Srgrimes
8641553Srgrimes/*
8651553Srgrimes * Send the daemon control file (cf) and any data files.
8661553Srgrimes * Return -1 if a non-recoverable error occured, 1 if a recoverable error and
8671553Srgrimes * 0 if all is well.
8681553Srgrimes */
8691553Srgrimesstatic int
87078146Sgadsendit(struct printer *pp, char *file)
8711553Srgrimes{
8721553Srgrimes	register int i, err = OK;
8731553Srgrimes	char *cp, last[BUFSIZ];
8741553Srgrimes
8751553Srgrimes	/*
8761553Srgrimes	 * open control file
8771553Srgrimes	 */
8781553Srgrimes	if ((cfp = fopen(file, "r")) == NULL)
8791553Srgrimes		return(OK);
88068253Sgad
88168253Sgad	/* initialize job-specific count of datafiles processed */
88268253Sgad	job_dfcnt = 0;
88368253Sgad
8841553Srgrimes	/*
8851553Srgrimes	 *      read the control file for work to do
8861553Srgrimes	 *
8871553Srgrimes	 *      file format -- first character in the line is a command
8881553Srgrimes	 *      rest of the line is the argument.
8891553Srgrimes	 *      commands of interest are:
8901553Srgrimes	 *
8911553Srgrimes	 *            a-z -- "file name" name of file to print
8921553Srgrimes	 *              U -- "unlink" name of file to remove
8931553Srgrimes	 *                    (after we print it. (Pass 2 only)).
8941553Srgrimes	 */
8951553Srgrimes
8961553Srgrimes	/*
8971553Srgrimes	 * pass 1
8981553Srgrimes	 */
8991553Srgrimes	while (getline(cfp)) {
9001553Srgrimes	again:
9011553Srgrimes		if (line[0] == 'S') {
9021553Srgrimes			cp = line+1;
9031553Srgrimes			i = 0;
9041553Srgrimes			while (*cp >= '0' && *cp <= '9')
9051553Srgrimes				i = i * 10 + (*cp++ - '0');
9061553Srgrimes			fdev = i;
9071553Srgrimes			cp++;
9081553Srgrimes			i = 0;
9091553Srgrimes			while (*cp >= '0' && *cp <= '9')
9101553Srgrimes				i = i * 10 + (*cp++ - '0');
9111553Srgrimes			fino = i;
91224831Sbrian		} else if (line[0] == 'H') {
91378300Sgad			strlcpy(origin_host, line + 1, sizeof(origin_host));
91468343Sgad			if (class[0] == '\0') {
91580133Sgad				strlcpy(class, line + 1, sizeof(class));
91668343Sgad			}
91724831Sbrian		} else if (line[0] == 'P') {
91880133Sgad			strlcpy(logname, line + 1, sizeof(logname));
91931492Swollman			if (pp->restricted) { /* restricted */
92024831Sbrian				if (getpwnam(logname) == NULL) {
92131492Swollman					sendmail(pp, line+1, NOACCT);
92224831Sbrian					err = ERROR;
92324831Sbrian					break;
92424831Sbrian				}
92524831Sbrian			}
92624831Sbrian		} else if (line[0] == 'I') {
92780133Sgad			strlcpy(indent+2, line + 1, sizeof(indent) - 2);
92824831Sbrian		} else if (line[0] >= 'a' && line[0] <= 'z') {
9291553Srgrimes			strcpy(last, line);
93031492Swollman			while ((i = getline(cfp)) != 0)
9311553Srgrimes				if (strcmp(last, line))
9321553Srgrimes					break;
93331492Swollman			switch (sendfile(pp, '\3', last+1, *last)) {
9341553Srgrimes			case OK:
9351553Srgrimes				if (i)
9361553Srgrimes					goto again;
9371553Srgrimes				break;
9381553Srgrimes			case REPRINT:
9391553Srgrimes				(void) fclose(cfp);
9401553Srgrimes				return(REPRINT);
9411553Srgrimes			case ACCESS:
94231492Swollman				sendmail(pp, logname, ACCESS);
9431553Srgrimes			case ERROR:
9441553Srgrimes				err = ERROR;
9451553Srgrimes			}
9461553Srgrimes			break;
9471553Srgrimes		}
9481553Srgrimes	}
94931492Swollman	if (err == OK && sendfile(pp, '\2', file, '\0') > 0) {
9501553Srgrimes		(void) fclose(cfp);
9511553Srgrimes		return(REPRINT);
9521553Srgrimes	}
9531553Srgrimes	/*
9541553Srgrimes	 * pass 2
9551553Srgrimes	 */
9561553Srgrimes	fseek(cfp, 0L, 0);
9571553Srgrimes	while (getline(cfp))
95827748Simp		if (line[0] == 'U' && !strchr(line+1, '/'))
9591553Srgrimes			(void) unlink(line+1);
9601553Srgrimes	/*
9611553Srgrimes	 * clean-up in case another control file exists
9621553Srgrimes	 */
9631553Srgrimes	(void) fclose(cfp);
9641553Srgrimes	(void) unlink(file);
9651553Srgrimes	return(err);
9661553Srgrimes}
9671553Srgrimes
9681553Srgrimes/*
9691553Srgrimes * Send a data file to the remote machine and spool it.
9701553Srgrimes * Return positive if we should try resending.
9711553Srgrimes */
9721553Srgrimesstatic int
97378146Sgadsendfile(struct printer *pp, int type, char *file, char format)
9741553Srgrimes{
97594036Sgad	int i, amt;
9761553Srgrimes	struct stat stb;
97794032Sgad	char *av[15], *filtcmd;
97894032Sgad	char buf[BUFSIZ], opt_c[4], opt_h[4], opt_n[4];
97994036Sgad	int filtstat, narg, resp, sfd, sfres, sizerr, statrc;
9801553Srgrimes
98174124Sgad	statrc = lstat(file, &stb);
98274124Sgad	if (statrc < 0) {
98374124Sgad		syslog(LOG_ERR, "%s: error from lstat(%s): %m",
98474124Sgad		    pp->printer, file);
98594036Sgad		return (ERROR);
98674124Sgad	}
98794036Sgad	sfd = open(file, O_RDONLY);
98894036Sgad	if (sfd < 0) {
98974124Sgad		syslog(LOG_ERR, "%s: error from open(%s,O_RDONLY): %m",
99074124Sgad		    pp->printer, file);
99194036Sgad		return (ERROR);
99274124Sgad	}
9931553Srgrimes	/*
9941553Srgrimes	 * Check to see if data file is a symbolic link. If so, it should
9951553Srgrimes	 * still point to the same file or someone is trying to print something
9961553Srgrimes	 * he shouldn't.
9971553Srgrimes	 */
99894036Sgad	if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(sfd, &stb) == 0 &&
99994036Sgad	    (stb.st_dev != fdev || stb.st_ino != fino)) {
100094036Sgad		close(sfd);
100194036Sgad		return (ACCESS);
100294036Sgad	}
100324831Sbrian
100494032Sgad	/* Everything seems OK for reading the file, now to send it */
100594032Sgad	filtcmd = NULL;
100624831Sbrian	sizerr = 0;
100794032Sgad	tfd = -1;
100824831Sbrian	if (type == '\3') {
100994032Sgad		/*
101094032Sgad		 * Type == 3 means this is a datafile, not a control file.
101194032Sgad		 * Increment the counter of data-files in this job, and
101294032Sgad		 * then check for input or output filters (which are only
101394032Sgad		 * applied to datafiles, not control files).
101494032Sgad		 */
101594032Sgad		job_dfcnt++;
101694032Sgad
101794032Sgad		/*
101894032Sgad		 * Note that here we are filtering datafiles, one at a time,
101994032Sgad		 * as they are sent to the remote machine.  Here, the *only*
102094032Sgad		 * difference between an input filter (`if=') and an output
102194032Sgad		 * filter (`of=') is the argument list that the filter is
102294032Sgad		 * started up with.  Here, the output filter is executed
102394032Sgad		 * for each individual file as it is sent.  This is not the
102494032Sgad		 * same as local print queues, where the output filter is
102594032Sgad		 * started up once, and then all jobs are passed thru that
102694032Sgad		 * single invocation of the output filter.
102794032Sgad		 *
102894032Sgad		 * Also note that a queue for a remote-machine can have an
102994032Sgad		 * input filter or an output filter, but not both.
103094032Sgad		 */
103131492Swollman		if (pp->filters[LPF_INPUT]) {
103294032Sgad			filtcmd = pp->filters[LPF_INPUT];
103394032Sgad			av[0] = filtcmd;
103494032Sgad			narg = 0;
103594032Sgad			strcpy(opt_c, "-c");
103694032Sgad			strcpy(opt_h, "-h");
103794032Sgad			strcpy(opt_n, "-n");
103824831Sbrian			if (format == 'l')
103994032Sgad				av[++narg] = opt_c;
104094032Sgad			av[++narg] = width;
104194032Sgad			av[++narg] = length;
104294032Sgad			av[++narg] = indent;
104394032Sgad			av[++narg] = opt_n;
104494032Sgad			av[++narg] = logname;
104594032Sgad			av[++narg] = opt_h;
104694032Sgad			av[++narg] = origin_host;
104794032Sgad			av[++narg] = pp->acct_file;
104894032Sgad			av[++narg] = NULL;
104994032Sgad		} else if (pp->filters[LPF_OUTPUT]) {
105094032Sgad			filtcmd = pp->filters[LPF_OUTPUT];
105194032Sgad			av[0] = filtcmd;
105294032Sgad			narg = 0;
105394032Sgad			av[++narg] = width;
105494032Sgad			av[++narg] = length;
105594032Sgad			av[++narg] = NULL;
105624831Sbrian		}
105724831Sbrian	}
105894032Sgad	if (filtcmd) {
105994032Sgad		/*
106094032Sgad		 * If there is an input or output filter, we have to run
106194032Sgad		 * the datafile thru that filter and store the result as
106294032Sgad		 * a temporary spool file, because the protocol requires
106394032Sgad		 * that we send the remote host the file-size before we
106494032Sgad		 * start to send any of the data.
106594032Sgad		 */
106694032Sgad		strcpy(tfile, TFILENAME);
106794032Sgad		tfd = mkstemp(tfile);
106894032Sgad		if (tfd == -1) {
106994032Sgad			syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
107094032Sgad			    TFILENAME);
107194036Sgad			sfres = ERROR;
107294036Sgad			goto return_sfres;
107394032Sgad		}
107494036Sgad		filtstat = execfilter(pp, filtcmd, av, sfd, tfd);
107524831Sbrian
107694032Sgad		/* process the return-code from the filter */
107794032Sgad		switch (filtstat) {
107894032Sgad		case 0:
107994032Sgad			break;
108094032Sgad		case 1:
108194036Sgad			sfres = REPRINT;
108294036Sgad			goto return_sfres;
108394032Sgad		case 2:
108494036Sgad			sfres = ERROR;
108594036Sgad			goto return_sfres;
108694032Sgad		default:
108794032Sgad			syslog(LOG_WARNING,
108894032Sgad			    "%s: filter '%c' exited (retcode=%d)",
108994032Sgad			    pp->printer, format, filtstat);
109094036Sgad			sfres = FILTERERR;
109194036Sgad			goto return_sfres;
109294032Sgad		}
109394032Sgad		statrc = fstat(tfd, &stb);   /* to find size of tfile */
109494032Sgad		if (statrc < 0)	{
109594032Sgad			syslog(LOG_ERR,
109694032Sgad			    "%s: error processing 'if', fstat(%s): %m",
109794032Sgad			    pp->printer, tfile);
109894036Sgad			sfres = ERROR;
109994036Sgad			goto return_sfres;
110094032Sgad		}
110194036Sgad		close(sfd);
110294036Sgad		sfd = tfd;
110394036Sgad		lseek(sfd, 0, SEEK_SET);
110494032Sgad	}
110594032Sgad
11061553Srgrimes	(void) sprintf(buf, "%c%qd %s\n", type, stb.st_size, file);
11071553Srgrimes	amt = strlen(buf);
11081553Srgrimes	for (i = 0;  ; i++) {
11091553Srgrimes		if (write(pfd, buf, amt) != amt ||
111031492Swollman		    (resp = response(pp)) < 0 || resp == '\1') {
111194036Sgad			sfres = REPRINT;
111294036Sgad			goto return_sfres;
11131553Srgrimes		} else if (resp == '\0')
11141553Srgrimes			break;
11151553Srgrimes		if (i == 0)
111631492Swollman			pstatus(pp,
111731492Swollman				"no space on remote; waiting for queue to drain");
11181553Srgrimes		if (i == 10)
11191553Srgrimes			syslog(LOG_ALERT, "%s: can't send to %s; queue full",
112031492Swollman				pp->printer, pp->remote_host);
11211553Srgrimes		sleep(5 * 60);
11221553Srgrimes	}
11231553Srgrimes	if (i)
112431492Swollman		pstatus(pp, "sending to %s", pp->remote_host);
112568253Sgad	if (type == '\3')
112668253Sgad		trstat_init(pp, file, job_dfcnt);
11271553Srgrimes	for (i = 0; i < stb.st_size; i += BUFSIZ) {
11281553Srgrimes		amt = BUFSIZ;
11291553Srgrimes		if (i + amt > stb.st_size)
11301553Srgrimes			amt = stb.st_size - i;
113194036Sgad		if (sizerr == 0 && read(sfd, buf, amt) != amt)
11321553Srgrimes			sizerr = 1;
11331553Srgrimes		if (write(pfd, buf, amt) != amt) {
113494036Sgad			sfres = REPRINT;
113594036Sgad			goto return_sfres;
11361553Srgrimes		}
11371553Srgrimes	}
11381553Srgrimes
11391553Srgrimes	if (sizerr) {
114031492Swollman		syslog(LOG_INFO, "%s: %s: changed size", pp->printer, file);
11411553Srgrimes		/* tell recvjob to ignore this file */
11421553Srgrimes		(void) write(pfd, "\1", 1);
114394036Sgad		sfres = ERROR;
114494036Sgad		goto return_sfres;
11451553Srgrimes	}
114631492Swollman	if (write(pfd, "", 1) != 1 || response(pp)) {
114794036Sgad		sfres = REPRINT;
114894036Sgad		goto return_sfres;
114924831Sbrian	}
115068253Sgad	if (type == '\3')
115168253Sgad		trstat_write(pp, TR_SENDING, stb.st_size, logname,
115278300Sgad				 pp->remote_host, origin_host);
115394036Sgad	sfres = OK;
115494036Sgad
115594036Sgadreturn_sfres:
115694036Sgad	(void)close(sfd);
115794036Sgad	if (tfd != -1) {
115894036Sgad		/*
115994036Sgad		 * If tfd is set, then it is the same value as sfd, and
116094036Sgad		 * therefore it is already closed at this point.  All
116194036Sgad		 * we need to do is remove the temporary file.
116294036Sgad		 */
116394036Sgad		tfd = -1;
116494036Sgad		unlink(tfile);
116594036Sgad	}
116694036Sgad	return (sfres);
11671553Srgrimes}
11681553Srgrimes
11691553Srgrimes/*
117094032Sgad *  This routine is called to execute one of the filters as was
117194036Sgad *  specified in a printcap entry.  While the child-process will read
117294036Sgad *  all of 'infd', it is up to the caller to close that file descriptor
117394036Sgad *  in the parent process.
117494032Sgad */
117594032Sgadstatic int
117694032Sgadexecfilter(struct printer *pp, char *f_cmd, char *f_av[], int infd, int outfd)
117794032Sgad{
117894032Sgad	int errfd, fpid, wpid;
117994032Sgad	FILE *errfp;
118094032Sgad	union wait status; /* XXX */
118194032Sgad	char buf[BUFSIZ], *slash;
118294032Sgad
118394032Sgad	fpid = dofork(pp, DORETURN);
118494032Sgad	if (fpid != 0) {
118594032Sgad		/*
118694032Sgad		 * This is the parent process, which just waits for the child
118794032Sgad		 * to complete and then returns the result.  Note that it is
118894032Sgad		 * the child process which reads the input stream.
118994032Sgad		 */
119094032Sgad		if (fpid < 0)
119194032Sgad			status.w_retcode = 100;
119294032Sgad		else {
119394032Sgad			while ((wpid = wait((int *)&status)) > 0 &&
119494032Sgad			    wpid != fpid)
119594032Sgad				;
119694032Sgad			if (wpid < 0) {
119794032Sgad				status.w_retcode = 100;
119894032Sgad				syslog(LOG_WARNING,
119994032Sgad				    "%s: after execv(%s), wait() returned: %m",
120094032Sgad				    pp->printer, f_cmd);
120194032Sgad			}
120294032Sgad		}
120394032Sgad
120494032Sgad		/*
120594032Sgad		 * Copy everything the filter wrote to stderr from our
120694032Sgad		 * temporary errors file to the "lf=" logfile.
120794032Sgad		 */
120894032Sgad		errfp = fopen(tempstderr, "r");
120994032Sgad		if (errfp) {
121094032Sgad			while (fgets(buf, sizeof(buf), errfp))
121194032Sgad				fputs(buf, stderr);
121294032Sgad			fclose(errfp);
121394032Sgad		}
121494032Sgad
121594032Sgad		return (status.w_retcode);
121694032Sgad	}
121794032Sgad
121894032Sgad	/*
121994032Sgad	 * This is the child process, which is the one that executes the
122094032Sgad	 * given filter.
122194032Sgad	 */
122294032Sgad	/*
122394032Sgad	 * If the first parameter has any slashes in it, then change it
122494032Sgad	 * to point to the first character after the last slash.
122594032Sgad	 */
122694032Sgad	slash = strrchr(f_av[0], '/');
122794032Sgad	if (slash != NULL)
122894032Sgad		f_av[0] = slash + 1;
122994032Sgad	/*
123094032Sgad	 * XXX - in the future, this should setup an explicit list of
123194032Sgad	 *       environment variables and use execve()!
123294032Sgad	 */
123394032Sgad
123494032Sgad	/*
123594032Sgad	 * Setup stdin, stdout, and stderr as we want them when the filter
123694032Sgad	 * is running.  Stderr is setup so it points to a temporary errors
123794032Sgad	 * file, and the parent process will copy that temporary file to
123894032Sgad	 * the real logfile after the filter completes.
123994032Sgad	 */
124094032Sgad	dup2(infd, 0);
124194032Sgad	dup2(outfd, 1);
124294032Sgad	errfd = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
124394032Sgad	if (errfd >= 0)
124494032Sgad		dup2(errfd, 2);
124594032Sgad	closelog();
124694032Sgad	closeallfds(3);
124794032Sgad	execv(f_cmd, f_av);
124895067Sgad	syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer, f_cmd);
124994032Sgad	exit(2);
125094032Sgad	/* NOTREACHED */
125194032Sgad}
125294032Sgad
125394032Sgad/*
12541553Srgrimes * Check to make sure there have been no errors and that both programs
12551553Srgrimes * are in sync with eachother.
12561553Srgrimes * Return non-zero if the connection was lost.
12571553Srgrimes */
12581553Srgrimesstatic char
125978146Sgadresponse(const struct printer *pp)
12601553Srgrimes{
12611553Srgrimes	char resp;
12621553Srgrimes
12631553Srgrimes	if (read(pfd, &resp, 1) != 1) {
126431492Swollman		syslog(LOG_INFO, "%s: lost connection", pp->printer);
12651553Srgrimes		return(-1);
12661553Srgrimes	}
12671553Srgrimes	return(resp);
12681553Srgrimes}
12691553Srgrimes
12701553Srgrimes/*
12711553Srgrimes * Banner printing stuff
12721553Srgrimes */
12731553Srgrimesstatic void
127478146Sgadbanner(struct printer *pp, char *name1, char *name2)
12751553Srgrimes{
12761553Srgrimes	time_t tvec;
12771553Srgrimes
12781553Srgrimes	time(&tvec);
127931492Swollman	if (!pp->no_formfeed && !pp->tof)
128031492Swollman		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
128131492Swollman	if (pp->short_banner) {	/* short banner only */
12821553Srgrimes		if (class[0]) {
12831553Srgrimes			(void) write(ofd, class, strlen(class));
12841553Srgrimes			(void) write(ofd, ":", 1);
12851553Srgrimes		}
12861553Srgrimes		(void) write(ofd, name1, strlen(name1));
12871553Srgrimes		(void) write(ofd, "  Job: ", 7);
12881553Srgrimes		(void) write(ofd, name2, strlen(name2));
12891553Srgrimes		(void) write(ofd, "  Date: ", 8);
12901553Srgrimes		(void) write(ofd, ctime(&tvec), 24);
12911553Srgrimes		(void) write(ofd, "\n", 1);
12921553Srgrimes	} else {	/* normal banner */
12931553Srgrimes		(void) write(ofd, "\n\n\n", 3);
129431492Swollman		scan_out(pp, ofd, name1, '\0');
12951553Srgrimes		(void) write(ofd, "\n\n", 2);
129631492Swollman		scan_out(pp, ofd, name2, '\0');
12971553Srgrimes		if (class[0]) {
12981553Srgrimes			(void) write(ofd,"\n\n\n",3);
129931492Swollman			scan_out(pp, ofd, class, '\0');
13001553Srgrimes		}
13011553Srgrimes		(void) write(ofd, "\n\n\n\n\t\t\t\t\tJob:  ", 15);
13021553Srgrimes		(void) write(ofd, name2, strlen(name2));
13031553Srgrimes		(void) write(ofd, "\n\t\t\t\t\tDate: ", 12);
13041553Srgrimes		(void) write(ofd, ctime(&tvec), 24);
13051553Srgrimes		(void) write(ofd, "\n", 1);
13061553Srgrimes	}
130731492Swollman	if (!pp->no_formfeed)
130831492Swollman		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
130931492Swollman	pp->tof = 1;
13101553Srgrimes}
13111553Srgrimes
13121553Srgrimesstatic char *
131378146Sgadscnline(int key, char *p, int c)
13141553Srgrimes{
131539084Swollman	register int scnwidth;
13161553Srgrimes
13171553Srgrimes	for (scnwidth = WIDTH; --scnwidth;) {
13181553Srgrimes		key <<= 1;
13191553Srgrimes		*p++ = key & 0200 ? c : BACKGND;
13201553Srgrimes	}
13211553Srgrimes	return (p);
13221553Srgrimes}
13231553Srgrimes
13241553Srgrimes#define TRC(q)	(((q)-' ')&0177)
13251553Srgrimes
13261553Srgrimesstatic void
132778146Sgadscan_out(struct printer *pp, int scfd, char *scsp, int dlm)
13281553Srgrimes{
13291553Srgrimes	register char *strp;
133039084Swollman	register int nchrs, j;
13311553Srgrimes	char outbuf[LINELEN+1], *sp, c, cc;
13321553Srgrimes	int d, scnhgt;
13331553Srgrimes
13341553Srgrimes	for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) {
13351553Srgrimes		strp = &outbuf[0];
13361553Srgrimes		sp = scsp;
13371553Srgrimes		for (nchrs = 0; ; ) {
13381553Srgrimes			d = dropit(c = TRC(cc = *sp++));
13391553Srgrimes			if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d))
13401553Srgrimes				for (j = WIDTH; --j;)
13411553Srgrimes					*strp++ = BACKGND;
13421553Srgrimes			else
134331492Swollman				strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc);
134431492Swollman			if (*sp == dlm || *sp == '\0' ||
134531492Swollman			    nchrs++ >= pp->page_width/(WIDTH+1)-1)
13461553Srgrimes				break;
13471553Srgrimes			*strp++ = BACKGND;
13481553Srgrimes			*strp++ = BACKGND;
13491553Srgrimes		}
13501553Srgrimes		while (*--strp == BACKGND && strp >= outbuf)
13511553Srgrimes			;
13521553Srgrimes		strp++;
13538857Srgrimes		*strp++ = '\n';
13541553Srgrimes		(void) write(scfd, outbuf, strp-outbuf);
13551553Srgrimes	}
13561553Srgrimes}
13571553Srgrimes
13581553Srgrimesstatic int
135978146Sgaddropit(int c)
13601553Srgrimes{
13611553Srgrimes	switch(c) {
13621553Srgrimes
13631553Srgrimes	case TRC('_'):
13641553Srgrimes	case TRC(';'):
13651553Srgrimes	case TRC(','):
13661553Srgrimes	case TRC('g'):
13671553Srgrimes	case TRC('j'):
13681553Srgrimes	case TRC('p'):
13691553Srgrimes	case TRC('q'):
13701553Srgrimes	case TRC('y'):
13711553Srgrimes		return (DROP);
13721553Srgrimes
13731553Srgrimes	default:
13741553Srgrimes		return (0);
13751553Srgrimes	}
13761553Srgrimes}
13771553Srgrimes
13781553Srgrimes/*
13791553Srgrimes * sendmail ---
13801553Srgrimes *   tell people about job completion
13811553Srgrimes */
13821553Srgrimesstatic void
138394038Sgadsendmail(struct printer *pp, char *userid, int bombed)
13841553Srgrimes{
13851553Srgrimes	register int i;
13861553Srgrimes	int p[2], s;
138778146Sgad	register const char *cp;
13881553Srgrimes	struct stat stb;
13891553Srgrimes	FILE *fp;
13901553Srgrimes
13911553Srgrimes	pipe(p);
139231492Swollman	if ((s = dofork(pp, DORETURN)) == 0) {		/* child */
13931553Srgrimes		dup2(p[0], 0);
13948094Sjkh		closelog();
139531492Swollman		closeallfds(3);
139627635Simp		if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL)
13971553Srgrimes			cp++;
139831492Swollman		else
13991553Srgrimes			cp = _PATH_SENDMAIL;
140079452Sbrian		execl(_PATH_SENDMAIL, cp, "-t", (char *)0);
140131492Swollman		_exit(0);
14021553Srgrimes	} else if (s > 0) {				/* parent */
14031553Srgrimes		dup2(p[1], 1);
140494038Sgad		printf("To: %s@%s\n", userid, origin_host);
140531492Swollman		printf("Subject: %s printer job \"%s\"\n", pp->printer,
140615648Sjoerg			*jobname ? jobname : "<unknown>");
140778300Sgad		printf("Reply-To: root@%s\n\n", local_host);
14081553Srgrimes		printf("Your printer job ");
14091553Srgrimes		if (*jobname)
14101553Srgrimes			printf("(%s) ", jobname);
141194040Sgad
14121553Srgrimes		switch (bombed) {
14131553Srgrimes		case OK:
141494040Sgad			cp = "OK";
14151553Srgrimes			printf("\ncompleted successfully\n");
14161553Srgrimes			break;
14171553Srgrimes		default:
14181553Srgrimes		case FATALERR:
141994040Sgad			cp = "FATALERR";
14201553Srgrimes			printf("\ncould not be printed\n");
14211553Srgrimes			break;
14221553Srgrimes		case NOACCT:
142394040Sgad			cp = "NOACCT";
142478300Sgad			printf("\ncould not be printed without an account on %s\n",
142578300Sgad			    local_host);
14261553Srgrimes			break;
14271553Srgrimes		case FILTERERR:
142894040Sgad			cp = "FILTERERR";
142968664Sgad			if (stat(tempstderr, &stb) < 0 || stb.st_size == 0
143068664Sgad			    || (fp = fopen(tempstderr, "r")) == NULL) {
143115648Sjoerg				printf("\nhad some errors and may not have printed\n");
14321553Srgrimes				break;
14331553Srgrimes			}
143415648Sjoerg			printf("\nhad the following errors and may not have printed:\n");
14351553Srgrimes			while ((i = getc(fp)) != EOF)
14361553Srgrimes				putchar(i);
14371553Srgrimes			(void) fclose(fp);
14381553Srgrimes			break;
14391553Srgrimes		case ACCESS:
144094040Sgad			cp = "ACCESS";
14411553Srgrimes			printf("\nwas not printed because it was not linked to the original file\n");
14421553Srgrimes		}
14431553Srgrimes		fflush(stdout);
14441553Srgrimes		(void) close(1);
144531492Swollman	} else {
144694038Sgad		syslog(LOG_WARNING, "unable to send mail to %s: %m", userid);
144731492Swollman		return;
14481553Srgrimes	}
14491553Srgrimes	(void) close(p[0]);
14501553Srgrimes	(void) close(p[1]);
145115648Sjoerg	wait(NULL);
145215648Sjoerg	syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)",
145394038Sgad	    userid, *jobname ? jobname : "<unknown>", pp->printer, cp);
14541553Srgrimes}
14551553Srgrimes
14561553Srgrimes/*
14571553Srgrimes * dofork - fork with retries on failure
14581553Srgrimes */
14591553Srgrimesstatic int
146078146Sgaddofork(const struct printer *pp, int action)
14611553Srgrimes{
146280230Sgad	int i, fail, forkpid;
146360871Smpp	struct passwd *pwd;
14641553Srgrimes
146580230Sgad	forkpid = -1;
146680230Sgad	if (daemon_uname == NULL) {
146780230Sgad		pwd = getpwuid(pp->daemon_user);
146880230Sgad		if (pwd == NULL) {
146980230Sgad			syslog(LOG_ERR, "%s: Can't lookup default daemon uid (%ld) in password file",
147080230Sgad			    pp->printer, pp->daemon_user);
147180230Sgad			goto error_ret;
147280230Sgad		}
147380230Sgad		daemon_uname = strdup(pwd->pw_name);
147480230Sgad		daemon_defgid = pwd->pw_gid;
147580230Sgad	}
147680230Sgad
14771553Srgrimes	for (i = 0; i < 20; i++) {
147880230Sgad		forkpid = fork();
147980230Sgad		if (forkpid < 0) {
14801553Srgrimes			sleep((unsigned)(i*i));
14811553Srgrimes			continue;
14821553Srgrimes		}
14831553Srgrimes		/*
14841553Srgrimes		 * Child should run as daemon instead of root
14851553Srgrimes		 */
148678146Sgad		if (forkpid == 0) {
148780230Sgad			errno = 0;
148880230Sgad			fail = initgroups(daemon_uname, daemon_defgid);
148980230Sgad			if (fail) {
149080230Sgad				syslog(LOG_ERR, "%s: initgroups(%s,%u): %m",
149180230Sgad				    pp->printer, daemon_uname, daemon_defgid);
149260871Smpp				break;
149360871Smpp			}
149480230Sgad			fail = setgid(daemon_defgid);
149580230Sgad			if (fail) {
149680230Sgad				syslog(LOG_ERR, "%s: setgid(%u): %m",
149780230Sgad				    pp->printer, daemon_defgid);
149880230Sgad				break;
149980230Sgad			}
150080230Sgad			fail = setuid(pp->daemon_user);
150180230Sgad			if (fail) {
150280230Sgad				syslog(LOG_ERR, "%s: setuid(%ld): %m",
150380230Sgad				    pp->printer, pp->daemon_user);
150480230Sgad				break;
150580230Sgad			}
150660871Smpp		}
150780230Sgad		return forkpid;
15081553Srgrimes	}
15091553Srgrimes
151080230Sgad	/*
151180230Sgad	 * An error occurred.  If the error is in the child process, then
151280230Sgad	 * this routine MUST always exit().  DORETURN only effects how
151380230Sgad	 * errors should be handled in the parent process.
151480230Sgad	 */
151580230Sgaderror_ret:
151680230Sgad	if (forkpid == 0) {
151780230Sgad		syslog(LOG_ERR, "%s: dofork(): aborting child process...",
151880230Sgad		    pp->printer);
151980230Sgad		exit(1);
152080230Sgad	}
152180230Sgad	syslog(LOG_ERR, "%s: dofork(): failure in fork", pp->printer);
152280230Sgad
152380230Sgad	sleep(1);		/* throttle errors, as a safety measure */
15241553Srgrimes	switch (action) {
15251553Srgrimes	case DORETURN:
152680230Sgad		return -1;
15271553Srgrimes	default:
15281553Srgrimes		syslog(LOG_ERR, "bad action (%d) to dofork", action);
152980230Sgad		/* FALLTHROUGH */
15301553Srgrimes	case DOABORT:
15311553Srgrimes		exit(1);
15321553Srgrimes	}
15331553Srgrimes	/*NOTREACHED*/
15341553Srgrimes}
15351553Srgrimes
15361553Srgrimes/*
15371553Srgrimes * Kill child processes to abort current job.
15381553Srgrimes */
15391553Srgrimesstatic void
154078146Sgadabortpr(int signo __unused)
15411553Srgrimes{
154268664Sgad
154368664Sgad	(void) unlink(tempstderr);
15441553Srgrimes	kill(0, SIGINT);
15451553Srgrimes	if (ofilter > 0)
15461553Srgrimes		kill(ofilter, SIGCONT);
15471553Srgrimes	while (wait(NULL) > 0)
15481553Srgrimes		;
154924831Sbrian	if (ofilter > 0 && tfd != -1)
155024831Sbrian		unlink(tfile);
15511553Srgrimes	exit(0);
15521553Srgrimes}
15531553Srgrimes
15541553Srgrimesstatic void
155578146Sgadinit(struct printer *pp)
15561553Srgrimes{
15571553Srgrimes	char *s;
15581553Srgrimes
155931492Swollman	sprintf(&width[2], "%ld", pp->page_width);
156031492Swollman	sprintf(&length[2], "%ld", pp->page_length);
156131492Swollman	sprintf(&pxwidth[2], "%ld", pp->page_pwidth);
156231492Swollman	sprintf(&pxlength[2], "%ld", pp->page_plength);
156331492Swollman	if ((s = checkremote(pp)) != 0) {
156431492Swollman		syslog(LOG_WARNING, "%s", s);
156531492Swollman		free(s);
156631492Swollman	}
156731492Swollman}
156831492Swollman
156931492Swollmanvoid
157078146Sgadstartprinting(const char *printer)
157131492Swollman{
157231492Swollman	struct printer myprinter, *pp = &myprinter;
157331492Swollman	int status;
157431492Swollman
157531492Swollman	init_printer(pp);
157631492Swollman	status = getprintcap(printer, pp);
157731492Swollman	switch(status) {
157831492Swollman	case PCAPERR_OSERR:
157931492Swollman		syslog(LOG_ERR, "can't open printer description file: %m");
15801553Srgrimes		exit(1);
158131492Swollman	case PCAPERR_NOTFOUND:
15821553Srgrimes		syslog(LOG_ERR, "unknown printer: %s", printer);
15831553Srgrimes		exit(1);
158431492Swollman	case PCAPERR_TCLOOP:
158531492Swollman		fatal(pp, "potential reference loop detected in printcap file");
158631492Swollman	default:
158731492Swollman		break;
158831492Swollman	}
158931492Swollman	printjob(pp);
15901553Srgrimes}
15911553Srgrimes
15921553Srgrimes/*
15931553Srgrimes * Acquire line printer or remote connection.
15941553Srgrimes */
15951553Srgrimesstatic void
159678146Sgadopenpr(const struct printer *pp)
15971553Srgrimes{
159831492Swollman	int p[2];
159915648Sjoerg	char *cp;
16001553Srgrimes
160131492Swollman	if (pp->remote) {
160231492Swollman		openrem(pp);
160394032Sgad		/*
160494032Sgad		 * Lpd does support the setting of 'of=' filters for
160594032Sgad		 * jobs going to remote machines, but that does not
160694032Sgad		 * have the same meaning as 'of=' does when handling
160794032Sgad		 * local print queues.  For remote machines, all 'of='
160894032Sgad		 * filter processing is handled in sendfile(), and that
160994032Sgad		 * does not use these global "output filter" variables.
161094032Sgad		 */
161194032Sgad		ofd = -1;
161294032Sgad		ofilter = 0;
161394032Sgad		return;
161431492Swollman	} else if (*pp->lp) {
161531492Swollman		if ((cp = strchr(pp->lp, '@')) != NULL)
161631492Swollman			opennet(pp);
161715648Sjoerg		else
161831492Swollman			opentty(pp);
16191553Srgrimes	} else {
16201553Srgrimes		syslog(LOG_ERR, "%s: no line printer device or host name",
162131492Swollman			pp->printer);
16221553Srgrimes		exit(1);
16231553Srgrimes	}
162415648Sjoerg
16251553Srgrimes	/*
16261553Srgrimes	 * Start up an output filter, if needed.
16271553Srgrimes	 */
162831492Swollman	if (pp->filters[LPF_OUTPUT] && !pp->filters[LPF_INPUT] && !ofilter) {
16291553Srgrimes		pipe(p);
163031492Swollman		if (pp->remote) {
163131492Swollman			strcpy(tfile, TFILENAME);
163224831Sbrian			tfd = mkstemp(tfile);
163324831Sbrian		}
163431492Swollman		if ((ofilter = dofork(pp, DOABORT)) == 0) {	/* child */
16351553Srgrimes			dup2(p[0], 0);		/* pipe is std in */
163624831Sbrian			/* tfile/printer is stdout */
163731492Swollman			dup2(pp->remote ? tfd : pfd, 1);
16388094Sjkh			closelog();
163931492Swollman			closeallfds(3);
164031492Swollman			if ((cp = strrchr(pp->filters[LPF_OUTPUT], '/')) == NULL)
164131492Swollman				cp = pp->filters[LPF_OUTPUT];
16421553Srgrimes			else
16431553Srgrimes				cp++;
164479452Sbrian			execl(pp->filters[LPF_OUTPUT], cp, width, length,
164579452Sbrian			      (char *)0);
164631492Swollman			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
164731492Swollman			       pp->filters[LPF_OUTPUT]);
16481553Srgrimes			exit(1);
16491553Srgrimes		}
16501553Srgrimes		(void) close(p[0]);		/* close input side */
16511553Srgrimes		ofd = p[1];			/* use pipe for output */
16521553Srgrimes	} else {
16531553Srgrimes		ofd = pfd;
16541553Srgrimes		ofilter = 0;
16551553Srgrimes	}
16561553Srgrimes}
16571553Srgrimes
165815648Sjoerg/*
165915648Sjoerg * Printer connected directly to the network
166015648Sjoerg * or to a terminal server on the net
166115648Sjoerg */
166215648Sjoergstatic void
166378146Sgadopennet(const struct printer *pp)
166415648Sjoerg{
166515648Sjoerg	register int i;
166631492Swollman	int resp;
166731492Swollman	u_long port;
166831492Swollman	char *ep;
166930407Sjoerg	void (*savealrm)(int);
167015648Sjoerg
167131492Swollman	port = strtoul(pp->lp, &ep, 0);
167238470Sbrian	if (*ep != '@' || port > 65535) {
167331492Swollman		syslog(LOG_ERR, "%s: bad port number: %s", pp->printer,
167431492Swollman		       pp->lp);
167515648Sjoerg		exit(1);
167615648Sjoerg	}
167731492Swollman	ep++;
167815648Sjoerg
167915648Sjoerg	for (i = 1; ; i = i < 256 ? i << 1 : i) {
168015648Sjoerg		resp = -1;
168130407Sjoerg		savealrm = signal(SIGALRM, alarmhandler);
168231492Swollman		alarm(pp->conn_timeout);
168331492Swollman		pfd = getport(pp, ep, port);
168431020Sjoerg		alarm(0);
168530407Sjoerg		(void)signal(SIGALRM, savealrm);
168615648Sjoerg		if (pfd < 0 && errno == ECONNREFUSED)
168715648Sjoerg			resp = 1;
168815648Sjoerg		else if (pfd >= 0) {
168915648Sjoerg			/*
169015648Sjoerg			 * need to delay a bit for rs232 lines
169115648Sjoerg			 * to stabilize in case printer is
169215648Sjoerg			 * connected via a terminal server
169315648Sjoerg			 */
169415648Sjoerg			delay(500);
169515648Sjoerg			break;
169615648Sjoerg		}
169715648Sjoerg		if (i == 1) {
169831492Swollman			if (resp < 0)
169931492Swollman				pstatus(pp, "waiting for %s to come up",
170031492Swollman					pp->lp);
170131492Swollman			else
170231492Swollman				pstatus(pp,
170331492Swollman					"waiting for access to printer on %s",
170431492Swollman					pp->lp);
170515648Sjoerg		}
170615648Sjoerg		sleep(i);
170715648Sjoerg	}
170879739Sgad	pstatus(pp, "sending to %s port %lu", ep, port);
170915648Sjoerg}
171015648Sjoerg
171115648Sjoerg/*
171215648Sjoerg * Printer is connected to an RS232 port on this host
171315648Sjoerg */
171415648Sjoergstatic void
171578146Sgadopentty(const struct printer *pp)
171615648Sjoerg{
171715648Sjoerg	register int i;
171815648Sjoerg
171915648Sjoerg	for (i = 1; ; i = i < 32 ? i << 1 : i) {
172031492Swollman		pfd = open(pp->lp, pp->rw ? O_RDWR : O_WRONLY);
172115648Sjoerg		if (pfd >= 0) {
172215648Sjoerg			delay(500);
172315648Sjoerg			break;
172415648Sjoerg		}
172515648Sjoerg		if (errno == ENOENT) {
172631492Swollman			syslog(LOG_ERR, "%s: %m", pp->lp);
172715648Sjoerg			exit(1);
172815648Sjoerg		}
172915648Sjoerg		if (i == 1)
173031492Swollman			pstatus(pp,
173131492Swollman				"waiting for %s to become ready (offline?)",
173231492Swollman				pp->printer);
173315648Sjoerg		sleep(i);
173415648Sjoerg	}
173515648Sjoerg	if (isatty(pfd))
173631492Swollman		setty(pp);
173731492Swollman	pstatus(pp, "%s is ready and printing", pp->printer);
173815648Sjoerg}
173915648Sjoerg
174015648Sjoerg/*
174115648Sjoerg * Printer is on a remote host
174215648Sjoerg */
174315648Sjoergstatic void
174478146Sgadopenrem(const struct printer *pp)
174515648Sjoerg{
174631492Swollman	register int i;
174727748Simp	int resp;
174830407Sjoerg	void (*savealrm)(int);
174915648Sjoerg
175015648Sjoerg	for (i = 1; ; i = i < 256 ? i << 1 : i) {
175115648Sjoerg		resp = -1;
175230407Sjoerg		savealrm = signal(SIGALRM, alarmhandler);
175331492Swollman		alarm(pp->conn_timeout);
175431492Swollman		pfd = getport(pp, pp->remote_host, 0);
175531020Sjoerg		alarm(0);
175630407Sjoerg		(void)signal(SIGALRM, savealrm);
175715648Sjoerg		if (pfd >= 0) {
175831492Swollman			if ((writel(pfd, "\2", pp->remote_queue, "\n",
175931492Swollman				    (char *)0)
176031492Swollman			     == 2 + strlen(pp->remote_queue))
176131492Swollman			    && (resp = response(pp)) == 0)
176215648Sjoerg				break;
176315648Sjoerg			(void) close(pfd);
176415648Sjoerg		}
176515648Sjoerg		if (i == 1) {
176615648Sjoerg			if (resp < 0)
176731492Swollman				pstatus(pp, "waiting for %s to come up",
176831492Swollman					pp->remote_host);
176915648Sjoerg			else {
177031492Swollman				pstatus(pp,
177131492Swollman					"waiting for queue to be enabled on %s",
177231492Swollman					pp->remote_host);
177315648Sjoerg				i = 256;
177415648Sjoerg			}
177515648Sjoerg		}
177615648Sjoerg		sleep(i);
177715648Sjoerg	}
177831492Swollman	pstatus(pp, "sending to %s", pp->remote_host);
177915648Sjoerg}
178015648Sjoerg
17811553Srgrimes/*
17821553Srgrimes * setup tty lines.
17831553Srgrimes */
17841553Srgrimesstatic void
178578146Sgadsetty(const struct printer *pp)
17861553Srgrimes{
178715032Ssef	struct termios ttybuf;
17881553Srgrimes
17891553Srgrimes	if (ioctl(pfd, TIOCEXCL, (char *)0) < 0) {
179031492Swollman		syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", pp->printer);
17911553Srgrimes		exit(1);
17921553Srgrimes	}
179315032Ssef	if (tcgetattr(pfd, &ttybuf) < 0) {
179431492Swollman		syslog(LOG_ERR, "%s: tcgetattr: %m", pp->printer);
17951553Srgrimes		exit(1);
17961553Srgrimes	}
179731492Swollman	if (pp->baud_rate > 0)
179831492Swollman		cfsetspeed(&ttybuf, pp->baud_rate);
179931492Swollman	if (pp->mode_set) {
180031492Swollman		char *s = strdup(pp->mode_set), *tmp;
180115032Ssef
180231492Swollman		while ((tmp = strsep(&s, ",")) != NULL) {
180339084Swollman			(void) msearch(tmp, &ttybuf);
18041553Srgrimes		}
18051553Srgrimes	}
180631492Swollman	if (pp->mode_set != 0 || pp->baud_rate > 0) {
180715032Ssef		if (tcsetattr(pfd, TCSAFLUSH, &ttybuf) == -1) {
180831492Swollman			syslog(LOG_ERR, "%s: tcsetattr: %m", pp->printer);
18091553Srgrimes		}
18101553Srgrimes	}
18111553Srgrimes}
18121553Srgrimes
181327757Simp#ifdef __STDC__
18141553Srgrimes#include <stdarg.h>
18151553Srgrimes#else
18161553Srgrimes#include <varargs.h>
18171553Srgrimes#endif
18181553Srgrimes
181915648Sjoergstatic void
182027757Simp#ifdef __STDC__
182131492Swollmanpstatus(const struct printer *pp, const char *msg, ...)
18221553Srgrimes#else
182331492Swollmanpstatus(pp, msg, va_alist)
182431492Swollman	const struct printer *pp;
18251553Srgrimes	char *msg;
18261553Srgrimes        va_dcl
18271553Srgrimes#endif
18281553Srgrimes{
182931492Swollman	int fd;
183031492Swollman	char *buf;
18311553Srgrimes	va_list ap;
183227757Simp#ifdef __STDC__
18331553Srgrimes	va_start(ap, msg);
18341553Srgrimes#else
18351553Srgrimes	va_start(ap);
18361553Srgrimes#endif
18371553Srgrimes
18381553Srgrimes	umask(0);
183931492Swollman	fd = open(pp->status_file, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
184031492Swollman	if (fd < 0) {
184131492Swollman		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->status_file);
18421553Srgrimes		exit(1);
18431553Srgrimes	}
18441553Srgrimes	ftruncate(fd, 0);
184531492Swollman	vasprintf(&buf, msg, ap);
18461553Srgrimes	va_end(ap);
184731492Swollman	writel(fd, buf, "\n", (char *)0);
184831492Swollman	close(fd);
184931492Swollman	free(buf);
18501553Srgrimes}
185130407Sjoerg
185230407Sjoergvoid
185378146Sgadalarmhandler(int signo __unused)
185430407Sjoerg{
185578146Sgad	/* the signal is ignored */
185678146Sgad	/* (the '__unused' is just to avoid a compile-time warning) */
185730407Sjoerg}
1858