xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision a79bd069ba3ca395b5a7cae7059eea7c9dddcdea)
1 /*	$OpenBSD: common.c,v 1.21 2002/06/09 03:44:50 millert 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.21 2002/06/09 03:44:50 millert 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(rhost, rport)
130 	char *rhost;
131 	int rport;
132 {
133 	struct addrinfo hints, *res, *r;
134 	u_int timo = 1;
135 	int s, lport = IPPORT_RESERVED - 1;
136 	int error;
137 	int refuse, trial;
138 	char pbuf[NI_MAXSERV];
139 
140 	/*
141 	 * Get the host address and port number to connect to.
142 	 */
143 	if (rhost == NULL)
144 		fatal("no remote host to connect to");
145 	memset(&hints, 0, sizeof(hints));
146 	hints.ai_family = PF_UNSPEC;
147 	hints.ai_socktype = SOCK_STREAM;
148 	if (rport)
149 		snprintf(pbuf, sizeof(pbuf), "%d", rport);
150 	else
151 		snprintf(pbuf, sizeof(pbuf), "printer");
152 	siginterrupt(SIGINT, 1);
153 	error = getaddrinfo(rhost, pbuf, &hints, &res);
154 	siginterrupt(SIGINT, 0);
155 	if (error)
156 		fatal("printer/tcp: %s", gai_strerror(error));
157 
158 	/*
159 	 * Try connecting to the server.
160 	 */
161 retry:
162 	s = -1;
163 	refuse = trial = 0;
164 	for (r = res; r; r = r->ai_next) {
165 		trial++;
166 retryport:
167 		PRIV_START;
168 		s = rresvport_af(&lport, r->ai_family);
169 		PRIV_END;
170 		if (s < 0) {
171 			/* fall back to non-privileged port */
172 			if (errno != EACCES ||
173 			    (s = socket(r->ai_family, SOCK_STREAM, 0)) < 0)
174 				return(-1);
175 		}
176 		siginterrupt(SIGINT, 1);
177 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
178 			error = errno;
179 			siginterrupt(SIGINT, 0);
180 			(void)close(s);
181 			s = -1;
182 			errno = error;
183 			if (errno == EADDRINUSE) {
184 				lport--;
185 				goto retryport;
186 			} else if (errno == ECONNREFUSED)
187 				refuse++;
188 			continue;
189 		} else {
190 			siginterrupt(SIGINT, 0);
191 			break;
192 		}
193 	}
194 	if (s < 0 && trial == refuse && timo <= 16) {
195 		sleep(timo);
196 		timo *= 2;
197 		goto retry;
198 	}
199 	if (res)
200 		freeaddrinfo(res);
201 
202 	/* Don't worry if we get an error from setsockopt(). */
203 	trial = 1;
204 	setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &trial, sizeof(trial));
205 
206 	return(s);
207 }
208 
209 /*
210  * Getline reads a line from the control file cfp, removes tabs, converts
211  *  new-line to null and leaves it in line.
212  * Returns 0 at EOF or the number of characters read.
213  */
214 int
215 getline(cfp)
216 	FILE *cfp;
217 {
218 	int linel = 0;
219 	char *lp = line;
220 	int c;
221 
222 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
223 		if (c == EOF)
224 			return(0);
225 		if (c == '\t') {
226 			do {
227 				*lp++ = ' ';
228 				linel++;
229 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
230 			continue;
231 		}
232 		*lp++ = c;
233 		linel++;
234 	}
235 	*lp++ = '\0';
236 	return(linel);
237 }
238 
239 /*
240  * Scan the current directory and make a list of daemon files sorted by
241  * creation time.
242  * Return the number of entries and a pointer to the list.
243  */
244 int
245 getq(namelist)
246 	struct queue *(*namelist[]);
247 {
248 	struct dirent *d;
249 	struct queue *q, **queue;
250 	size_t nitems, arraysz;
251 	struct stat stbuf;
252 	DIR *dirp;
253 
254 	PRIV_START;
255 	dirp = opendir(SD);
256 	PRIV_END;
257 	if (dirp == NULL)
258 		return(-1);
259 	if (fstat(dirfd(dirp), &stbuf) < 0)
260 		goto errdone;
261 
262 	/*
263 	 * Estimate the array size by taking the size of the directory file
264 	 * and dividing it by a multiple of the minimum size entry.
265 	 */
266 	arraysz = (stbuf.st_size / 24);
267 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
268 	if (queue == NULL)
269 		goto errdone;
270 
271 	nitems = 0;
272 	while ((d = readdir(dirp)) != NULL) {
273 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
274 			continue;	/* daemon control files only */
275 		PRIV_START;
276 		if (stat(d->d_name, &stbuf) < 0) {
277 			PRIV_END;
278 			continue;	/* Doesn't exist */
279 		}
280 		PRIV_END;
281 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
282 		if (q == NULL)
283 			goto errdone;
284 		q->q_time = stbuf.st_mtime;
285 		strcpy(q->q_name, d->d_name);	/* safe */
286 		/*
287 		 * Check to make sure the array has space left and
288 		 * realloc the maximum size.
289 		 */
290 		if (++nitems > arraysz) {
291 			arraysz *= 2;
292 			queue = (struct queue **)realloc(queue,
293 				arraysz * sizeof(struct queue *));
294 			if (queue == NULL)
295 				goto errdone;
296 		}
297 		queue[nitems-1] = q;
298 	}
299 	closedir(dirp);
300 	if (nitems)
301 		qsort(queue, nitems, sizeof(struct queue *), compar);
302 	*namelist = queue;
303 	return(nitems);
304 
305 errdone:
306 	closedir(dirp);
307 	return(-1);
308 }
309 
310 /*
311  * Compare modification times.
312  */
313 static int
314 compar(v1, v2)
315 	const void *v1, *v2;
316 {
317 	struct queue *p1 = *(struct queue **)v1;
318 	struct queue *p2 = *(struct queue **)v2;
319 
320 	return(p1->q_time - p2->q_time);
321 }
322 
323 /*
324  * Figure out whether the local machine is the same
325  * as the remote machine (RM) entry (if it exists).
326  */
327 char *
328 checkremote(void)
329 {
330 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
331 	struct addrinfo hints, *res, *res0;
332 	static char errbuf[128];
333 	int error;
334 	struct ifaddrs *ifap, *ifa;
335 #ifdef NI_WITHSCOPEID
336 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
337 #else
338 	const int niflags = NI_NUMERICHOST;
339 #endif
340 #ifdef __KAME__
341 	struct sockaddr_in6 sin6;
342 	struct sockaddr_in6 *sin6p;
343 #endif
344 
345 	remote = 0;	/* assume printer is local on failure */
346 
347 	if (RM == NULL || *RM == '\0')
348 		return NULL;
349 
350 	/* get the local interface addresses */
351 	siginterrupt(SIGINT, 1);
352 	if (getifaddrs(&ifap) < 0) {
353 		(void)snprintf(errbuf, sizeof(errbuf),
354 		    "unable to get local interface address: %s",
355 		    strerror(errno));
356 		siginterrupt(SIGINT, 0);
357 		return errbuf;
358 	}
359 	siginterrupt(SIGINT, 0);
360 
361 	/* get the remote host addresses (RM) */
362 	memset(&hints, 0, sizeof(hints));
363 	hints.ai_flags = AI_CANONNAME;
364 	hints.ai_family = PF_UNSPEC;
365 	hints.ai_socktype = SOCK_STREAM;
366 	res = NULL;
367 	siginterrupt(SIGINT, 1);
368 	error = getaddrinfo(RM, NULL, &hints, &res0);
369 	siginterrupt(SIGINT, 0);
370 	if (error) {
371 		(void)snprintf(errbuf, sizeof(errbuf),
372 		    "unable to resolve remote machine %s: %s",
373 		    RM, gai_strerror(error));
374 		freeifaddrs(ifap);
375 		return errbuf;
376 	}
377 
378 	remote = 1;	/* assume printer is remote */
379 
380 	for (res = res0; res; res = res->ai_next) {
381 		siginterrupt(SIGINT, 1);
382 		error = getnameinfo(res->ai_addr, res->ai_addrlen,
383 		    rname, sizeof(rname), NULL, 0, niflags);
384 		siginterrupt(SIGINT, 0);
385 		if (error != 0)
386 			continue;
387 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
388 #ifdef __KAME__
389 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
390 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
391 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
392 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
393 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
394 				/* kame scopeid hack */
395 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
396 				sin6.sin6_scope_id =
397 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
398 				sin6.sin6_addr.s6_addr[2] = 0;
399 				sin6.sin6_addr.s6_addr[3] = 0;
400 				siginterrupt(SIGINT, 1);
401 				error = getnameinfo((struct sockaddr *)&sin6,
402 				    sin6.sin6_len, lname, sizeof(lname),
403 				    NULL, 0, niflags);
404 				siginterrupt(SIGINT, 0);
405 				if (error != 0)
406 					continue;
407 			} else
408 #endif
409 			siginterrupt(SIGINT, 1);
410 			error = getnameinfo(ifa->ifa_addr,
411 			    ifa->ifa_addr->sa_len, lname, sizeof(lname), NULL,
412 			    0, niflags);
413 			siginterrupt(SIGINT, 0);
414 			if (error != 0)
415 				continue;
416 
417 			if (strcmp(rname, lname) == 0) {
418 				remote = 0;
419 				goto done;
420 			}
421 		}
422 	}
423 done:
424 	freeaddrinfo(res0);
425 	freeifaddrs(ifap);
426 	return NULL;
427 }
428 
429 /* sleep n milliseconds */
430 void
431 delay(int n)
432 {
433 	struct timeval tdelay;
434 
435 	if (n <= 0 || n > 10000)
436 		fatal("unreasonable delay period (%d)", n);
437 	tdelay.tv_sec = n / 1000;
438 	tdelay.tv_usec = n * 1000 % 1000000;
439 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
440 }
441 
442 void
443 fatal(const char *msg, ...)
444 {
445 	extern char *__progname;
446 	va_list ap;
447 
448 	va_start(ap, msg);
449 	if (from != host)
450 		(void)printf("%s: ", host);
451 	(void)printf("%s: ", __progname);
452 	if (printer)
453 		(void)printf("%s: ", printer);
454 	(void)vprintf(msg, ap);
455 	va_end(ap);
456 	(void)putchar('\n');
457 	exit(1);
458 }
459 
460 int
461 safe_open(const char *path, int flags, mode_t mode)
462 {
463 	int fd, serrno;
464 	struct stat stbuf;
465 
466 	if ((fd = open(path, flags|O_NONBLOCK, mode)) < 0 ||
467 	    fstat(fd, &stbuf) < 0) {
468 		if (fd >= 0) {
469 			serrno = errno;
470 			close(fd);
471 			errno = serrno;
472 		}
473 		return (-1);
474 	}
475 	if (!S_ISREG(stbuf.st_mode)) {
476 		close(fd);
477 		errno = EACCES;
478 		return (-1);
479 	}
480 	if (mode)
481 		(void)fchmod(fd, mode);
482 	return (fd);
483 }
484