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