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