printjob.c revision 97781
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 *    must display the following acknowledgement:
16 *	This product includes software developed by the University of
17 *	California, Berkeley and its contributors.
18 * 4. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#ifndef lint
36static const char copyright[] =
37"@(#) Copyright (c) 1983, 1993\n\
38	The Regents of the University of California.  All rights reserved.\n";
39#endif /* not lint */
40
41#ifndef lint
42/*
43static char sccsid[] = "@(#)printjob.c	8.7 (Berkeley) 5/10/95";
44*/
45static const char rcsid[] =
46  "$FreeBSD: head/usr.sbin/lpr/lpd/printjob.c 97781 2002-06-03 20:47:01Z gad $";
47#endif /* not lint */
48
49
50/*
51 * printjob -- print jobs in the queue.
52 *
53 *	NOTE: the lock file is used to pass information to lpq and lprm.
54 *	it does not need to be removed because file locks are dynamic.
55 */
56
57#include <sys/param.h>
58#include <sys/wait.h>
59#include <sys/stat.h>
60#include <sys/types.h>
61
62#include <pwd.h>
63#include <unistd.h>
64#include <signal.h>
65#include <syslog.h>
66#include <fcntl.h>
67#include <dirent.h>
68#include <errno.h>
69#include <stdio.h>
70#include <string.h>
71#include <stdlib.h>
72#include <sys/ioctl.h>
73#include <termios.h>
74#include <time.h>
75#include "lp.h"
76#include "lp.local.h"
77#include "pathnames.h"
78#include "extern.h"
79
80#define DORETURN	0	/* dofork should return "can't fork" error */
81#define DOABORT		1	/* dofork should just die if fork() fails */
82
83/*
84 * Error tokens
85 */
86#define REPRINT		-2
87#define ERROR		-1
88#define	OK		0
89#define	FATALERR	1
90#define	NOACCT		2
91#define	FILTERERR	3
92#define	ACCESS		4
93
94static dev_t	 fdev;		/* device of file pointed to by symlink */
95static ino_t	 fino;		/* inode of file pointed to by symlink */
96static FILE	*cfp;		/* control file */
97static int	 child;		/* id of any filters */
98static int	 job_dfcnt;	/* count of datafiles in current user job */
99static int	 lfd;		/* lock file descriptor */
100static int	 ofd;		/* output filter file descriptor */
101static int	 ofilter;	/* id of output filter, if any */
102static int	 tfd = -1;	/* output filter temp file output */
103static int	 pfd;		/* prstatic inter file descriptor */
104static int	 pid;		/* pid of lpd process */
105static int	 prchild;	/* id of pr process */
106static char	 title[80];	/* ``pr'' title */
107static char      locale[80];    /* ``pr'' locale */
108
109/* these two are set from pp->daemon_user, but only if they are needed */
110static char	*daemon_uname;	/* set from pwd->pw_name */
111static int	 daemon_defgid;
112
113static char	class[32];		/* classification field */
114static char	origin_host[MAXHOSTNAMELEN];	/* user's host machine */
115				/* indentation size in static characters */
116static char	indent[10] = "-i0";
117static char	jobname[100];		/* job or file name */
118static char	length[10] = "-l";	/* page length in lines */
119static char	logname[32];		/* user's login name */
120static char	pxlength[10] = "-y";	/* page length in pixels */
121static char	pxwidth[10] = "-x";	/* page width in pixels */
122/* tempstderr is the filename used to catch stderr from exec-ing filters */
123static char	tempstderr[] = "errs.XXXXXXX";
124static char	width[10] = "-w";	/* page width in static characters */
125#define TFILENAME "fltXXXXXX"
126static char	tfile[] = TFILENAME;	/* file name for filter output */
127
128static void	 abortpr(int _signo);
129static void	 alarmhandler(int _signo);
130static void	 banner(struct printer *_pp, char *_name1, char *_name2);
131static int	 dofork(const struct printer *_pp, int _action);
132static int	 dropit(int _c);
133static int	 execfilter(struct printer *_pp, char *_f_cmd, char **_f_av,
134		    int _infd, int _outfd);
135static void	 init(struct printer *_pp);
136static void	 openpr(const struct printer *_pp);
137static void	 opennet(const struct printer *_pp);
138static void	 opentty(const struct printer *_pp);
139static void	 openrem(const struct printer *pp);
140static int	 print(struct printer *_pp, int _format, char *_file);
141static int	 printit(struct printer *_pp, char *_file);
142static void	 pstatus(const struct printer *_pp, const char *_msg, ...)
143		    __printflike(2, 3);
144static char	 response(const struct printer *_pp);
145static void	 scan_out(struct printer *_pp, int _scfd, char *_scsp,
146		    int _dlm);
147static char	*scnline(int _key, char *_p, int _c);
148static int	 sendfile(struct printer *_pp, int _type, char *_file,
149		    char _format, int _copyreq);
150static int	 sendit(struct printer *_pp, char *_file);
151static void	 sendmail(struct printer *_pp, char *_userid, int _bombed);
152static void	 setty(const struct printer *_pp);
153
154void
155printjob(struct printer *pp)
156{
157	struct stat stb;
158	register struct jobqueue *q, **qp;
159	struct jobqueue **queue;
160	register int i, nitems;
161	off_t pidoff;
162	int errcnt, jobcount, tempfd;
163
164	jobcount = 0;
165	init(pp); /* set up capabilities */
166	(void) write(1, "", 1);	/* ack that daemon is started */
167	(void) close(2);			/* set up log file */
168	if (open(pp->log_file, O_WRONLY|O_APPEND, LOG_FILE_MODE) < 0) {
169		syslog(LOG_ERR, "%s: %m", pp->log_file);
170		(void) open(_PATH_DEVNULL, O_WRONLY);
171	}
172	setgid(getegid());
173	pid = getpid();				/* for use with lprm */
174	setpgrp(0, pid);
175
176	/*
177	 * At initial lpd startup, printjob may be called with various
178	 * signal handlers in effect.  After that initial startup, any
179	 * calls to printjob will have a *different* set of signal-handlers
180	 * in effect.  Make sure all handlers are the ones we want.
181	 */
182	signal(SIGCHLD, SIG_DFL);
183	signal(SIGHUP, abortpr);
184	signal(SIGINT, abortpr);
185	signal(SIGQUIT, abortpr);
186	signal(SIGTERM, abortpr);
187
188	/*
189	 * uses short form file names
190	 */
191	if (chdir(pp->spool_dir) < 0) {
192		syslog(LOG_ERR, "%s: %m", pp->spool_dir);
193		exit(1);
194	}
195	if (stat(pp->lock_file, &stb) == 0 && (stb.st_mode & LFM_PRINT_DIS))
196		exit(0);		/* printing disabled */
197	lfd = open(pp->lock_file, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
198		   LOCK_FILE_MODE);
199	if (lfd < 0) {
200		if (errno == EWOULDBLOCK)	/* active daemon present */
201			exit(0);
202		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
203		exit(1);
204	}
205	/* turn off non-blocking mode (was turned on for lock effects only) */
206	if (fcntl(lfd, F_SETFL, 0) < 0) {
207		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
208		exit(1);
209	}
210	ftruncate(lfd, 0);
211	/*
212	 * write process id for others to know
213	 */
214	sprintf(line, "%u\n", pid);
215	pidoff = i = strlen(line);
216	if (write(lfd, line, i) != i) {
217		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->lock_file);
218		exit(1);
219	}
220	/*
221	 * search the spool directory for work and sort by queue order.
222	 */
223	if ((nitems = getq(pp, &queue)) < 0) {
224		syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
225		       pp->spool_dir);
226		exit(1);
227	}
228	if (nitems == 0)		/* no work to do */
229		exit(0);
230	if (stb.st_mode & LFM_RESET_QUE) { /* reset queue flag */
231		if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE) < 0)
232			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
233			       pp->lock_file);
234	}
235
236	/* create a file which will be used to hold stderr from filters */
237	if ((tempfd = mkstemp(tempstderr)) == -1) {
238		syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
239		       tempstderr);
240		exit(1);
241	}
242	if ((i = fchmod(tempfd, 0664)) == -1) {
243		syslog(LOG_ERR, "%s: fchmod(%s): %m", pp->printer,
244		       tempstderr);
245		exit(1);
246	}
247	/* lpd doesn't need it to be open, it just needs it to exist */
248	close(tempfd);
249
250	openpr(pp);			/* open printer or remote */
251again:
252	/*
253	 * we found something to do now do it --
254	 *    write the name of the current control file into the lock file
255	 *    so the spool queue program can tell what we're working on
256	 */
257	for (qp = queue; nitems--; free((char *) q)) {
258		q = *qp++;
259		if (stat(q->job_cfname, &stb) < 0)
260			continue;
261		errcnt = 0;
262	restart:
263		(void) lseek(lfd, pidoff, 0);
264		(void) snprintf(line, sizeof(line), "%s\n", q->job_cfname);
265		i = strlen(line);
266		if (write(lfd, line, i) != i)
267			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
268			       pp->lock_file);
269		if (!pp->remote)
270			i = printit(pp, q->job_cfname);
271		else
272			i = sendit(pp, q->job_cfname);
273		/*
274		 * Check to see if we are supposed to stop printing or
275		 * if we are to rebuild the queue.
276		 */
277		if (fstat(lfd, &stb) == 0) {
278			/* stop printing before starting next job? */
279			if (stb.st_mode & LFM_PRINT_DIS)
280				goto done;
281			/* rebuild queue (after lpc topq) */
282			if (stb.st_mode & LFM_RESET_QUE) {
283				for (free(q); nitems--; free(q))
284					q = *qp++;
285				if (fchmod(lfd, stb.st_mode & ~LFM_RESET_QUE)
286				    < 0)
287					syslog(LOG_WARNING, "%s: %s: %m",
288					       pp->printer, pp->lock_file);
289				break;
290			}
291		}
292		if (i == OK)		/* all files of this job printed */
293			jobcount++;
294		else if (i == REPRINT && ++errcnt < 5) {
295			/* try reprinting the job */
296			syslog(LOG_INFO, "restarting %s", pp->printer);
297			if (ofilter > 0) {
298				kill(ofilter, SIGCONT);	/* to be sure */
299				(void) close(ofd);
300				while ((i = wait(NULL)) > 0 && i != ofilter)
301					;
302				if (i < 0)
303					syslog(LOG_WARNING, "%s: after kill(of=%d), wait() returned: %m",
304					    pp->printer, ofilter);
305				ofilter = 0;
306			}
307			(void) close(pfd);	/* close printer */
308			if (ftruncate(lfd, pidoff) < 0)
309				syslog(LOG_WARNING, "%s: %s: %m",
310				       pp->printer, pp->lock_file);
311			openpr(pp);		/* try to reopen printer */
312			goto restart;
313		} else {
314			syslog(LOG_WARNING, "%s: job could not be %s (%s)",
315			       pp->printer,
316			       pp->remote ? "sent to remote host" : "printed",
317			       q->job_cfname);
318			if (i == REPRINT) {
319				/* ensure we don't attempt this job again */
320				(void) unlink(q->job_cfname);
321				q->job_cfname[0] = 'd';
322				(void) unlink(q->job_cfname);
323				if (logname[0])
324					sendmail(pp, logname, FATALERR);
325			}
326		}
327	}
328	free(queue);
329	/*
330	 * search the spool directory for more work.
331	 */
332	if ((nitems = getq(pp, &queue)) < 0) {
333		syslog(LOG_ERR, "%s: can't scan %s", pp->printer,
334		       pp->spool_dir);
335		exit(1);
336	}
337	if (nitems == 0) {		/* no more work to do */
338	done:
339		if (jobcount > 0) {	/* jobs actually printed */
340			if (!pp->no_formfeed && !pp->tof)
341				(void) write(ofd, pp->form_feed,
342					     strlen(pp->form_feed));
343			if (pp->trailer != NULL) /* output trailer */
344				(void) write(ofd, pp->trailer,
345					     strlen(pp->trailer));
346		}
347		(void) close(ofd);
348		(void) wait(NULL);
349		(void) unlink(tempstderr);
350		exit(0);
351	}
352	goto again;
353}
354
355char	fonts[4][50];	/* fonts for troff */
356
357char ifonts[4][40] = {
358	_PATH_VFONTR,
359	_PATH_VFONTI,
360	_PATH_VFONTB,
361	_PATH_VFONTS,
362};
363
364/*
365 * The remaining part is the reading of the control file (cf)
366 * and performing the various actions.
367 */
368static int
369printit(struct printer *pp, char *file)
370{
371	register int i;
372	char *cp;
373	int bombed, didignorehdr;
374
375	bombed = OK;
376	didignorehdr = 0;
377	/*
378	 * open control file; ignore if no longer there.
379	 */
380	if ((cfp = fopen(file, "r")) == NULL) {
381		syslog(LOG_INFO, "%s: %s: %m", pp->printer, file);
382		return(OK);
383	}
384	/*
385	 * Reset troff fonts.
386	 */
387	for (i = 0; i < 4; i++)
388		strcpy(fonts[i], ifonts[i]);
389	sprintf(&width[2], "%ld", pp->page_width);
390	strcpy(indent+2, "0");
391
392	/* initialize job-specific count of datafiles processed */
393	job_dfcnt = 0;
394
395	/*
396	 *      read the control file for work to do
397	 *
398	 *      file format -- first character in the line is a command
399	 *      rest of the line is the argument.
400	 *      valid commands are:
401	 *
402	 *		S -- "stat info" for symbolic link protection
403	 *		J -- "job name" on banner page
404	 *		C -- "class name" on banner page
405	 *              L -- "literal" user's name to print on banner
406	 *		T -- "title" for pr
407	 *		H -- "host name" of machine where lpr was done
408	 *              P -- "person" user's login name
409	 *              I -- "indent" amount to indent output
410	 *		R -- laser dpi "resolution"
411	 *              f -- "file name" name of text file to print
412	 *		l -- "file name" text file with control chars
413	 *		o -- "file name" postscript file, according to
414	 *		     the RFC.  Here it is treated like an 'f'.
415	 *		p -- "file name" text file to print with pr(1)
416	 *		t -- "file name" troff(1) file to print
417	 *		n -- "file name" ditroff(1) file to print
418	 *		d -- "file name" dvi file to print
419	 *		g -- "file name" plot(1G) file to print
420	 *		v -- "file name" plain raster file to print
421	 *		c -- "file name" cifplot file to print
422	 *		1 -- "R font file" for troff
423	 *		2 -- "I font file" for troff
424	 *		3 -- "B font file" for troff
425	 *		4 -- "S font file" for troff
426	 *		N -- "name" of file (used by lpq)
427	 *              U -- "unlink" name of file to remove
428	 *                    (after we print it. (Pass 2 only)).
429	 *		M -- "mail" to user when done printing
430	 *              Z -- "locale" for pr
431	 *
432	 *      getline reads a line and expands tabs to blanks
433	 */
434
435	/* pass 1 */
436
437	while (getline(cfp))
438		switch (line[0]) {
439		case 'H':
440			strlcpy(origin_host, line + 1, sizeof(origin_host));
441			if (class[0] == '\0') {
442				strlcpy(class, line+1, sizeof(class));
443			}
444			continue;
445
446		case 'P':
447			strlcpy(logname, line + 1, sizeof(logname));
448			if (pp->restricted) { /* restricted */
449				if (getpwnam(logname) == NULL) {
450					bombed = NOACCT;
451					sendmail(pp, line+1, bombed);
452					goto pass2;
453				}
454			}
455			continue;
456
457		case 'S':
458			cp = line+1;
459			i = 0;
460			while (*cp >= '0' && *cp <= '9')
461				i = i * 10 + (*cp++ - '0');
462			fdev = i;
463			cp++;
464			i = 0;
465			while (*cp >= '0' && *cp <= '9')
466				i = i * 10 + (*cp++ - '0');
467			fino = i;
468			continue;
469
470		case 'J':
471			if (line[1] != '\0') {
472				strlcpy(jobname, line + 1, sizeof(jobname));
473			} else
474				strcpy(jobname, " ");
475			continue;
476
477		case 'C':
478			if (line[1] != '\0')
479				strlcpy(class, line + 1, sizeof(class));
480			else if (class[0] == '\0') {
481				/* XXX - why call gethostname instead of
482				 *       just strlcpy'ing local_host? */
483				gethostname(class, sizeof(class));
484				class[sizeof(class) - 1] = '\0';
485			}
486			continue;
487
488		case 'T':	/* header title for pr */
489			strlcpy(title, line + 1, sizeof(title));
490			continue;
491
492		case 'L':	/* identification line */
493			if (!pp->no_header && !pp->header_last)
494				banner(pp, line+1, jobname);
495			continue;
496
497		case '1':	/* troff fonts */
498		case '2':
499		case '3':
500		case '4':
501			if (line[1] != '\0') {
502				strlcpy(fonts[line[0]-'1'], line + 1,
503				    (size_t)50);
504			}
505			continue;
506
507		case 'W':	/* page width */
508			strlcpy(width+2, line + 1, sizeof(width) - 2);
509			continue;
510
511		case 'I':	/* indent amount */
512			strlcpy(indent+2, line + 1, sizeof(indent) - 2);
513			continue;
514
515		case 'Z':       /* locale for pr */
516			strlcpy(locale, line + 1, sizeof(locale));
517			continue;
518
519		default:	/* some file to print */
520			/* only lowercase cmd-codes include a file-to-print */
521			if ((line[0] < 'a') || (line[0] > 'z')) {
522				/* ignore any other lines */
523				if (lflag <= 1)
524					continue;
525				if (!didignorehdr) {
526					syslog(LOG_INFO, "%s: in %s :",
527					       pp->printer, file);
528					didignorehdr = 1;
529				}
530				syslog(LOG_INFO, "%s: ignoring line: '%c' %s",
531				       pp->printer, line[0], &line[1]);
532				continue;
533			}
534			i = print(pp, line[0], line+1);
535			switch (i) {
536			case ERROR:
537				if (bombed == OK)
538					bombed = FATALERR;
539				break;
540			case REPRINT:
541				(void) fclose(cfp);
542				return(REPRINT);
543			case FILTERERR:
544			case ACCESS:
545				bombed = i;
546				sendmail(pp, logname, bombed);
547			}
548			title[0] = '\0';
549			continue;
550
551		case 'N':
552		case 'U':
553		case 'M':
554		case 'R':
555			continue;
556		}
557
558	/* pass 2 */
559
560pass2:
561	fseek(cfp, 0L, 0);
562	while (getline(cfp))
563		switch (line[0]) {
564		case 'L':	/* identification line */
565			if (!pp->no_header && pp->header_last)
566				banner(pp, line+1, jobname);
567			continue;
568
569		case 'M':
570			if (bombed < NOACCT)	/* already sent if >= NOACCT */
571				sendmail(pp, line+1, bombed);
572			continue;
573
574		case 'U':
575			if (strchr(line+1, '/'))
576				continue;
577			(void) unlink(line+1);
578		}
579	/*
580	 * clean-up in case another control file exists
581	 */
582	(void) fclose(cfp);
583	(void) unlink(file);
584	return(bombed == OK ? OK : ERROR);
585}
586
587/*
588 * Print a file.
589 * Set up the chain [ PR [ | {IF, OF} ] ] or {IF, RF, TF, NF, DF, CF, VF}.
590 * Return -1 if a non-recoverable error occured,
591 * 2 if the filter detected some errors (but printed the job anyway),
592 * 1 if we should try to reprint this job and
593 * 0 if all is well.
594 * Note: all filters take stdin as the file, stdout as the printer,
595 * stderr as the log file, and must not ignore SIGINT.
596 */
597static int
598print(struct printer *pp, int format, char *file)
599{
600	register int n, i;
601	register char *prog;
602	int fi, fo;
603	FILE *fp;
604	char *av[15], buf[BUFSIZ];
605	int pid, p[2], retcode, stopped, wstatus;
606	struct stat stb;
607
608	if (lstat(file, &stb) < 0 || (fi = open(file, O_RDONLY)) < 0) {
609		syslog(LOG_INFO, "%s: unable to open %s ('%c' line)",
610		       pp->printer, file, format);
611		return(ERROR);
612	}
613	/*
614	 * Check to see if data file is a symbolic link. If so, it should
615	 * still point to the same file or someone is trying to print
616	 * something he shouldn't.
617	 */
618	if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(fi, &stb) == 0 &&
619	    (stb.st_dev != fdev || stb.st_ino != fino))
620		return(ACCESS);
621
622	job_dfcnt++;		/* increment datafile counter for this job */
623	stopped = 0;		/* output filter is not stopped */
624
625	/* everything seems OK, start it up */
626	if (!pp->no_formfeed && !pp->tof) { /* start on a fresh page */
627		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
628		pp->tof = 1;
629	}
630	if (pp->filters[LPF_INPUT] == NULL
631	    && (format == 'f' || format == 'l' || format == 'o')) {
632		pp->tof = 0;
633		while ((n = read(fi, buf, BUFSIZ)) > 0)
634			if (write(ofd, buf, n) != n) {
635				(void) close(fi);
636				return(REPRINT);
637			}
638		(void) close(fi);
639		return(OK);
640	}
641	switch (format) {
642	case 'p':	/* print file using 'pr' */
643		if (pp->filters[LPF_INPUT] == NULL) {	/* use output filter */
644			prog = _PATH_PR;
645			i = 0;
646			av[i++] = "pr";
647			av[i++] = width;
648			av[i++] = length;
649			av[i++] = "-h";
650			av[i++] = *title ? title : " ";
651			av[i++] = "-L";
652			av[i++] = *locale ? locale : "C";
653			av[i++] = "-F";
654			av[i] = 0;
655			fo = ofd;
656			goto start;
657		}
658		pipe(p);
659		if ((prchild = dofork(pp, DORETURN)) == 0) {	/* child */
660			dup2(fi, 0);		/* file is stdin */
661			dup2(p[1], 1);		/* pipe is stdout */
662			closelog();
663			closeallfds(3);
664			execl(_PATH_PR, "pr", width, length,
665			    "-h", *title ? title : " ",
666			    "-L", *locale ? locale : "C",
667			    "-F", (char *)0);
668			syslog(LOG_ERR, "cannot execl %s", _PATH_PR);
669			exit(2);
670		}
671		(void) close(p[1]);		/* close output side */
672		(void) close(fi);
673		if (prchild < 0) {
674			prchild = 0;
675			(void) close(p[0]);
676			return(ERROR);
677		}
678		fi = p[0];			/* use pipe for input */
679	case 'f':	/* print plain text file */
680		prog = pp->filters[LPF_INPUT];
681		av[1] = width;
682		av[2] = length;
683		av[3] = indent;
684		n = 4;
685		break;
686	case 'o':	/* print postscript file */
687		/*
688		 * Treat this as a "plain file with control characters", and
689		 * assume the standard LPF_INPUT filter will recognize that
690		 * the data is postscript and know what to do with it.  These
691		 * 'o'-file requests could come from MacOS 10.1 systems.
692		 * (later versions of MacOS 10 will explicitly use 'l')
693		 * A postscript file can contain binary data, which is why 'l'
694		 * is somewhat more appropriate than 'f'.
695		 */
696		/* FALLTHROUGH */
697	case 'l':	/* like 'f' but pass control characters */
698		prog = pp->filters[LPF_INPUT];
699		av[1] = "-c";
700		av[2] = width;
701		av[3] = length;
702		av[4] = indent;
703		n = 5;
704		break;
705	case 'r':	/* print a fortran text file */
706		prog = pp->filters[LPF_FORTRAN];
707		av[1] = width;
708		av[2] = length;
709		n = 3;
710		break;
711	case 't':	/* print troff output */
712	case 'n':	/* print ditroff output */
713	case 'd':	/* print tex output */
714		(void) unlink(".railmag");
715		if ((fo = creat(".railmag", FILMOD)) < 0) {
716			syslog(LOG_ERR, "%s: cannot create .railmag",
717			       pp->printer);
718			(void) unlink(".railmag");
719		} else {
720			for (n = 0; n < 4; n++) {
721				if (fonts[n][0] != '/')
722					(void) write(fo, _PATH_VFONT,
723					    sizeof(_PATH_VFONT) - 1);
724				(void) write(fo, fonts[n], strlen(fonts[n]));
725				(void) write(fo, "\n", 1);
726			}
727			(void) close(fo);
728		}
729		prog = (format == 't') ? pp->filters[LPF_TROFF]
730			: ((format == 'n') ? pp->filters[LPF_DITROFF]
731			   : pp->filters[LPF_DVI]);
732		av[1] = pxwidth;
733		av[2] = pxlength;
734		n = 3;
735		break;
736	case 'c':	/* print cifplot output */
737		prog = pp->filters[LPF_CIFPLOT];
738		av[1] = pxwidth;
739		av[2] = pxlength;
740		n = 3;
741		break;
742	case 'g':	/* print plot(1G) output */
743		prog = pp->filters[LPF_GRAPH];
744		av[1] = pxwidth;
745		av[2] = pxlength;
746		n = 3;
747		break;
748	case 'v':	/* print raster output */
749		prog = pp->filters[LPF_RASTER];
750		av[1] = pxwidth;
751		av[2] = pxlength;
752		n = 3;
753		break;
754	default:
755		(void) close(fi);
756		syslog(LOG_ERR, "%s: illegal format character '%c'",
757			pp->printer, format);
758		return(ERROR);
759	}
760	if (prog == NULL) {
761		(void) close(fi);
762		syslog(LOG_ERR,
763		   "%s: no filter found in printcap for format character '%c'",
764		   pp->printer, format);
765		return(ERROR);
766	}
767	if ((av[0] = strrchr(prog, '/')) != NULL)
768		av[0]++;
769	else
770		av[0] = prog;
771	av[n++] = "-n";
772	av[n++] = logname;
773	av[n++] = "-h";
774	av[n++] = origin_host;
775	av[n++] = pp->acct_file;
776	av[n] = 0;
777	fo = pfd;
778	if (ofilter > 0) {		/* stop output filter */
779		write(ofd, "\031\1", 2);
780		while ((pid =
781		    wait3(&wstatus, WUNTRACED, 0)) > 0 && pid != ofilter)
782			;
783		if (pid < 0)
784			syslog(LOG_WARNING, "%s: after stopping 'of', wait3() returned: %m",
785			    pp->printer);
786		else if (!WIFSTOPPED(wstatus)) {
787			(void) close(fi);
788			syslog(LOG_WARNING, "%s: output filter died "
789			    "(pid=%d retcode=%d termsig=%d)",
790			    pp->printer, ofilter, WEXITSTATUS(wstatus),
791			    WTERMSIG(wstatus));
792			return(REPRINT);
793		}
794		stopped++;
795	}
796start:
797	if ((child = dofork(pp, DORETURN)) == 0) { /* child */
798		dup2(fi, 0);
799		dup2(fo, 1);
800		/* setup stderr for the filter (child process)
801		 * so it goes to our temporary errors file */
802		n = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
803		if (n >= 0)
804			dup2(n, 2);
805		closelog();
806		closeallfds(3);
807		execv(prog, av);
808		syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer,
809		    prog);
810		exit(2);
811	}
812	(void) close(fi);
813	if (child < 0)
814		retcode = 100;
815	else {
816		while ((pid = wait(&wstatus)) > 0 && pid != child)
817			;
818		if (pid < 0) {
819			retcode = 100;
820			syslog(LOG_WARNING, "%s: after execv(%s), wait() returned: %m",
821			    pp->printer, prog);
822		} else
823			retcode = WEXITSTATUS(wstatus);
824	}
825	child = 0;
826	prchild = 0;
827	if (stopped) {		/* restart output filter */
828		if (kill(ofilter, SIGCONT) < 0) {
829			syslog(LOG_ERR, "cannot restart output filter");
830			exit(1);
831		}
832	}
833	pp->tof = 0;
834
835	/* Copy the filter's output to "lf" logfile */
836	if ((fp = fopen(tempstderr, "r"))) {
837		while (fgets(buf, sizeof(buf), fp))
838			fputs(buf, stderr);
839		fclose(fp);
840	}
841
842	if (!WIFEXITED(wstatus)) {
843		syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d)",
844		    pp->printer, format, WTERMSIG(wstatus));
845		return(ERROR);
846	}
847	switch (retcode) {
848	case 0:
849		pp->tof = 1;
850		return(OK);
851	case 1:
852		return(REPRINT);
853	case 2:
854		return(ERROR);
855	default:
856		syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d)",
857			pp->printer, format, retcode);
858		return(FILTERERR);
859	}
860}
861
862/*
863 * Send the daemon control file (cf) and any data files.
864 * Return -1 if a non-recoverable error occured, 1 if a recoverable error and
865 * 0 if all is well.
866 */
867static int
868sendit(struct printer *pp, char *file)
869{
870	int dfcopies, err, i;
871	char *cp, last[BUFSIZ];
872
873	/*
874	 * open control file
875	 */
876	if ((cfp = fopen(file, "r")) == NULL)
877		return(OK);
878
879	/* initialize job-specific count of datafiles processed */
880	job_dfcnt = 0;
881
882	/*
883	 *      read the control file for work to do
884	 *
885	 *      file format -- first character in the line is a command
886	 *      rest of the line is the argument.
887	 *      commands of interest are:
888	 *
889	 *            a-z -- "file name" name of file to print
890	 *              U -- "unlink" name of file to remove
891	 *                    (after we print it. (Pass 2 only)).
892	 */
893
894	/*
895	 * pass 1
896	 */
897	err = OK;
898	while (getline(cfp)) {
899	again:
900		if (line[0] == 'S') {
901			cp = line+1;
902			i = 0;
903			while (*cp >= '0' && *cp <= '9')
904				i = i * 10 + (*cp++ - '0');
905			fdev = i;
906			cp++;
907			i = 0;
908			while (*cp >= '0' && *cp <= '9')
909				i = i * 10 + (*cp++ - '0');
910			fino = i;
911		} else if (line[0] == 'H') {
912			strlcpy(origin_host, line + 1, sizeof(origin_host));
913			if (class[0] == '\0') {
914				strlcpy(class, line + 1, sizeof(class));
915			}
916		} else if (line[0] == 'P') {
917			strlcpy(logname, line + 1, sizeof(logname));
918			if (pp->restricted) { /* restricted */
919				if (getpwnam(logname) == NULL) {
920					sendmail(pp, line+1, NOACCT);
921					err = ERROR;
922					break;
923				}
924			}
925		} else if (line[0] == 'I') {
926			strlcpy(indent+2, line + 1, sizeof(indent) - 2);
927		} else if (line[0] >= 'a' && line[0] <= 'z') {
928			dfcopies = 1;
929			strcpy(last, line);
930			while ((i = getline(cfp)) != 0) {
931				if (strcmp(last, line) != 0)
932					break;
933				dfcopies++;
934			}
935			switch (sendfile(pp, '\3', last+1, *last, dfcopies)) {
936			case OK:
937				if (i)
938					goto again;
939				break;
940			case REPRINT:
941				(void) fclose(cfp);
942				return(REPRINT);
943			case ACCESS:
944				sendmail(pp, logname, ACCESS);
945			case ERROR:
946				err = ERROR;
947			}
948			break;
949		}
950	}
951	if (err == OK && sendfile(pp, '\2', file, '\0', 1) > 0) {
952		(void) fclose(cfp);
953		return(REPRINT);
954	}
955	/*
956	 * pass 2
957	 */
958	fseek(cfp, 0L, 0);
959	while (getline(cfp))
960		if (line[0] == 'U' && !strchr(line+1, '/'))
961			(void) unlink(line+1);
962	/*
963	 * clean-up in case another control file exists
964	 */
965	(void) fclose(cfp);
966	(void) unlink(file);
967	return(err);
968}
969
970/*
971 * Send a data file to the remote machine and spool it.
972 * Return positive if we should try resending.
973 */
974static int
975sendfile(struct printer *pp, int type, char *file, char format, int copyreq)
976{
977	int i, amt;
978	struct stat stb;
979	char *av[15], *filtcmd;
980	char buf[BUFSIZ], opt_c[4], opt_h[4], opt_n[4];
981	int copycnt, filtstat, narg, resp, sfd, sfres, sizerr, statrc;
982
983	statrc = lstat(file, &stb);
984	if (statrc < 0) {
985		syslog(LOG_ERR, "%s: error from lstat(%s): %m",
986		    pp->printer, file);
987		return (ERROR);
988	}
989	sfd = open(file, O_RDONLY);
990	if (sfd < 0) {
991		syslog(LOG_ERR, "%s: error from open(%s,O_RDONLY): %m",
992		    pp->printer, file);
993		return (ERROR);
994	}
995	/*
996	 * Check to see if data file is a symbolic link. If so, it should
997	 * still point to the same file or someone is trying to print something
998	 * he shouldn't.
999	 */
1000	if ((stb.st_mode & S_IFMT) == S_IFLNK && fstat(sfd, &stb) == 0 &&
1001	    (stb.st_dev != fdev || stb.st_ino != fino)) {
1002		close(sfd);
1003		return (ACCESS);
1004	}
1005
1006	/* Everything seems OK for reading the file, now to send it */
1007	filtcmd = NULL;
1008	sizerr = 0;
1009	tfd = -1;
1010	if (type == '\3') {
1011		/*
1012		 * Type == 3 means this is a datafile, not a control file.
1013		 * Increment the counter of data-files in this job, and
1014		 * then check for input or output filters (which are only
1015		 * applied to datafiles, not control files).
1016		 */
1017		job_dfcnt++;
1018
1019		/*
1020		 * Note that here we are filtering datafiles, one at a time,
1021		 * as they are sent to the remote machine.  Here, the *only*
1022		 * difference between an input filter (`if=') and an output
1023		 * filter (`of=') is the argument list that the filter is
1024		 * started up with.  Here, the output filter is executed
1025		 * for each individual file as it is sent.  This is not the
1026		 * same as local print queues, where the output filter is
1027		 * started up once, and then all jobs are passed thru that
1028		 * single invocation of the output filter.
1029		 *
1030		 * Also note that a queue for a remote-machine can have an
1031		 * input filter or an output filter, but not both.
1032		 */
1033		if (pp->filters[LPF_INPUT]) {
1034			filtcmd = pp->filters[LPF_INPUT];
1035			av[0] = filtcmd;
1036			narg = 0;
1037			strcpy(opt_c, "-c");
1038			strcpy(opt_h, "-h");
1039			strcpy(opt_n, "-n");
1040			if (format == 'l')
1041				av[++narg] = opt_c;
1042			av[++narg] = width;
1043			av[++narg] = length;
1044			av[++narg] = indent;
1045			av[++narg] = opt_n;
1046			av[++narg] = logname;
1047			av[++narg] = opt_h;
1048			av[++narg] = origin_host;
1049			av[++narg] = pp->acct_file;
1050			av[++narg] = NULL;
1051		} else if (pp->filters[LPF_OUTPUT]) {
1052			filtcmd = pp->filters[LPF_OUTPUT];
1053			av[0] = filtcmd;
1054			narg = 0;
1055			av[++narg] = width;
1056			av[++narg] = length;
1057			av[++narg] = NULL;
1058		}
1059	}
1060	if (filtcmd) {
1061		/*
1062		 * If there is an input or output filter, we have to run
1063		 * the datafile thru that filter and store the result as
1064		 * a temporary spool file, because the protocol requires
1065		 * that we send the remote host the file-size before we
1066		 * start to send any of the data.
1067		 */
1068		strcpy(tfile, TFILENAME);
1069		tfd = mkstemp(tfile);
1070		if (tfd == -1) {
1071			syslog(LOG_ERR, "%s: mkstemp(%s): %m", pp->printer,
1072			    TFILENAME);
1073			sfres = ERROR;
1074			goto return_sfres;
1075		}
1076		filtstat = execfilter(pp, filtcmd, av, sfd, tfd);
1077
1078		/* process the return-code from the filter */
1079		switch (filtstat) {
1080		case 0:
1081			break;
1082		case 1:
1083			sfres = REPRINT;
1084			goto return_sfres;
1085		case 2:
1086			sfres = ERROR;
1087			goto return_sfres;
1088		default:
1089			syslog(LOG_WARNING,
1090			    "%s: filter '%c' exited (retcode=%d)",
1091			    pp->printer, format, filtstat);
1092			sfres = FILTERERR;
1093			goto return_sfres;
1094		}
1095		statrc = fstat(tfd, &stb);   /* to find size of tfile */
1096		if (statrc < 0)	{
1097			syslog(LOG_ERR,
1098			    "%s: error processing 'if', fstat(%s): %m",
1099			    pp->printer, tfile);
1100			sfres = ERROR;
1101			goto return_sfres;
1102		}
1103		close(sfd);
1104		sfd = tfd;
1105		lseek(sfd, 0, SEEK_SET);
1106	}
1107
1108	copycnt = 0;
1109sendagain:
1110	copycnt++;
1111
1112	if (copycnt < 2)
1113		(void) sprintf(buf, "%c%qd %s\n", type, stb.st_size, file);
1114	else
1115		(void) sprintf(buf, "%c%qd %s_c%d\n", type, stb.st_size,
1116		    file, copycnt);
1117	amt = strlen(buf);
1118	for (i = 0;  ; i++) {
1119		if (write(pfd, buf, amt) != amt ||
1120		    (resp = response(pp)) < 0 || resp == '\1') {
1121			sfres = REPRINT;
1122			goto return_sfres;
1123		} else if (resp == '\0')
1124			break;
1125		if (i == 0)
1126			pstatus(pp,
1127				"no space on remote; waiting for queue to drain");
1128		if (i == 10)
1129			syslog(LOG_ALERT, "%s: can't send to %s; queue full",
1130				pp->printer, pp->remote_host);
1131		sleep(5 * 60);
1132	}
1133	if (i)
1134		pstatus(pp, "sending to %s", pp->remote_host);
1135	/*
1136	 * XXX - we should change trstat_init()/trstat_write() to include
1137	 *	 the copycnt in the statistics record it may write.
1138	 */
1139	if (type == '\3')
1140		trstat_init(pp, file, job_dfcnt);
1141	for (i = 0; i < stb.st_size; i += BUFSIZ) {
1142		amt = BUFSIZ;
1143		if (i + amt > stb.st_size)
1144			amt = stb.st_size - i;
1145		if (sizerr == 0 && read(sfd, buf, amt) != amt)
1146			sizerr = 1;
1147		if (write(pfd, buf, amt) != amt) {
1148			sfres = REPRINT;
1149			goto return_sfres;
1150		}
1151	}
1152
1153	if (sizerr) {
1154		syslog(LOG_INFO, "%s: %s: changed size", pp->printer, file);
1155		/* tell recvjob to ignore this file */
1156		(void) write(pfd, "\1", 1);
1157		sfres = ERROR;
1158		goto return_sfres;
1159	}
1160	if (write(pfd, "", 1) != 1 || response(pp)) {
1161		sfres = REPRINT;
1162		goto return_sfres;
1163	}
1164	if (type == '\3') {
1165		trstat_write(pp, TR_SENDING, stb.st_size, logname,
1166		    pp->remote_host, origin_host);
1167		/*
1168		 * Usually we only need to send one copy of a datafile,
1169		 * because the control-file will simply print the same
1170		 * file multiple times.  However, some printers ignore
1171		 * the control file, and simply print each data file as
1172		 * it arrives.  For such "remote hosts", we need to
1173		 * transfer the same data file multiple times.  Such a
1174		 * a host is indicated by adding 'rc' to the printcap
1175		 * entry.
1176		 * XXX - Right now this ONLY works for remote hosts which
1177		 *	do ignore the name of the data file, because
1178		 *	this sends the file multiple times with slight
1179		 *	changes to the filename.  To do this right would
1180		 *	require that we also rewrite the control file
1181		 *	to match those filenames.
1182		 */
1183		if (pp->resend_copies && (copycnt < copyreq)) {
1184			lseek(sfd, 0, SEEK_SET);
1185			goto sendagain;
1186		}
1187	}
1188	sfres = OK;
1189
1190return_sfres:
1191	(void)close(sfd);
1192	if (tfd != -1) {
1193		/*
1194		 * If tfd is set, then it is the same value as sfd, and
1195		 * therefore it is already closed at this point.  All
1196		 * we need to do is remove the temporary file.
1197		 */
1198		tfd = -1;
1199		unlink(tfile);
1200	}
1201	return (sfres);
1202}
1203
1204/*
1205 *  This routine is called to execute one of the filters as was
1206 *  specified in a printcap entry.  While the child-process will read
1207 *  all of 'infd', it is up to the caller to close that file descriptor
1208 *  in the parent process.
1209 */
1210static int
1211execfilter(struct printer *pp, char *f_cmd, char *f_av[], int infd, int outfd)
1212{
1213	int errfd, fpid, retcode, wpid, wstatus;
1214	FILE *errfp;
1215	char buf[BUFSIZ], *slash;
1216
1217	fpid = dofork(pp, DORETURN);
1218	if (fpid != 0) {
1219		/*
1220		 * This is the parent process, which just waits for the child
1221		 * to complete and then returns the result.  Note that it is
1222		 * the child process which reads the input stream.
1223		 */
1224		if (fpid < 0)
1225			retcode = 100;
1226		else {
1227			while ((wpid = wait(&wstatus)) > 0 &&
1228			    wpid != fpid)
1229				;
1230			if (wpid < 0) {
1231				retcode = 100;
1232				syslog(LOG_WARNING,
1233				    "%s: after execv(%s), wait() returned: %m",
1234				    pp->printer, f_cmd);
1235			} else
1236				retcode = WEXITSTATUS(wstatus);
1237		}
1238
1239		/*
1240		 * Copy everything the filter wrote to stderr from our
1241		 * temporary errors file to the "lf=" logfile.
1242		 */
1243		errfp = fopen(tempstderr, "r");
1244		if (errfp) {
1245			while (fgets(buf, sizeof(buf), errfp))
1246				fputs(buf, stderr);
1247			fclose(errfp);
1248		}
1249
1250		return (retcode);
1251	}
1252
1253	/*
1254	 * This is the child process, which is the one that executes the
1255	 * given filter.
1256	 */
1257	/*
1258	 * If the first parameter has any slashes in it, then change it
1259	 * to point to the first character after the last slash.
1260	 */
1261	slash = strrchr(f_av[0], '/');
1262	if (slash != NULL)
1263		f_av[0] = slash + 1;
1264	/*
1265	 * XXX - in the future, this should setup an explicit list of
1266	 *       environment variables and use execve()!
1267	 */
1268
1269	/*
1270	 * Setup stdin, stdout, and stderr as we want them when the filter
1271	 * is running.  Stderr is setup so it points to a temporary errors
1272	 * file, and the parent process will copy that temporary file to
1273	 * the real logfile after the filter completes.
1274	 */
1275	dup2(infd, 0);
1276	dup2(outfd, 1);
1277	errfd = open(tempstderr, O_WRONLY|O_TRUNC, 0664);
1278	if (errfd >= 0)
1279		dup2(errfd, 2);
1280	closelog();
1281	closeallfds(3);
1282	execv(f_cmd, f_av);
1283	syslog(LOG_ERR, "%s: cannot execv(%s): %m", pp->printer, f_cmd);
1284	exit(2);
1285	/* NOTREACHED */
1286}
1287
1288/*
1289 * Check to make sure there have been no errors and that both programs
1290 * are in sync with eachother.
1291 * Return non-zero if the connection was lost.
1292 */
1293static char
1294response(const struct printer *pp)
1295{
1296	char resp;
1297
1298	if (read(pfd, &resp, 1) != 1) {
1299		syslog(LOG_INFO, "%s: lost connection", pp->printer);
1300		return(-1);
1301	}
1302	return(resp);
1303}
1304
1305/*
1306 * Banner printing stuff
1307 */
1308static void
1309banner(struct printer *pp, char *name1, char *name2)
1310{
1311	time_t tvec;
1312
1313	time(&tvec);
1314	if (!pp->no_formfeed && !pp->tof)
1315		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1316	if (pp->short_banner) {	/* short banner only */
1317		if (class[0]) {
1318			(void) write(ofd, class, strlen(class));
1319			(void) write(ofd, ":", 1);
1320		}
1321		(void) write(ofd, name1, strlen(name1));
1322		(void) write(ofd, "  Job: ", 7);
1323		(void) write(ofd, name2, strlen(name2));
1324		(void) write(ofd, "  Date: ", 8);
1325		(void) write(ofd, ctime(&tvec), 24);
1326		(void) write(ofd, "\n", 1);
1327	} else {	/* normal banner */
1328		(void) write(ofd, "\n\n\n", 3);
1329		scan_out(pp, ofd, name1, '\0');
1330		(void) write(ofd, "\n\n", 2);
1331		scan_out(pp, ofd, name2, '\0');
1332		if (class[0]) {
1333			(void) write(ofd,"\n\n\n",3);
1334			scan_out(pp, ofd, class, '\0');
1335		}
1336		(void) write(ofd, "\n\n\n\n\t\t\t\t\tJob:  ", 15);
1337		(void) write(ofd, name2, strlen(name2));
1338		(void) write(ofd, "\n\t\t\t\t\tDate: ", 12);
1339		(void) write(ofd, ctime(&tvec), 24);
1340		(void) write(ofd, "\n", 1);
1341	}
1342	if (!pp->no_formfeed)
1343		(void) write(ofd, pp->form_feed, strlen(pp->form_feed));
1344	pp->tof = 1;
1345}
1346
1347static char *
1348scnline(int key, char *p, int c)
1349{
1350	register int scnwidth;
1351
1352	for (scnwidth = WIDTH; --scnwidth;) {
1353		key <<= 1;
1354		*p++ = key & 0200 ? c : BACKGND;
1355	}
1356	return (p);
1357}
1358
1359#define TRC(q)	(((q)-' ')&0177)
1360
1361static void
1362scan_out(struct printer *pp, int scfd, char *scsp, int dlm)
1363{
1364	register char *strp;
1365	register int nchrs, j;
1366	char outbuf[LINELEN+1], *sp, c, cc;
1367	int d, scnhgt;
1368
1369	for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) {
1370		strp = &outbuf[0];
1371		sp = scsp;
1372		for (nchrs = 0; ; ) {
1373			d = dropit(c = TRC(cc = *sp++));
1374			if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d))
1375				for (j = WIDTH; --j;)
1376					*strp++ = BACKGND;
1377			else
1378				strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc);
1379			if (*sp == dlm || *sp == '\0' ||
1380			    nchrs++ >= pp->page_width/(WIDTH+1)-1)
1381				break;
1382			*strp++ = BACKGND;
1383			*strp++ = BACKGND;
1384		}
1385		while (*--strp == BACKGND && strp >= outbuf)
1386			;
1387		strp++;
1388		*strp++ = '\n';
1389		(void) write(scfd, outbuf, strp-outbuf);
1390	}
1391}
1392
1393static int
1394dropit(int c)
1395{
1396	switch(c) {
1397
1398	case TRC('_'):
1399	case TRC(';'):
1400	case TRC(','):
1401	case TRC('g'):
1402	case TRC('j'):
1403	case TRC('p'):
1404	case TRC('q'):
1405	case TRC('y'):
1406		return (DROP);
1407
1408	default:
1409		return (0);
1410	}
1411}
1412
1413/*
1414 * sendmail ---
1415 *   tell people about job completion
1416 */
1417static void
1418sendmail(struct printer *pp, char *userid, int bombed)
1419{
1420	register int i;
1421	int p[2], s;
1422	register const char *cp;
1423	struct stat stb;
1424	FILE *fp;
1425
1426	pipe(p);
1427	if ((s = dofork(pp, DORETURN)) == 0) {		/* child */
1428		dup2(p[0], 0);
1429		closelog();
1430		closeallfds(3);
1431		if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL)
1432			cp++;
1433		else
1434			cp = _PATH_SENDMAIL;
1435		execl(_PATH_SENDMAIL, cp, "-t", (char *)0);
1436		_exit(0);
1437	} else if (s > 0) {				/* parent */
1438		dup2(p[1], 1);
1439		printf("To: %s@%s\n", userid, origin_host);
1440		printf("Subject: %s printer job \"%s\"\n", pp->printer,
1441			*jobname ? jobname : "<unknown>");
1442		printf("Reply-To: root@%s\n\n", local_host);
1443		printf("Your printer job ");
1444		if (*jobname)
1445			printf("(%s) ", jobname);
1446
1447		switch (bombed) {
1448		case OK:
1449			cp = "OK";
1450			printf("\ncompleted successfully\n");
1451			break;
1452		default:
1453		case FATALERR:
1454			cp = "FATALERR";
1455			printf("\ncould not be printed\n");
1456			break;
1457		case NOACCT:
1458			cp = "NOACCT";
1459			printf("\ncould not be printed without an account on %s\n",
1460			    local_host);
1461			break;
1462		case FILTERERR:
1463			cp = "FILTERERR";
1464			if (stat(tempstderr, &stb) < 0 || stb.st_size == 0
1465			    || (fp = fopen(tempstderr, "r")) == NULL) {
1466				printf("\nhad some errors and may not have printed\n");
1467				break;
1468			}
1469			printf("\nhad the following errors and may not have printed:\n");
1470			while ((i = getc(fp)) != EOF)
1471				putchar(i);
1472			(void) fclose(fp);
1473			break;
1474		case ACCESS:
1475			cp = "ACCESS";
1476			printf("\nwas not printed because it was not linked to the original file\n");
1477		}
1478		fflush(stdout);
1479		(void) close(1);
1480	} else {
1481		syslog(LOG_WARNING, "unable to send mail to %s: %m", userid);
1482		return;
1483	}
1484	(void) close(p[0]);
1485	(void) close(p[1]);
1486	wait(NULL);
1487	syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)",
1488	    userid, *jobname ? jobname : "<unknown>", pp->printer, cp);
1489}
1490
1491/*
1492 * dofork - fork with retries on failure
1493 */
1494static int
1495dofork(const struct printer *pp, int action)
1496{
1497	int i, fail, forkpid;
1498	struct passwd *pwd;
1499
1500	forkpid = -1;
1501	if (daemon_uname == NULL) {
1502		pwd = getpwuid(pp->daemon_user);
1503		if (pwd == NULL) {
1504			syslog(LOG_ERR, "%s: Can't lookup default daemon uid (%ld) in password file",
1505			    pp->printer, pp->daemon_user);
1506			goto error_ret;
1507		}
1508		daemon_uname = strdup(pwd->pw_name);
1509		daemon_defgid = pwd->pw_gid;
1510	}
1511
1512	for (i = 0; i < 20; i++) {
1513		forkpid = fork();
1514		if (forkpid < 0) {
1515			sleep((unsigned)(i*i));
1516			continue;
1517		}
1518		/*
1519		 * Child should run as daemon instead of root
1520		 */
1521		if (forkpid == 0) {
1522			errno = 0;
1523			fail = initgroups(daemon_uname, daemon_defgid);
1524			if (fail) {
1525				syslog(LOG_ERR, "%s: initgroups(%s,%u): %m",
1526				    pp->printer, daemon_uname, daemon_defgid);
1527				break;
1528			}
1529			fail = setgid(daemon_defgid);
1530			if (fail) {
1531				syslog(LOG_ERR, "%s: setgid(%u): %m",
1532				    pp->printer, daemon_defgid);
1533				break;
1534			}
1535			fail = setuid(pp->daemon_user);
1536			if (fail) {
1537				syslog(LOG_ERR, "%s: setuid(%ld): %m",
1538				    pp->printer, pp->daemon_user);
1539				break;
1540			}
1541		}
1542		return forkpid;
1543	}
1544
1545	/*
1546	 * An error occurred.  If the error is in the child process, then
1547	 * this routine MUST always exit().  DORETURN only effects how
1548	 * errors should be handled in the parent process.
1549	 */
1550error_ret:
1551	if (forkpid == 0) {
1552		syslog(LOG_ERR, "%s: dofork(): aborting child process...",
1553		    pp->printer);
1554		exit(1);
1555	}
1556	syslog(LOG_ERR, "%s: dofork(): failure in fork", pp->printer);
1557
1558	sleep(1);		/* throttle errors, as a safety measure */
1559	switch (action) {
1560	case DORETURN:
1561		return -1;
1562	default:
1563		syslog(LOG_ERR, "bad action (%d) to dofork", action);
1564		/* FALLTHROUGH */
1565	case DOABORT:
1566		exit(1);
1567	}
1568	/*NOTREACHED*/
1569}
1570
1571/*
1572 * Kill child processes to abort current job.
1573 */
1574static void
1575abortpr(int signo __unused)
1576{
1577
1578	(void) unlink(tempstderr);
1579	kill(0, SIGINT);
1580	if (ofilter > 0)
1581		kill(ofilter, SIGCONT);
1582	while (wait(NULL) > 0)
1583		;
1584	if (ofilter > 0 && tfd != -1)
1585		unlink(tfile);
1586	exit(0);
1587}
1588
1589static void
1590init(struct printer *pp)
1591{
1592	char *s;
1593
1594	sprintf(&width[2], "%ld", pp->page_width);
1595	sprintf(&length[2], "%ld", pp->page_length);
1596	sprintf(&pxwidth[2], "%ld", pp->page_pwidth);
1597	sprintf(&pxlength[2], "%ld", pp->page_plength);
1598	if ((s = checkremote(pp)) != 0) {
1599		syslog(LOG_WARNING, "%s", s);
1600		free(s);
1601	}
1602}
1603
1604void
1605startprinting(const char *printer)
1606{
1607	struct printer myprinter, *pp = &myprinter;
1608	int status;
1609
1610	init_printer(pp);
1611	status = getprintcap(printer, pp);
1612	switch(status) {
1613	case PCAPERR_OSERR:
1614		syslog(LOG_ERR, "can't open printer description file: %m");
1615		exit(1);
1616	case PCAPERR_NOTFOUND:
1617		syslog(LOG_ERR, "unknown printer: %s", printer);
1618		exit(1);
1619	case PCAPERR_TCLOOP:
1620		fatal(pp, "potential reference loop detected in printcap file");
1621	default:
1622		break;
1623	}
1624	printjob(pp);
1625}
1626
1627/*
1628 * Acquire line printer or remote connection.
1629 */
1630static void
1631openpr(const struct printer *pp)
1632{
1633	int p[2];
1634	char *cp;
1635
1636	if (pp->remote) {
1637		openrem(pp);
1638		/*
1639		 * Lpd does support the setting of 'of=' filters for
1640		 * jobs going to remote machines, but that does not
1641		 * have the same meaning as 'of=' does when handling
1642		 * local print queues.  For remote machines, all 'of='
1643		 * filter processing is handled in sendfile(), and that
1644		 * does not use these global "output filter" variables.
1645		 */
1646		ofd = -1;
1647		ofilter = 0;
1648		return;
1649	} else if (*pp->lp) {
1650		if ((cp = strchr(pp->lp, '@')) != NULL)
1651			opennet(pp);
1652		else
1653			opentty(pp);
1654	} else {
1655		syslog(LOG_ERR, "%s: no line printer device or host name",
1656			pp->printer);
1657		exit(1);
1658	}
1659
1660	/*
1661	 * Start up an output filter, if needed.
1662	 */
1663	if (pp->filters[LPF_OUTPUT] && !pp->filters[LPF_INPUT] && !ofilter) {
1664		pipe(p);
1665		if (pp->remote) {
1666			strcpy(tfile, TFILENAME);
1667			tfd = mkstemp(tfile);
1668		}
1669		if ((ofilter = dofork(pp, DOABORT)) == 0) {	/* child */
1670			dup2(p[0], 0);		/* pipe is std in */
1671			/* tfile/printer is stdout */
1672			dup2(pp->remote ? tfd : pfd, 1);
1673			closelog();
1674			closeallfds(3);
1675			if ((cp = strrchr(pp->filters[LPF_OUTPUT], '/')) == NULL)
1676				cp = pp->filters[LPF_OUTPUT];
1677			else
1678				cp++;
1679			execl(pp->filters[LPF_OUTPUT], cp, width, length,
1680			      (char *)0);
1681			syslog(LOG_ERR, "%s: %s: %m", pp->printer,
1682			       pp->filters[LPF_OUTPUT]);
1683			exit(1);
1684		}
1685		(void) close(p[0]);		/* close input side */
1686		ofd = p[1];			/* use pipe for output */
1687	} else {
1688		ofd = pfd;
1689		ofilter = 0;
1690	}
1691}
1692
1693/*
1694 * Printer connected directly to the network
1695 * or to a terminal server on the net
1696 */
1697static void
1698opennet(const struct printer *pp)
1699{
1700	register int i;
1701	int resp;
1702	u_long port;
1703	char *ep;
1704	void (*savealrm)(int);
1705
1706	port = strtoul(pp->lp, &ep, 0);
1707	if (*ep != '@' || port > 65535) {
1708		syslog(LOG_ERR, "%s: bad port number: %s", pp->printer,
1709		       pp->lp);
1710		exit(1);
1711	}
1712	ep++;
1713
1714	for (i = 1; ; i = i < 256 ? i << 1 : i) {
1715		resp = -1;
1716		savealrm = signal(SIGALRM, alarmhandler);
1717		alarm(pp->conn_timeout);
1718		pfd = getport(pp, ep, port);
1719		alarm(0);
1720		(void)signal(SIGALRM, savealrm);
1721		if (pfd < 0 && errno == ECONNREFUSED)
1722			resp = 1;
1723		else if (pfd >= 0) {
1724			/*
1725			 * need to delay a bit for rs232 lines
1726			 * to stabilize in case printer is
1727			 * connected via a terminal server
1728			 */
1729			delay(500);
1730			break;
1731		}
1732		if (i == 1) {
1733			if (resp < 0)
1734				pstatus(pp, "waiting for %s to come up",
1735					pp->lp);
1736			else
1737				pstatus(pp,
1738					"waiting for access to printer on %s",
1739					pp->lp);
1740		}
1741		sleep(i);
1742	}
1743	pstatus(pp, "sending to %s port %lu", ep, port);
1744}
1745
1746/*
1747 * Printer is connected to an RS232 port on this host
1748 */
1749static void
1750opentty(const struct printer *pp)
1751{
1752	register int i;
1753
1754	for (i = 1; ; i = i < 32 ? i << 1 : i) {
1755		pfd = open(pp->lp, pp->rw ? O_RDWR : O_WRONLY);
1756		if (pfd >= 0) {
1757			delay(500);
1758			break;
1759		}
1760		if (errno == ENOENT) {
1761			syslog(LOG_ERR, "%s: %m", pp->lp);
1762			exit(1);
1763		}
1764		if (i == 1)
1765			pstatus(pp,
1766				"waiting for %s to become ready (offline?)",
1767				pp->printer);
1768		sleep(i);
1769	}
1770	if (isatty(pfd))
1771		setty(pp);
1772	pstatus(pp, "%s is ready and printing", pp->printer);
1773}
1774
1775/*
1776 * Printer is on a remote host
1777 */
1778static void
1779openrem(const struct printer *pp)
1780{
1781	register int i;
1782	int resp;
1783	void (*savealrm)(int);
1784
1785	for (i = 1; ; i = i < 256 ? i << 1 : i) {
1786		resp = -1;
1787		savealrm = signal(SIGALRM, alarmhandler);
1788		alarm(pp->conn_timeout);
1789		pfd = getport(pp, pp->remote_host, 0);
1790		alarm(0);
1791		(void)signal(SIGALRM, savealrm);
1792		if (pfd >= 0) {
1793			if ((writel(pfd, "\2", pp->remote_queue, "\n",
1794				    (char *)0)
1795			     == 2 + strlen(pp->remote_queue))
1796			    && (resp = response(pp)) == 0)
1797				break;
1798			(void) close(pfd);
1799		}
1800		if (i == 1) {
1801			if (resp < 0)
1802				pstatus(pp, "waiting for %s to come up",
1803					pp->remote_host);
1804			else {
1805				pstatus(pp,
1806					"waiting for queue to be enabled on %s",
1807					pp->remote_host);
1808				i = 256;
1809			}
1810		}
1811		sleep(i);
1812	}
1813	pstatus(pp, "sending to %s", pp->remote_host);
1814}
1815
1816/*
1817 * setup tty lines.
1818 */
1819static void
1820setty(const struct printer *pp)
1821{
1822	struct termios ttybuf;
1823
1824	if (ioctl(pfd, TIOCEXCL, (char *)0) < 0) {
1825		syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", pp->printer);
1826		exit(1);
1827	}
1828	if (tcgetattr(pfd, &ttybuf) < 0) {
1829		syslog(LOG_ERR, "%s: tcgetattr: %m", pp->printer);
1830		exit(1);
1831	}
1832	if (pp->baud_rate > 0)
1833		cfsetspeed(&ttybuf, pp->baud_rate);
1834	if (pp->mode_set) {
1835		char *s = strdup(pp->mode_set), *tmp;
1836
1837		while ((tmp = strsep(&s, ",")) != NULL) {
1838			(void) msearch(tmp, &ttybuf);
1839		}
1840	}
1841	if (pp->mode_set != 0 || pp->baud_rate > 0) {
1842		if (tcsetattr(pfd, TCSAFLUSH, &ttybuf) == -1) {
1843			syslog(LOG_ERR, "%s: tcsetattr: %m", pp->printer);
1844		}
1845	}
1846}
1847
1848#include <stdarg.h>
1849
1850static void
1851pstatus(const struct printer *pp, const char *msg, ...)
1852{
1853	int fd;
1854	char *buf;
1855	va_list ap;
1856	va_start(ap, msg);
1857
1858	umask(0);
1859	fd = open(pp->status_file, O_WRONLY|O_CREAT|O_EXLOCK, STAT_FILE_MODE);
1860	if (fd < 0) {
1861		syslog(LOG_ERR, "%s: %s: %m", pp->printer, pp->status_file);
1862		exit(1);
1863	}
1864	ftruncate(fd, 0);
1865	vasprintf(&buf, msg, ap);
1866	va_end(ap);
1867	writel(fd, buf, "\n", (char *)0);
1868	close(fd);
1869	free(buf);
1870}
1871
1872void
1873alarmhandler(int signo __unused)
1874{
1875	/* the signal is ignored */
1876	/* (the '__unused' is just to avoid a compile-time warning) */
1877}
1878