xref: /netbsd-src/usr.sbin/lpr/common_source/common.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: common.c,v 1.29 2006/01/04 15:32:50 garbled Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
41 #else
42 __RCSID("$NetBSD: common.c,v 1.29 2006/01/04 15:32:50 garbled 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 <unistd.h>
58 #include <stdlib.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <ifaddrs.h>
62 #include "lp.h"
63 #include "lp.local.h"
64 #include "pathnames.h"
65 
66 /*
67  * Routines and data common to all the line printer functions.
68  */
69 
70 const char	*AF;		/* accounting file */
71 long		 BR;		/* baud rate if lp is a tty */
72 const char	*CF;		/* name of cifplot filter (per job) */
73 const char	*DF;		/* name of tex filter (per job) */
74 long		 DU;		/* daeomon user-id */
75 long		 FC;		/* flags to clear if lp is a tty */
76 const char	*FF;		/* form feed string */
77 long		 FS;		/* flags to set if lp is a tty */
78 const char	*GF;		/* name of graph(1G) filter (per job) */
79 long		 HL;		/* print header last */
80 const char	*IF;		/* name of input filter (created per job) */
81 const char	*LF;		/* log file for error messages */
82 const char	*LO;		/* lock file name */
83 const char	*LP;		/* line printer device name */
84 long		 MC;		/* maximum number of copies allowed */
85 const char	*MS;		/* stty flags to set if lp is a tty */
86 long		 MX;		/* maximum number of blocks to copy */
87 const char	*NF;		/* name of ditroff filter (per job) */
88 const char	*OF;		/* name of output filter (created once) */
89 const char	*PF;		/* name of vrast filter (per job) */
90 long		 PL;		/* page length */
91 long		 PW;		/* page width */
92 long		 PX;		/* page width in pixels */
93 long		 PY;		/* page length in pixels */
94 const char	*RF;		/* name of fortran text filter (per job) */
95 const char	*RG;		/* resricted group */
96 const char	*RM;		/* remote machine name */
97 const char	*RP;		/* remote printer name */
98 long		 RS;		/* restricted to those with local accounts */
99 long		 RW;		/* open LP for reading and writing */
100 long		 SB;		/* short banner instead of normal header */
101 long		 SC;		/* suppress multiple copies */
102 const char	*SD;		/* spool directory */
103 long		 SF;		/* suppress FF on each print job */
104 long		 SH;		/* suppress header page */
105 const char	*ST;		/* status file name */
106 const char	*TF;		/* name of troff filter (per job) */
107 const char	*TR;		/* trailer string to be output when Q empties */
108 const char	*VF;		/* name of vplot filter (per job) */
109 long		 XC;		/* flags to clear for local mode */
110 long		 XS;		/* flags to set for local mode */
111 
112 char	line[BUFSIZ];
113 int	remote;		/* true if sending files to a remote host */
114 
115 extern uid_t	uid, euid;
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(const 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 	error = getaddrinfo(rhost, pbuf, &hints, &res);
147 	if (error)
148 		fatal("printer/tcp: %s", gai_strerror(error));
149 
150 	/*
151 	 * Try connecting to the server.
152 	 */
153 retry:
154 	s = -1;
155 	refuse = trial = 0;
156 	for (r = res; r; r = r->ai_next) {
157 		trial++;
158 retryport:
159 		seteuid(euid);
160 		s = rresvport_af(&lport, r->ai_family);
161 		seteuid(uid);
162 		if (s < 0)
163 			return(-1);
164 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
165 			error = errno;
166 			(void)close(s);
167 			s = -1;
168 			errno = error;
169 			if (errno == EADDRINUSE) {
170 				lport--;
171 				goto retryport;
172 			} else if (errno == ECONNREFUSED)
173 				refuse++;
174 			continue;
175 		} else
176 			break;
177 	}
178 	if (s < 0 && trial == refuse && timo <= 16) {
179 		sleep(timo);
180 		timo *= 2;
181 		goto retry;
182 	}
183 	if (res)
184 		freeaddrinfo(res);
185 	return(s);
186 }
187 
188 /*
189  * Getline reads a line from the control file cfp, removes tabs, converts
190  *  new-line to null and leaves it in line.
191  * Returns 0 at EOF or the number of characters read.
192  */
193 int
194 getline(FILE *cfp)
195 {
196 	int linel = 0, c;
197 	char *lp = line;
198 
199 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
200 		if (c == EOF)
201 			return(0);
202 		if (c == '\t') {
203 			do {
204 				*lp++ = ' ';
205 				linel++;
206 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
207 			continue;
208 		}
209 		*lp++ = c;
210 		linel++;
211 	}
212 	*lp++ = '\0';
213 	return(linel);
214 }
215 
216 /*
217  * Scan the current directory and make a list of daemon files sorted by
218  * creation time.
219  * Return the number of entries and a pointer to the list.
220  */
221 int
222 getq(struct queue **namelist[])
223 {
224 	struct dirent *d;
225 	struct queue *q, **queue, **nqueue;
226 	struct stat stbuf;
227 	DIR *dirp;
228 	u_int nitems, arraysz;
229 
230 	seteuid(euid);
231 	dirp = opendir(SD);
232 	seteuid(uid);
233 	if (dirp == NULL)
234 		return(-1);
235 	if (fstat(dirp->dd_fd, &stbuf) < 0)
236 		goto errdone;
237 
238 	/*
239 	 * Estimate the array size by taking the size of the directory file
240 	 * and dividing it by a multiple of the minimum size entry.
241 	 */
242 	arraysz = (int)(stbuf.st_size / 24);
243 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
244 	if (queue == NULL)
245 		goto errdone;
246 
247 	nitems = 0;
248 	while ((d = readdir(dirp)) != NULL) {
249 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
250 			continue;	/* daemon control files only */
251 		seteuid(euid);
252 		if (stat(d->d_name, &stbuf) < 0) {
253 			seteuid(uid);
254 			continue;	/* Doesn't exist */
255 		}
256 		seteuid(uid);
257 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
258 		if (q == NULL)
259 			goto errdone;
260 		q->q_time = stbuf.st_mtime;
261 		strcpy(q->q_name, d->d_name);	/* XXX: strcpy is safe */
262 		/*
263 		 * Check to make sure the array has space left and
264 		 * realloc the maximum size.
265 		 */
266 		if (++nitems > arraysz) {
267 			nqueue = (struct queue **)realloc(queue,
268 				arraysz * 2 * sizeof(struct queue *));
269 			if (nqueue == NULL)
270 				goto errdone;
271 			queue = nqueue;
272 			arraysz *= 2;
273 		}
274 		queue[nitems-1] = q;
275 	}
276 	closedir(dirp);
277 	if (nitems)
278 		qsort(queue, nitems, sizeof(struct queue *), compar);
279 	*namelist = queue;
280 	return(nitems);
281 
282 errdone:
283 	closedir(dirp);
284 	return(-1);
285 }
286 
287 /*
288  * Compare modification times.
289  */
290 static int
291 compar(const void *p1, const void *p2)
292 {
293 	const struct queue *const *q1 = p1;
294 	const struct queue *const *q2 = p2;
295 
296 	if ((*q1)->q_time < (*q2)->q_time)
297 		return -1;
298 	if ((*q1)->q_time > (*q2)->q_time)
299 		return 1;
300 	return 0;
301 }
302 
303 /*
304  * Figure out whether the local machine is the same
305  * as the remote machine (RM) entry (if it exists).
306  */
307 const char *
308 checkremote(void)
309 {
310 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
311 	const char *rmhost;
312 	struct addrinfo hints, *res, *res0;
313 	static char errbuf[128];
314 	int error;
315 	struct ifaddrs *ifap, *ifa;
316 	const int niflags = NI_NUMERICHOST;
317 #ifdef __KAME__
318 	struct sockaddr_in6 sin6;
319 	struct sockaddr_in6 *sin6p;
320 #endif
321 
322 	remote = 0;	/* assume printer is local on failure */
323 
324 	if (RM == NULL)
325 		return NULL;
326 
327 	/* get the local interface addresses */
328 	if (getifaddrs(&ifap) < 0) {
329 		(void)snprintf(errbuf, sizeof(errbuf),
330 		    "unable to get local interface address: %s",
331 		    strerror(errno));
332 		return errbuf;
333 	}
334 
335 	/* get the remote host addresses (RM) */
336 	memset(&hints, 0, sizeof(hints));
337 	hints.ai_flags = AI_CANONNAME;
338 	hints.ai_family = PF_UNSPEC;
339 	hints.ai_socktype = SOCK_STREAM;
340 	res = NULL;
341 	if ((rmhost = strchr(RM, '@')))
342 		rmhost++;
343 	else
344 		rmhost = RM;
345 	error = getaddrinfo(rmhost, NULL, &hints, &res0);
346 	if (error) {
347 		(void)snprintf(errbuf, sizeof(errbuf),
348 		    "unable to resolve remote machine %s: %s",
349 		    RM, gai_strerror(error));
350 		freeifaddrs(ifap);
351 		return errbuf;
352 	}
353 
354 	remote = 1;	/* assume printer is remote */
355 
356 	for (res = res0; res; res = res->ai_next) {
357 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
358 		    rname, sizeof(rname), NULL, 0, niflags) != 0)
359 			continue;
360 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
361 #ifdef __KAME__
362 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
363 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
364 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
365 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
366 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
367 				/* kame scopeid hack */
368 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
369 				sin6.sin6_scope_id =
370 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
371 				sin6.sin6_addr.s6_addr[2] = 0;
372 				sin6.sin6_addr.s6_addr[3] = 0;
373 				if (getnameinfo((struct sockaddr *)&sin6,
374 				    sin6.sin6_len, lname, sizeof(lname),
375 				    NULL, 0, niflags) != 0)
376 					continue;
377 			} else
378 #endif
379 			if (getnameinfo(ifa->ifa_addr, ifa->ifa_addr->sa_len,
380 			    lname, sizeof(lname), NULL, 0, niflags) != 0)
381 				continue;
382 
383 			if (strcmp(rname, lname) == 0) {
384 				remote = 0;
385 				goto done;
386 			}
387 		}
388 	}
389 done:
390 	freeaddrinfo(res0);
391 	freeifaddrs(ifap);
392 	return NULL;
393 }
394 
395 /* sleep n milliseconds */
396 void
397 delay(int n)
398 {
399 	struct timespec tdelay;
400 
401 	if (n <= 0 || n > 10000)
402 		fatal("unreasonable delay period (%d)", n);
403 	tdelay.tv_sec = n / 1000;
404 	tdelay.tv_nsec = (n % 1000) * 1000000;
405 	nanosleep(&tdelay, NULL);
406 }
407 
408 void
409 getprintcap(const char *pr)
410 {
411 	char *cp;
412 	const char *dp;
413 	int i;
414 
415 	if ((i = cgetent(&bp, printcapdb, pr)) == -2)
416 		fatal("can't open printer description file");
417 	else if (i == -1)
418 		fatal("unknown printer: %s", pr);
419 	else if (i == -3)
420 		fatal("potential reference loop detected in printcap file");
421 
422 	LP = cgetstr(bp, DEFLP, &cp) == -1 ? _PATH_DEFDEVLP : cp;
423 	RP = cgetstr(bp, "rp", &cp) == -1 ? DEFLP : cp;
424 	SD = cgetstr(bp, "sd", &cp) == -1 ? _PATH_DEFSPOOL : cp;
425 	LO = cgetstr(bp, "lo", &cp) == -1 ? DEFLOCK : cp;
426 	ST = cgetstr(bp, "st", &cp) == -1 ? DEFSTAT : cp;
427 	RM = cgetstr(bp, "rm", &cp) == -1 ? NULL : cp;
428 	if ((dp = checkremote()) != NULL)
429 		printf("Warning: %s\n", dp);
430 	LF = cgetstr(bp, "lf", &cp) == -1 ? _PATH_CONSOLE : cp;
431 }
432 
433 /*
434  * Make sure there's some work to do before forking off a child
435  */
436 int
437 ckqueue(char *cap)
438 {
439 	struct dirent *d;
440 	DIR *dirp;
441 	const char *spooldir;
442 	char *sd;
443 	int rv = 0;
444 
445 	spooldir = cgetstr(cap, "sd", &sd) == -1 ? _PATH_DEFSPOOL : sd;
446 	if ((dirp = opendir(spooldir)) == NULL) {
447 		rv = -1;
448 		goto out;
449 	}
450 	while ((d = readdir(dirp)) != NULL) {
451 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
452 			continue;	/* daemon control files only */
453 		rv = 1;
454 		break;
455 	}
456 out:
457 	if (dirp != NULL)
458 		closedir(dirp);
459 	if (spooldir != sd)
460 		free(sd);
461 	return (0);
462 }
463