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