xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision f733074b3d59a9e1028393c8c9ee53841f4eb25c)
1 /*	$OpenBSD: common.c,v 1.26 2003/09/26 06:01:41 pvalchev 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.26 2003/09/26 06:01:41 pvalchev 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;		/* daeomon 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 char	*PF;		/* name of vrast filter (per job) */
92 long	 PL;		/* page length */
93 long	 PW;		/* page width */
94 long	 PX;		/* page width in pixels */
95 long	 PY;		/* page length in pixels */
96 char	*RF;		/* name of fortran text filter (per job) */
97 char    *RG;		/* resricted group */
98 char	*RM;		/* remote machine name */
99 char	*RP;		/* remote printer name */
100 long	 RS;		/* restricted to those with local accounts */
101 long	 RW;		/* open LP for reading and writing */
102 long	 SB;		/* short banner instead of normal header */
103 long	 SC;		/* suppress multiple copies */
104 char	*SD;		/* spool directory */
105 long	 SF;		/* suppress FF on each print job */
106 long	 SH;		/* suppress header page */
107 char	*ST;		/* status file name */
108 char	*TF;		/* name of troff filter (per job) */
109 char	*TR;		/* trailer string to be output when Q empties */
110 char	*VF;		/* name of vplot filter (per job) */
111 long	 XC;		/* flags to clear for local mode */
112 long	 XS;		/* flags to set for local mode */
113 
114 char	line[BUFSIZ];
115 int	remote;		/* true if sending files to a remote host */
116 
117 static int compar(const void *, const void *);
118 
119 /*
120  * Create a TCP connection to host "rhost" at port "rport".
121  * If rport == 0, then use the printer service port.
122  * Most of this code comes from rcmd.c.
123  */
124 int
125 getport(char *rhost, int rport)
126 {
127 	struct addrinfo hints, *res, *r;
128 	u_int timo = 1;
129 	int s, lport = IPPORT_RESERVED - 1;
130 	int error;
131 	int refuse, trial;
132 	char pbuf[NI_MAXSERV];
133 
134 	/*
135 	 * Get the host address and port number to connect to.
136 	 */
137 	if (rhost == NULL)
138 		fatal("no remote host to connect to");
139 	memset(&hints, 0, sizeof(hints));
140 	hints.ai_family = PF_UNSPEC;
141 	hints.ai_socktype = SOCK_STREAM;
142 	if (rport)
143 		snprintf(pbuf, sizeof(pbuf), "%d", rport);
144 	else
145 		snprintf(pbuf, sizeof(pbuf), "printer");
146 	siginterrupt(SIGINT, 1);
147 	error = getaddrinfo(rhost, pbuf, &hints, &res);
148 	siginterrupt(SIGINT, 0);
149 	if (error)
150 		fatal("printer/tcp: %s", gai_strerror(error));
151 
152 	/*
153 	 * Try connecting to the server.
154 	 */
155 retry:
156 	s = -1;
157 	refuse = trial = 0;
158 	for (r = res; r; r = r->ai_next) {
159 		trial++;
160 retryport:
161 		PRIV_START;
162 		s = rresvport_af(&lport, r->ai_family);
163 		PRIV_END;
164 		if (s < 0) {
165 			/* fall back to non-privileged port */
166 			if (errno != EACCES ||
167 			    (s = socket(r->ai_family, SOCK_STREAM, 0)) < 0)
168 				return(-1);
169 		}
170 		siginterrupt(SIGINT, 1);
171 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
172 			error = errno;
173 			siginterrupt(SIGINT, 0);
174 			(void)close(s);
175 			s = -1;
176 			errno = error;
177 			if (errno == EADDRINUSE) {
178 				lport--;
179 				goto retryport;
180 			} else if (errno == ECONNREFUSED)
181 				refuse++;
182 			continue;
183 		} else {
184 			siginterrupt(SIGINT, 0);
185 			break;
186 		}
187 	}
188 	if (s < 0 && trial == refuse && timo <= 16) {
189 		sleep(timo);
190 		timo *= 2;
191 		goto retry;
192 	}
193 	if (res)
194 		freeaddrinfo(res);
195 
196 	/* Don't worry if we get an error from setsockopt(). */
197 	trial = 1;
198 	setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &trial, sizeof(trial));
199 
200 	return(s);
201 }
202 
203 /*
204  * Getline reads a line from the control file cfp, removes tabs, converts
205  *  new-line to null and leaves it in line.
206  * Returns 0 at EOF or the number of characters read.
207  */
208 int
209 getline(FILE *cfp)
210 {
211 	int linel = 0;
212 	char *lp = line;
213 	int c;
214 
215 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
216 		if (c == EOF)
217 			return(0);
218 		if (c == '\t') {
219 			do {
220 				*lp++ = ' ';
221 				linel++;
222 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
223 			continue;
224 		}
225 		*lp++ = c;
226 		linel++;
227 	}
228 	*lp++ = '\0';
229 	return(linel);
230 }
231 
232 /*
233  * Scan the current directory and make a list of daemon files sorted by
234  * creation time.
235  * Return the number of entries and a pointer to the list.
236  */
237 int
238 getq(struct queue ***namelist)
239 {
240 	struct dirent *d;
241 	struct queue *q, **queue;
242 	size_t nitems, arraysz;
243 	struct stat stbuf;
244 	DIR *dirp;
245 
246 	PRIV_START;
247 	dirp = opendir(SD);
248 	PRIV_END;
249 	if (dirp == NULL)
250 		return(-1);
251 	if (fstat(dirfd(dirp), &stbuf) < 0)
252 		goto errdone;
253 
254 	/*
255 	 * Estimate the array size by taking the size of the directory file
256 	 * and dividing it by a multiple of the minimum size entry.
257 	 */
258 	arraysz = (stbuf.st_size / 24);
259 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
260 	if (queue == NULL)
261 		goto errdone;
262 
263 	nitems = 0;
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(queue);
290 				queue = NULL;
291 				goto errdone;
292 			}
293 			queue = newqueue;
294 			arraysz = newarraysz;
295 		}
296 		queue[nitems-1] = q;
297 	}
298 	closedir(dirp);
299 	if (nitems)
300 		qsort(queue, nitems, sizeof(struct queue *), compar);
301 	*namelist = queue;
302 	return(nitems);
303 
304 errdone:
305 	closedir(dirp);
306 	return(-1);
307 }
308 
309 /*
310  * Compare modification times.
311  */
312 static int
313 compar(const void *v1, const void *v2)
314 {
315 	struct queue *p1 = *(struct queue **)v1;
316 	struct queue *p2 = *(struct queue **)v2;
317 
318 	return(p1->q_time - p2->q_time);
319 }
320 
321 /*
322  * Figure out whether the local machine is the same
323  * as the remote machine (RM) entry (if it exists).
324  */
325 char *
326 checkremote(void)
327 {
328 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
329 	struct addrinfo hints, *res, *res0;
330 	static char errbuf[128];
331 	int error;
332 	struct ifaddrs *ifap, *ifa;
333 #ifdef NI_WITHSCOPEID
334 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
335 #else
336 	const int niflags = NI_NUMERICHOST;
337 #endif
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