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