xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision 12e23270e7fbff26817f1d5800ef4ca7afde8e4c)
1 /*	$OpenBSD: common.c,v 1.24 2003/04/07 22:55:50 deraadt Exp $	*/
2 /*	$NetBSD: common.c,v 1.21 2000/08/09 14:28:50 itojun Exp $	*/
3 
4 /*
5  * Copyright (c) 1983, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by the University of
24  *	California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41 
42 #ifndef lint
43 #if 0
44 static const char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
45 #else
46 static const char rcsid[] = "$OpenBSD: common.c,v 1.24 2003/04/07 22:55:50 deraadt Exp $";
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57 #include <netdb.h>
58 
59 #include <dirent.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <unistd.h>
63 #include <stdlib.h>
64 #include <stdio.h>
65 #include <string.h>
66 #include <signal.h>
67 #include <stdarg.h>
68 #include <ifaddrs.h>
69 #include "lp.h"
70 #include "pathnames.h"
71 
72 /*
73  * Routines and data common to all the line printer functions.
74  */
75 
76 char	*AF;		/* accounting file */
77 long	 BR;		/* baud rate if lp is a tty */
78 char	*CF;		/* name of cifplot filter (per job) */
79 char	*DF;		/* name of tex filter (per job) */
80 long	 DU;		/* daeomon user-id */
81 long	 FC;		/* flags to clear if lp is a tty */
82 char	*FF;		/* form feed string */
83 long	 FS;		/* flags to set if lp is a tty */
84 char	*GF;		/* name of graph(1G) filter (per job) */
85 long	 HL;		/* print header last */
86 char	*IF;		/* name of input filter (created per job) */
87 char	*LF;		/* log file for error messages */
88 char	*LO;		/* lock file name */
89 char	*LP;		/* line printer device name */
90 long	 MC;		/* maximum number of copies allowed */
91 char	*MS;		/* stty flags to set if lp is a tty */
92 long	 MX;		/* maximum number of blocks to copy */
93 char	*NF;		/* name of ditroff filter (per job) */
94 char	*OF;		/* name of output filter (created once) */
95 char	*PF;		/* name of vrast filter (per job) */
96 long	 PL;		/* page length */
97 long	 PW;		/* page width */
98 long	 PX;		/* page width in pixels */
99 long	 PY;		/* page length in pixels */
100 char	*RF;		/* name of fortran text filter (per job) */
101 char    *RG;		/* resricted group */
102 char	*RM;		/* remote machine name */
103 char	*RP;		/* remote printer name */
104 long	 RS;		/* restricted to those with local accounts */
105 long	 RW;		/* open LP for reading and writing */
106 long	 SB;		/* short banner instead of normal header */
107 long	 SC;		/* suppress multiple copies */
108 char	*SD;		/* spool directory */
109 long	 SF;		/* suppress FF on each print job */
110 long	 SH;		/* suppress header page */
111 char	*ST;		/* status file name */
112 char	*TF;		/* name of troff filter (per job) */
113 char	*TR;		/* trailer string to be output when Q empties */
114 char	*VF;		/* name of vplot filter (per job) */
115 long	 XC;		/* flags to clear for local mode */
116 long	 XS;		/* flags to set for local mode */
117 
118 char	line[BUFSIZ];
119 int	remote;		/* true if sending files to a remote host */
120 
121 static int compar(const void *, const void *);
122 
123 /*
124  * Create a TCP connection to host "rhost" at port "rport".
125  * If rport == 0, then use the printer service port.
126  * Most of this code comes from rcmd.c.
127  */
128 int
129 getport(char *rhost, int rport)
130 {
131 	struct addrinfo hints, *res, *r;
132 	u_int timo = 1;
133 	int s, lport = IPPORT_RESERVED - 1;
134 	int error;
135 	int refuse, trial;
136 	char pbuf[NI_MAXSERV];
137 
138 	/*
139 	 * Get the host address and port number to connect to.
140 	 */
141 	if (rhost == NULL)
142 		fatal("no remote host to connect to");
143 	memset(&hints, 0, sizeof(hints));
144 	hints.ai_family = PF_UNSPEC;
145 	hints.ai_socktype = SOCK_STREAM;
146 	if (rport)
147 		snprintf(pbuf, sizeof(pbuf), "%d", rport);
148 	else
149 		snprintf(pbuf, sizeof(pbuf), "printer");
150 	siginterrupt(SIGINT, 1);
151 	error = getaddrinfo(rhost, pbuf, &hints, &res);
152 	siginterrupt(SIGINT, 0);
153 	if (error)
154 		fatal("printer/tcp: %s", gai_strerror(error));
155 
156 	/*
157 	 * Try connecting to the server.
158 	 */
159 retry:
160 	s = -1;
161 	refuse = trial = 0;
162 	for (r = res; r; r = r->ai_next) {
163 		trial++;
164 retryport:
165 		PRIV_START;
166 		s = rresvport_af(&lport, r->ai_family);
167 		PRIV_END;
168 		if (s < 0) {
169 			/* fall back to non-privileged port */
170 			if (errno != EACCES ||
171 			    (s = socket(r->ai_family, SOCK_STREAM, 0)) < 0)
172 				return(-1);
173 		}
174 		siginterrupt(SIGINT, 1);
175 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
176 			error = errno;
177 			siginterrupt(SIGINT, 0);
178 			(void)close(s);
179 			s = -1;
180 			errno = error;
181 			if (errno == EADDRINUSE) {
182 				lport--;
183 				goto retryport;
184 			} else if (errno == ECONNREFUSED)
185 				refuse++;
186 			continue;
187 		} else {
188 			siginterrupt(SIGINT, 0);
189 			break;
190 		}
191 	}
192 	if (s < 0 && trial == refuse && timo <= 16) {
193 		sleep(timo);
194 		timo *= 2;
195 		goto retry;
196 	}
197 	if (res)
198 		freeaddrinfo(res);
199 
200 	/* Don't worry if we get an error from setsockopt(). */
201 	trial = 1;
202 	setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &trial, sizeof(trial));
203 
204 	return(s);
205 }
206 
207 /*
208  * Getline reads a line from the control file cfp, removes tabs, converts
209  *  new-line to null and leaves it in line.
210  * Returns 0 at EOF or the number of characters read.
211  */
212 int
213 getline(FILE *cfp)
214 {
215 	int linel = 0;
216 	char *lp = line;
217 	int c;
218 
219 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
220 		if (c == EOF)
221 			return(0);
222 		if (c == '\t') {
223 			do {
224 				*lp++ = ' ';
225 				linel++;
226 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
227 			continue;
228 		}
229 		*lp++ = c;
230 		linel++;
231 	}
232 	*lp++ = '\0';
233 	return(linel);
234 }
235 
236 /*
237  * Scan the current directory and make a list of daemon files sorted by
238  * creation time.
239  * Return the number of entries and a pointer to the list.
240  */
241 int
242 getq(struct queue ***namelist)
243 {
244 	struct dirent *d;
245 	struct queue *q, **queue;
246 	size_t nitems, arraysz;
247 	struct stat stbuf;
248 	DIR *dirp;
249 
250 	PRIV_START;
251 	dirp = opendir(SD);
252 	PRIV_END;
253 	if (dirp == NULL)
254 		return(-1);
255 	if (fstat(dirfd(dirp), &stbuf) < 0)
256 		goto errdone;
257 
258 	/*
259 	 * Estimate the array size by taking the size of the directory file
260 	 * and dividing it by a multiple of the minimum size entry.
261 	 */
262 	arraysz = (stbuf.st_size / 24);
263 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
264 	if (queue == NULL)
265 		goto errdone;
266 
267 	nitems = 0;
268 	while ((d = readdir(dirp)) != NULL) {
269 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
270 			continue;	/* daemon control files only */
271 		PRIV_START;
272 		if (stat(d->d_name, &stbuf) < 0) {
273 			PRIV_END;
274 			continue;	/* Doesn't exist */
275 		}
276 		PRIV_END;
277 		q = (struct queue *)malloc(sizeof(struct queue));
278 		if (q == NULL)
279 			goto errdone;
280 		q->q_time = stbuf.st_mtime;
281 		strlcpy(q->q_name, d->d_name, sizeof(q->q_name));
282 
283 		/*
284 		 * Check to make sure the array has space left and
285 		 * realloc the maximum size.
286 		 */
287 		if (++nitems > arraysz) {
288 			arraysz *= 2;
289 			queue = (struct queue **)realloc(queue,
290 				arraysz * sizeof(struct queue *));
291 			if (queue == NULL)
292 				goto errdone;
293 		}
294 		queue[nitems-1] = q;
295 	}
296 	closedir(dirp);
297 	if (nitems)
298 		qsort(queue, nitems, sizeof(struct queue *), compar);
299 	*namelist = queue;
300 	return(nitems);
301 
302 errdone:
303 	closedir(dirp);
304 	return(-1);
305 }
306 
307 /*
308  * Compare modification times.
309  */
310 static int
311 compar(const void *v1, const void *v2)
312 {
313 	struct queue *p1 = *(struct queue **)v1;
314 	struct queue *p2 = *(struct queue **)v2;
315 
316 	return(p1->q_time - p2->q_time);
317 }
318 
319 /*
320  * Figure out whether the local machine is the same
321  * as the remote machine (RM) entry (if it exists).
322  */
323 char *
324 checkremote(void)
325 {
326 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
327 	struct addrinfo hints, *res, *res0;
328 	static char errbuf[128];
329 	int error;
330 	struct ifaddrs *ifap, *ifa;
331 #ifdef NI_WITHSCOPEID
332 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
333 #else
334 	const int niflags = NI_NUMERICHOST;
335 #endif
336 #ifdef __KAME__
337 	struct sockaddr_in6 sin6;
338 	struct sockaddr_in6 *sin6p;
339 #endif
340 
341 	remote = 0;	/* assume printer is local on failure */
342 
343 	if (RM == NULL || *RM == '\0')
344 		return NULL;
345 
346 	/* get the local interface addresses */
347 	siginterrupt(SIGINT, 1);
348 	if (getifaddrs(&ifap) < 0) {
349 		(void)snprintf(errbuf, sizeof(errbuf),
350 		    "unable to get local interface address: %s",
351 		    strerror(errno));
352 		siginterrupt(SIGINT, 0);
353 		return errbuf;
354 	}
355 	siginterrupt(SIGINT, 0);
356 
357 	/* get the remote host addresses (RM) */
358 	memset(&hints, 0, sizeof(hints));
359 	hints.ai_flags = AI_CANONNAME;
360 	hints.ai_family = PF_UNSPEC;
361 	hints.ai_socktype = SOCK_STREAM;
362 	res = NULL;
363 	siginterrupt(SIGINT, 1);
364 	error = getaddrinfo(RM, NULL, &hints, &res0);
365 	siginterrupt(SIGINT, 0);
366 	if (error) {
367 		(void)snprintf(errbuf, sizeof(errbuf),
368 		    "unable to resolve remote machine %s: %s",
369 		    RM, gai_strerror(error));
370 		freeifaddrs(ifap);
371 		return errbuf;
372 	}
373 
374 	remote = 1;	/* assume printer is remote */
375 
376 	for (res = res0; res; res = res->ai_next) {
377 		siginterrupt(SIGINT, 1);
378 		error = getnameinfo(res->ai_addr, res->ai_addrlen,
379 		    rname, sizeof(rname), NULL, 0, niflags);
380 		siginterrupt(SIGINT, 0);
381 		if (error != 0)
382 			continue;
383 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
384 #ifdef __KAME__
385 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
386 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
387 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
388 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
389 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
390 				/* kame scopeid hack */
391 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
392 				sin6.sin6_scope_id =
393 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
394 				sin6.sin6_addr.s6_addr[2] = 0;
395 				sin6.sin6_addr.s6_addr[3] = 0;
396 				siginterrupt(SIGINT, 1);
397 				error = getnameinfo((struct sockaddr *)&sin6,
398 				    sin6.sin6_len, lname, sizeof(lname),
399 				    NULL, 0, niflags);
400 				siginterrupt(SIGINT, 0);
401 				if (error != 0)
402 					continue;
403 			} else
404 #endif
405 			siginterrupt(SIGINT, 1);
406 			error = getnameinfo(ifa->ifa_addr,
407 			    ifa->ifa_addr->sa_len, lname, sizeof(lname), NULL,
408 			    0, niflags);
409 			siginterrupt(SIGINT, 0);
410 			if (error != 0)
411 				continue;
412 
413 			if (strcmp(rname, lname) == 0) {
414 				remote = 0;
415 				goto done;
416 			}
417 		}
418 	}
419 done:
420 	freeaddrinfo(res0);
421 	freeifaddrs(ifap);
422 	return NULL;
423 }
424 
425 /* sleep n milliseconds */
426 void
427 delay(int n)
428 {
429 	struct timeval tdelay;
430 
431 	if (n <= 0 || n > 10000)
432 		fatal("unreasonable delay period (%d)", n);
433 	tdelay.tv_sec = n / 1000;
434 	tdelay.tv_usec = n * 1000 % 1000000;
435 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
436 }
437 
438 __dead void
439 fatal(const char *msg, ...)
440 {
441 	extern char *__progname;
442 	va_list ap;
443 
444 	va_start(ap, msg);
445 	if (from != host)
446 		(void)printf("%s: ", host);
447 	(void)printf("%s: ", __progname);
448 	if (printer)
449 		(void)printf("%s: ", printer);
450 	(void)vprintf(msg, ap);
451 	va_end(ap);
452 	(void)putchar('\n');
453 	exit(1);
454 }
455 
456 int
457 safe_open(const char *path, int flags, mode_t mode)
458 {
459 	int fd, serrno;
460 	struct stat stbuf;
461 
462 	if ((fd = open(path, flags|O_NONBLOCK, mode)) < 0 ||
463 	    fstat(fd, &stbuf) < 0) {
464 		if (fd >= 0) {
465 			serrno = errno;
466 			close(fd);
467 			errno = serrno;
468 		}
469 		return (-1);
470 	}
471 	if (!S_ISREG(stbuf.st_mode)) {
472 		close(fd);
473 		errno = EACCES;
474 		return (-1);
475 	}
476 	if (mode)
477 		(void)fchmod(fd, mode);
478 	return (fd);
479 }
480