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