recvjob.c revision 80113
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#if 0
43static char sccsid[] = "@(#)recvjob.c	8.2 (Berkeley) 4/27/95";
44#endif
45static const char rcsid[] =
46  "$FreeBSD: head/usr.sbin/lpr/lpd/recvjob.c 80113 2001-07-22 00:03:21Z gad $";
47#endif /* not lint */
48
49/*
50 * Receive printer jobs from the network, queue them and
51 * start the printer daemon.
52 */
53#include <sys/param.h>
54#include <sys/mount.h>
55#include <sys/stat.h>
56
57#include <unistd.h>
58#include <signal.h>
59#include <fcntl.h>
60#include <dirent.h>
61#include <errno.h>
62#include <syslog.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include "lp.h"
67#include "lp.local.h"
68#include "ctlinfo.h"
69#include "extern.h"
70#include "pathnames.h"
71
72#define ack()	(void) write(STDOUT_FILENO, sp, 1);
73
74static char	 dfname[NAME_MAX];	/* data files */
75static int	 minfree;       /* keep at least minfree blocks available */
76static const char	*sp = "";
77static char	 tfname[NAME_MAX];	/* tmp copy of cf before linking */
78
79static int	 chksize(int _size);
80static void	 frecverr(const char *_msg, ...) __printf0like(1, 2);
81static int	 noresponse(void);
82static void	 rcleanup(int _signo);
83static int	 read_number(const char *_fn);
84static int	 readfile(struct printer *_pp, char *_file, int _size);
85static int	 readjob(struct printer *_pp);
86
87
88void
89recvjob(const char *printer)
90{
91	struct stat stb;
92	int status;
93	struct printer myprinter, *pp = &myprinter;
94
95	/*
96	 * Perform lookup for printer name or abbreviation
97	 */
98	init_printer(pp);
99	status = getprintcap(printer, pp);
100	switch (status) {
101	case PCAPERR_OSERR:
102		frecverr("cannot open printer description file");
103		break;
104	case PCAPERR_NOTFOUND:
105		frecverr("unknown printer %s", printer);
106		break;
107	case PCAPERR_TCLOOP:
108		fatal(pp, "potential reference loop detected in printcap file");
109	default:
110		break;
111	}
112
113	(void) close(2);			/* set up log file */
114	if (open(pp->log_file, O_WRONLY|O_APPEND, 0664) < 0) {
115		syslog(LOG_ERR, "%s: %m", pp->log_file);
116		(void) open(_PATH_DEVNULL, O_WRONLY);
117	}
118
119	if (chdir(pp->spool_dir) < 0)
120		frecverr("%s: chdir(%s): %s", pp->printer, pp->spool_dir,
121		    strerror(errno));
122	if (stat(pp->lock_file, &stb) == 0) {
123		if (stb.st_mode & 010) {
124			/* queue is disabled */
125			putchar('\1');		/* return error code */
126			exit(1);
127		}
128	} else if (stat(pp->spool_dir, &stb) < 0)
129		frecverr("%s: stat(%s): %s", pp->printer, pp->spool_dir,
130		    strerror(errno));
131	minfree = 2 * read_number("minfree");	/* scale KB to 512 blocks */
132	signal(SIGTERM, rcleanup);
133	signal(SIGPIPE, rcleanup);
134
135	if (readjob(pp))
136		printjob(pp);
137}
138
139/*
140 * Read printer jobs sent by lpd and copy them to the spooling directory.
141 * Return the number of jobs successfully transfered.
142 */
143static int
144readjob(struct printer *pp)
145{
146	register int size;
147	register char *cp;
148	int cfcnt, dfcnt;
149	char *errmsg;
150	char givenid[32], givenhost[MAXHOSTNAMELEN];
151
152	ack();
153	cfcnt = 0;
154	dfcnt = 0;
155	for (;;) {
156		/*
157		 * Read a command to tell us what to do
158		 */
159		cp = line;
160		do {
161			if ((size = read(STDOUT_FILENO, cp, 1)) != 1) {
162				if (size < 0) {
163					frecverr("%s: lost connection",
164					    pp->printer);
165					/*NOTREACHED*/
166				}
167				return (cfcnt);
168			}
169		} while (*cp++ != '\n' && (cp - line + 1) < sizeof(line));
170		if (cp - line + 1 >= sizeof(line)) {
171			frecverr("%s: readjob overflow", pp->printer);
172			/*NOTREACHED*/
173		}
174		*--cp = '\0';
175		cp = line;
176		switch (*cp++) {
177		case '\1':	/* cleanup because data sent was bad */
178			rcleanup(0);
179			continue;
180
181		case '\2':	/* read cf file */
182			size = 0;
183			dfcnt = 0;
184			while (*cp >= '0' && *cp <= '9')
185				size = size * 10 + (*cp++ - '0');
186			if (*cp++ != ' ')
187				break;
188			/*
189			 * host name has been authenticated, we use our
190			 * view of the host name since we may be passed
191			 * something different than what gethostbyaddr()
192			 * returns
193			 */
194			strncpy(cp + 6, from_host, sizeof(line) + line - cp
195			    - 7);
196			line[sizeof(line) - 1 ] = '\0';
197			strncpy(tfname, cp, sizeof(tfname) - 1);
198			tfname[sizeof (tfname) - 1] = '\0';
199			tfname[0] = 't';
200			if (strchr(tfname, '/'))
201				frecverr("readjob: %s: illegal path name",
202				    tfname);
203			if (!chksize(size)) {
204				(void) write(STDOUT_FILENO, "\2", 1);
205				continue;
206			}
207			if (!readfile(pp, tfname, size)) {
208				rcleanup(0);
209				continue;
210			}
211			errmsg = ctl_renametf(pp->printer, tfname);
212			tfname[0] = '\0';
213			if (errmsg != NULL) {
214				frecverr("%s: %s", pp->printer, errmsg);
215				/*NOTREACHED*/
216			}
217			cfcnt++;
218			continue;
219
220		case '\3':	/* read df file */
221			*givenid = '\0';
222			*givenhost = '\0';
223			size = 0;
224			while (*cp >= '0' && *cp <= '9')
225				size = size * 10 + (*cp++ - '0');
226			if (*cp++ != ' ')
227				break;
228			if (!chksize(size)) {
229				(void) write(STDOUT_FILENO, "\2", 1);
230				continue;
231			}
232			(void) strncpy(dfname, cp, sizeof(dfname) - 1);
233			dfname[sizeof(dfname) - 1] = '\0';
234			if (strchr(dfname, '/')) {
235				frecverr("readjob: %s: illegal path name",
236					dfname);
237				/*NOTREACHED*/
238			}
239			dfcnt++;
240			trstat_init(pp, dfname, dfcnt);
241			(void) readfile(pp, dfname, size);
242			trstat_write(pp, TR_RECVING, size, givenid, from_host,
243				     givenhost);
244			continue;
245		}
246		frecverr("protocol screwup: %s", line);
247		/*NOTREACHED*/
248	}
249}
250
251/*
252 * Read files send by lpd and copy them to the spooling directory.
253 */
254static int
255readfile(struct printer *pp, char *file, int size)
256{
257	register char *cp;
258	char buf[BUFSIZ];
259	register int i, j, amt;
260	int fd, err;
261
262	fd = open(file, O_CREAT|O_EXCL|O_WRONLY, FILMOD);
263	if (fd < 0) {
264		frecverr("%s: readfile: error on open(%s): %s",
265			 pp->printer, file, strerror(errno));
266		/*NOTREACHED*/
267	}
268	ack();
269	err = 0;
270	for (i = 0; i < size; i += BUFSIZ) {
271		amt = BUFSIZ;
272		cp = buf;
273		if (i + amt > size)
274			amt = size - i;
275		do {
276			j = read(STDOUT_FILENO, cp, amt);
277			if (j <= 0) {
278				frecverr("%s: lost connection", pp->printer);
279				/*NOTREACHED*/
280			}
281			amt -= j;
282			cp += j;
283		} while (amt > 0);
284		amt = BUFSIZ;
285		if (i + amt > size)
286			amt = size - i;
287		if (write(fd, buf, amt) != amt) {
288			err++;
289			break;
290		}
291	}
292	(void) close(fd);
293	if (err) {
294		frecverr("%s: write error on close(%s)", pp->printer, file);
295		/*NOTREACHED*/
296	}
297	if (noresponse()) {		/* file sent had bad data in it */
298		if (strchr(file, '/') == NULL)
299			(void) unlink(file);
300		return (0);
301	}
302	ack();
303	return (1);
304}
305
306static int
307noresponse(void)
308{
309	char resp;
310
311	if (read(STDOUT_FILENO, &resp, 1) != 1) {
312		frecverr("lost connection in noresponse()");
313		/*NOTREACHED*/
314	}
315	if (resp == '\0')
316		return(0);
317	return(1);
318}
319
320/*
321 * Check to see if there is enough space on the disk for size bytes.
322 * 1 == OK, 0 == Not OK.
323 */
324static int
325chksize(int size)
326{
327	int spacefree;
328	struct statfs sfb;
329
330	if (statfs(".", &sfb) < 0) {
331		syslog(LOG_ERR, "%s: %m", "statfs(\".\")");
332		return (1);
333	}
334	spacefree = sfb.f_bavail * (sfb.f_bsize / 512);
335	size = (size + 511) / 512;
336	if (minfree + size > spacefree)
337		return(0);
338	return(1);
339}
340
341static int
342read_number(const char *fn)
343{
344	char lin[80];
345	register FILE *fp;
346
347	if ((fp = fopen(fn, "r")) == NULL)
348		return (0);
349	if (fgets(lin, 80, fp) == NULL) {
350		fclose(fp);
351		return (0);
352	}
353	fclose(fp);
354	return (atoi(lin));
355}
356
357/*
358 * Remove all the files associated with the current job being transfered.
359 */
360static void
361rcleanup(int signo __unused)
362{
363	if (tfname[0] && strchr(tfname, '/') == NULL)
364		(void) unlink(tfname);
365	if (dfname[0] && strchr(dfname, '/') == NULL) {
366		do {
367			do
368				(void) unlink(dfname);
369			while (dfname[2]-- != 'A');
370			dfname[2] = 'z';
371		} while (dfname[0]-- != 'd');
372	}
373	dfname[0] = '\0';
374}
375
376#ifdef __STDC__
377#include <stdarg.h>
378#else
379#include <varargs.h>
380#endif
381
382static void
383#ifdef __STDC__
384frecverr(const char *msg, ...)
385#else
386frecverr(msg, va_alist)
387	char *msg;
388        va_dcl
389#endif
390{
391	va_list ap;
392#ifdef __STDC__
393	va_start(ap, msg);
394#else
395	va_start(ap);
396#endif
397	syslog(LOG_ERR, "Error receiving job from %s:", from_host);
398	vsyslog(LOG_ERR, msg, ap);
399	va_end(ap);
400	/*
401	 * rcleanup is not called until AFTER logging the error message,
402	 * because rcleanup will zap some variables which may have been
403	 * supplied as parameters for that msg...
404	 */
405	rcleanup(0);
406	/*
407	 * Add a minimal delay before returning the final error code to
408	 * the sending host.  This just in case that machine responds
409	 * this error by INSTANTLY retrying (and instantly re-failing...).
410	 * It would be stupid of the sending host to do that, but if there
411	 * was a broken implementation which did it, the result might be
412	 * obscure performance problems and a flood of syslog messages on
413	 * the receiving host.
414	 */
415	sleep(2);		/* a paranoid throttling measure */
416	putchar('\1');		/* return error code */
417	exit(1);
418}
419