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