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