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