Home | History | Annotate | Line # | Download | only in common_source
common.c revision 1.21
      1 /*	$NetBSD: common.c,v 1.21 2000/08/09 14:28:50 itojun 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.21 2000/08/09 14:28:50 itojun 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 	if ((dirp = opendir(SD)) == NULL)
    239 		return(-1);
    240 	if (fstat(dirp->dd_fd, &stbuf) < 0)
    241 		goto errdone;
    242 	seteuid(uid);
    243 
    244 	/*
    245 	 * Estimate the array size by taking the size of the directory file
    246 	 * and dividing it by a multiple of the minimum size entry.
    247 	 */
    248 	arraysz = (int)(stbuf.st_size / 24);
    249 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
    250 	if (queue == NULL)
    251 		goto errdone;
    252 
    253 	nitems = 0;
    254 	while ((d = readdir(dirp)) != NULL) {
    255 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    256 			continue;	/* daemon control files only */
    257 		seteuid(euid);
    258 		if (stat(d->d_name, &stbuf) < 0)
    259 			continue;	/* Doesn't exist */
    260 		seteuid(uid);
    261 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
    262 		if (q == NULL)
    263 			goto errdone;
    264 		q->q_time = stbuf.st_mtime;
    265 		strcpy(q->q_name, d->d_name);	/* XXX: strcpy is safe */
    266 		/*
    267 		 * Check to make sure the array has space left and
    268 		 * realloc the maximum size.
    269 		 */
    270 		if (++nitems > arraysz) {
    271 			arraysz *= 2;
    272 			queue = (struct queue **)realloc(queue,
    273 				arraysz * sizeof(struct queue *));
    274 			if (queue == NULL)
    275 				goto errdone;
    276 		}
    277 		queue[nitems-1] = q;
    278 	}
    279 	closedir(dirp);
    280 	if (nitems)
    281 		qsort(queue, nitems, sizeof(struct queue *), compar);
    282 	*namelist = queue;
    283 	return(nitems);
    284 
    285 errdone:
    286 	closedir(dirp);
    287 	return(-1);
    288 }
    289 
    290 /*
    291  * Compare modification times.
    292  */
    293 static int
    294 compar(p1, p2)
    295 	const void *p1, *p2;
    296 {
    297 	if ((*(struct queue **)p1)->q_time < (*(struct queue **)p2)->q_time)
    298 		return(-1);
    299 	if ((*(struct queue **)p1)->q_time > (*(struct queue **)p2)->q_time)
    300 		return(1);
    301 	return(0);
    302 }
    303 
    304 /*
    305  * Figure out whether the local machine is the same
    306  * as the remote machine (RM) entry (if it exists).
    307  */
    308 char *
    309 checkremote()
    310 {
    311 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
    312 	struct addrinfo hints, *res, *res0;
    313 	static char errbuf[128];
    314 	int error;
    315 	struct ifaddrs *ifap, *ifa;
    316 #ifdef NI_WITHSCOPEID
    317 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
    318 #else
    319 	const int niflags = NI_NUMERICHOST;
    320 #endif
    321 #ifdef __KAME__
    322 	struct sockaddr_in6 sin6;
    323 	struct sockaddr_in6 *sin6p;
    324 #endif
    325 
    326 	remote = 0;	/* assume printer is local on failure */
    327 
    328 	if (RM == NULL)
    329 		return NULL;
    330 
    331 	/* get the local interface addresses */
    332 	if (getifaddrs(&ifap) < 0) {
    333 		(void)snprintf(errbuf, sizeof(errbuf),
    334 		    "unable to get local interface address: %s",
    335 		    strerror(errno));
    336 		return errbuf;
    337 	}
    338 
    339 	/* get the remote host addresses (RM) */
    340 	memset(&hints, 0, sizeof(hints));
    341 	hints.ai_flags = AI_CANONNAME;
    342 	hints.ai_family = PF_UNSPEC;
    343 	hints.ai_socktype = SOCK_STREAM;
    344 	res = NULL;
    345 	error = getaddrinfo(RM, 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(n)
    398 	int 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