ypbind.c revision 1.96 1 /* $NetBSD: ypbind.c,v 1.96 2014/06/10 17:19:22 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.96 2014/06/10 17:19:22 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 enum domainstates {
88 DOM_NEW, /* not yet bound */
89 DOM_ALIVE, /* bound and healthy */
90 DOM_PINGING, /* ping outstanding */
91 DOM_LOST, /* binding timed out, looking for a new one */
92 DOM_DEAD, /* long-term lost, in exponential backoff */
93 };
94
95 struct domain {
96 struct domain *dom_next;
97
98 char dom_name[YPMAXDOMAIN + 1];
99 struct sockaddr_in dom_server_addr;
100 long dom_vers;
101 time_t dom_checktime; /* time of next check/contact */
102 time_t dom_asktime; /* time we were last DOMAIN'd */
103 time_t dom_losttime; /* time the binding was lost, or 0 */
104 unsigned dom_backofftime; /* current backoff period, when DEAD */
105 int dom_lockfd;
106 enum domainstates dom_state;
107 uint32_t dom_xid;
108 FILE *dom_serversfile; /* /var/yp/binding/foo.ypservers */
109 int dom_been_ypset; /* ypset been done on this domain? */
110 ypbind_mode_t dom_ypbindmode; /* broadcast or direct */
111 };
112
113 #define BUFSIZE 1400
114
115 /* the list of all domains */
116 static struct domain *domains;
117 static int check;
118
119 /* option settings */
120 static ypbind_mode_t default_ypbindmode;
121 static int allow_local_ypset = 0, allow_any_ypset = 0;
122 static int insecure;
123
124 /* the sockets we use to interact with servers */
125 static int rpcsock, pingsock;
126
127 /* stuff used for manually interacting with servers */
128 static struct rmtcallargs rmtca;
129 static struct rmtcallres rmtcr;
130 static bool_t rmtcr_outval;
131 static unsigned long rmtcr_port;
132
133 /* The ypbind service transports */
134 static SVCXPRT *udptransp, *tcptransp;
135
136 ////////////////////////////////////////////////////////////
137 // utilities
138
139 /*
140 * Combo of open() and flock().
141 */
142 static int
143 open_locked(const char *path, int flags, mode_t mode)
144 {
145 int fd;
146
147 fd = open(path, flags|O_SHLOCK, mode);
148 if (fd < 0) {
149 return -1;
150 }
151 #if O_SHLOCK == 0
152 /* dholland 20110522 wouldn't it be better to check this for error? */
153 (void)flock(fd, LOCK_SH);
154 #endif
155 return fd;
156 }
157
158 /*
159 * Exponential backoff for pinging servers for a dead domain.
160 *
161 * We go 10 -> 20 -> 40 -> 60 seconds, then 2 -> 4 -> 8 -> 15 -> 30 ->
162 * 60 minutes, and stay at 60 minutes. This is overengineered.
163 *
164 * With a 60 minute max backoff the response time for when things come
165 * back is not awful, but we only try (and log) about 60 times even if
166 * things are down for a whole long weekend. This is an acceptable log
167 * load, I think.
168 */
169 static void
170 backoff(unsigned *psecs)
171 {
172 unsigned secs;
173
174 secs = *psecs;
175 if (secs < 60) {
176 secs *= 2;
177 if (secs > 60) {
178 secs = 60;
179 }
180 } else if (secs < 60 * 15) {
181 secs *= 2;
182 if (secs > 60 * 15) {
183 secs = 60 * 15;
184 }
185 } else if (secs < 60 * 60) {
186 secs *= 2;
187 }
188 *psecs = secs;
189 }
190
191 ////////////////////////////////////////////////////////////
192 // logging
193
194 #ifdef DEBUG
195 #define DPRINTF(...) (debug ? (void)printf(__VA_ARGS__) : (void)0)
196 static int debug;
197 #else
198 #define DPRINTF(...)
199 #endif
200
201 static void yp_log(int, const char *, ...) __printflike(2, 3);
202
203 /*
204 * Log some stuff, to syslog or stderr depending on the debug setting.
205 */
206 static void
207 yp_log(int pri, const char *fmt, ...)
208 {
209 va_list ap;
210
211 va_start(ap, fmt);
212
213 #if defined(DEBUG)
214 if (debug) {
215 (void)vprintf(fmt, ap);
216 (void)printf("\n");
217 } else
218 #endif
219 vsyslog(pri, fmt, ap);
220 va_end(ap);
221 }
222
223 ////////////////////////////////////////////////////////////
224 // ypservers file
225
226 /*
227 * Get pathname for the ypservers file for a given domain
228 * (/var/yp/binding/DOMAIN.ypservers)
229 */
230 static const char *
231 ypservers_filename(const char *domain)
232 {
233 static char ret[PATH_MAX];
234
235 (void)snprintf(ret, sizeof(ret), "%s/%s%s",
236 BINDINGDIR, domain, YPSERVERSSUFF);
237 return ret;
238 }
239
240 ////////////////////////////////////////////////////////////
241 // struct domain
242
243 /*
244 * The state transitions of a domain work as follows:
245 *
246 * in state NEW:
247 * nag_servers every 5 seconds
248 * upon answer, state is ALIVE
249 *
250 * in state ALIVE:
251 * every 60 seconds, send ping and switch to state PINGING
252 *
253 * in state PINGING:
254 * upon answer, go to state ALIVE
255 * if no answer in 5 seconds, go to state LOST and do nag_servers
256 *
257 * in state LOST:
258 * do nag_servers every 5 seconds
259 * upon answer, go to state ALIVE
260 * if no answer in 60 seconds, go to state DEAD
261 *
262 * in state DEAD
263 * do nag_servers every backofftime seconds (starts at 10)
264 * upon answer go to state ALIVE
265 * backofftime doubles (approximately) each try, with a cap of 1 hour
266 */
267
268 /*
269 * Look up a domain by the XID we assigned it.
270 */
271 static struct domain *
272 domain_find(uint32_t xid)
273 {
274 struct domain *dom;
275
276 for (dom = domains; dom != NULL; dom = dom->dom_next)
277 if (dom->dom_xid == xid)
278 break;
279 return dom;
280 }
281
282 /*
283 * Pick an XID for a domain.
284 *
285 * XXX: this should just generate a random number.
286 */
287 static uint32_t
288 unique_xid(struct domain *dom)
289 {
290 uint32_t tmp_xid;
291
292 tmp_xid = ((uint32_t)(unsigned long)dom) & 0xffffffff;
293 while (domain_find(tmp_xid) != NULL)
294 tmp_xid++;
295
296 return tmp_xid;
297 }
298
299 /*
300 * Construct a new domain. Adds it to the global linked list of all
301 * domains.
302 */
303 static struct domain *
304 domain_create(const char *name)
305 {
306 struct domain *dom;
307 const char *pathname;
308 struct stat st;
309
310 dom = malloc(sizeof *dom);
311 if (dom == NULL) {
312 yp_log(LOG_ERR, "domain_create: Out of memory");
313 exit(1);
314 }
315
316 dom->dom_next = NULL;
317
318 (void)strlcpy(dom->dom_name, name, sizeof(dom->dom_name));
319 (void)memset(&dom->dom_server_addr, 0, sizeof(dom->dom_server_addr));
320 dom->dom_vers = YPVERS;
321 dom->dom_checktime = 0;
322 dom->dom_asktime = 0;
323 dom->dom_losttime = 0;
324 dom->dom_backofftime = 10;
325 dom->dom_lockfd = -1;
326 dom->dom_state = DOM_NEW;
327 dom->dom_xid = unique_xid(dom);
328 dom->dom_been_ypset = 0;
329 dom->dom_serversfile = NULL;
330
331 /*
332 * Per traditional ypbind(8) semantics, if a ypservers
333 * file does not exist, we revert to broadcast mode.
334 *
335 * The sysadmin can force broadcast mode by passing the
336 * -broadcast flag. There is currently no way to fail and
337 * reject domains for which there is no ypservers file.
338 */
339 dom->dom_ypbindmode = default_ypbindmode;
340 if (dom->dom_ypbindmode == YPBIND_DIRECT) {
341 pathname = ypservers_filename(dom->dom_name);
342 if (stat(pathname, &st) < 0) {
343 /* XXX syslog a warning here? */
344 DPRINTF("%s does not exist, defaulting to broadcast\n",
345 pathname);
346 dom->dom_ypbindmode = YPBIND_BROADCAST;
347 }
348 }
349
350 /* add to global list */
351 dom->dom_next = domains;
352 domains = dom;
353
354 return dom;
355 }
356
357 ////////////////////////////////////////////////////////////
358 // locks
359
360 /*
361 * Open a new binding file. Does not write the contents out; the
362 * caller (there's only one) does that.
363 */
364 static int
365 makelock(struct domain *dom)
366 {
367 int fd;
368 char path[MAXPATHLEN];
369
370 (void)snprintf(path, sizeof(path), "%s/%s.%ld", BINDINGDIR,
371 dom->dom_name, dom->dom_vers);
372
373 fd = open_locked(path, O_CREAT|O_RDWR|O_TRUNC, 0644);
374 if (fd == -1) {
375 (void)mkdir(BINDINGDIR, 0755);
376 fd = open_locked(path, O_CREAT|O_RDWR|O_TRUNC, 0644);
377 if (fd == -1) {
378 return -1;
379 }
380 }
381
382 return fd;
383 }
384
385 /*
386 * Remove a binding file.
387 */
388 static void
389 removelock(struct domain *dom)
390 {
391 char path[MAXPATHLEN];
392
393 (void)snprintf(path, sizeof(path), "%s/%s.%ld",
394 BINDINGDIR, dom->dom_name, dom->dom_vers);
395 (void)unlink(path);
396 }
397
398 /*
399 * purge_bindingdir: remove old binding files (i.e. "rm *.[0-9]" in BINDINGDIR)
400 *
401 * The local YP functions [e.g. yp_master()] will fail without even
402 * talking to ypbind if there is a stale (non-flock'd) binding file
403 * present.
404 *
405 * We have to remove all binding files in BINDINGDIR, not just the one
406 * for the default domain.
407 */
408 static int
409 purge_bindingdir(const char *dirpath)
410 {
411 DIR *dirp;
412 int unlinkedfiles, l;
413 struct dirent *dp;
414 char pathname[MAXPATHLEN];
415
416 if ((dirp = opendir(dirpath)) == NULL)
417 return(-1); /* at this point, shouldn't ever happen */
418
419 do {
420 unlinkedfiles = 0;
421 while ((dp = readdir(dirp)) != NULL) {
422 l = dp->d_namlen;
423 /* 'rm *.[0-9]' */
424 if (l > 2 && dp->d_name[l-2] == '.' &&
425 dp->d_name[l-1] >= '0' && dp->d_name[l-1] <= '9') {
426 (void)snprintf(pathname, sizeof(pathname),
427 "%s/%s", dirpath, dp->d_name);
428 if (unlink(pathname) < 0 && errno != ENOENT)
429 return(-1);
430 unlinkedfiles++;
431 }
432 }
433
434 /* rescan dir if we removed it */
435 if (unlinkedfiles)
436 rewinddir(dirp);
437
438 } while (unlinkedfiles);
439
440 closedir(dirp);
441 return(0);
442 }
443
444 ////////////////////////////////////////////////////////////
445 // sunrpc twaddle
446
447 /*
448 * Check if the info coming in is (at least somewhat) valid.
449 */
450 static int
451 rpc_is_valid_response(char *name, struct sockaddr_in *addr)
452 {
453 if (name == NULL) {
454 return 0;
455 }
456
457 if (_yp_invalid_domain(name)) {
458 return 0;
459 }
460
461 /* don't support insecure servers by default */
462 if (!insecure && ntohs(addr->sin_port) >= IPPORT_RESERVED) {
463 return 0;
464 }
465
466 return 1;
467 }
468
469 /*
470 * Take note of the fact that we've received a reply from a ypserver.
471 * Or, in the case of being ypset, that we've been ypset, which
472 * functions much the same.
473 *
474 * Note that FORCE is set if and only if IS_YPSET is set.
475 *
476 * This function has also for the past 20+ years carried the annotation
477 *
478 * LOOPBACK IS MORE IMPORTANT: PUT IN HACK
479 *
480 * whose meaning isn't entirely clear.
481 */
482 static void
483 rpc_received(char *dom_name, struct sockaddr_in *raddrp, int force,
484 int is_ypset)
485 {
486 struct domain *dom;
487 struct iovec iov[2];
488 struct ypbind_resp ybr;
489 ssize_t result;
490 int fd;
491
492 DPRINTF("returned from %s about %s\n",
493 inet_ntoa(raddrp->sin_addr), dom_name);
494
495 /* validate some stuff */
496 if (!rpc_is_valid_response(dom_name, raddrp)) {
497 return;
498 }
499
500 /* look for the domain */
501 for (dom = domains; dom != NULL; dom = dom->dom_next)
502 if (!strcmp(dom->dom_name, dom_name))
503 break;
504
505 /* if not found, create it, but only if FORCE; otherwise ignore */
506 if (dom == NULL) {
507 if (force == 0)
508 return;
509 dom = domain_create(dom_name);
510 }
511
512 /* the domain needs to know if it's been explicitly ypset */
513 if (is_ypset) {
514 dom->dom_been_ypset = 1;
515 }
516
517 /*
518 * If the domain is alive and we aren't being called by ypset,
519 * we shouldn't be getting a response at all. Log it, as it
520 * might be hostile.
521 */
522 if (dom->dom_state == DOM_ALIVE && force == 0) {
523 if (!memcmp(&dom->dom_server_addr, raddrp,
524 sizeof(dom->dom_server_addr))) {
525 yp_log(LOG_WARNING,
526 "Unexpected reply from server %s for domain %s",
527 inet_ntoa(dom->dom_server_addr.sin_addr),
528 dom->dom_name);
529 } else {
530 yp_log(LOG_WARNING,
531 "Falsified reply from %s for domain %s",
532 inet_ntoa(dom->dom_server_addr.sin_addr),
533 dom->dom_name);
534 }
535 return;
536 }
537
538 /*
539 * If we're expected a ping response, and we've got it
540 * (meaning we aren't being called by ypset), we don't need to
541 * do anything.
542 */
543 if (dom->dom_state == DOM_PINGING && force == 0) {
544 /*
545 * If the reply came from the server we expect, set
546 * dom_state back to ALIVE and ping again in 60
547 * seconds.
548 *
549 * If it came from somewhere else, log it.
550 */
551 if (!memcmp(&dom->dom_server_addr, raddrp,
552 sizeof(dom->dom_server_addr))) {
553 dom->dom_state = DOM_ALIVE;
554 /* recheck binding in 60 sec */
555 dom->dom_checktime = time(NULL) + 60;
556 } else {
557 yp_log(LOG_WARNING,
558 "Falsified reply from %s for domain %s",
559 inet_ntoa(dom->dom_server_addr.sin_addr),
560 dom->dom_name);
561 }
562 return;
563 }
564
565 #ifdef HEURISTIC
566 /*
567 * If transitioning to the alive state from a non-alive state,
568 * clear dom_asktime. This will help prevent any requests that
569 * are still coming in from triggering unnecessary pings via
570 * the HEURISTIC code.
571 *
572 * XXX: this may not be an adequate measure; we may need to
573 * keep more state so we can disable the HEURISTIC code for
574 * the first few seconds after rebinding.
575 */
576 if (dom->dom_state == DOM_NEW ||
577 dom->dom_state == DOM_LOST ||
578 dom->dom_state == DOM_DEAD) {
579 dom->dom_asktime = 0;
580 }
581 #endif
582
583 /*
584 * Take the address we got the message from (or in the case of
585 * ypset, the explicit address we were given) as the server
586 * address for this domain, mark the domain alive, and we'll
587 * check it again in 60 seconds.
588 *
589 * XXX: it looks like if we get a random unsolicited reply
590 * from somewhere, we'll silently switch to that server
591 * address, regardless of merit.
592 *
593 * 1. If we have a foo.ypservers file the address should be
594 * checked against it and rejected if it's not one of the
595 * addresses of one of the listed hostnames. Note that it
596 * might not be the same address we sent to; even fairly smart
597 * UDP daemons don't always handle multihomed hosts correctly
598 * and we can't expect sunrpc code to do anything intelligent
599 * at all.
600 *
601 * 2. If we're in broadcast mode the address should be
602 * checked against the local addresses and netmasks so we
603 * don't accept responses from Mars.
604 *
605 * 2a. If we're in broadcast mode and we've been ypset, we
606 * should not accept anything else until we drop the ypset
607 * state for not responding.
608 *
609 * 3. Either way we should not accept a response from an
610 * arbitrary host unless we don't currently have a binding.
611 * (This is now fixed above.)
612 *
613 * Note that for a random unsolicited reply to work it has to
614 * carry the XID of one of the domains we know about; but
615 * those values are predictable.
616 */
617 (void)memcpy(&dom->dom_server_addr, raddrp,
618 sizeof(dom->dom_server_addr));
619 /* recheck binding in 60 seconds */
620 dom->dom_checktime = time(NULL) + 60;
621 dom->dom_state = DOM_ALIVE;
622
623 /* Clear the dead/backoff state. */
624 dom->dom_losttime = 0;
625 dom->dom_backofftime = 10;
626
627 /*
628 * Generate a new binding file. If this fails, forget about it.
629 * (But we keep the binding and we'll report it to anyone who
630 * asks via the ypbind service.) XXX: this will interact badly,
631 * maybe very badly, with the code in HEURISTIC.
632 *
633 * Note that makelock() doesn't log on failure.
634 */
635
636 if (dom->dom_lockfd != -1)
637 (void)close(dom->dom_lockfd);
638
639 if ((fd = makelock(dom)) == -1)
640 return;
641
642 dom->dom_lockfd = fd;
643
644 iov[0].iov_base = &(udptransp->xp_port);
645 iov[0].iov_len = sizeof udptransp->xp_port;
646 iov[1].iov_base = &ybr;
647 iov[1].iov_len = sizeof ybr;
648
649 (void)memset(&ybr, 0, sizeof ybr);
650 ybr.ypbind_status = YPBIND_SUCC_VAL;
651 ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr =
652 raddrp->sin_addr;
653 ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_port =
654 raddrp->sin_port;
655
656 result = writev(dom->dom_lockfd, iov, 2);
657 if (result < 0 || (size_t)result != iov[0].iov_len + iov[1].iov_len) {
658 if (result < 0)
659 yp_log(LOG_WARNING, "writev: %s", strerror(errno));
660 else
661 yp_log(LOG_WARNING, "writev: short count");
662 (void)close(dom->dom_lockfd);
663 removelock(dom);
664 dom->dom_lockfd = -1;
665 }
666 }
667
668 /*
669 * The NULL call: do nothing. This is obliged to exist because of
670 * sunrpc silliness.
671 */
672 static void *
673 /*ARGSUSED*/
674 ypbindproc_null_2(SVCXPRT *transp, void *argp)
675 {
676 static char res;
677
678 DPRINTF("ypbindproc_null_2\n");
679 (void)memset(&res, 0, sizeof(res));
680 return (void *)&res;
681 }
682
683 /*
684 * The DOMAIN call: look up the ypserver for a specified domain.
685 */
686 static void *
687 /*ARGSUSED*/
688 ypbindproc_domain_2(SVCXPRT *transp, void *argp)
689 {
690 static struct ypbind_resp res;
691 struct domain *dom;
692 char *arg = *(char **) argp;
693 time_t now;
694 int count;
695
696 DPRINTF("ypbindproc_domain_2 %s\n", arg);
697
698 /* Reject invalid domains. */
699 if (_yp_invalid_domain(arg))
700 return NULL;
701
702 (void)memset(&res, 0, sizeof res);
703 res.ypbind_status = YPBIND_FAIL_VAL;
704
705 /*
706 * Look for the domain. XXX: Behave erratically if we have
707 * more than 100 domains. The intent here is to avoid allowing
708 * arbitrary incoming requests to create more than 100
709 * domains; but this logic means that if we legitimately have
710 * more than 100 (e.g. via ypset) we'll only actually bind the
711 * first 100 and the rest will fail. The test on 'count' should
712 * be moved further down.
713 */
714 for (count = 0, dom = domains;
715 dom != NULL;
716 dom = dom->dom_next, count++) {
717 if (count > 100)
718 return NULL; /* prevent denial of service */
719 if (!strcmp(dom->dom_name, arg))
720 break;
721 }
722
723 /*
724 * If the domain doesn't exist, create it, then fail the call
725 * because we have no information yet.
726 *
727 * Set "check" so that checkwork() will run and look for a
728 * server.
729 *
730 * XXX: like during startup there's a spurious call to
731 * removelock() after domain_create().
732 */
733 if (dom == NULL) {
734 dom = domain_create(arg);
735 removelock(dom);
736 check++;
737 DPRINTF("unknown domain %s\n", arg);
738 return NULL;
739 }
740
741 if (dom->dom_state == DOM_NEW) {
742 DPRINTF("new domain %s\n", arg);
743 return NULL;
744 }
745
746 #ifdef HEURISTIC
747 /*
748 * Keep track of the last time we were explicitly asked about
749 * this domain. If it happens a lot, force a ping. This works
750 * (or "works") because we only get asked specifically when
751 * things aren't going; otherwise the client code in libc and
752 * elsewhere uses the binding file.
753 *
754 * Note: HEURISTIC is enabled by default.
755 *
756 * dholland 20140609: I think this is part of the mechanism
757 * that causes ypbind to spam. I'm changing this logic so it
758 * only triggers when the state is DOM_ALIVE: if the domain
759 * is new, lost, or dead we shouldn't send more requests than
760 * the ones already scheduled, and if we're already in the
761 * middle of pinging there's no point doing it again.
762 */
763 (void)time(&now);
764 if (dom->dom_state == DOM_ALIVE && now < dom->dom_asktime + 5) {
765 /*
766 * Hmm. More than 2 requests in 5 seconds have indicated
767 * that my binding is possibly incorrect.
768 * Ok, do an immediate poll of the server.
769 */
770 if (dom->dom_checktime >= now) {
771 /* don't flood it */
772 dom->dom_checktime = 0;
773 check++;
774 }
775 }
776 dom->dom_asktime = now;
777 #endif
778
779 res.ypbind_status = YPBIND_SUCC_VAL;
780 res.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr.s_addr =
781 dom->dom_server_addr.sin_addr.s_addr;
782 res.ypbind_respbody.ypbind_bindinfo.ypbind_binding_port =
783 dom->dom_server_addr.sin_port;
784 DPRINTF("domain %s at %s/%d\n", dom->dom_name,
785 inet_ntoa(dom->dom_server_addr.sin_addr),
786 ntohs(dom->dom_server_addr.sin_port));
787 return &res;
788 }
789
790 /*
791 * The SETDOM call: ypset.
792 *
793 * Unless -ypsetme was given on the command line, this is rejected;
794 * even then it's only allowed from localhost unless -ypset was
795 * given on the command line.
796 *
797 * Allowing anyone anywhere to ypset you (and therefore provide your
798 * password file and such) is a horrible thing and it isn't clear to
799 * me why this functionality even exists.
800 *
801 * ypset from localhost has some but limited utility.
802 */
803 static void *
804 ypbindproc_setdom_2(SVCXPRT *transp, void *argp)
805 {
806 struct ypbind_setdom *sd = argp;
807 struct sockaddr_in *fromsin, bindsin;
808 static bool_t res;
809
810 (void)memset(&res, 0, sizeof(res));
811 fromsin = svc_getcaller(transp);
812 DPRINTF("ypbindproc_setdom_2 from %s\n", inet_ntoa(fromsin->sin_addr));
813
814 /*
815 * Reject unless enabled.
816 */
817
818 if (allow_any_ypset) {
819 /* nothing */
820 } else if (allow_local_ypset) {
821 if (fromsin->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
822 DPRINTF("ypset denied from %s\n",
823 inet_ntoa(fromsin->sin_addr));
824 return NULL;
825 }
826 } else {
827 DPRINTF("ypset denied\n");
828 return NULL;
829 }
830
831 /* Make a "security" check. */
832 if (ntohs(fromsin->sin_port) >= IPPORT_RESERVED) {
833 DPRINTF("ypset from unprivileged port denied\n");
834 return &res;
835 }
836
837 /* Ignore requests we don't understand. */
838 if (sd->ypsetdom_vers != YPVERS) {
839 DPRINTF("ypset with wrong version denied\n");
840 return &res;
841 }
842
843 /*
844 * Fetch the arguments out of the xdr-decoded blob and call
845 * rpc_received(), setting FORCE so that the domain will be
846 * created if we don't already know about it, and also saying
847 * that it's actually a ypset.
848 *
849 * Effectively we're telilng rpc_received() that we got an
850 * RPC response from the server specified by ypset.
851 */
852 (void)memset(&bindsin, 0, sizeof bindsin);
853 bindsin.sin_family = AF_INET;
854 bindsin.sin_len = sizeof(bindsin);
855 bindsin.sin_addr = sd->ypsetdom_addr;
856 bindsin.sin_port = sd->ypsetdom_port;
857 rpc_received(sd->ypsetdom_domain, &bindsin, 1, 1);
858
859 DPRINTF("ypset to %s for domain %s succeeded\n",
860 inet_ntoa(bindsin.sin_addr), sd->ypsetdom_domain);
861 res = 1;
862 return &res;
863 }
864
865 /*
866 * Dispatcher for the ypbind service.
867 *
868 * There are three calls: NULL, which does nothing, DOMAIN, which
869 * gets the binding for a particular domain, and SETDOM, which
870 * does ypset.
871 */
872 static void
873 ypbindprog_2(struct svc_req *rqstp, register SVCXPRT *transp)
874 {
875 union {
876 char ypbindproc_domain_2_arg[YPMAXDOMAIN + 1];
877 struct ypbind_setdom ypbindproc_setdom_2_arg;
878 void *alignment;
879 } argument;
880 struct authunix_parms *creds;
881 char *result;
882 xdrproc_t xdr_argument, xdr_result;
883 void *(*local)(SVCXPRT *, void *);
884
885 switch (rqstp->rq_proc) {
886 case YPBINDPROC_NULL:
887 xdr_argument = (xdrproc_t)xdr_void;
888 xdr_result = (xdrproc_t)xdr_void;
889 local = ypbindproc_null_2;
890 break;
891
892 case YPBINDPROC_DOMAIN:
893 xdr_argument = (xdrproc_t)xdr_ypdomain_wrap_string;
894 xdr_result = (xdrproc_t)xdr_ypbind_resp;
895 local = ypbindproc_domain_2;
896 break;
897
898 case YPBINDPROC_SETDOM:
899 switch (rqstp->rq_cred.oa_flavor) {
900 case AUTH_UNIX:
901 creds = (struct authunix_parms *)rqstp->rq_clntcred;
902 if (creds->aup_uid != 0) {
903 svcerr_auth(transp, AUTH_BADCRED);
904 return;
905 }
906 break;
907 default:
908 svcerr_auth(transp, AUTH_TOOWEAK);
909 return;
910 }
911
912 xdr_argument = (xdrproc_t)xdr_ypbind_setdom;
913 xdr_result = (xdrproc_t)xdr_void;
914 local = ypbindproc_setdom_2;
915 break;
916
917 default:
918 svcerr_noproc(transp);
919 return;
920 }
921 (void)memset(&argument, 0, sizeof(argument));
922 if (!svc_getargs(transp, xdr_argument, (caddr_t)(void *)&argument)) {
923 svcerr_decode(transp);
924 return;
925 }
926 result = (*local)(transp, &argument);
927 if (result != NULL && !svc_sendreply(transp, xdr_result, result)) {
928 svcerr_systemerr(transp);
929 }
930 return;
931 }
932
933 /*
934 * Set up sunrpc stuff.
935 *
936 * This sets up the ypbind service (both TCP and UDP) and also opens
937 * the sockets we use for talking to ypservers.
938 */
939 static void
940 sunrpc_setup(void)
941 {
942 int one;
943
944 (void)pmap_unset(YPBINDPROG, YPBINDVERS);
945
946 udptransp = svcudp_create(RPC_ANYSOCK);
947 if (udptransp == NULL)
948 errx(1, "Cannot create udp service.");
949
950 if (!svc_register(udptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
951 IPPROTO_UDP))
952 errx(1, "Unable to register (YPBINDPROG, YPBINDVERS, udp).");
953
954 tcptransp = svctcp_create(RPC_ANYSOCK, 0, 0);
955 if (tcptransp == NULL)
956 errx(1, "Cannot create tcp service.");
957
958 if (!svc_register(tcptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
959 IPPROTO_TCP))
960 errx(1, "Unable to register (YPBINDPROG, YPBINDVERS, tcp).");
961
962 /* XXX use SOCK_STREAM for direct queries? */
963 if ((rpcsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
964 err(1, "rpc socket");
965 if ((pingsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
966 err(1, "ping socket");
967
968 (void)fcntl(rpcsock, F_SETFL, fcntl(rpcsock, F_GETFL, 0) | FNDELAY);
969 (void)fcntl(pingsock, F_SETFL, fcntl(pingsock, F_GETFL, 0) | FNDELAY);
970
971 one = 1;
972 (void)setsockopt(rpcsock, SOL_SOCKET, SO_BROADCAST, &one,
973 (socklen_t)sizeof(one));
974 rmtca.prog = YPPROG;
975 rmtca.vers = YPVERS;
976 rmtca.proc = YPPROC_DOMAIN_NONACK;
977 rmtca.xdr_args = NULL; /* set at call time */
978 rmtca.args_ptr = NULL; /* set at call time */
979 rmtcr.port_ptr = &rmtcr_port;
980 rmtcr.xdr_results = (xdrproc_t)xdr_bool;
981 rmtcr.results_ptr = (caddr_t)(void *)&rmtcr_outval;
982 }
983
984 ////////////////////////////////////////////////////////////
985 // operational logic
986
987 /*
988 * Broadcast an RPC packet to hopefully contact some servers for a
989 * domain.
990 */
991 static int
992 broadcast(char *buf, int outlen)
993 {
994 struct ifaddrs *ifap, *ifa;
995 struct sockaddr_in bindsin;
996 struct in_addr in;
997
998 (void)memset(&bindsin, 0, sizeof bindsin);
999 bindsin.sin_family = AF_INET;
1000 bindsin.sin_len = sizeof(bindsin);
1001 bindsin.sin_port = htons(PMAPPORT);
1002
1003 if (getifaddrs(&ifap) != 0) {
1004 yp_log(LOG_WARNING, "broadcast: getifaddrs: %s",
1005 strerror(errno));
1006 return (-1);
1007 }
1008 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1009 if (ifa->ifa_addr->sa_family != AF_INET)
1010 continue;
1011 if ((ifa->ifa_flags & IFF_UP) == 0)
1012 continue;
1013
1014 switch (ifa->ifa_flags & (IFF_LOOPBACK | IFF_BROADCAST)) {
1015 case IFF_BROADCAST:
1016 if (!ifa->ifa_broadaddr)
1017 continue;
1018 if (ifa->ifa_broadaddr->sa_family != AF_INET)
1019 continue;
1020 in = ((struct sockaddr_in *)(void *)ifa->ifa_broadaddr)->sin_addr;
1021 break;
1022 case IFF_LOOPBACK:
1023 in = ((struct sockaddr_in *)(void *)ifa->ifa_addr)->sin_addr;
1024 break;
1025 default:
1026 continue;
1027 }
1028
1029 bindsin.sin_addr = in;
1030 DPRINTF("broadcast %x\n", bindsin.sin_addr.s_addr);
1031 if (sendto(rpcsock, buf, outlen, 0,
1032 (struct sockaddr *)(void *)&bindsin,
1033 (socklen_t)bindsin.sin_len) == -1)
1034 yp_log(LOG_WARNING, "broadcast: sendto: %s",
1035 strerror(errno));
1036 }
1037 freeifaddrs(ifap);
1038 return (0);
1039 }
1040
1041 /*
1042 * Send an RPC packet to all the configured (in /var/yp/foo.ypservers)
1043 * servers for a domain.
1044 *
1045 * XXX: we should read and parse the file up front and reread it only
1046 * if it changes.
1047 */
1048 static int
1049 direct(char *buf, int outlen, struct domain *dom)
1050 {
1051 const char *path;
1052 char line[_POSIX2_LINE_MAX];
1053 char *p;
1054 struct hostent *hp;
1055 struct sockaddr_in bindsin;
1056 int i, count = 0;
1057
1058 /*
1059 * XXX what happens if someone's editor unlinks and replaces
1060 * the servers file?
1061 */
1062
1063 if (dom->dom_serversfile != NULL) {
1064 rewind(dom->dom_serversfile);
1065 } else {
1066 path = ypservers_filename(dom->dom_name);
1067 dom->dom_serversfile = fopen(path, "r");
1068 if (dom->dom_serversfile == NULL) {
1069 /*
1070 * XXX there should be a time restriction on
1071 * this (and/or on trying the open) so we
1072 * don't flood the log. Or should we fall back
1073 * to broadcast mode?
1074 */
1075 yp_log(LOG_ERR, "%s: %s", path,
1076 strerror(errno));
1077 return -1;
1078 }
1079 }
1080
1081 (void)memset(&bindsin, 0, sizeof bindsin);
1082 bindsin.sin_family = AF_INET;
1083 bindsin.sin_len = sizeof(bindsin);
1084 bindsin.sin_port = htons(PMAPPORT);
1085
1086 while (fgets(line, (int)sizeof(line), dom->dom_serversfile) != NULL) {
1087 /* skip lines that are too big */
1088 p = strchr(line, '\n');
1089 if (p == NULL) {
1090 int c;
1091
1092 while ((c = getc(dom->dom_serversfile)) != '\n' && c != EOF)
1093 ;
1094 continue;
1095 }
1096 *p = '\0';
1097 p = line;
1098 while (isspace((unsigned char)*p))
1099 p++;
1100 if (*p == '#')
1101 continue;
1102 hp = gethostbyname(p);
1103 if (!hp) {
1104 yp_log(LOG_WARNING, "%s: %s", p, hstrerror(h_errno));
1105 continue;
1106 }
1107 /* step through all addresses in case first is unavailable */
1108 for (i = 0; hp->h_addr_list[i]; i++) {
1109 (void)memcpy(&bindsin.sin_addr, hp->h_addr_list[0],
1110 hp->h_length);
1111 if (sendto(rpcsock, buf, outlen, 0,
1112 (struct sockaddr *)(void *)&bindsin,
1113 (socklen_t)sizeof(bindsin)) < 0) {
1114 yp_log(LOG_WARNING, "direct: sendto: %s",
1115 strerror(errno));
1116 continue;
1117 } else
1118 count++;
1119 }
1120 }
1121 if (!count) {
1122 yp_log(LOG_WARNING, "No contactable servers found in %s",
1123 ypservers_filename(dom->dom_name));
1124 return -1;
1125 }
1126 return 0;
1127 }
1128
1129 /*
1130 * Send an RPC packet to the server that's been selected with ypset.
1131 * (This is only used when in broadcast mode and when ypset is
1132 * allowed.)
1133 */
1134 static int
1135 direct_set(char *buf, int outlen, struct domain *dom)
1136 {
1137 struct sockaddr_in bindsin;
1138 char path[MAXPATHLEN];
1139 struct iovec iov[2];
1140 struct ypbind_resp ybr;
1141 SVCXPRT dummy_svc;
1142 int fd;
1143 ssize_t bytes;
1144
1145 /*
1146 * Gack, we lose if binding file went away. We reset
1147 * "been_set" if this happens, otherwise we'll never
1148 * bind again.
1149 */
1150 (void)snprintf(path, sizeof(path), "%s/%s.%ld", BINDINGDIR,
1151 dom->dom_name, dom->dom_vers);
1152
1153 fd = open_locked(path, O_RDONLY, 0644);
1154 if (fd == -1) {
1155 yp_log(LOG_WARNING, "%s: %s", path, strerror(errno));
1156 dom->dom_been_ypset = 0;
1157 return -1;
1158 }
1159
1160 /* Read the binding file... */
1161 iov[0].iov_base = &(dummy_svc.xp_port);
1162 iov[0].iov_len = sizeof(dummy_svc.xp_port);
1163 iov[1].iov_base = &ybr;
1164 iov[1].iov_len = sizeof(ybr);
1165 bytes = readv(fd, iov, 2);
1166 (void)close(fd);
1167 if (bytes <0 || (size_t)bytes != (iov[0].iov_len + iov[1].iov_len)) {
1168 /* Binding file corrupt? */
1169 if (bytes < 0)
1170 yp_log(LOG_WARNING, "%s: %s", path, strerror(errno));
1171 else
1172 yp_log(LOG_WARNING, "%s: short read", path);
1173 dom->dom_been_ypset = 0;
1174 return -1;
1175 }
1176
1177 bindsin.sin_addr =
1178 ybr.ypbind_respbody.ypbind_bindinfo.ypbind_binding_addr;
1179
1180 if (sendto(rpcsock, buf, outlen, 0,
1181 (struct sockaddr *)(void *)&bindsin,
1182 (socklen_t)sizeof(bindsin)) < 0) {
1183 yp_log(LOG_WARNING, "direct_set: sendto: %s", strerror(errno));
1184 return -1;
1185 }
1186
1187 return 0;
1188 }
1189
1190 /*
1191 * Receive and dispatch packets on the general RPC socket.
1192 */
1193 static enum clnt_stat
1194 handle_replies(void)
1195 {
1196 char buf[BUFSIZE];
1197 socklen_t fromlen;
1198 ssize_t inlen;
1199 struct domain *dom;
1200 struct sockaddr_in raddr;
1201 struct rpc_msg msg;
1202 XDR xdr;
1203
1204 recv_again:
1205 DPRINTF("handle_replies receiving\n");
1206 (void)memset(&xdr, 0, sizeof(xdr));
1207 (void)memset(&msg, 0, sizeof(msg));
1208 msg.acpted_rply.ar_verf = _null_auth;
1209 msg.acpted_rply.ar_results.where = (caddr_t)(void *)&rmtcr;
1210 msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_rmtcallres;
1211
1212 try_again:
1213 fromlen = sizeof(struct sockaddr);
1214 inlen = recvfrom(rpcsock, buf, sizeof buf, 0,
1215 (struct sockaddr *)(void *)&raddr, &fromlen);
1216 if (inlen < 0) {
1217 if (errno == EINTR)
1218 goto try_again;
1219 DPRINTF("handle_replies: recvfrom failed (%s)\n",
1220 strerror(errno));
1221 return RPC_CANTRECV;
1222 }
1223 if ((size_t)inlen < sizeof(uint32_t))
1224 goto recv_again;
1225
1226 /*
1227 * see if reply transaction id matches sent id.
1228 * If so, decode the results.
1229 */
1230 xdrmem_create(&xdr, buf, (unsigned)inlen, XDR_DECODE);
1231 if (xdr_replymsg(&xdr, &msg)) {
1232 if ((msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
1233 (msg.acpted_rply.ar_stat == SUCCESS)) {
1234 raddr.sin_port = htons((uint16_t)rmtcr_port);
1235 dom = domain_find(msg.rm_xid);
1236 if (dom != NULL)
1237 rpc_received(dom->dom_name, &raddr, 0, 0);
1238 }
1239 }
1240 xdr.x_op = XDR_FREE;
1241 msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void;
1242 xdr_destroy(&xdr);
1243
1244 return RPC_SUCCESS;
1245 }
1246
1247 /*
1248 * Receive and dispatch packets on the ping socket.
1249 */
1250 static enum clnt_stat
1251 handle_ping(void)
1252 {
1253 char buf[BUFSIZE];
1254 socklen_t fromlen;
1255 ssize_t inlen;
1256 struct domain *dom;
1257 struct sockaddr_in raddr;
1258 struct rpc_msg msg;
1259 XDR xdr;
1260 bool_t res;
1261
1262 recv_again:
1263 DPRINTF("handle_ping receiving\n");
1264 (void)memset(&xdr, 0, sizeof(xdr));
1265 (void)memset(&msg, 0, sizeof(msg));
1266 msg.acpted_rply.ar_verf = _null_auth;
1267 msg.acpted_rply.ar_results.where = (caddr_t)(void *)&res;
1268 msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_bool;
1269
1270 try_again:
1271 fromlen = sizeof (struct sockaddr);
1272 inlen = recvfrom(pingsock, buf, sizeof buf, 0,
1273 (struct sockaddr *)(void *)&raddr, &fromlen);
1274 if (inlen < 0) {
1275 if (errno == EINTR)
1276 goto try_again;
1277 DPRINTF("handle_ping: recvfrom failed (%s)\n",
1278 strerror(errno));
1279 return RPC_CANTRECV;
1280 }
1281 if ((size_t)inlen < sizeof(uint32_t))
1282 goto recv_again;
1283
1284 /*
1285 * see if reply transaction id matches sent id.
1286 * If so, decode the results.
1287 */
1288 xdrmem_create(&xdr, buf, (unsigned)inlen, XDR_DECODE);
1289 if (xdr_replymsg(&xdr, &msg)) {
1290 if ((msg.rm_reply.rp_stat == MSG_ACCEPTED) &&
1291 (msg.acpted_rply.ar_stat == SUCCESS)) {
1292 dom = domain_find(msg.rm_xid);
1293 if (dom != NULL)
1294 rpc_received(dom->dom_name, &raddr, 0, 0);
1295 }
1296 }
1297 xdr.x_op = XDR_FREE;
1298 msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void;
1299 xdr_destroy(&xdr);
1300
1301 return RPC_SUCCESS;
1302 }
1303
1304 /*
1305 * Contact all known servers for a domain in the hopes that one of
1306 * them's awake. Also, if we previously had a binding but it timed
1307 * out, try the portmapper on that host in case ypserv moved ports for
1308 * some reason.
1309 *
1310 * As a side effect, wipe out any existing binding file.
1311 */
1312 static int
1313 nag_servers(struct domain *dom)
1314 {
1315 char *dom_name = dom->dom_name;
1316 struct rpc_msg msg;
1317 char buf[BUFSIZE];
1318 enum clnt_stat st;
1319 int outlen;
1320 AUTH *rpcua;
1321 XDR xdr;
1322
1323 DPRINTF("nag_servers\n");
1324 rmtca.xdr_args = (xdrproc_t)xdr_ypdomain_wrap_string;
1325 rmtca.args_ptr = (caddr_t)(void *)&dom_name;
1326
1327 (void)memset(&xdr, 0, sizeof xdr);
1328 (void)memset(&msg, 0, sizeof msg);
1329
1330 rpcua = authunix_create_default();
1331 if (rpcua == NULL) {
1332 DPRINTF("cannot get unix auth\n");
1333 return RPC_SYSTEMERROR;
1334 }
1335 msg.rm_direction = CALL;
1336 msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
1337 msg.rm_call.cb_prog = PMAPPROG;
1338 msg.rm_call.cb_vers = PMAPVERS;
1339 msg.rm_call.cb_proc = PMAPPROC_CALLIT;
1340 msg.rm_call.cb_cred = rpcua->ah_cred;
1341 msg.rm_call.cb_verf = rpcua->ah_verf;
1342
1343 msg.rm_xid = dom->dom_xid;
1344 xdrmem_create(&xdr, buf, (unsigned)sizeof(buf), XDR_ENCODE);
1345 if (!xdr_callmsg(&xdr, &msg)) {
1346 st = RPC_CANTENCODEARGS;
1347 AUTH_DESTROY(rpcua);
1348 return st;
1349 }
1350 if (!xdr_rmtcall_args(&xdr, &rmtca)) {
1351 st = RPC_CANTENCODEARGS;
1352 AUTH_DESTROY(rpcua);
1353 return st;
1354 }
1355 outlen = (int)xdr_getpos(&xdr);
1356 xdr_destroy(&xdr);
1357 if (outlen < 1) {
1358 st = RPC_CANTENCODEARGS;
1359 AUTH_DESTROY(rpcua);
1360 return st;
1361 }
1362 AUTH_DESTROY(rpcua);
1363
1364 if (dom->dom_lockfd != -1) {
1365 (void)close(dom->dom_lockfd);
1366 dom->dom_lockfd = -1;
1367 removelock(dom);
1368 }
1369
1370 if (dom->dom_state == DOM_PINGING || dom->dom_state == DOM_LOST) {
1371 /*
1372 * This resolves the following situation:
1373 * ypserver on other subnet was once bound,
1374 * but rebooted and is now using a different port
1375 */
1376 struct sockaddr_in bindsin;
1377
1378 (void)memset(&bindsin, 0, sizeof bindsin);
1379 bindsin.sin_family = AF_INET;
1380 bindsin.sin_len = sizeof(bindsin);
1381 bindsin.sin_port = htons(PMAPPORT);
1382 bindsin.sin_addr = dom->dom_server_addr.sin_addr;
1383
1384 if (sendto(rpcsock, buf, outlen, 0,
1385 (struct sockaddr *)(void *)&bindsin,
1386 (socklen_t)sizeof bindsin) == -1)
1387 yp_log(LOG_WARNING, "nag_servers: sendto: %s",
1388 strerror(errno));
1389 }
1390
1391 switch (dom->dom_ypbindmode) {
1392 case YPBIND_BROADCAST:
1393 if (dom->dom_been_ypset) {
1394 return direct_set(buf, outlen, dom);
1395 }
1396 return broadcast(buf, outlen);
1397
1398 case YPBIND_DIRECT:
1399 return direct(buf, outlen, dom);
1400 }
1401 /*NOTREACHED*/
1402 return -1;
1403 }
1404
1405 /*
1406 * Send a ping message to a domain's current ypserver.
1407 */
1408 static int
1409 ping(struct domain *dom)
1410 {
1411 char *dom_name = dom->dom_name;
1412 struct rpc_msg msg;
1413 char buf[BUFSIZE];
1414 enum clnt_stat st;
1415 int outlen;
1416 AUTH *rpcua;
1417 XDR xdr;
1418
1419 (void)memset(&xdr, 0, sizeof xdr);
1420 (void)memset(&msg, 0, sizeof msg);
1421
1422 rpcua = authunix_create_default();
1423 if (rpcua == NULL) {
1424 DPRINTF("cannot get unix auth\n");
1425 return RPC_SYSTEMERROR;
1426 }
1427
1428 msg.rm_direction = CALL;
1429 msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
1430 msg.rm_call.cb_prog = YPPROG;
1431 msg.rm_call.cb_vers = YPVERS;
1432 msg.rm_call.cb_proc = YPPROC_DOMAIN_NONACK;
1433 msg.rm_call.cb_cred = rpcua->ah_cred;
1434 msg.rm_call.cb_verf = rpcua->ah_verf;
1435
1436 msg.rm_xid = dom->dom_xid;
1437 xdrmem_create(&xdr, buf, (unsigned)sizeof(buf), XDR_ENCODE);
1438 if (!xdr_callmsg(&xdr, &msg)) {
1439 st = RPC_CANTENCODEARGS;
1440 AUTH_DESTROY(rpcua);
1441 return st;
1442 }
1443 if (!xdr_ypdomain_wrap_string(&xdr, &dom_name)) {
1444 st = RPC_CANTENCODEARGS;
1445 AUTH_DESTROY(rpcua);
1446 return st;
1447 }
1448 outlen = (int)xdr_getpos(&xdr);
1449 xdr_destroy(&xdr);
1450 if (outlen < 1) {
1451 st = RPC_CANTENCODEARGS;
1452 AUTH_DESTROY(rpcua);
1453 return st;
1454 }
1455 AUTH_DESTROY(rpcua);
1456
1457 DPRINTF("ping %x\n", dom->dom_server_addr.sin_addr.s_addr);
1458
1459 if (sendto(pingsock, buf, outlen, 0,
1460 (struct sockaddr *)(void *)&dom->dom_server_addr,
1461 (socklen_t)(sizeof dom->dom_server_addr)) == -1)
1462 yp_log(LOG_WARNING, "ping: sendto: %s", strerror(errno));
1463 return 0;
1464
1465 }
1466
1467 /*
1468 * Scan for timer-based work to do.
1469 *
1470 * If the domain is currently alive, ping the server we're currently
1471 * bound to. Otherwise, try all known servers and/or broadcast for a
1472 * server via nag_servers.
1473 *
1474 * Try again in five seconds.
1475 *
1476 * If we get back here and the state is still DOM_PINGING, it means
1477 * we didn't receive a ping response within five seconds. Declare the
1478 * binding lost. If the binding is already lost, and it's been lost
1479 * for 60 seconds, switch to DOM_DEAD and begin exponential backoff.
1480 * The exponential backoff starts at 10 seconds and tops out at one
1481 * hour; see above.
1482 */
1483 static void
1484 checkwork(void)
1485 {
1486 struct domain *dom;
1487 time_t t;
1488
1489 check = 0;
1490
1491 (void)time(&t);
1492 for (dom = domains; dom != NULL; dom = dom->dom_next) {
1493 if (dom->dom_checktime >= t) {
1494 continue;
1495 }
1496 switch (dom->dom_state) {
1497 case DOM_NEW:
1498 /* XXX should be a timeout for this state */
1499 dom->dom_checktime = t + 5;
1500 (void)nag_servers(dom);
1501 break;
1502
1503 case DOM_ALIVE:
1504 dom->dom_state = DOM_PINGING;
1505 dom->dom_checktime = t + 5;
1506 (void)ping(dom);
1507 break;
1508
1509 case DOM_PINGING:
1510 dom->dom_state = DOM_LOST;
1511 dom->dom_losttime = t;
1512 dom->dom_checktime = t + 5;
1513 (void)nag_servers(dom);
1514 break;
1515
1516 case DOM_LOST:
1517 if (t > dom->dom_losttime + 60) {
1518 dom->dom_state = DOM_DEAD;
1519 dom->dom_backofftime = 10;
1520 }
1521 dom->dom_checktime = t + 5;
1522 (void)nag_servers(dom);
1523 break;
1524
1525 case DOM_DEAD:
1526 dom->dom_checktime = t + dom->dom_backofftime;
1527 backoff(&dom->dom_backofftime);
1528 (void)nag_servers(dom);
1529 break;
1530 }
1531 /* re-fetch the time in case we hung sending packets */
1532 (void)time(&t);
1533 }
1534 }
1535
1536 ////////////////////////////////////////////////////////////
1537 // main
1538
1539 /*
1540 * Usage message.
1541 */
1542 __dead static void
1543 usage(void)
1544 {
1545 const char *opt = "";
1546 #ifdef DEBUG
1547 opt = " [-d]";
1548 #endif
1549
1550 (void)fprintf(stderr,
1551 "Usage: %s [-broadcast] [-insecure] [-ypset] [-ypsetme]%s\n",
1552 getprogname(), opt);
1553 exit(1);
1554 }
1555
1556 /*
1557 * Main.
1558 */
1559 int
1560 main(int argc, char *argv[])
1561 {
1562 struct timeval tv;
1563 fd_set fdsr;
1564 int width, lockfd;
1565 int started = 0;
1566 char *domainname;
1567
1568 setprogname(argv[0]);
1569
1570 /*
1571 * Process arguments.
1572 */
1573
1574 default_ypbindmode = YPBIND_DIRECT;
1575 while (--argc) {
1576 ++argv;
1577 if (!strcmp("-insecure", *argv)) {
1578 insecure = 1;
1579 } else if (!strcmp("-ypset", *argv)) {
1580 allow_any_ypset = 1;
1581 allow_local_ypset = 1;
1582 } else if (!strcmp("-ypsetme", *argv)) {
1583 allow_any_ypset = 0;
1584 allow_local_ypset = 1;
1585 } else if (!strcmp("-broadcast", *argv)) {
1586 default_ypbindmode = YPBIND_BROADCAST;
1587 #ifdef DEBUG
1588 } else if (!strcmp("-d", *argv)) {
1589 debug = 1;
1590 #endif
1591 } else {
1592 usage();
1593 }
1594 }
1595
1596 /*
1597 * Look up the name of the default domain.
1598 */
1599
1600 (void)yp_get_default_domain(&domainname);
1601 if (domainname[0] == '\0')
1602 errx(1, "Domainname not set. Aborting.");
1603 if (_yp_invalid_domain(domainname))
1604 errx(1, "Invalid domainname: %s", domainname);
1605
1606 /*
1607 * Start things up.
1608 */
1609
1610 /* Open the system log. */
1611 openlog("ypbind", LOG_PERROR | LOG_PID, LOG_DAEMON);
1612
1613 /* Acquire /var/run/ypbind.lock. */
1614 lockfd = open_locked(_PATH_YPBIND_LOCK, O_CREAT|O_RDWR|O_TRUNC, 0644);
1615 if (lockfd == -1)
1616 err(1, "Cannot create %s", _PATH_YPBIND_LOCK);
1617
1618 /* Initialize sunrpc stuff. */
1619 sunrpc_setup();
1620
1621 /* Clean out BINDINGDIR, deleting all existing (now stale) bindings */
1622 if (purge_bindingdir(BINDINGDIR) < 0)
1623 errx(1, "Unable to purge old bindings from %s", BINDINGDIR);
1624
1625 /*
1626 * We start with one binding, for the default domain. It starts
1627 * out "unsuccessful".
1628 *
1629 * XXX: domain_create adds the new domain to 'domains' (the
1630 * global linked list) and therefore we shouldn't assign
1631 * 'domains' again on return.
1632 */
1633
1634 domains = domain_create(domainname);
1635
1636 /*
1637 * Delete the lock for the default domain again, just in case something
1638 * magically caused it to appear since purge_bindingdir() was called.
1639 * XXX: this is useless and redundant; remove it.
1640 */
1641 removelock(domains);
1642
1643 /*
1644 * Main loop. Wake up at least once a second and check for
1645 * timer-based work to do (checkwork) and also handle incoming
1646 * responses from ypservers and any RPCs made to the ypbind
1647 * service.
1648 *
1649 * There are two sockets used for ypserver traffic: one for
1650 * pings and one for everything else. These call XDR manually
1651 * for encoding and are *not* dispatched via the sunrpc
1652 * libraries.
1653 *
1654 * The ypbind serivce *is* dispatched via the sunrpc libraries.
1655 * svc_getreqset() does whatever internal muck and ultimately
1656 * ypbind service calls arrive at ypbindprog_2().
1657 */
1658 checkwork();
1659 for (;;) {
1660 width = svc_maxfd;
1661 if (rpcsock > width)
1662 width = rpcsock;
1663 if (pingsock > width)
1664 width = pingsock;
1665 width++;
1666 fdsr = svc_fdset;
1667 FD_SET(rpcsock, &fdsr);
1668 FD_SET(pingsock, &fdsr);
1669 tv.tv_sec = 1;
1670 tv.tv_usec = 0;
1671
1672 switch (select(width, &fdsr, NULL, NULL, &tv)) {
1673 case 0:
1674 /* select timed out - check for timer-based work */
1675 checkwork();
1676 break;
1677 case -1:
1678 yp_log(LOG_WARNING, "select: %s", strerror(errno));
1679 break;
1680 default:
1681 /* incoming of our own; read it */
1682 if (FD_ISSET(rpcsock, &fdsr))
1683 (void)handle_replies();
1684 if (FD_ISSET(pingsock, &fdsr))
1685 (void)handle_ping();
1686
1687 /* read any incoming packets for the ypbind service */
1688 svc_getreqset(&fdsr);
1689
1690 /*
1691 * Only check for timer-based work if
1692 * something in the incoming RPC logic said
1693 * to. This might be just a hack to avoid
1694 * scanning the list unnecessarily, but I
1695 * suspect it's also a hack to cover wrong
1696 * state logic. - dholland 20140609
1697 */
1698 if (check)
1699 checkwork();
1700 break;
1701 }
1702
1703 /*
1704 * Defer daemonizing until the default domain binds
1705 * successfully. XXX: there seems to be no timeout
1706 * on this, which means that if the default domain
1707 * is dead upstream boot will hang indefinitely.
1708 */
1709 if (!started && domains->dom_state == DOM_ALIVE) {
1710 started = 1;
1711 #ifdef DEBUG
1712 if (!debug)
1713 #endif
1714 (void)daemon(0, 0);
1715 (void)pidfile(NULL);
1716 }
1717 }
1718 }
1719
1720