Home | History | Annotate | Line # | Download | only in ypbind
ypbind.c revision 1.45
      1 /*	$NetBSD: ypbind.c,v 1.45 2001/01/11 01:47:55 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1992, 1993 Theo de Raadt <deraadt (at) fsa.ca>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by Theo de Raadt.
     18  * 4. The name of the author may not be used to endorse or promote
     19  *    products derived from this software without specific prior written
     20  *    permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
     23  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     24  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
     26  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef LINT
     37 __RCSID("$NetBSD: ypbind.c,v 1.45 2001/01/11 01:47:55 lukem Exp $");
     38 #endif
     39 
     40 #include <sys/param.h>
     41 #include <sys/types.h>
     42 #include <sys/ioctl.h>
     43 #include <sys/signal.h>
     44 #include <sys/socket.h>
     45 #include <sys/file.h>
     46 #include <sys/uio.h>
     47 #include <sys/syslog.h>
     48 #include <sys/stat.h>
     49 #include <fcntl.h>
     50 #include <limits.h>
     51 #include <stdio.h>
     52 #include <stdlib.h>
     53 #include <errno.h>
     54 #include <syslog.h>
     55 #if __STDC__
     56 #include <stdarg.h>
     57 #else
     58 #include <varargs.h>
     59 #endif
     60 #include <ctype.h>
     61 #include <dirent.h>
     62 #include <netdb.h>
     63 #include <string.h>
     64 #include <err.h>
     65 #include <rpc/rpc.h>
     66 #include <rpc/xdr.h>
     67 #include <net/if.h>
     68 #include <arpa/inet.h>
     69 #include <rpc/pmap_clnt.h>
     70 #include <rpc/pmap_prot.h>
     71 #include <rpc/pmap_rmt.h>
     72 #include <unistd.h>
     73 #include <util.h>
     74 #include <rpcsvc/yp_prot.h>
     75 #include <rpcsvc/ypclnt.h>
     76 #include <ifaddrs.h>
     77 
     78 #include "pathnames.h"
     79 
     80 #ifndef O_SHLOCK
     81 #define O_SHLOCK 0
     82 #endif
     83 
     84 #define BUFSIZE		1400
     85 
     86 #define YPSERVERSSUFF	".ypservers"
     87 #define BINDINGDIR	(_PATH_VAR_YP "binding")
     88 
     89 struct _dom_binding {
     90 	struct _dom_binding *dom_pnext;
     91 	char dom_domain[YPMAXDOMAIN + 1];
     92 	struct sockaddr_in dom_server_addr;
     93 	unsigned short int dom_server_port;
     94 	int dom_socket;
     95 	CLIENT *dom_client;
     96 	long dom_vers;
     97 	time_t dom_check_t;
     98 	time_t dom_ask_t;
     99 	int dom_lockfd;
    100 	int dom_alive;
    101 	u_int32_t dom_xid;
    102 };
    103 
    104 static char *domainname;
    105 
    106 static struct _dom_binding *ypbindlist;
    107 static int check;
    108 
    109 typedef enum {
    110 	YPBIND_DIRECT, YPBIND_BROADCAST, YPBIND_SETLOCAL, YPBIND_SETALL
    111 } ypbind_mode_t;
    112 
    113 ypbind_mode_t ypbindmode;
    114 
    115 /*
    116  * If ypbindmode is YPBIND_SETLOCAL or YPBIND_SETALL, this indicates
    117  * whether or not we've been "ypset".  If we haven't, we behave like
    118  * YPBIND_BROADCAST.  If we have, we behave like YPBIND_DIRECT.
    119  */
    120 int been_ypset;
    121 
    122 #ifdef DEBUG
    123 static int debug;
    124 #endif
    125 
    126 static int insecure;
    127 static int rpcsock, pingsock;
    128 static struct rmtcallargs rmtca;
    129 static struct rmtcallres rmtcr;
    130 static bool_t rmtcr_outval;
    131 static u_long rmtcr_port;
    132 static SVCXPRT *udptransp, *tcptransp;
    133 
    134 int	_yp_invalid_domain __P((const char *));		/* from libc */
    135 int	main __P((int, char *[]));
    136 
    137 static void usage __P((void));
    138 static void yp_log __P((int, const char *, ...))
    139 	__attribute__((__format__(__printf__, 2, 3)));
    140 static struct _dom_binding *makebinding __P((const char *));
    141 static int makelock __P((struct _dom_binding *));
    142 static void removelock __P((struct _dom_binding *));
    143 static void *ypbindproc_null_2 __P((SVCXPRT *, void *));
    144 static void *ypbindproc_domain_2 __P((SVCXPRT *, void *));
    145 static void *ypbindproc_setdom_2 __P((SVCXPRT *, void *));
    146 static void ypbindprog_2 __P((struct svc_req *, SVCXPRT *));
    147 static void checkwork __P((void));
    148 static int ping __P((struct _dom_binding *));
    149 static int nag_servers __P((struct _dom_binding *));
    150 static enum clnt_stat handle_replies __P((void));
    151 static enum clnt_stat handle_ping __P((void));
    152 static void rpc_received __P((char *, struct sockaddr_in *, int));
    153 static struct _dom_binding *xid2ypdb __P((u_int32_t));
    154 static u_int32_t unique_xid __P((struct _dom_binding *));
    155 static int broadcast __P((char *, int));
    156 static int direct __P((char *, int));
    157 static int direct_set __P((char *, int, struct _dom_binding *));
    158 
    159 static void
    160 usage()
    161 {
    162 	extern char *__progname;
    163 	char *opt = "";
    164 #ifdef DEBUG
    165 	opt = " [-d]";
    166 #endif
    167 
    168 	(void)fprintf(stderr,
    169 	    "Usage: %s [-broadcast] [-insecure] [-ypset] [-ypsetme] %s\n",
    170 	    __progname, opt);
    171 	exit(1);
    172 }
    173 
    174 static void
    175 #if __STDC__
    176 yp_log(int pri, const char *fmt, ...)
    177 #else
    178 yp_log(pri, fmt, va_alist)
    179 	int pri;
    180 	char *fmt;
    181 	va_dcl
    182 #endif
    183 {
    184 	va_list ap;
    185 
    186 #if __STDC__
    187 	va_start(ap, fmt);
    188 #else
    189 	va_start(ap);
    190 #endif
    191 
    192 #if defined(DEBUG)
    193 	if (debug)
    194 		vfprintf(stderr, fmt, ap);
    195 	else
    196 #endif
    197 		vsyslog(pri, fmt, ap);
    198 	va_end(ap);
    199 }
    200 
    201 static struct _dom_binding *
    202 makebinding(dm)
    203 	const char *dm;
    204 {
    205 	struct _dom_binding *ypdb;
    206 
    207 	if ((ypdb = (struct _dom_binding *)malloc(sizeof *ypdb)) == NULL) {
    208 		yp_log(LOG_ERR, "makebinding");
    209 		exit(1);
    210 	}
    211 
    212 	(void)memset(ypdb, 0, sizeof *ypdb);
    213 	(void)strncpy(ypdb->dom_domain, dm, sizeof ypdb->dom_domain);
    214 	ypdb->dom_domain[sizeof(ypdb->dom_domain) - 1] = '\0';
    215 	return ypdb;
    216 }
    217 
    218 static int
    219 makelock(ypdb)
    220 	struct _dom_binding *ypdb;
    221 {
    222 	int fd;
    223 	char path[MAXPATHLEN];
    224 
    225 	(void)snprintf(path, sizeof(path), "%s/%s.%ld", BINDINGDIR,
    226 	    ypdb->dom_domain, ypdb->dom_vers);
    227 
    228 	if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1) {
    229 		(void)mkdir(BINDINGDIR, 0755);
    230 		if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1)
    231 			return -1;
    232 	}
    233 
    234 #if O_SHLOCK == 0
    235 	(void)flock(fd, LOCK_SH);
    236 #endif
    237 	return fd;
    238 }
    239 
    240 static void
    241 removelock(ypdb)
    242 	struct _dom_binding *ypdb;
    243 {
    244 	char path[MAXPATHLEN];
    245 
    246 	(void)snprintf(path, sizeof(path), "%s/%s.%ld",
    247 	    BINDINGDIR, ypdb->dom_domain, ypdb->dom_vers);
    248 	(void)unlink(path);
    249 }
    250 
    251 static void *
    252 ypbindproc_null_2(transp, argp)
    253 	SVCXPRT *transp;
    254 	void *argp;
    255 {
    256 	static char res;
    257 
    258 #ifdef DEBUG
    259 	if (debug)
    260 		printf("ypbindproc_null_2\n");
    261 #endif
    262 	(void)memset(&res, 0, sizeof(res));
    263 	return (void *)&res;
    264 }
    265 
    266 static void *
    267 ypbindproc_domain_2(transp, argp)
    268 	SVCXPRT *transp;
    269 	void *argp;
    270 {
    271 	static struct ypbind_resp res;
    272 	struct _dom_binding *ypdb;
    273 	char *arg = *(char **) argp;
    274 	time_t now;
    275 	int count;
    276 
    277 #ifdef DEBUG
    278 	if (debug)
    279 		printf("ypbindproc_domain_2 %s\n", arg);
    280 #endif
    281 	if (_yp_invalid_domain(arg))
    282 		return NULL;
    283 
    284 	(void)memset(&res, 0, sizeof res);
    285 	res.ypbind_status = YPBIND_FAIL_VAL;
    286 
    287 	for (count = 0, ypdb = ypbindlist;
    288 	    ypdb != NULL;
    289 	    ypdb = ypdb->dom_pnext, count++) {
    290 		if (count > 100)
    291 			return NULL;		/* prevent denial of service */
    292 		if (!strcmp(ypdb->dom_domain, arg))
    293 			break;
    294 	}
    295 
    296 	if (ypdb == NULL) {
    297 		ypdb = makebinding(arg);
    298 		ypdb->dom_vers = YPVERS;
    299 		ypdb->dom_alive = 0;
    300 		ypdb->dom_lockfd = -1;
    301 		removelock(ypdb);
    302 		ypdb->dom_xid = unique_xid(ypdb);
    303 		ypdb->dom_pnext = ypbindlist;
    304 		ypbindlist = ypdb;
    305 		check++;
    306 #ifdef DEBUG
    307 		if (debug)
    308 			printf("unknown domain %s\n", arg);
    309 #endif
    310 		return NULL;
    311 	}
    312 
    313 	if (ypdb->dom_alive == 0) {
    314 #ifdef DEBUG
    315 		if (debug)
    316 			printf("dead domain %s\n", arg);
    317 #endif
    318 		return NULL;
    319 	}
    320 
    321 #ifdef HEURISTIC
    322 	time(&now);
    323 	if (now < ypdb->dom_ask_t + 5) {
    324 		/*
    325 		 * Hmm. More than 2 requests in 5 seconds have indicated
    326 		 * that my binding is possibly incorrect.
    327 		 * Ok, do an immediate poll of the server.
    328 		 */
    329 		if (ypdb->dom_check_t >= now) {
    330 			/* don't flood it */
    331 			ypdb->dom_check_t = 0;
    332 			check++;
    333 		}
    334 	}
    335 	ypdb->dom_ask_t = now;
    336 #endif
    337 
    338 	res.ypbind_status = YPBIND_SUCC_VAL;
    339 	res.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr.s_addr =
    340 		ypdb->dom_server_addr.sin_addr.s_addr;
    341 	res.ypbind_respbody.ypbind_bindinfo.ypbind_binding_port =
    342 		ypdb->dom_server_port;
    343 #ifdef DEBUG
    344 	if (debug)
    345 		printf("domain %s at %s/%d\n", ypdb->dom_domain,
    346 		    inet_ntoa(ypdb->dom_server_addr.sin_addr),
    347 		    ntohs(ypdb->dom_server_addr.sin_port));
    348 #endif
    349 	return &res;
    350 }
    351 
    352 static void *
    353 ypbindproc_setdom_2(transp, argp)
    354 	SVCXPRT *transp;
    355 	void *argp;
    356 {
    357 	struct ypbind_setdom *sd = argp;
    358 	struct sockaddr_in *fromsin, bindsin;
    359 	static bool_t res;
    360 
    361 #ifdef DEBUG
    362 	if (debug)
    363 		printf("ypbindproc_setdom_2 %s\n", inet_ntoa(bindsin.sin_addr));
    364 #endif
    365 	(void)memset(&res, 0, sizeof(res));
    366 	fromsin = svc_getcaller(transp);
    367 
    368 	switch (ypbindmode) {
    369 	case YPBIND_SETLOCAL:
    370 		if (fromsin->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
    371 #ifdef DEBUG
    372 			if (debug)
    373 				printf("ypset from %s denied\n",
    374 				    inet_ntoa(fromsin->sin_addr));
    375 #endif
    376 			return NULL;
    377 		}
    378 		/* FALLTHROUGH */
    379 
    380 	case YPBIND_SETALL:
    381 		been_ypset = 1;
    382 		break;
    383 
    384 	case YPBIND_DIRECT:
    385 	case YPBIND_BROADCAST:
    386 	default:
    387 #ifdef DEBUG
    388 		if (debug)
    389 			printf("ypset denied\n");
    390 #endif
    391 		return NULL;
    392 	}
    393 
    394 	if (ntohs(fromsin->sin_port) >= IPPORT_RESERVED) {
    395 #ifdef DEBUG
    396 		if (debug)
    397 			printf("ypset from unprivileged port denied\n");
    398 #endif
    399 		return &res;
    400 	}
    401 
    402 	if (sd->ypsetdom_vers != YPVERS) {
    403 #ifdef DEBUG
    404 		if (debug)
    405 			printf("ypset with wrong version denied\n");
    406 #endif
    407 		return &res;
    408 	}
    409 
    410 	(void)memset(&bindsin, 0, sizeof bindsin);
    411 	bindsin.sin_family = AF_INET;
    412 	bindsin.sin_len = sizeof(bindsin);
    413 	bindsin.sin_addr = sd->ypsetdom_addr;
    414 	bindsin.sin_port = sd->ypsetdom_port;
    415 	rpc_received(sd->ypsetdom_domain, &bindsin, 1);
    416 
    417 #ifdef DEBUG
    418 	if (debug)
    419 		printf("ypset to %s succeeded\n", inet_ntoa(bindsin.sin_addr));
    420 #endif
    421 	res = 1;
    422 	return &res;
    423 }
    424 
    425 static void
    426 ypbindprog_2(rqstp, transp)
    427 	struct svc_req *rqstp;
    428 	register SVCXPRT *transp;
    429 {
    430 	union {
    431 		char ypbindproc_domain_2_arg[YPMAXDOMAIN + 1];
    432 		struct ypbind_setdom ypbindproc_setdom_2_arg;
    433 	} argument;
    434 	struct authunix_parms *creds;
    435 	char *result;
    436 	xdrproc_t xdr_argument, xdr_result;
    437 	void *(*local) __P((SVCXPRT *, void *));
    438 
    439 	switch (rqstp->rq_proc) {
    440 	case YPBINDPROC_NULL:
    441 		xdr_argument = xdr_void;
    442 		xdr_result = xdr_void;
    443 		local = ypbindproc_null_2;
    444 		break;
    445 
    446 	case YPBINDPROC_DOMAIN:
    447 		xdr_argument = xdr_ypdomain_wrap_string;
    448 		xdr_result = xdr_ypbind_resp;
    449 		local = ypbindproc_domain_2;
    450 		break;
    451 
    452 	case YPBINDPROC_SETDOM:
    453 		switch (rqstp->rq_cred.oa_flavor) {
    454 		case AUTH_UNIX:
    455 			creds = (struct authunix_parms *)rqstp->rq_clntcred;
    456 			if (creds->aup_uid != 0) {
    457 				svcerr_auth(transp, AUTH_BADCRED);
    458 				return;
    459 			}
    460 			break;
    461 		default:
    462 			svcerr_auth(transp, AUTH_TOOWEAK);
    463 			return;
    464 		}
    465 
    466 		xdr_argument = xdr_ypbind_setdom;
    467 		xdr_result = xdr_void;
    468 		local = ypbindproc_setdom_2;
    469 		break;
    470 
    471 	default:
    472 		svcerr_noproc(transp);
    473 		return;
    474 	}
    475 	(void)memset(&argument, 0, sizeof(argument));
    476 	if (!svc_getargs(transp, xdr_argument, (caddr_t)&argument)) {
    477 		svcerr_decode(transp);
    478 		return;
    479 	}
    480 	result = (*local)(transp, &argument);
    481 	if (result != NULL && !svc_sendreply(transp, xdr_result, result)) {
    482 		svcerr_systemerr(transp);
    483 	}
    484 	return;
    485 }
    486 
    487 int
    488 main(argc, argv)
    489 	int argc;
    490 	char *argv[];
    491 {
    492 	struct timeval tv;
    493 	fd_set fdsr;
    494 	int width, lockfd;
    495 	int evil = 0, one;
    496 	char pathname[MAXPATHLEN];
    497 	struct stat st;
    498 
    499 	yp_get_default_domain(&domainname);
    500 	if (domainname[0] == '\0')
    501 		errx(1, "Domainname not set. Aborting.");
    502 
    503 	/*
    504 	 * Per traditional ypbind(8) semantics, if a ypservers
    505 	 * file does not exist, we default to broadcast mode.
    506 	 * If the file does exist, we default to direct mode.
    507 	 * Note that we can still override direct mode by passing
    508 	 * the -broadcast flag.
    509 	 */
    510 	snprintf(pathname, sizeof(pathname), "%s/%s%s", BINDINGDIR,
    511 	    domainname, YPSERVERSSUFF);
    512 	if (stat(pathname, &st) < 0) {
    513 #ifdef DEBUG
    514 		if (debug)
    515 			fprintf(stderr,
    516 			    "%s does not exist, defaulting to broadcast\n",
    517 			    pathname);
    518 #endif
    519 		ypbindmode = YPBIND_BROADCAST;
    520 	} else
    521 		ypbindmode = YPBIND_DIRECT;
    522 
    523 	while (--argc) {
    524 		++argv;
    525 		if (!strcmp("-insecure", *argv))
    526 			insecure = 1;
    527 		else if (!strcmp("-ypset", *argv))
    528 			ypbindmode = YPBIND_SETALL;
    529 		else if (!strcmp("-ypsetme", *argv))
    530 			ypbindmode = YPBIND_SETLOCAL;
    531 		else if (!strcmp("-broadcast", *argv))
    532 			ypbindmode = YPBIND_BROADCAST;
    533 #ifdef DEBUG
    534 		else if (!strcmp("-d", *argv))
    535 			debug++;
    536 #endif
    537 		else
    538 			usage();
    539 	}
    540 
    541 	/* initialise syslog */
    542 	openlog("ypbind", LOG_PERROR | LOG_PID, LOG_DAEMON);
    543 
    544 	/* blow away everything in BINDINGDIR */
    545 
    546 	lockfd = open(_PATH_YPBIND_LOCK, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644);
    547 	if (lockfd == -1)
    548 		err(1, "Cannot create %s", _PATH_YPBIND_LOCK);
    549 
    550 #if O_SHLOCK == 0
    551 	(void)flock(lockfd, LOCK_SH);
    552 #endif
    553 
    554 	(void)pmap_unset(YPBINDPROG, YPBINDVERS);
    555 
    556 	udptransp = svcudp_create(RPC_ANYSOCK);
    557 	if (udptransp == NULL)
    558 		errx(1, "Cannot create udp service.");
    559 
    560 	if (!svc_register(udptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
    561 	    IPPROTO_UDP))
    562 		errx(1, "Unable to register (YPBINDPROG, YPBINDVERS, udp).");
    563 
    564 	tcptransp = svctcp_create(RPC_ANYSOCK, 0, 0);
    565 	if (tcptransp == NULL)
    566 		errx(1, "Cannot create tcp service.");
    567 
    568 	if (!svc_register(tcptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
    569 	    IPPROTO_TCP))
    570 		errx(1, "Unable to register (YPBINDPROG, YPBINDVERS, tcp).");
    571 
    572 	/* XXX use SOCK_STREAM for direct queries? */
    573 	if ((rpcsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    574 		err(1, "rpc socket");
    575 	if ((pingsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    576 		err(1, "ping socket");
    577 
    578 	(void)fcntl(rpcsock, F_SETFL, fcntl(rpcsock, F_GETFL, 0) | FNDELAY);
    579 	(void)fcntl(pingsock, F_SETFL, fcntl(pingsock, F_GETFL, 0) | FNDELAY);
    580 
    581 	one = 1;
    582 	(void)setsockopt(rpcsock, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));
    583 	rmtca.prog = YPPROG;
    584 	rmtca.vers = YPVERS;
    585 	rmtca.proc = YPPROC_DOMAIN_NONACK;
    586 	rmtca.xdr_args = NULL;		/* set at call time */
    587 	rmtca.args_ptr = NULL;		/* set at call time */
    588 	rmtcr.port_ptr = &rmtcr_port;
    589 	rmtcr.xdr_results = xdr_bool;
    590 	rmtcr.results_ptr = (caddr_t)&rmtcr_outval;
    591 
    592 	if (_yp_invalid_domain(domainname))
    593 		errx(1, "bad domainname: %s", domainname);
    594 
    595 	/* build initial domain binding, make it "unsuccessful" */
    596 	ypbindlist = makebinding(domainname);
    597 	ypbindlist->dom_vers = YPVERS;
    598 	ypbindlist->dom_alive = 0;
    599 	ypbindlist->dom_lockfd = -1;
    600 	removelock(ypbindlist);
    601 
    602 	checkwork();
    603 
    604 	width = svc_maxfd;
    605 	if (rpcsock > width)
    606 		width = rpcsock;
    607 	if (pingsock > width)
    608 		width = pingsock;
    609 	width++;
    610 
    611 	for (;;) {
    612 		fdsr = svc_fdset;
    613 		FD_SET(rpcsock, &fdsr);
    614 		FD_SET(pingsock, &fdsr);
    615 		tv.tv_sec = 1;
    616 		tv.tv_usec = 0;
    617 
    618 		switch (select(width, &fdsr, NULL, NULL, &tv)) {
    619 		case 0:
    620 			checkwork();
    621 			break;
    622 		case -1:
    623 			yp_log(LOG_WARNING, "select: %m");
    624 			break;
    625 		default:
    626 			if (FD_ISSET(rpcsock, &fdsr))
    627 				handle_replies();
    628 			if (FD_ISSET(pingsock, &fdsr))
    629 				handle_ping();
    630 			svc_getreqset(&fdsr);
    631 			if (check)
    632 				checkwork();
    633 			break;
    634 		}
    635 
    636 		if (!evil && ypbindlist->dom_alive) {
    637 			evil = 1;
    638 #ifdef DEBUG
    639 			if (!debug)
    640 #endif
    641 				daemon(0, 0);
    642 			pidfile(NULL);
    643 		}
    644 	}
    645 }
    646 
    647 /*
    648  * State transition is done like this:
    649  *
    650  * STATE	EVENT		ACTION			NEWSTATE	TIMEOUT
    651  * no binding	timeout		broadcast 		no binding	5 sec
    652  * no binding	answer		--			binding		60 sec
    653  * binding	timeout		ping server		checking	5 sec
    654  * checking	timeout		ping server + broadcast	checking	5 sec
    655  * checking	answer		--			binding		60 sec
    656  */
    657 void
    658 checkwork()
    659 {
    660 	struct _dom_binding *ypdb;
    661 	time_t t;
    662 
    663 	check = 0;
    664 
    665 	time(&t);
    666 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
    667 		if (ypdb->dom_check_t < t) {
    668 			if (ypdb->dom_alive == 1)
    669 				ping(ypdb);
    670 			else
    671 				nag_servers(ypdb);
    672 			time(&t);
    673 			ypdb->dom_check_t = t + 5;
    674 		}
    675 	}
    676 }
    677 
    678 int
    679 ping(ypdb)
    680 	struct _dom_binding *ypdb;
    681 {
    682 	char *dom = ypdb->dom_domain;
    683 	struct rpc_msg msg;
    684 	char buf[BUFSIZE];
    685 	enum clnt_stat st;
    686 	int outlen;
    687 	AUTH *rpcua;
    688 	XDR xdr;
    689 
    690 	(void)memset(&xdr, 0, sizeof xdr);
    691 	(void)memset(&msg, 0, sizeof msg);
    692 
    693 	rpcua = authunix_create_default();
    694 	if (rpcua == NULL) {
    695 #ifdef DEBUG
    696 		if (debug)
    697 			printf("cannot get unix auth\n");
    698 #endif
    699 		return RPC_SYSTEMERROR;
    700 	}
    701 
    702 	msg.rm_direction = CALL;
    703 	msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
    704 	msg.rm_call.cb_prog = YPPROG;
    705 	msg.rm_call.cb_vers = YPVERS;
    706 	msg.rm_call.cb_proc = YPPROC_DOMAIN_NONACK;
    707 	msg.rm_call.cb_cred = rpcua->ah_cred;
    708 	msg.rm_call.cb_verf = rpcua->ah_verf;
    709 
    710 	msg.rm_xid = ypdb->dom_xid;
    711 	xdrmem_create(&xdr, buf, sizeof buf, XDR_ENCODE);
    712 	if (!xdr_callmsg(&xdr, &msg)) {
    713 		st = RPC_CANTENCODEARGS;
    714 		AUTH_DESTROY(rpcua);
    715 		return st;
    716 	}
    717 	if (!xdr_ypdomain_wrap_string(&xdr, &dom)) {
    718 		st = RPC_CANTENCODEARGS;
    719 		AUTH_DESTROY(rpcua);
    720 		return st;
    721 	}
    722 	outlen = (int)xdr_getpos(&xdr);
    723 	xdr_destroy(&xdr);
    724 	if (outlen < 1) {
    725 		st = RPC_CANTENCODEARGS;
    726 		AUTH_DESTROY(rpcua);
    727 		return st;
    728 	}
    729 	AUTH_DESTROY(rpcua);
    730 
    731 	ypdb->dom_alive = 2;
    732 	if (sendto(pingsock, buf, outlen, 0,
    733 		   (struct sockaddr *)&ypdb->dom_server_addr,
    734 		   sizeof ypdb->dom_server_addr) == -1)
    735 		yp_log(LOG_WARNING, "ping: sendto: %m");
    736 	return 0;
    737 
    738 }
    739 
    740 static int
    741 nag_servers(ypdb)
    742 	struct _dom_binding *ypdb;
    743 {
    744 	char *dom = ypdb->dom_domain;
    745 	struct rpc_msg msg;
    746 	char buf[BUFSIZE];
    747 	enum clnt_stat st;
    748 	int outlen;
    749 	AUTH *rpcua;
    750 	XDR xdr;
    751 
    752 	rmtca.xdr_args = xdr_ypdomain_wrap_string;
    753 	rmtca.args_ptr = (char *)&dom;
    754 
    755 	(void)memset(&xdr, 0, sizeof xdr);
    756 	(void)memset(&msg, 0, sizeof msg);
    757 
    758 	rpcua = authunix_create_default();
    759 	if (rpcua == NULL) {
    760 #ifdef DEBUG
    761 		if (debug)
    762 			printf("cannot get unix auth\n");
    763 #endif
    764 		return RPC_SYSTEMERROR;
    765 	}
    766 	msg.rm_direction = CALL;
    767 	msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
    768 	msg.rm_call.cb_prog = PMAPPROG;
    769 	msg.rm_call.cb_vers = PMAPVERS;
    770 	msg.rm_call.cb_proc = PMAPPROC_CALLIT;
    771 	msg.rm_call.cb_cred = rpcua->ah_cred;
    772 	msg.rm_call.cb_verf = rpcua->ah_verf;
    773 
    774 	msg.rm_xid = ypdb->dom_xid;
    775 	xdrmem_create(&xdr, buf, sizeof buf, XDR_ENCODE);
    776 	if (!xdr_callmsg(&xdr, &msg)) {
    777 		st = RPC_CANTENCODEARGS;
    778 		AUTH_DESTROY(rpcua);
    779 		return st;
    780 	}
    781 	if (!xdr_rmtcall_args(&xdr, &rmtca)) {
    782 		st = RPC_CANTENCODEARGS;
    783 		AUTH_DESTROY(rpcua);
    784 		return st;
    785 	}
    786 	outlen = (int)xdr_getpos(&xdr);
    787 	xdr_destroy(&xdr);
    788 	if (outlen < 1) {
    789 		st = RPC_CANTENCODEARGS;
    790 		AUTH_DESTROY(rpcua);
    791 		return st;
    792 	}
    793 	AUTH_DESTROY(rpcua);
    794 
    795 	if (ypdb->dom_lockfd != -1) {
    796 		(void)close(ypdb->dom_lockfd);
    797 		ypdb->dom_lockfd = -1;
    798 		removelock(ypdb);
    799 	}
    800 
    801 	if (ypdb->dom_alive == 2) {
    802 		/*
    803 		 * This resolves the following situation:
    804 		 * ypserver on other subnet was once bound,
    805 		 * but rebooted and is now using a different port
    806 		 */
    807 		struct sockaddr_in bindsin;
    808 
    809 		memset(&bindsin, 0, sizeof bindsin);
    810 		bindsin.sin_family = AF_INET;
    811 		bindsin.sin_len = sizeof(bindsin);
    812 		bindsin.sin_port = htons(PMAPPORT);
    813 		bindsin.sin_addr = ypdb->dom_server_addr.sin_addr;
    814 
    815 		if (sendto(rpcsock, buf, outlen, 0, (struct sockaddr *)&bindsin,
    816 			   sizeof bindsin) == -1)
    817 			yp_log(LOG_WARNING, "broadcast: sendto: %m");
    818 	}
    819 
    820 	switch (ypbindmode) {
    821 	case YPBIND_SETALL:
    822 	case YPBIND_SETLOCAL:
    823 		if (been_ypset)
    824 			return direct_set(buf, outlen, ypdb);
    825 		/* FALLTHROUGH */
    826 
    827 	case YPBIND_BROADCAST:
    828 		return broadcast(buf, outlen);
    829 
    830 	case YPBIND_DIRECT:
    831 		return direct(buf, outlen);
    832 	}
    833 
    834 	return -1;
    835 }
    836 
    837 static int
    838 broadcast(buf, outlen)
    839 	char *buf;
    840 	int outlen;
    841 {
    842 	struct ifaddrs *ifap, *ifa;
    843 	struct sockaddr_in bindsin;
    844 	struct in_addr in;
    845 
    846 	memset(&bindsin, 0, sizeof bindsin);
    847 	bindsin.sin_family = AF_INET;
    848 	bindsin.sin_len = sizeof(bindsin);
    849 	bindsin.sin_port = htons(PMAPPORT);
    850 
    851 	if (getifaddrs(&ifap) != 0) {
    852 		yp_log(LOG_WARNING, "broadcast: getifaddrs: %m");
    853 		return (-1);
    854 	}
    855 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
    856 		if (ifa->ifa_addr->sa_family != AF_INET)
    857 			continue;
    858 		if ((ifa->ifa_flags & IFF_UP) == 0)
    859 			continue;
    860 
    861 		switch (ifa->ifa_flags & (IFF_LOOPBACK | IFF_BROADCAST)) {
    862 		case IFF_BROADCAST:
    863 			if (!ifa->ifa_broadaddr)
    864 				continue;
    865 			if (ifa->ifa_broadaddr->sa_family != AF_INET)
    866 				continue;
    867 			in = ((struct sockaddr_in *)ifa->ifa_broadaddr)->sin_addr;
    868 			break;
    869 		case IFF_LOOPBACK:
    870 			in = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
    871 			break;
    872 		default:
    873 			continue;
    874 		}
    875 
    876 		bindsin.sin_addr = in;
    877 		if (sendto(rpcsock, buf, outlen, 0, (struct sockaddr *)&bindsin,
    878 			   bindsin.sin_len) == -1)
    879 			yp_log(LOG_WARNING, "broadcast: sendto: %m");
    880 	}
    881 	freeifaddrs(ifap);
    882 	return (0);
    883 }
    884 
    885 static int
    886 direct(buf, outlen)
    887 	char *buf;
    888 	int outlen;
    889 {
    890 	static FILE *df;
    891 	static char ypservers_path[MAXPATHLEN];
    892 	char line[_POSIX2_LINE_MAX];
    893 	char *p;
    894 	struct hostent *hp;
    895 	struct sockaddr_in bindsin;
    896 	int i, count = 0;
    897 
    898 	if (df)
    899 		rewind(df);
    900 	else {
    901 		snprintf(ypservers_path, sizeof(ypservers_path),
    902 		    "%s/%s%s", BINDINGDIR, domainname, YPSERVERSSUFF);
    903 		df = fopen(ypservers_path, "r");
    904 		if (df == NULL) {
    905 			yp_log(LOG_ERR, "%s: ", ypservers_path);
    906 			exit(1);
    907 		}
    908 	}
    909 
    910 	memset(&bindsin, 0, sizeof bindsin);
    911 	bindsin.sin_family = AF_INET;
    912 	bindsin.sin_len = sizeof(bindsin);
    913 	bindsin.sin_port = htons(PMAPPORT);
    914 
    915 	while(fgets(line, sizeof(line), df) != NULL) {
    916 		/* skip lines that are too big */
    917 		p = strchr(line, '\n');
    918 		if (p == NULL) {
    919 			int c;
    920 
    921 			while ((c = getc(df)) != '\n' && c != EOF)
    922 				;
    923 			continue;
    924 		}
    925 		*p = '\0';
    926 		p = line;
    927 		while (isspace(*p))
    928 			p++;
    929 		if (*p == '#')
    930 			continue;
    931 		hp = gethostbyname(p);
    932 		if (!hp) {
    933 			yp_log(LOG_WARNING, "%s: %s", p, hstrerror(h_errno));
    934 			continue;
    935 		}
    936 		/* step through all addresses in case first is unavailable */
    937 		for (i = 0; hp->h_addr_list[i]; i++) {
    938 			memmove(&bindsin.sin_addr, hp->h_addr_list[0],
    939 			    hp->h_length);
    940 			if (sendto(rpcsock, buf, outlen, 0,
    941 			    (struct sockaddr *)&bindsin, sizeof bindsin) < 0) {
    942 				yp_log(LOG_WARNING, "direct: sendto: %m");
    943 				continue;
    944 			} else
    945 				count++;
    946 		}
    947 	}
    948 	if (!count) {
    949 		yp_log(LOG_WARNING, "no contactable servers found in %s",
    950 		    ypservers_path);
    951 		return -1;
    952 	}
    953 	return 0;
    954 }
    955 
    956 static int
    957 direct_set(buf, outlen, ypdb)
    958 	char *buf;
    959 	int outlen;
    960 	struct _dom_binding *ypdb;
    961 {
    962 	struct sockaddr_in bindsin;
    963 	char path[MAXPATHLEN];
    964 	struct iovec iov[2];
    965 	struct ypbind_resp ybr;
    966 	SVCXPRT dummy_svc;
    967 	int fd, bytes;
    968 
    969 	/*
    970 	 * Gack, we lose if binding file went away.  We reset
    971 	 * "been_set" if this happens, otherwise we'll never
    972 	 * bind again.
    973 	 */
    974 	snprintf(path, sizeof(path), "%s/%s.%ld", BINDINGDIR,
    975 	    ypdb->dom_domain, ypdb->dom_vers);
    976 
    977 	if ((fd = open(path, O_SHLOCK|O_RDONLY, 0644)) == -1) {
    978 		yp_log(LOG_WARNING, "%s: %m", path);
    979 		been_ypset = 0;
    980 		return -1;
    981 	}
    982 
    983 #if O_SHLOCK == 0
    984 	(void)flock(fd, LOCK_SH);
    985 #endif
    986 
    987 	/* Read the binding file... */
    988 	iov[0].iov_base = (caddr_t)&(dummy_svc.xp_port);
    989 	iov[0].iov_len = sizeof(dummy_svc.xp_port);
    990 	iov[1].iov_base = (caddr_t)&ybr;
    991 	iov[1].iov_len = sizeof(ybr);
    992 	bytes = readv(fd, iov, 2);
    993 	(void)close(fd);
    994 	if (bytes != (iov[0].iov_len + iov[1].iov_len)) {
    995 		/* Binding file corrupt? */
    996 		yp_log(LOG_WARNING, "%s: %m", path);
    997 		been_ypset = 0;
    998 		return -1;
    999 	}
   1000 
   1001 	bindsin.sin_addr =
   1002 	    ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr;
   1003 
   1004 	if (sendto(rpcsock, buf, outlen, 0, (struct sockaddr *)&bindsin,
   1005 	    sizeof(bindsin)) < 0) {
   1006 		yp_log(LOG_WARNING, "direct_set: sendto: %m");
   1007 		return -1;
   1008 	}
   1009 
   1010 	return 0;
   1011 }
   1012 
   1013 static enum clnt_stat
   1014 handle_replies()
   1015 {
   1016 	char buf[BUFSIZE];
   1017 	int fromlen, inlen;
   1018 	struct _dom_binding *ypdb;
   1019 	struct sockaddr_in raddr;
   1020 	struct rpc_msg msg;
   1021 	XDR xdr;
   1022 
   1023 recv_again:
   1024 	(void)memset(&xdr, 0, sizeof(xdr));
   1025 	(void)memset(&msg, 0, sizeof(msg));
   1026 	msg.acpted_rply.ar_verf = _null_auth;
   1027 	msg.acpted_rply.ar_results.where = (caddr_t)&rmtcr;
   1028 	msg.acpted_rply.ar_results.proc = xdr_rmtcallres;
   1029 
   1030 try_again:
   1031 	fromlen = sizeof(struct sockaddr);
   1032 	inlen = recvfrom(rpcsock, buf, sizeof buf, 0,
   1033 		(struct sockaddr *)&raddr, &fromlen);
   1034 	if (inlen < 0) {
   1035 		if (errno == EINTR)
   1036 			goto try_again;
   1037 		return RPC_CANTRECV;
   1038 	}
   1039 	if (inlen < sizeof(u_int32_t))
   1040 		goto recv_again;
   1041 
   1042 	/*
   1043 	 * see if reply transaction id matches sent id.
   1044 	 * If so, decode the results.
   1045 	 */
   1046 	xdrmem_create(&xdr, buf, (u_int)inlen, XDR_DECODE);
   1047 	if (xdr_replymsg(&xdr, &msg)) {
   1048 		if ((msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
   1049 		    (msg.acpted_rply.ar_stat == SUCCESS)) {
   1050 			raddr.sin_port = htons((u_short)rmtcr_port);
   1051 			ypdb = xid2ypdb(msg.rm_xid);
   1052 			if (ypdb != NULL)
   1053 				rpc_received(ypdb->dom_domain, &raddr, 0);
   1054 		}
   1055 	}
   1056 	xdr.x_op = XDR_FREE;
   1057 	msg.acpted_rply.ar_results.proc = xdr_void;
   1058 	xdr_destroy(&xdr);
   1059 
   1060 	return RPC_SUCCESS;
   1061 }
   1062 
   1063 static enum clnt_stat
   1064 handle_ping()
   1065 {
   1066 	char buf[BUFSIZE];
   1067 	int fromlen, inlen;
   1068 	struct _dom_binding *ypdb;
   1069 	struct sockaddr_in raddr;
   1070 	struct rpc_msg msg;
   1071 	XDR xdr;
   1072 	bool_t res;
   1073 
   1074 recv_again:
   1075 	(void)memset(&xdr, 0, sizeof(xdr));
   1076 	(void)memset(&msg, 0, sizeof(msg));
   1077 	msg.acpted_rply.ar_verf = _null_auth;
   1078 	msg.acpted_rply.ar_results.where = (caddr_t)&res;
   1079 	msg.acpted_rply.ar_results.proc = xdr_bool;
   1080 
   1081 try_again:
   1082 	fromlen = sizeof (struct sockaddr);
   1083 	inlen = recvfrom(pingsock, buf, sizeof buf, 0,
   1084 		(struct sockaddr *)&raddr, &fromlen);
   1085 	if (inlen < 0) {
   1086 		if (errno == EINTR)
   1087 			goto try_again;
   1088 		return RPC_CANTRECV;
   1089 	}
   1090 	if (inlen < sizeof(u_int32_t))
   1091 		goto recv_again;
   1092 
   1093 	/*
   1094 	 * see if reply transaction id matches sent id.
   1095 	 * If so, decode the results.
   1096 	 */
   1097 	xdrmem_create(&xdr, buf, (u_int)inlen, XDR_DECODE);
   1098 	if (xdr_replymsg(&xdr, &msg)) {
   1099 		if ((msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
   1100 		    (msg.acpted_rply.ar_stat == SUCCESS)) {
   1101 			ypdb = xid2ypdb(msg.rm_xid);
   1102 			if (ypdb != NULL)
   1103 				rpc_received(ypdb->dom_domain, &raddr, 0);
   1104 		}
   1105 	}
   1106 	xdr.x_op = XDR_FREE;
   1107 	msg.acpted_rply.ar_results.proc = xdr_void;
   1108 	xdr_destroy(&xdr);
   1109 
   1110 	return RPC_SUCCESS;
   1111 }
   1112 
   1113 /*
   1114  * LOOPBACK IS MORE IMPORTANT: PUT IN HACK
   1115  */
   1116 void
   1117 rpc_received(dom, raddrp, force)
   1118 	char *dom;
   1119 	struct sockaddr_in *raddrp;
   1120 	int force;
   1121 {
   1122 	struct _dom_binding *ypdb;
   1123 	struct iovec iov[2];
   1124 	struct ypbind_resp ybr;
   1125 	int fd;
   1126 
   1127 #ifdef DEBUG
   1128 	if (debug)
   1129 		printf("returned from %s about %s\n",
   1130 		    inet_ntoa(raddrp->sin_addr), dom);
   1131 #endif
   1132 
   1133 	if (dom == NULL)
   1134 		return;
   1135 
   1136 	if (_yp_invalid_domain(dom))
   1137 		return;
   1138 
   1139 		/* don't support insecure servers by default */
   1140 	if (!insecure && ntohs(raddrp->sin_port) >= IPPORT_RESERVED)
   1141 		return;
   1142 
   1143 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext)
   1144 		if (!strcmp(ypdb->dom_domain, dom))
   1145 			break;
   1146 
   1147 	if (ypdb == NULL) {
   1148 		if (force == 0)
   1149 			return;
   1150 		ypdb = makebinding(dom);
   1151 		ypdb->dom_lockfd = -1;
   1152 		ypdb->dom_pnext = ypbindlist;
   1153 		ypbindlist = ypdb;
   1154 	}
   1155 
   1156 	/* soft update, alive */
   1157 	if (ypdb->dom_alive == 1 && force == 0) {
   1158 		if (!memcmp(&ypdb->dom_server_addr, raddrp,
   1159 			    sizeof ypdb->dom_server_addr)) {
   1160 			ypdb->dom_alive = 1;
   1161 			/* recheck binding in 60 sec */
   1162 			ypdb->dom_check_t = time(NULL) + 60;
   1163 		}
   1164 		return;
   1165 	}
   1166 
   1167 	(void)memcpy(&ypdb->dom_server_addr, raddrp,
   1168 	    sizeof ypdb->dom_server_addr);
   1169 	/* recheck binding in 60 seconds */
   1170 	ypdb->dom_check_t = time(NULL) + 60;
   1171 	ypdb->dom_vers = YPVERS;
   1172 	ypdb->dom_alive = 1;
   1173 
   1174 	if (ypdb->dom_lockfd != -1)
   1175 		(void)close(ypdb->dom_lockfd);
   1176 
   1177 	if ((fd = makelock(ypdb)) == -1)
   1178 		return;
   1179 
   1180 	/*
   1181 	 * ok, if BINDINGDIR exists, and we can create the binding file,
   1182 	 * then write to it..
   1183 	 */
   1184 	ypdb->dom_lockfd = fd;
   1185 
   1186 	iov[0].iov_base = (caddr_t)&(udptransp->xp_port);
   1187 	iov[0].iov_len = sizeof udptransp->xp_port;
   1188 	iov[1].iov_base = (caddr_t)&ybr;
   1189 	iov[1].iov_len = sizeof ybr;
   1190 
   1191 	(void)memset(&ybr, 0, sizeof ybr);
   1192 	ybr.ypbind_status = YPBIND_SUCC_VAL;
   1193 	ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr =
   1194 	    raddrp->sin_addr;
   1195 	ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_port =
   1196 	    raddrp->sin_port;
   1197 
   1198 	if (writev(ypdb->dom_lockfd, iov, 2) !=
   1199 	    iov[0].iov_len + iov[1].iov_len) {
   1200 		yp_log(LOG_WARNING, "writev: %m");
   1201 		(void)close(ypdb->dom_lockfd);
   1202 		removelock(ypdb);
   1203 		ypdb->dom_lockfd = -1;
   1204 	}
   1205 }
   1206 
   1207 static struct _dom_binding *
   1208 xid2ypdb(xid)
   1209 	u_int32_t xid;
   1210 {
   1211 	struct _dom_binding *ypdb;
   1212 
   1213 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext)
   1214 		if (ypdb->dom_xid == xid)
   1215 			break;
   1216 	return (ypdb);
   1217 }
   1218 
   1219 static u_int32_t
   1220 unique_xid(ypdb)
   1221 	struct _dom_binding *ypdb;
   1222 {
   1223 	u_int32_t tmp_xid;
   1224 
   1225 	tmp_xid = (u_int32_t)(((u_long)ypdb) & 0xffffffff);
   1226 	while (xid2ypdb(tmp_xid) != NULL)
   1227 		tmp_xid++;
   1228 
   1229 	return tmp_xid;
   1230 }
   1231