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