Home | History | Annotate | Line # | Download | only in common_source
common.c revision 1.23
      1 /*	$NetBSD: common.c,v 1.23 2002/07/14 15:27:58 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.23 2002/07/14 15:27:58 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(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(char *rhost, int rport)
    129 {
    130 	struct addrinfo hints, *res, *r;
    131 	u_int timo = 1;
    132 	int s, lport = IPPORT_RESERVED - 1;
    133 	int error;
    134 	int refuse, trial;
    135 	char pbuf[NI_MAXSERV];
    136 
    137 	/*
    138 	 * Get the host address and port number to connect to.
    139 	 */
    140 	if (rhost == NULL)
    141 		fatal("no remote host to connect to");
    142 	memset(&hints, 0, sizeof(hints));
    143 	hints.ai_family = PF_UNSPEC;
    144 	hints.ai_socktype = SOCK_STREAM;
    145 	if (rport)
    146 		snprintf(pbuf, sizeof(pbuf), "%d", rport);
    147 	else
    148 		snprintf(pbuf, sizeof(pbuf), "printer");
    149 	error = getaddrinfo(rhost, pbuf, &hints, &res);
    150 	if (error)
    151 		fatal("printer/tcp: %s", gai_strerror(error));
    152 
    153 	/*
    154 	 * Try connecting to the server.
    155 	 */
    156 retry:
    157 	s = -1;
    158 	refuse = trial = 0;
    159 	for (r = res; r; r = r->ai_next) {
    160 		trial++;
    161 retryport:
    162 		seteuid(euid);
    163 		s = rresvport_af(&lport, r->ai_family);
    164 		seteuid(uid);
    165 		if (s < 0)
    166 			return(-1);
    167 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
    168 			error = errno;
    169 			(void)close(s);
    170 			s = -1;
    171 			errno = error;
    172 			if (errno == EADDRINUSE) {
    173 				lport--;
    174 				goto retryport;
    175 			} else if (errno == ECONNREFUSED)
    176 				refuse++;
    177 			continue;
    178 		} else
    179 			break;
    180 	}
    181 	if (s < 0 && trial == refuse && timo <= 16) {
    182 		sleep(timo);
    183 		timo *= 2;
    184 		goto retry;
    185 	}
    186 	if (res)
    187 		freeaddrinfo(res);
    188 	return(s);
    189 }
    190 
    191 /*
    192  * Getline reads a line from the control file cfp, removes tabs, converts
    193  *  new-line to null and leaves it in line.
    194  * Returns 0 at EOF or the number of characters read.
    195  */
    196 int
    197 getline(FILE *cfp)
    198 {
    199 	int linel = 0, c;
    200 	char *lp = line;
    201 
    202 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
    203 		if (c == EOF)
    204 			return(0);
    205 		if (c == '\t') {
    206 			do {
    207 				*lp++ = ' ';
    208 				linel++;
    209 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
    210 			continue;
    211 		}
    212 		*lp++ = c;
    213 		linel++;
    214 	}
    215 	*lp++ = '\0';
    216 	return(linel);
    217 }
    218 
    219 /*
    220  * Scan the current directory and make a list of daemon files sorted by
    221  * creation time.
    222  * Return the number of entries and a pointer to the list.
    223  */
    224 int
    225 getq(struct queue **namelist[])
    226 {
    227 	struct dirent *d;
    228 	struct queue *q, **queue;
    229 	struct stat stbuf;
    230 	DIR *dirp;
    231 	u_int nitems, arraysz;
    232 
    233 	seteuid(euid);
    234 	dirp = opendir(SD);
    235 	seteuid(uid);
    236 	if (dirp == NULL)
    237 		return(-1);
    238 	if (fstat(dirp->dd_fd, &stbuf) < 0)
    239 		goto errdone;
    240 
    241 	/*
    242 	 * Estimate the array size by taking the size of the directory file
    243 	 * and dividing it by a multiple of the minimum size entry.
    244 	 */
    245 	arraysz = (int)(stbuf.st_size / 24);
    246 	queue = (struct queue **)malloc(arraysz * sizeof(struct queue *));
    247 	if (queue == NULL)
    248 		goto errdone;
    249 
    250 	nitems = 0;
    251 	while ((d = readdir(dirp)) != NULL) {
    252 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    253 			continue;	/* daemon control files only */
    254 		seteuid(euid);
    255 		if (stat(d->d_name, &stbuf) < 0) {
    256 			seteuid(uid);
    257 			continue;	/* Doesn't exist */
    258 		}
    259 		seteuid(uid);
    260 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
    261 		if (q == NULL)
    262 			goto errdone;
    263 		q->q_time = stbuf.st_mtime;
    264 		strcpy(q->q_name, d->d_name);	/* XXX: strcpy is safe */
    265 		/*
    266 		 * Check to make sure the array has space left and
    267 		 * realloc the maximum size.
    268 		 */
    269 		if (++nitems > arraysz) {
    270 			arraysz *= 2;
    271 			queue = (struct queue **)realloc(queue,
    272 				arraysz * sizeof(struct queue *));
    273 			if (queue == NULL)
    274 				goto errdone;
    275 		}
    276 		queue[nitems-1] = q;
    277 	}
    278 	closedir(dirp);
    279 	if (nitems)
    280 		qsort(queue, nitems, sizeof(struct queue *), compar);
    281 	*namelist = queue;
    282 	return(nitems);
    283 
    284 errdone:
    285 	closedir(dirp);
    286 	return(-1);
    287 }
    288 
    289 /*
    290  * Compare modification times.
    291  */
    292 static int
    293 compar(const void *p1, const void *p2)
    294 {
    295 	if ((*(struct queue **)p1)->q_time < (*(struct queue **)p2)->q_time)
    296 		return(-1);
    297 	if ((*(struct queue **)p1)->q_time > (*(struct queue **)p2)->q_time)
    298 		return(1);
    299 	return(0);
    300 }
    301 
    302 /*
    303  * Figure out whether the local machine is the same
    304  * as the remote machine (RM) entry (if it exists).
    305  */
    306 char *
    307 checkremote(void)
    308 {
    309 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
    310 	struct addrinfo hints, *res, *res0;
    311 	static char errbuf[128];
    312 	int error;
    313 	struct ifaddrs *ifap, *ifa;
    314 #ifdef NI_WITHSCOPEID
    315 	const int niflags = NI_NUMERICHOST | NI_WITHSCOPEID;
    316 #else
    317 	const int niflags = NI_NUMERICHOST;
    318 #endif
    319 #ifdef __KAME__
    320 	struct sockaddr_in6 sin6;
    321 	struct sockaddr_in6 *sin6p;
    322 #endif
    323 
    324 	remote = 0;	/* assume printer is local on failure */
    325 
    326 	if (RM == NULL)
    327 		return NULL;
    328 
    329 	/* get the local interface addresses */
    330 	if (getifaddrs(&ifap) < 0) {
    331 		(void)snprintf(errbuf, sizeof(errbuf),
    332 		    "unable to get local interface address: %s",
    333 		    strerror(errno));
    334 		return errbuf;
    335 	}
    336 
    337 	/* get the remote host addresses (RM) */
    338 	memset(&hints, 0, sizeof(hints));
    339 	hints.ai_flags = AI_CANONNAME;
    340 	hints.ai_family = PF_UNSPEC;
    341 	hints.ai_socktype = SOCK_STREAM;
    342 	res = NULL;
    343 	error = getaddrinfo(RM, NULL, &hints, &res0);
    344 	if (error) {
    345 		(void)snprintf(errbuf, sizeof(errbuf),
    346 		    "unable to resolve remote machine %s: %s",
    347 		    RM, gai_strerror(error));
    348 		freeifaddrs(ifap);
    349 		return errbuf;
    350 	}
    351 
    352 	remote = 1;	/* assume printer is remote */
    353 
    354 	for (res = res0; res; res = res->ai_next) {
    355 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
    356 		    rname, sizeof(rname), NULL, 0, niflags) != 0)
    357 			continue;
    358 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
    359 #ifdef __KAME__
    360 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
    361 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
    362 			    ifa->ifa_addr->sa_len == sizeof(sin6) &&
    363 			    IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr) &&
    364 			    *(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]) {
    365 				/* kame scopeid hack */
    366 				memcpy(&sin6, ifa->ifa_addr, sizeof(sin6));
    367 				sin6.sin6_scope_id =
    368 				    ntohs(*(u_int16_t *)&sin6p->sin6_addr.s6_addr[2]);
    369 				sin6.sin6_addr.s6_addr[2] = 0;
    370 				sin6.sin6_addr.s6_addr[3] = 0;
    371 				if (getnameinfo((struct sockaddr *)&sin6,
    372 				    sin6.sin6_len, lname, sizeof(lname),
    373 				    NULL, 0, niflags) != 0)
    374 					continue;
    375 			} else
    376 #endif
    377 			if (getnameinfo(ifa->ifa_addr, ifa->ifa_addr->sa_len,
    378 			    lname, sizeof(lname), NULL, 0, niflags) != 0)
    379 				continue;
    380 
    381 			if (strcmp(rname, lname) == 0) {
    382 				remote = 0;
    383 				goto done;
    384 			}
    385 		}
    386 	}
    387 done:
    388 	freeaddrinfo(res0);
    389 	freeifaddrs(ifap);
    390 	return NULL;
    391 }
    392 
    393 /* sleep n milliseconds */
    394 void
    395 delay(int n)
    396 {
    397 	struct timeval tdelay;
    398 
    399 	if (n <= 0 || n > 10000)
    400 		fatal("unreasonable delay period (%d)", n);
    401 	tdelay.tv_sec = n / 1000;
    402 	tdelay.tv_usec = n * 1000 % 1000000;
    403 	(void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
    404 }
    405