xref: /openbsd-src/usr.sbin/lpr/common_source/common.c (revision 424cafc0f68555630272c9c95237021a1bef9fdd)
1 /*	$OpenBSD: common.c,v 1.11 2001/04/05 16:59:49 deraadt 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 char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
44 #else
45 static char rcsid[] = "$OpenBSD: common.c,v 1.11 2001/04/05 16:59:49 deraadt 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 "lp.h"
65 #include "pathnames.h"
66 
67 /*
68  * Routines and data common to all the line printer functions.
69  */
70 
71 char	*AF;		/* accounting file */
72 long	 BR;		/* baud rate if lp is a tty */
73 char	*CF;		/* name of cifplot filter (per job) */
74 char	*DF;		/* name of tex filter (per job) */
75 long	 DU;		/* daeomon user-id */
76 long	 FC;		/* flags to clear if lp is a tty */
77 char	*FF;		/* form feed string */
78 long	 FS;		/* flags to set if lp is a tty */
79 char	*GF;		/* name of graph(1G) filter (per job) */
80 long	 HL;		/* print header last */
81 char	*IF;		/* name of input filter (created per job) */
82 char	*LF;		/* log file for error messages */
83 char	*LO;		/* lock file name */
84 char	*LP;		/* line printer device name */
85 long	 MC;		/* maximum number of copies allowed */
86 char	*MS;		/* stty flags to set if lp is a tty */
87 long	 MX;		/* maximum number of blocks to copy */
88 char	*NF;		/* name of ditroff filter (per job) */
89 char	*OF;		/* name of output filter (created once) */
90 char	*PF;		/* name of vrast filter (per job) */
91 long	 PL;		/* page length */
92 long	 PW;		/* page width */
93 long	 PX;		/* page width in pixels */
94 long	 PY;		/* page length in pixels */
95 char	*RF;		/* name of fortran text filter (per job) */
96 char    *RG;		/* resricted group */
97 char	*RM;		/* remote machine name */
98 char	*RP;		/* remote printer name */
99 long	 RS;		/* restricted to those with local accounts */
100 long	 RW;		/* open LP for reading and writing */
101 long	 SB;		/* short banner instead of normal header */
102 long	 SC;		/* suppress multiple copies */
103 char	*SD;		/* spool directory */
104 long	 SF;		/* suppress FF on each print job */
105 long	 SH;		/* suppress header page */
106 char	*ST;		/* status file name */
107 char	*TF;		/* name of troff filter (per job) */
108 char	*TR;		/* trailer string to be output when Q empties */
109 char	*VF;		/* name of vplot filter (per job) */
110 long	 XC;		/* flags to clear for local mode */
111 long	 XS;		/* flags to set for local mode */
112 
113 char	line[BUFSIZ];
114 char	*bp;		/* pointer into printcap buffer. */
115 char	*name;		/* program name */
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 __P((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 		hp = gethostbyname(rhost);
153 		if (hp == NULL)
154 			fatal("unknown host %s", rhost);
155 		bcopy(hp->h_addr, (caddr_t)&sin.sin_addr, hp->h_length);
156 		sin.sin_family = hp->h_addrtype;
157 	}
158 	if (rport == 0) {
159 		sp = getservbyname("printer", "tcp");
160 		if (sp == NULL)
161 			fatal("printer/tcp: unknown service");
162 		sin.sin_port = sp->s_port;
163 	} else
164 		sin.sin_port = htons(rport);
165 
166 	/*
167 	 * Try connecting to the server.
168 	 */
169 retry:
170 	seteuid(euid);
171 	s = rresvport(&lport);
172 	seteuid(uid);
173 	if (s < 0)
174 		return(-1);
175 	if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
176 		err = errno;
177 		(void) close(s);
178 		errno = err;
179 		if (errno == EADDRINUSE) {
180 			lport--;
181 			goto retry;
182 		}
183 		if (errno == ECONNREFUSED && timo <= 16) {
184 			sleep(timo);
185 			timo *= 2;
186 			goto retry;
187 		}
188 		return(-1);
189 	}
190 
191 	/* Don't bother if we get an error here.  */
192 	setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
193 	return(s);
194 }
195 
196 /*
197  * Getline reads a line from the control file cfp, removes tabs, converts
198  *  new-line to null and leaves it in line.
199  * Returns 0 at EOF or the number of characters read.
200  */
201 int
202 getline(cfp)
203 	FILE *cfp;
204 {
205 	register int linel = 0;
206 	register char *lp = line;
207 	register c;
208 
209 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
210 		if (c == EOF)
211 			return(0);
212 		if (c == '\t') {
213 			do {
214 				*lp++ = ' ';
215 				linel++;
216 			} while ((linel & 07) != 0 && linel+1<sizeof(line));
217 			continue;
218 		}
219 		*lp++ = c;
220 		linel++;
221 	}
222 	*lp++ = '\0';
223 	return(linel);
224 }
225 
226 /*
227  * Scan the current directory and make a list of daemon files sorted by
228  * creation time.
229  * Return the number of entries and a pointer to the list.
230  */
231 int
232 getq(namelist)
233 	struct queue *(*namelist[]);
234 {
235 	register struct dirent *d;
236 	register struct queue *q, **queue;
237 	register int nitems;
238 	struct stat stbuf;
239 	DIR *dirp;
240 	int arraysz;
241 
242 
243 	seteuid(euid);
244 	dirp = opendir(SD);
245 	seteuid(uid);
246 	if (dirp== NULL)
247 		return(-1);
248 	if (fstat(dirp->dd_fd, &stbuf) < 0)
249 		goto errdone;
250 
251 	/*
252 	 * Estimate the array size by taking the size of the directory file
253 	 * and dividing it by a multiple of the minimum size entry.
254 	 */
255 	arraysz = (stbuf.st_size / 24);
256 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
257 	if (queue == NULL)
258 		goto errdone;
259 
260 	nitems = 0;
261 	while ((d = readdir(dirp)) != NULL) {
262 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
263 			continue;	/* daemon control files only */
264 		seteuid(euid);
265 		if (stat(d->d_name, &stbuf) < 0) {
266 			seteuid(uid);
267 			continue;	/* Doesn't exist */
268 		}
269 		seteuid(uid);
270 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
271 		if (q == NULL)
272 			goto errdone;
273 		q->q_time = stbuf.st_mtime;
274 		strcpy(q->q_name, d->d_name);
275 		/*
276 		 * Check to make sure the array has space left and
277 		 * realloc the maximum size.
278 		 */
279 		if (++nitems > arraysz) {
280 			arraysz *= 2;
281 			queue = (struct queue **)realloc((char *)queue,
282 				arraysz * sizeof(struct queue *));
283 			if (queue == NULL)
284 				goto errdone;
285 		}
286 		queue[nitems-1] = q;
287 	}
288 	closedir(dirp);
289 	if (nitems)
290 		qsort(queue, nitems, sizeof(struct queue *), compar);
291 	*namelist = queue;
292 	return(nitems);
293 
294 errdone:
295 	closedir(dirp);
296 	return(-1);
297 }
298 
299 /*
300  * Compare modification times.
301  */
302 static int
303 compar(p1, p2)
304 	const void *p1, *p2;
305 {
306 	if ((*(struct queue **)p1)->q_time < (*(struct queue **)p2)->q_time)
307 		return(-1);
308 	if ((*(struct queue **)p1)->q_time > (*(struct queue **)p2)->q_time)
309 		return(1);
310 	return(0);
311 }
312 
313 /*
314  * Figure out whether the local machine is the same
315  * as the remote machine (RM) entry (if it exists).
316  */
317 char *
318 checkremote()
319 {
320 	char name[MAXHOSTNAMELEN];
321 	register struct hostent *hp;
322 	static char errbuf[128];
323 	char *rp, *rp_b;
324 
325 	remote = 0;	/* assume printer is local */
326 	if (RM != NULL) {
327 		/* get the official name of the local host */
328 		gethostname(name, sizeof(name));
329 		name[sizeof(name)-1] = '\0';
330 		hp = gethostbyname(name);
331 		if (hp == (struct hostent *) NULL) {
332 		    (void) snprintf(errbuf, sizeof(errbuf),
333 			"unable to get official name for local machine %s",
334 			name);
335 		    return errbuf;
336 		} else (void) strcpy(name, hp->h_name);
337 
338 		/* get the official name of RM */
339 		hp = gethostbyname(RM);
340 		if (hp == (struct hostent *) NULL) {
341 		    (void) snprintf(errbuf, sizeof(errbuf),
342 			"unable to get official name for remote machine %s",
343 			RM);
344 		    return errbuf;
345 		}
346 
347 		/*
348 		 * if the two hosts are not the same,
349 		 * then the printer must be remote.
350 		 */
351 		if (strcasecmp(name, hp->h_name) != 0)
352 			remote = 1;
353 		else if (cgetstr(bp, "rp", &rp) > 0) {
354 			if (cgetent(&rp_b, printcapdb, rp) == 0) {
355 				if (cgetmatch(rp_b, printer) != 0)
356 					remote = 1;
357 				free(rp_b);
358 			} else {
359 				(void) snprintf(errbuf, sizeof(errbuf),
360 					"can't find (local) remote printer %s",
361 					rp);
362 					free(rp);
363 					return errbuf;
364 			}
365 			free(rp);
366 		}
367 	}
368 	return NULL;
369 }
370 
371 /* sleep n milliseconds */
372 void
373 delay(n)
374 {
375 	struct timeval tdelay;
376 
377 	if (n <= 0 || n > 10000)
378 		fatal("unreasonable delay period (%d)", n);
379 	tdelay.tv_sec = n / 1000;
380 	tdelay.tv_usec = n * 1000 % 1000000;
381 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
382 }
383 
384 #ifdef __STDC__
385 #include <stdarg.h>
386 #else
387 #include <varargs.h>
388 #endif
389 
390 void
391 #ifdef __STDC__
392 fatal(const char *msg, ...)
393 #else
394 fatal(msg, va_alist)
395 	char *msg;
396         va_dcl
397 #endif
398 {
399 	va_list ap;
400 #ifdef __STDC__
401 	va_start(ap, msg);
402 #else
403 	va_start(ap);
404 #endif
405 	if (from != host)
406 		(void)printf("%s: ", host);
407 	(void)printf("%s: ", name);
408 	if (printer)
409 		(void)printf("%s: ", printer);
410 	(void)vprintf(msg, ap);
411 	va_end(ap);
412 	(void)putchar('\n');
413 	exit(1);
414 }
415