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