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