xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: common.c,v 1.25 2003/06/02 23:36:53 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. 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.25 2003/06/02 23:36:53 millert 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 			arraysz *= 2;
285 			queue = (struct queue **)realloc(queue,
286 				arraysz * sizeof(struct queue *));
287 			if (queue == NULL)
288 				goto errdone;
289 		}
290 		queue[nitems-1] = q;
291 	}
292 	closedir(dirp);
293 	if (nitems)
294 		qsort(queue, nitems, sizeof(struct queue *), compar);
295 	*namelist = queue;
296 	return(nitems);
297 
298 errdone:
299 	closedir(dirp);
300 	return(-1);
301 }
302 
303 /*
304  * Compare modification times.
305  */
306 static int
307 compar(const void *v1, const void *v2)
308 {
309 	struct queue *p1 = *(struct queue **)v1;
310 	struct queue *p2 = *(struct queue **)v2;
311 
312 	return(p1->q_time - p2->q_time);
313 }
314 
315 /*
316  * Figure out whether the local machine is the same
317  * as the remote machine (RM) entry (if it exists).
318  */
319 char *
320 checkremote(void)
321 {
322 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
323 	struct addrinfo hints, *res, *res0;
324 	static char errbuf[128];
325 	int error;
326 	struct ifaddrs *ifap, *ifa;
327 #ifdef NI_WITHSCOPEID
328 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
329 #else
330 	const int niflags = NI_NUMERICHOST;
331 #endif
332 #ifdef __KAME__
333 	struct sockaddr_in6 sin6;
334 	struct sockaddr_in6 *sin6p;
335 #endif
336 
337 	remote = 0;	/* assume printer is local on failure */
338 
339 	if (RM == NULL || *RM == '\0')
340 		return NULL;
341 
342 	/* get the local interface addresses */
343 	siginterrupt(SIGINT, 1);
344 	if (getifaddrs(&ifap) < 0) {
345 		(void)snprintf(errbuf, sizeof(errbuf),
346 		    "unable to get local interface address: %s",
347 		    strerror(errno));
348 		siginterrupt(SIGINT, 0);
349 		return errbuf;
350 	}
351 	siginterrupt(SIGINT, 0);
352 
353 	/* get the remote host addresses (RM) */
354 	memset(&hints, 0, sizeof(hints));
355 	hints.ai_flags = AI_CANONNAME;
356 	hints.ai_family = PF_UNSPEC;
357 	hints.ai_socktype = SOCK_STREAM;
358 	res = NULL;
359 	siginterrupt(SIGINT, 1);
360 	error = getaddrinfo(RM, NULL, &hints, &res0);
361 	siginterrupt(SIGINT, 0);
362 	if (error) {
363 		(void)snprintf(errbuf, sizeof(errbuf),
364 		    "unable to resolve remote machine %s: %s",
365 		    RM, gai_strerror(error));
366 		freeifaddrs(ifap);
367 		return errbuf;
368 	}
369 
370 	remote = 1;	/* assume printer is remote */
371 
372 	for (res = res0; res; res = res->ai_next) {
373 		siginterrupt(SIGINT, 1);
374 		error = getnameinfo(res->ai_addr, res->ai_addrlen,
375 		    rname, sizeof(rname), NULL, 0, niflags);
376 		siginterrupt(SIGINT, 0);
377 		if (error != 0)
378 			continue;
379 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
380 #ifdef __KAME__
381 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
382 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
383 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
384 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
385 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
386 				/* kame scopeid hack */
387 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
388 				sin6.sin6_scope_id =
389 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
390 				sin6.sin6_addr.s6_addr[2] = 0;
391 				sin6.sin6_addr.s6_addr[3] = 0;
392 				siginterrupt(SIGINT, 1);
393 				error = getnameinfo((struct sockaddr *)&sin6,
394 				    sin6.sin6_len, lname, sizeof(lname),
395 				    NULL, 0, niflags);
396 				siginterrupt(SIGINT, 0);
397 				if (error != 0)
398 					continue;
399 			} else
400 #endif
401 			siginterrupt(SIGINT, 1);
402 			error = getnameinfo(ifa->ifa_addr,
403 			    ifa->ifa_addr->sa_len, lname, sizeof(lname), NULL,
404 			    0, niflags);
405 			siginterrupt(SIGINT, 0);
406 			if (error != 0)
407 				continue;
408 
409 			if (strcmp(rname, lname) == 0) {
410 				remote = 0;
411 				goto done;
412 			}
413 		}
414 	}
415 done:
416 	freeaddrinfo(res0);
417 	freeifaddrs(ifap);
418 	return NULL;
419 }
420 
421 /* sleep n milliseconds */
422 void
423 delay(int n)
424 {
425 	struct timeval tdelay;
426 
427 	if (n <= 0 || n > 10000)
428 		fatal("unreasonable delay period (%d)", n);
429 	tdelay.tv_sec = n / 1000;
430 	tdelay.tv_usec = n * 1000 % 1000000;
431 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
432 }
433 
434 __dead void
435 fatal(const char *msg, ...)
436 {
437 	extern char *__progname;
438 	va_list ap;
439 
440 	va_start(ap, msg);
441 	if (from != host)
442 		(void)printf("%s: ", host);
443 	(void)printf("%s: ", __progname);
444 	if (printer)
445 		(void)printf("%s: ", printer);
446 	(void)vprintf(msg, ap);
447 	va_end(ap);
448 	(void)putchar('\n');
449 	exit(1);
450 }
451 
452 int
453 safe_open(const char *path, int flags, mode_t mode)
454 {
455 	int fd, serrno;
456 	struct stat stbuf;
457 
458 	if ((fd = open(path, flags|O_NONBLOCK, mode)) < 0 ||
459 	    fstat(fd, &stbuf) < 0) {
460 		if (fd >= 0) {
461 			serrno = errno;
462 			close(fd);
463 			errno = serrno;
464 		}
465 		return (-1);
466 	}
467 	if (!S_ISREG(stbuf.st_mode)) {
468 		close(fd);
469 		errno = EACCES;
470 		return (-1);
471 	}
472 	if (mode)
473 		(void)fchmod(fd, mode);
474 	return (fd);
475 }
476