Home | History | Annotate | Line # | Download | only in common_source
common.c revision 1.22
      1 /*	$NetBSD: common.c,v 1.22 2001/04/05 13:30:02 wiz 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 #include <sys/cdefs.h>
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)common.c	8.5 (Berkeley) 4/28/95";
     45 #else
     46 __RCSID("$NetBSD: common.c,v 1.22 2001/04/05 13:30:02 wiz 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 <unistd.h>
     62 #include <stdlib.h>
     63 #include <stdio.h>
     64 #include <string.h>
     65 #include <ifaddrs.h>
     66 #include "lp.h"
     67 #include "pathnames.h"
     68 
     69 /*
     70  * Routines and data common to all the line printer functions.
     71  */
     72 
     73 char	*AF;		/* accounting file */
     74 long	 BR;		/* baud rate if lp is a tty */
     75 char	*CF;		/* name of cifplot filter (per job) */
     76 char	*DF;		/* name of tex filter (per job) */
     77 long	 DU;		/* daeomon user-id */
     78 long	 FC;		/* flags to clear if lp is a tty */
     79 char	*FF;		/* form feed string */
     80 long	 FS;		/* flags to set if lp is a tty */
     81 char	*GF;		/* name of graph(1G) filter (per job) */
     82 long	 HL;		/* print header last */
     83 char	*IF;		/* name of input filter (created per job) */
     84 char	*LF;		/* log file for error messages */
     85 char	*LO;		/* lock file name */
     86 char	*LP;		/* line printer device name */
     87 long	 MC;		/* maximum number of copies allowed */
     88 char	*MS;		/* stty flags to set if lp is a tty */
     89 long	 MX;		/* maximum number of blocks to copy */
     90 char	*NF;		/* name of ditroff filter (per job) */
     91 char	*OF;		/* name of output filter (created once) */
     92 char	*PF;		/* name of vrast filter (per job) */
     93 long	 PL;		/* page length */
     94 long	 PW;		/* page width */
     95 long	 PX;		/* page width in pixels */
     96 long	 PY;		/* page length in pixels */
     97 char	*RF;		/* name of fortran text filter (per job) */
     98 char    *RG;		/* resricted group */
     99 char	*RM;		/* remote machine name */
    100 char	*RP;		/* remote printer name */
    101 long	 RS;		/* restricted to those with local accounts */
    102 long	 RW;		/* open LP for reading and writing */
    103 long	 SB;		/* short banner instead of normal header */
    104 long	 SC;		/* suppress multiple copies */
    105 char	*SD;		/* spool directory */
    106 long	 SF;		/* suppress FF on each print job */
    107 long	 SH;		/* suppress header page */
    108 char	*ST;		/* status file name */
    109 char	*TF;		/* name of troff filter (per job) */
    110 char	*TR;		/* trailer string to be output when Q empties */
    111 char	*VF;		/* name of vplot filter (per job) */
    112 long	 XC;		/* flags to clear for local mode */
    113 long	 XS;		/* flags to set for local mode */
    114 
    115 char	line[BUFSIZ];
    116 int	remote;		/* true if sending files to a remote host */
    117 
    118 extern uid_t	uid, euid;
    119 
    120 static int compar __P((const void *, const void *));
    121 
    122 /*
    123  * Create a TCP connection to host "rhost" at port "rport".
    124  * If rport == 0, then use the printer service port.
    125  * Most of this code comes from rcmd.c.
    126  */
    127 int
    128 getport(rhost, rport)
    129 	char *rhost;
    130 	int rport;
    131 {
    132 	struct addrinfo hints, *res, *r;
    133 	u_int timo = 1;
    134 	int s, lport = IPPORT_RESERVED - 1;
    135 	int error;
    136 	int refuse, trial;
    137 	char pbuf[NI_MAXSERV];
    138 
    139 	/*
    140 	 * Get the host address and port number to connect to.
    141 	 */
    142 	if (rhost == NULL)
    143 		fatal("no remote host to connect to");
    144 	memset(&hints, 0, sizeof(hints));
    145 	hints.ai_family = PF_UNSPEC;
    146 	hints.ai_socktype = SOCK_STREAM;
    147 	if (rport)
    148 		snprintf(pbuf, sizeof(pbuf), "%d", rport);
    149 	else
    150 		snprintf(pbuf, sizeof(pbuf), "printer");
    151 	error = getaddrinfo(rhost, pbuf, &hints, &res);
    152 	if (error)
    153 		fatal("printer/tcp: %s", gai_strerror(error));
    154 
    155 	/*
    156 	 * Try connecting to the server.
    157 	 */
    158 retry:
    159 	s = -1;
    160 	refuse = trial = 0;
    161 	for (r = res; r; r = r->ai_next) {
    162 		trial++;
    163 retryport:
    164 		seteuid(euid);
    165 		s = rresvport_af(&lport, r->ai_family);
    166 		seteuid(uid);
    167 		if (s < 0)
    168 			return(-1);
    169 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
    170 			error = errno;
    171 			(void)close(s);
    172 			s = -1;
    173 			errno = error;
    174 			if (errno == EADDRINUSE) {
    175 				lport--;
    176 				goto retryport;
    177 			} else if (errno == ECONNREFUSED)
    178 				refuse++;
    179 			continue;
    180 		} else
    181 			break;
    182 	}
    183 	if (s < 0 && trial == refuse && timo <= 16) {
    184 		sleep(timo);
    185 		timo *= 2;
    186 		goto retry;
    187 	}
    188 	if (res)
    189 		freeaddrinfo(res);
    190 	return(s);
    191 }
    192 
    193 /*
    194  * Getline reads a line from the control file cfp, removes tabs, converts
    195  *  new-line to null and leaves it in line.
    196  * Returns 0 at EOF or the number of characters read.
    197  */
    198 int
    199 getline(cfp)
    200 	FILE *cfp;
    201 {
    202 	int linel = 0, c;
    203 	char *lp = line;
    204 
    205 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
    206 		if (c == EOF)
    207 			return(0);
    208 		if (c == '\t') {
    209 			do {
    210 				*lp++ = ' ';
    211 				linel++;
    212 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
    213 			continue;
    214 		}
    215 		*lp++ = c;
    216 		linel++;
    217 	}
    218 	*lp++ = '\0';
    219 	return(linel);
    220 }
    221 
    222 /*
    223  * Scan the current directory and make a list of daemon files sorted by
    224  * creation time.
    225  * Return the number of entries and a pointer to the list.
    226  */
    227 int
    228 getq(namelist)
    229 	struct queue *(*namelist[]);
    230 {
    231 	struct dirent *d;
    232 	struct queue *q, **queue;
    233 	struct stat stbuf;
    234 	DIR *dirp;
    235 	u_int nitems, arraysz;
    236 
    237 	seteuid(euid);
    238 	dirp = opendir(SD);
    239 	seteuid(uid);
    240 	if (dirp == NULL)
    241 		return(-1);
    242 	if (fstat(dirp->dd_fd, &stbuf) < 0)
    243 		goto errdone;
    244 
    245 	/*
    246 	 * Estimate the array size by taking the size of the directory file
    247 	 * and dividing it by a multiple of the minimum size entry.
    248 	 */
    249 	arraysz = (int)(stbuf.st_size / 24);
    250 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
    251 	if (queue == NULL)
    252 		goto errdone;
    253 
    254 	nitems = 0;
    255 	while ((d = readdir(dirp)) != NULL) {
    256 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    257 			continue;	/* daemon control files only */
    258 		seteuid(euid);
    259 		if (stat(d->d_name, &stbuf) < 0) {
    260 			seteuid(uid);
    261 			continue;	/* Doesn't exist */
    262 		}
    263 		seteuid(uid);
    264 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
    265 		if (q == NULL)
    266 			goto errdone;
    267 		q->q_time = stbuf.st_mtime;
    268 		strcpy(q->q_name, d->d_name);	/* XXX: strcpy is safe */
    269 		/*
    270 		 * Check to make sure the array has space left and
    271 		 * realloc the maximum size.
    272 		 */
    273 		if (++nitems > arraysz) {
    274 			arraysz *= 2;
    275 			queue = (struct queue **)realloc(queue,
    276 				arraysz * sizeof(struct queue *));
    277 			if (queue == NULL)
    278 				goto errdone;
    279 		}
    280 		queue[nitems-1] = q;
    281 	}
    282 	closedir(dirp);
    283 	if (nitems)
    284 		qsort(queue, nitems, sizeof(struct queue *), compar);
    285 	*namelist = queue;
    286 	return(nitems);
    287 
    288 errdone:
    289 	closedir(dirp);
    290 	return(-1);
    291 }
    292 
    293 /*
    294  * Compare modification times.
    295  */
    296 static int
    297 compar(p1, p2)
    298 	const void *p1, *p2;
    299 {
    300 	if ((*(struct queue **)p1)->q_time < (*(struct queue **)p2)->q_time)
    301 		return(-1);
    302 	if ((*(struct queue **)p1)->q_time > (*(struct queue **)p2)->q_time)
    303 		return(1);
    304 	return(0);
    305 }
    306 
    307 /*
    308  * Figure out whether the local machine is the same
    309  * as the remote machine (RM) entry (if it exists).
    310  */
    311 char *
    312 checkremote()
    313 {
    314 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
    315 	struct addrinfo hints, *res, *res0;
    316 	static char errbuf[128];
    317 	int error;
    318 	struct ifaddrs *ifap, *ifa;
    319 #ifdef NI_WITHSCOPEID
    320 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
    321 #else
    322 	const int niflags = NI_NUMERICHOST;
    323 #endif
    324 #ifdef __KAME__
    325 	struct sockaddr_in6 sin6;
    326 	struct sockaddr_in6 *sin6p;
    327 #endif
    328 
    329 	remote = 0;	/* assume printer is local on failure */
    330 
    331 	if (RM == NULL)
    332 		return NULL;
    333 
    334 	/* get the local interface addresses */
    335 	if (getifaddrs(&ifap) < 0) {
    336 		(void)snprintf(errbuf, sizeof(errbuf),
    337 		    "unable to get local interface address: %s",
    338 		    strerror(errno));
    339 		return errbuf;
    340 	}
    341 
    342 	/* get the remote host addresses (RM) */
    343 	memset(&hints, 0, sizeof(hints));
    344 	hints.ai_flags = AI_CANONNAME;
    345 	hints.ai_family = PF_UNSPEC;
    346 	hints.ai_socktype = SOCK_STREAM;
    347 	res = NULL;
    348 	error = getaddrinfo(RM, NULL, &hints, &res0);
    349 	if (error) {
    350 		(void)snprintf(errbuf, sizeof(errbuf),
    351 		    "unable to resolve remote machine %s: %s",
    352 		    RM, gai_strerror(error));
    353 		freeifaddrs(ifap);
    354 		return errbuf;
    355 	}
    356 
    357 	remote = 1;	/* assume printer is remote */
    358 
    359 	for (res = res0; res; res = res->ai_next) {
    360 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
    361 		    rname, sizeof(rname), NULL, 0, niflags) != 0)
    362 			continue;
    363 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
    364 #ifdef __KAME__
    365 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
    366 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
    367 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
    368 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
    369 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
    370 				/* kame scopeid hack */
    371 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
    372 				sin6.sin6_scope_id =
    373 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
    374 				sin6.sin6_addr.s6_addr[2] = 0;
    375 				sin6.sin6_addr.s6_addr[3] = 0;
    376 				if (getnameinfo((struct sockaddr *)&sin6,
    377 				    sin6.sin6_len, lname, sizeof(lname),
    378 				    NULL, 0, niflags) != 0)
    379 					continue;
    380 			} else
    381 #endif
    382 			if (getnameinfo(ifa->ifa_addr, ifa->ifa_addr->sa_len,
    383 			    lname, sizeof(lname), NULL, 0, niflags) != 0)
    384 				continue;
    385 
    386 			if (strcmp(rname, lname) == 0) {
    387 				remote = 0;
    388 				goto done;
    389 			}
    390 		}
    391 	}
    392 done:
    393 	freeaddrinfo(res0);
    394 	freeifaddrs(ifap);
    395 	return NULL;
    396 }
    397 
    398 /* sleep n milliseconds */
    399 void
    400 delay(n)
    401 	int n;
    402 {
    403 	struct timeval tdelay;
    404 
    405 	if (n <= 0 || n > 10000)
    406 		fatal("unreasonable delay period (%d)", n);
    407 	tdelay.tv_sec = n / 1000;
    408 	tdelay.tv_usec = n * 1000 % 1000000;
    409 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
    410 }
    411