Home | History | Annotate | Line # | Download | only in common_source
      1 /*	$NetBSD: common.c,v 1.44 2023/05/13 11:48:19 andvar 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.44 2023/05/13 11:48:19 andvar 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 "lp.local.h"
     64 #include "pathnames.h"
     65 
     66 /*
     67  * Routines and data common to all the line printer functions.
     68  */
     69 
     70 const char	*AF;		/* accounting file */
     71 long		 BR;		/* baud rate if lp is a tty */
     72 const char	*CF;		/* name of cifplot filter (per job) */
     73 const char	*DF;		/* name of tex filter (per job) */
     74 long		 DU;		/* daeomon user-id */
     75 long		 FC;		/* flags to clear if lp is a tty */
     76 const char	*FF;		/* form feed string */
     77 long		 FS;		/* flags to set if lp is a tty */
     78 const char	*GF;		/* name of graph(1G) filter (per job) */
     79 long		 HL;		/* print header last */
     80 const char	*IF;		/* name of input filter (created per job) */
     81 const char	*LF;		/* log file for error messages */
     82 const char	*LO;		/* lock file name */
     83 const char	*LP;		/* line printer device name */
     84 long		 MC;		/* maximum number of copies allowed */
     85 const char	*MS;		/* stty flags to set if lp is a tty */
     86 long		 MX;		/* maximum number of blocks to copy */
     87 const char	*NF;		/* name of ditroff filter (per job) */
     88 const char	*OF;		/* name of output filter (created once) */
     89 const char	*PF;		/* name of postscript filter (per job) */
     90 long		 PL;		/* page length */
     91 long		 PW;		/* page width */
     92 long		 PX;		/* page width in pixels */
     93 long		 PY;		/* page length in pixels */
     94 const char	*RF;		/* name of fortran text filter (per job) */
     95 const char	*RG;		/* resricted group */
     96 const char	*RM;		/* remote machine name */
     97 const char	*RP;		/* remote printer name */
     98 long		 RS;		/* restricted to those with local accounts */
     99 long		 RW;		/* open LP for reading and writing */
    100 long		 SB;		/* short banner instead of normal header */
    101 long		 SC;		/* suppress multiple copies */
    102 const char	*SD;		/* spool directory */
    103 long		 SF;		/* suppress FF on each print job */
    104 long		 SH;		/* suppress header page */
    105 const char	*ST;		/* status file name */
    106 const char	*TF;		/* name of troff filter (per job) */
    107 const char	*TR;		/* trailer string to be output when Q empties */
    108 const char	*VF;		/* name of vplot/vrast filter (per job) */
    109 long		 XC;		/* flags to clear for local mode */
    110 long		 XS;		/* flags to set for local mode */
    111 
    112 char	line[BUFSIZ];
    113 int	remote;		/* true if sending files to a remote host */
    114 
    115 extern uid_t	uid, euid;
    116 
    117 static int compar(const void *, const void *);
    118 
    119 const char *
    120 gethost(const char *hname)
    121 {
    122 	const char *p = strchr(hname, '@');
    123 	return p ? ++p : hname;
    124 }
    125 
    126 /*
    127  * Create a TCP connection to host "rhost". If "rhost" is of the
    128  * form port@host, use the specified port. Otherwise use the
    129  * default printer port. Most of this code comes from rcmd.c.
    130  */
    131 int
    132 getport(const char *rhost)
    133 {
    134 	struct addrinfo hints, *res, *r;
    135 	u_int timo = 1;
    136 	int s, lport = IPPORT_RESERVED - 1;
    137 	int error;
    138 	int refuse, trial;
    139 	char hbuf[NI_MAXSERV], *ptr;
    140 	const char *port = "printer";
    141 	const char *hostname = rhost;
    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 	(void)strlcpy(hbuf, rhost, sizeof(hbuf));
    149 	for (ptr = hbuf; *ptr; ptr++)
    150 		if (*ptr == '@') {
    151 			*ptr++ = '\0';
    152 			port = hbuf;
    153 			hostname = ptr;
    154 			break;
    155 		}
    156 	(void)memset(&hints, 0, sizeof(hints));
    157 	hints.ai_family = PF_UNSPEC;
    158 	hints.ai_socktype = SOCK_STREAM;
    159 	error = getaddrinfo(hostname, port, &hints, &res);
    160 	if (error)
    161 		fatal("printer/tcp: %s", gai_strerror(error));
    162 
    163 	/*
    164 	 * Try connecting to the server.
    165 	 */
    166 retry:
    167 	s = -1;
    168 	refuse = trial = 0;
    169 	for (r = res; r; r = r->ai_next) {
    170 		trial++;
    171 retryport:
    172 		seteuid(euid);
    173 		s = rresvport_af(&lport, r->ai_family);
    174 		seteuid(uid);
    175 		if (s < 0)
    176 			return(-1);
    177 		if (connect(s, r->ai_addr, r->ai_addrlen) < 0) {
    178 			error = errno;
    179 			(void)close(s);
    180 			s = -1;
    181 			errno = error;
    182 			if (errno == EADDRINUSE) {
    183 				lport--;
    184 				goto retryport;
    185 			} else if (errno == ECONNREFUSED)
    186 				refuse++;
    187 			continue;
    188 		} else
    189 			break;
    190 	}
    191 	if (s < 0 && trial == refuse && timo <= 16) {
    192 		sleep(timo);
    193 		timo *= 2;
    194 		goto retry;
    195 	}
    196 	if (res)
    197 		freeaddrinfo(res);
    198 	return(s);
    199 }
    200 
    201 /*
    202  * Getline reads a line from the control file cfp, removes tabs, converts
    203  *  new-line to null and leaves it in line.
    204  * Returns 0 at EOF or the number of characters read.
    205  */
    206 size_t
    207 get_line(FILE *cfp)
    208 {
    209 	size_t linel = 0;
    210 	int c;
    211 	char *lp = line;
    212 
    213 	while ((c = getc(cfp)) != '\n' && linel+1<sizeof(line)) {
    214 		if (c == EOF)
    215 			return(0);
    216 		if (c == '\t') {
    217 			do {
    218 				*lp++ = ' ';
    219 				linel++;
    220 			} while ((linel & 07) != 0 && linel+1 < sizeof(line));
    221 			continue;
    222 		}
    223 		*lp++ = c;
    224 		linel++;
    225 	}
    226 	*lp++ = '\0';
    227 	return(linel);
    228 }
    229 
    230 /*
    231  * Scan the current directory and make a list of daemon files sorted by
    232  * creation time.
    233  * Return the number of entries and a pointer to the list.
    234  */
    235 int
    236 getq(struct queue **namelist[])
    237 {
    238 	struct dirent *d;
    239 	struct queue *q, **queue = NULL, **nqueue;
    240 	struct stat stbuf;
    241 	DIR *dirp;
    242 	u_int nitems = 0, arraysz;
    243 
    244 	seteuid(euid);
    245 	dirp = opendir(SD);
    246 	seteuid(uid);
    247 	if (dirp == NULL)
    248 		return(-1);
    249 	if (fstat(dirp->dd_fd, &stbuf) < 0)
    250 		goto errdone;
    251 
    252 	/*
    253 	 * Estimate the array size by taking the size of the directory file
    254 	 * and dividing it by a multiple of the minimum size entry.
    255 	 */
    256 	arraysz = (int)(stbuf.st_size / 24);
    257 	queue = calloc(arraysz, sizeof(struct queue *));
    258 	if (queue == NULL)
    259 		goto errdone;
    260 
    261 	while ((d = readdir(dirp)) != NULL) {
    262 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f'
    263 		    || d->d_name[2] == '\0')
    264 			continue;	/* daemon control files only */
    265 		seteuid(euid);
    266 		if (stat(d->d_name, &stbuf) < 0) {
    267 			seteuid(uid);
    268 			continue;	/* Doesn't exist */
    269 		}
    270 		seteuid(uid);
    271 		q = (struct queue *)malloc(sizeof(time_t)+strlen(d->d_name)+1);
    272 		if (q == NULL)
    273 			goto errdone;
    274 		q->q_time = stbuf.st_mtime;
    275 		strcpy(q->q_name, d->d_name);	/* XXX: strcpy is safe */
    276 		/*
    277 		 * Check to make sure the array has space left and
    278 		 * realloc the maximum size.
    279 		 */
    280 		if (++nitems > arraysz) {
    281 			nqueue = (struct queue **)realloc(queue,
    282 				arraysz * 2 * sizeof(struct queue *));
    283 			if (nqueue == NULL) {
    284 				free(q);
    285 				goto errdone;
    286 			}
    287 			(void)memset(&nqueue[arraysz], 0,
    288 			    arraysz * sizeof(nqueue[0]));
    289 			queue = nqueue;
    290 			arraysz *= 2;
    291 		}
    292 		queue[nitems-1] = q;
    293 	}
    294 	closedir(dirp);
    295 	if (nitems)
    296 		qsort(queue, nitems, sizeof(struct queue *), compar);
    297 	*namelist = queue;
    298 	return(nitems);
    299 
    300 errdone:
    301 	freeq(queue, nitems);
    302 	closedir(dirp);
    303 	return(-1);
    304 }
    305 
    306 void
    307 freeq(struct queue **namelist, u_int nitems)
    308 {
    309 	u_int i;
    310 	if (namelist == NULL)
    311 		return;
    312 	for (i = 0; i < nitems; i++)
    313 		if (namelist[i])
    314 			free(namelist[i]);
    315 	free(namelist);
    316 }
    317 
    318 /*
    319  * Compare modification times.
    320  */
    321 static int
    322 compar(const void *p1, const void *p2)
    323 {
    324 	const struct queue *const *q1 = p1;
    325 	const struct queue *const *q2 = p2;
    326 	int j1, j2;
    327 
    328 	if ((*q1)->q_time < (*q2)->q_time)
    329 		return -1;
    330 	if ((*q1)->q_time > (*q2)->q_time)
    331 		return 1;
    332 
    333 	j1 = atoi((*q1)->q_name+3);
    334 	j2 = atoi((*q2)->q_name+3);
    335 
    336         if (j1 == j2)
    337                 return 0;
    338         if ((j1 < j2 && j2-j1 < 500) || (j1 > j2 && j1-j2 > 500))
    339                 return -1;
    340         if ((j1 < j2 && j2-j1 > 500) || (j1 > j2 && j1-j2 < 500))
    341                 return 1;
    342 
    343 	return 0;
    344 }
    345 
    346 /*
    347  * Figure out whether the local machine is the same
    348  * as the remote machine (RM) entry (if it exists).
    349  */
    350 const char *
    351 checkremote(void)
    352 {
    353 	struct addrinfo hints, *res0;
    354 	static char errbuf[128];
    355 	int error;
    356 	struct ifaddrs *ifap;
    357 #if defined(INET6) && defined(__KAME__)
    358 	char lname[NI_MAXHOST], rname[NI_MAXHOST];
    359 	struct addrinfo *res;
    360 	struct ifaddrs *ifa;
    361 	const int niflags = NI_NUMERICHOST;
    362 	struct sockaddr_in6 sin6;
    363 	struct sockaddr_in6 *sin6p;
    364 #endif
    365 
    366 	remote = 0;	/* assume printer is local on failure */
    367 
    368 	if (RM == NULL)
    369 		return NULL;
    370 
    371 	/* get the local interface addresses */
    372 	if (getifaddrs(&ifap) < 0) {
    373 		(void)snprintf(errbuf, sizeof(errbuf),
    374 		    "unable to get local interface address: %s",
    375 		    strerror(errno));
    376 		return errbuf;
    377 	}
    378 
    379 	/* get the remote host addresses (RM) */
    380 	memset(&hints, 0, sizeof(hints));
    381 	hints.ai_flags = AI_CANONNAME;
    382 	hints.ai_family = PF_UNSPEC;
    383 	hints.ai_socktype = SOCK_STREAM;
    384 	error = getaddrinfo(gethost(RM), NULL, &hints, &res0);
    385 	if (error) {
    386 		(void)snprintf(errbuf, sizeof(errbuf),
    387 		    "unable to resolve remote machine %s: %s",
    388 		    RM, gai_strerror(error));
    389 		freeifaddrs(ifap);
    390 		return errbuf;
    391 	}
    392 
    393 	remote = 1;	/* assume printer is remote */
    394 
    395 #if defined(INET6) && defined(__KAME__)
    396 	for (res = res0; res; res = res->ai_next) {
    397 		if (getnameinfo(res->ai_addr, res->ai_addrlen,
    398 		    rname, sizeof(rname), NULL, 0, niflags) != 0)
    399 			continue;
    400 		for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
    401 			sin6p = (struct sockaddr_in6 *)ifa->ifa_addr;
    402 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
    403 			    ifa->ifa_addr->sa_len == sizeof(sin6)) {
    404 				inet6_getscopeid(sin6p, 3);
    405 				if (getnameinfo((struct sockaddr *)&sin6,
    406 				    sin6.sin6_len, lname, sizeof(lname),
    407 				    NULL, 0, niflags) != 0)
    408 					continue;
    409 				if (strcmp(rname, lname) == 0) {
    410 					remote = 0;
    411 					goto done;
    412 				}
    413 			}
    414 		}
    415 	}
    416 done:
    417 #endif
    418 	freeaddrinfo(res0);
    419 	freeifaddrs(ifap);
    420 	return NULL;
    421 }
    422 
    423 /* sleep n milliseconds */
    424 void
    425 delay(int n)
    426 {
    427 	struct timespec tdelay;
    428 
    429 	if (n <= 0 || n > 10000)
    430 		fatal("unreasonable delay period (%d)", n);
    431 	tdelay.tv_sec = n / 1000;
    432 	tdelay.tv_nsec = (n % 1000) * 1000000;
    433 	nanosleep(&tdelay, NULL);
    434 }
    435 
    436 void
    437 getprintcap(const char *pr)
    438 {
    439 	char *cp;
    440 	const char *dp;
    441 	int i;
    442 
    443 	if ((i = cgetent(&bp, printcapdb, pr)) == -2)
    444 		fatal("can't open printer description file");
    445 	else if (i == -1)
    446 		fatal("unknown printer: %s", pr);
    447 	else if (i == -3)
    448 		fatal("potential reference loop detected in printcap file");
    449 
    450 	LP = cgetstr(bp, DEFLP, &cp) == -1 ? _PATH_DEFDEVLP : cp;
    451 	RP = cgetstr(bp, "rp", &cp) == -1 ? DEFLP : cp;
    452 	SD = cgetstr(bp, "sd", &cp) == -1 ? _PATH_DEFSPOOL : cp;
    453 	LO = cgetstr(bp, "lo", &cp) == -1 ? DEFLOCK : cp;
    454 	ST = cgetstr(bp, "st", &cp) == -1 ? DEFSTAT : cp;
    455 	RM = cgetstr(bp, "rm", &cp) == -1 ? NULL : cp;
    456 	if ((dp = checkremote()) != NULL)
    457 		printf("Warning: %s\n", dp);
    458 	LF = cgetstr(bp, "lf", &cp) == -1 ? _PATH_CONSOLE : cp;
    459 }
    460 
    461 /*
    462  * Make sure there's some work to do before forking off a child
    463  */
    464 int
    465 ckqueue(char *cap)
    466 {
    467 	struct dirent *d;
    468 	DIR *dirp;
    469 	const char *spooldir;
    470 	char *sd = NULL;
    471 	int rv = 0;
    472 
    473 	spooldir = cgetstr(cap, "sd", &sd) == -1 ? _PATH_DEFSPOOL : sd;
    474 	if ((dirp = opendir(spooldir)) == NULL) {
    475 		rv = -1;
    476 		goto out;
    477 	}
    478 	while ((d = readdir(dirp)) != NULL) {
    479 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    480 			continue;	/* daemon control files only */
    481 		rv = 1;
    482 		break;
    483 	}
    484 out:
    485 	if (dirp != NULL)
    486 		closedir(dirp);
    487 	if (spooldir != sd)
    488 		free(sd);
    489 	return (rv);
    490 }
    491