xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision e7beb4a7d58a6a0955c07ef9465f5caa3383f928)
1 /*	$OpenBSD: common.c,v 1.16 2002/02/19 19:39:40 millert 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. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #ifndef lint
42 #if 0
43 static const char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
44 #else
45 static const char rcsid[] = "$OpenBSD: common.c,v 1.16 2002/02/19 19:39:40 millert Exp $";
46 #endif
47 #endif /* not lint */
48 
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52 
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 
58 #include <dirent.h>
59 #include <errno.h>
60 #include <unistd.h>
61 #include <stdlib.h>
62 #include <stdio.h>
63 #include <string.h>
64 #include <stdarg.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 char	*bp;		/* pointer into printcap buffer. */
116 char	*printer;	/* printer name */
117 			/* host machine name */
118 char	host[MAXHOSTNAMELEN];
119 char	*from = host;	/* client's machine name */
120 int	remote;		/* true if sending files to a remote host */
121 char	*printcapdb[2] = { _PATH_PRINTCAP, 0 };
122 
123 extern uid_t	uid, euid;
124 
125 static int compar(const void *, const void *);
126 
127 /*
128  * Create a TCP connection to host "rhost" at port "rport".
129  * If rport == 0, then use the printer service port.
130  * Most of this code comes from rcmd.c.
131  */
132 int
133 getport(rhost, rport)
134 	char *rhost;
135 	int rport;
136 {
137 	struct hostent *hp;
138 	struct servent *sp;
139 	struct sockaddr_in sin;
140 	int s, timo = 1, on = 1, lport = IPPORT_RESERVED - 1;
141 	int err;
142 
143 	/*
144 	 * Get the host address and port number to connect to.
145 	 */
146 	if (rhost == NULL)
147 		fatal("no remote host to connect to");
148 	bzero((char *)&sin, sizeof(sin));
149 	if (inet_aton(rhost, &sin.sin_addr) == 1)
150 		sin.sin_family = AF_INET;
151 	else {
152 		siginterrupt(SIGINT, 1);
153 		hp = gethostbyname(rhost);
154 		if (hp == NULL) {
155 			if (errno == EINTR && gotintr) {
156 				siginterrupt(SIGINT, 0);
157 				return (-1);
158 			}
159 			siginterrupt(SIGINT, 0);
160 			fatal("unknown host %s", rhost);
161 		}
162 		siginterrupt(SIGINT, 0);
163 		bcopy(hp->h_addr, (caddr_t)&sin.sin_addr, hp->h_length);
164 		sin.sin_family = hp->h_addrtype;
165 	}
166 	if (rport == 0) {
167 		sp = getservbyname("printer", "tcp");
168 		if (sp == NULL)
169 			fatal("printer/tcp: unknown service");
170 		sin.sin_port = sp->s_port;
171 	} else
172 		sin.sin_port = htons(rport);
173 
174 	/*
175 	 * Try connecting to the server.
176 	 */
177 retry:
178 	seteuid(euid);
179 	siginterrupt(SIGINT, 1);
180 	s = rresvport(&lport);
181 	siginterrupt(SIGINT, 0);
182 	seteuid(uid);
183 	if (s < 0)
184 		return(-1);
185 	siginterrupt(SIGINT, 1);
186 	if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
187 		err = errno;
188 		(void) close(s);
189 		siginterrupt(SIGINT, 0);
190 		errno = err;
191 		if (errno == EINTR && gotintr) {
192 			close(s);
193 			return (-1);
194 		}
195 		if (errno == EADDRINUSE) {
196 			lport--;
197 			goto retry;
198 		}
199 		if (errno == ECONNREFUSED && timo <= 16) {
200 			sleep(timo);
201 			timo *= 2;
202 			goto retry;
203 		}
204 		return(-1);
205 	}
206 		siginterrupt(SIGINT, 0);
207 
208 	/* Don't bother if we get an error here.  */
209 	setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
210 	return(s);
211 }
212 
213 /*
214  * Getline reads a line from the control file cfp, removes tabs, converts
215  *  new-line to null and leaves it in line.
216  * Returns 0 at EOF or the number of characters read.
217  */
218 int
219 getline(cfp)
220 	FILE *cfp;
221 {
222 	int linel = 0;
223 	char *lp = line;
224 	int c;
225 
226 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
227 		if (c == EOF)
228 			return(0);
229 		if (c == '\t') {
230 			do {
231 				*lp++ = ' ';
232 				linel++;
233 			} while ((linel & 07) != 0 && linel+1<sizeof(line));
234 			continue;
235 		}
236 		*lp++ = c;
237 		linel++;
238 	}
239 	*lp++ = '\0';
240 	return(linel);
241 }
242 
243 /*
244  * Scan the current directory and make a list of daemon files sorted by
245  * creation time.
246  * Return the number of entries and a pointer to the list.
247  */
248 int
249 getq(namelist)
250 	struct queue *(*namelist[]);
251 {
252 	struct dirent *d;
253 	struct queue *q, **queue;
254 	int nitems;
255 	struct stat stbuf;
256 	DIR *dirp;
257 	int arraysz;
258 
259 
260 	seteuid(euid);
261 	dirp = opendir(SD);
262 	seteuid(uid);
263 	if (dirp== NULL)
264 		return(-1);
265 	if (fstat(dirp->dd_fd, &stbuf) < 0)
266 		goto errdone;
267 
268 	/*
269 	 * Estimate the array size by taking the size of the directory file
270 	 * and dividing it by a multiple of the minimum size entry.
271 	 */
272 	arraysz = (stbuf.st_size / 24);
273 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
274 	if (queue == NULL)
275 		goto errdone;
276 
277 	nitems = 0;
278 	while ((d = readdir(dirp)) != NULL) {
279 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
280 			continue;	/* daemon control files only */
281 		seteuid(euid);
282 		if (stat(d->d_name, &stbuf) < 0) {
283 			seteuid(uid);
284 			continue;	/* Doesn't exist */
285 		}
286 		seteuid(uid);
287 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
288 		if (q == NULL)
289 			goto errdone;
290 		q->q_time = stbuf.st_mtime;
291 		strcpy(q->q_name, d->d_name);
292 		/*
293 		 * Check to make sure the array has space left and
294 		 * realloc the maximum size.
295 		 */
296 		if (++nitems > arraysz) {
297 			arraysz *= 2;
298 			queue = (struct queue **)realloc((char *)queue,
299 				arraysz * sizeof(struct queue *));
300 			if (queue == NULL)
301 				goto errdone;
302 		}
303 		queue[nitems-1] = q;
304 	}
305 	closedir(dirp);
306 	if (nitems)
307 		qsort(queue, nitems, sizeof(struct queue *), compar);
308 	*namelist = queue;
309 	return(nitems);
310 
311 errdone:
312 	closedir(dirp);
313 	return(-1);
314 }
315 
316 /*
317  * Compare modification times.
318  */
319 static int
320 compar(p1, p2)
321 	const void *p1, *p2;
322 {
323 	if ((*(struct queue **)p1)->q_time < (*(struct queue **)p2)->q_time)
324 		return(-1);
325 	if ((*(struct queue **)p1)->q_time > (*(struct queue **)p2)->q_time)
326 		return(1);
327 	return(0);
328 }
329 
330 /*
331  * Figure out whether the local machine is the same
332  * as the remote machine (RM) entry (if it exists).
333  */
334 char *
335 checkremote()
336 {
337 	char name[MAXHOSTNAMELEN];
338 	struct hostent *hp;
339 	static char errbuf[128];
340 	char *rp, *rp_b;
341 
342 	remote = 0;	/* assume printer is local */
343 	if (RM != NULL) {
344 		/* get the official name of the local host */
345 		gethostname(name, sizeof(name));
346 		name[sizeof(name)-1] = '\0';
347 		siginterrupt(SIGINT, 1);
348 		hp = gethostbyname(name);
349 		if (hp == (struct hostent *) NULL) {
350 			if (errno == EINTR && gotintr) {
351 				siginterrupt(SIGINT, 0);
352 				return NULL;
353 			}
354 			siginterrupt(SIGINT, 0);
355 			(void) snprintf(errbuf, sizeof(errbuf),
356 			    "unable to get official name for local machine %s",
357 			    name);
358 			return errbuf;
359 		} else
360 			strlcpy(name, hp->h_name, sizeof name);
361 		siginterrupt(SIGINT, 0);
362 
363 		/* get the official name of RM */
364 		hp = gethostbyname(RM);
365 		if (hp == (struct hostent *) NULL) {
366 		    (void) snprintf(errbuf, sizeof(errbuf),
367 			"unable to get official name for remote machine %s",
368 			RM);
369 		    return errbuf;
370 		}
371 
372 		/*
373 		 * if the two hosts are not the same,
374 		 * then the printer must be remote.
375 		 */
376 		if (strcasecmp(name, hp->h_name) != 0)
377 			remote = 1;
378 		else if (cgetstr(bp, "rp", &rp) > 0) {
379 			if (cgetent(&rp_b, printcapdb, rp) == 0) {
380 				if (cgetmatch(rp_b, printer) != 0)
381 					remote = 1;
382 				free(rp_b);
383 			} else {
384 				(void) snprintf(errbuf, sizeof(errbuf),
385 					"can't find (local) remote printer %s",
386 					rp);
387 					free(rp);
388 					return errbuf;
389 			}
390 			free(rp);
391 		}
392 	}
393 	return NULL;
394 }
395 
396 /* sleep n milliseconds */
397 void
398 delay(n)
399 {
400 	struct timeval tdelay;
401 
402 	if (n <= 0 || n > 10000)
403 		fatal("unreasonable delay period (%d)", n);
404 	tdelay.tv_sec = n / 1000;
405 	tdelay.tv_usec = n * 1000 % 1000000;
406 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
407 }
408 
409 void
410 fatal(const char *msg, ...)
411 {
412 	extern char *__progname;
413 	va_list ap;
414 
415 	va_start(ap, msg);
416 	if (from != host)
417 		(void)printf("%s: ", host);
418 	(void)printf("%s: ", __progname);
419 	if (printer)
420 		(void)printf("%s: ", printer);
421 	(void)vprintf(msg, ap);
422 	va_end(ap);
423 	(void)putchar('\n');
424 	exit(1);
425 }
426