xref: /freebsd/usr.sbin/yppush/yppush_main.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1995
5  *	Bill Paul <wpaul@ctr.columbia.edu>.  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  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Bill Paul.
18  * 4. Neither the name of the author nor the names of any co-contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <strings.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <sys/socket.h>
45 #include <sys/fcntl.h>
46 #include <sys/wait.h>
47 #include <sys/param.h>
48 #include <rpc/rpc.h>
49 #include <rpc/clnt.h>
50 #include <rpc/pmap_clnt.h>
51 #include <rpcsvc/yp.h>
52 #include <rpcsvc/ypclnt.h>
53 #include "ypxfr_extern.h"
54 #include "yppush_extern.h"
55 
56 char *progname = "yppush";
57 int debug = 1;
58 int _rpcpmstart = 0;
59 char *yp_dir = _PATH_YP;
60 
61 static char *yppush_mapname = NULL;	/* Map to transfer. */
62 static char *yppush_domain = NULL;	/* Domain in which map resides. */
63 static char *yppush_master = NULL;	/* Master NIS server for said domain. */
64 static int skip_master = 0;		/* Do not attempt to push map to master. */
65 static int verbose = 0;		/* Toggle verbose mode. */
66 static unsigned long yppush_transid = 0;
67 static int yppush_timeout = 80;	/* Default timeout. */
68 static int yppush_jobs = 1;		/* Number of allowed concurrent jobs. */
69 static int yppush_running_jobs = 0;	/* Number of currently running jobs. */
70 
71 /* Structure for holding information about a running job. */
72 struct jobs {
73 	unsigned long tid;
74 	int port;
75 	ypxfrstat stat;
76 	unsigned long prognum;
77 	char *server;
78 	char *map;
79 	int polled;
80 	struct jobs *next;
81 };
82 
83 static struct jobs *yppush_joblist;	/* Linked list of running jobs. */
84 static int yppush_svc_run(int);
85 
86 /*
87  * Local error messages.
88  */
89 static const char *
90 yppusherr_string(int err)
91 {
92 	switch (err) {
93 	case YPPUSH_TIMEDOUT:
94 		return("transfer or callback timed out");
95 	case YPPUSH_YPSERV:
96 		return("failed to contact ypserv");
97 	case YPPUSH_NOHOST:
98 		return("no such host");
99 	case YPPUSH_PMAP:
100 		return("portmapper failure");
101 	default:
102 		return("unknown error code");
103 	}
104 }
105 
106 /*
107  * Report state of a job.
108  */
109 static int
110 yppush_show_status(ypxfrstat status, unsigned long tid)
111 {
112 	struct jobs *job;
113 
114 	job = yppush_joblist;
115 
116 	while (job != NULL) {
117 		if (job->tid == tid)
118 			break;
119 		job = job->next;
120 	}
121 
122 	if (job == NULL) {
123 		yp_error("warning: received callback with invalid transaction ID: %lu",
124 			 tid);
125 		return (0);
126 	}
127 
128 	if (job->polled) {
129 		yp_error("warning: received callback with duplicate transaction ID: %lu",
130 			 tid);
131 		return (0);
132 	}
133 
134 	if (verbose > 1) {
135 		yp_error("checking return status: transaction ID: %lu",
136 								job->tid);
137 	}
138 
139 	if (status != YPXFR_SUCC || verbose) {
140 		yp_error("transfer of map %s to server %s %s",
141 		 	job->map, job->server, status == YPXFR_SUCC ?
142 		 	"succeeded" : "failed");
143 		yp_error("status returned by ypxfr: %s", status > YPXFR_AGE ?
144 			yppusherr_string(status) :
145 			ypxfrerr_string(status));
146 	}
147 
148 	job->polled = 1;
149 
150 	svc_unregister(job->prognum, 1);
151 
152 	yppush_running_jobs--;
153 	return(0);
154 }
155 
156 /* Exit routine. */
157 static void
158 yppush_exit(int now)
159 {
160 	struct jobs *jptr;
161 	int still_pending = 1;
162 
163 	/* Let all the information trickle in. */
164 	while (!now && still_pending) {
165 		jptr = yppush_joblist;
166 		still_pending = 0;
167 		while (jptr) {
168 			if (jptr->polled == 0) {
169 				still_pending++;
170 				if (verbose > 1)
171 					yp_error("%s has not responded",
172 						  jptr->server);
173 			} else {
174 				if (verbose > 1)
175 					yp_error("%s has responded",
176 						  jptr->server);
177 			}
178 			jptr = jptr->next;
179 		}
180 		if (still_pending) {
181 			if (verbose > 1)
182 				yp_error("%d transfer%sstill pending",
183 					still_pending,
184 					still_pending > 1 ? "s " : " ");
185 			if (yppush_svc_run (YPPUSH_RESPONSE_TIMEOUT) == 0) {
186 				yp_error("timed out");
187 				now = 1;
188 			}
189 		} else {
190 			if (verbose)
191 				yp_error("all transfers complete");
192 			break;
193 		}
194 	}
195 
196 
197 	/* All stats collected and reported -- kill all the stragglers. */
198 	jptr = yppush_joblist;
199 	while (jptr) {
200 		if (!jptr->polled)
201 			yp_error("warning: exiting with transfer \
202 to %s (transid = %lu) still pending", jptr->server, jptr->tid);
203 		svc_unregister(jptr->prognum, 1);
204 		jptr = jptr->next;
205 	}
206 
207 	exit(0);
208 }
209 
210 /*
211  * Handler for 'normal' signals.
212  */
213 
214 static void
215 handler(int sig)
216 {
217 	yppush_exit (1);
218 	return;
219 }
220 
221 /*
222  * Dispatch loop for callback RPC services.
223  * Return value:
224  *   -1 error
225  *    0 timeout
226  *   >0 request serviced
227  */
228 static int
229 yppush_svc_run(int timeout_secs)
230 {
231 	int rc;
232 	fd_set readfds;
233 	struct timeval timeout;
234 
235 	timeout.tv_usec = 0;
236 	timeout.tv_sec = timeout_secs;
237 
238 retry:
239 	readfds = svc_fdset;
240 	rc = select(svc_maxfd + 1, &readfds, NULL, NULL, &timeout);
241 	switch (rc) {
242 	case -1:
243 		if (errno == EINTR)
244 			goto retry;
245 		yp_error("select failed: %s", strerror(errno));
246 		break;
247 	case 0:
248 		yp_error("select() timed out");
249 		break;
250 	default:
251 		svc_getreqset(&readfds);
252 		break;
253 	}
254 	return rc;
255 }
256 
257 /*
258  * RPC service routines for callbacks.
259  */
260 void *
261 yppushproc_null_1_svc(void *argp, struct svc_req *rqstp)
262 {
263 	static char * result;
264 	/* Do nothing -- RPC conventions call for all a null proc. */
265 	return((void *) &result);
266 }
267 
268 void *
269 yppushproc_xfrresp_1_svc(yppushresp_xfr *argp, struct svc_req *rqstp)
270 {
271 	static char * result;
272 	yppush_show_status(argp->status, argp->transid);
273 	return((void *) &result);
274 }
275 
276 /*
277  * Transmit a YPPROC_XFR request to ypserv.
278  */
279 static int
280 yppush_send_xfr(struct jobs *job)
281 {
282 	ypreq_xfr req;
283 /*	ypresp_xfr *resp; */
284 	DBT key, data;
285 	CLIENT *clnt;
286 	struct rpc_err err;
287 	struct timeval timeout;
288 
289 	timeout.tv_usec = 0;
290 	timeout.tv_sec = 0;
291 
292 	/*
293 	 * The ypreq_xfr structure has a member of type map_parms,
294 	 * which seems to require the order number of the map.
295 	 * It isn't actually used at the other end (at least the
296 	 * FreeBSD ypserv doesn't use it) but we fill it in here
297 	 * for the sake of completeness.
298 	 */
299 	key.data = "YP_LAST_MODIFIED";
300 	key.size = sizeof ("YP_LAST_MODIFIED") - 1;
301 
302 	if (yp_get_record(yppush_domain, yppush_mapname, &key, &data,
303 			  1) != YP_TRUE) {
304 		yp_error("failed to read order number from %s: %s: %s",
305 			  yppush_mapname, yperr_string(yp_errno),
306 			  strerror(errno));
307 		return(1);
308 	}
309 
310 	/* Fill in the request arguments */
311 	req.map_parms.ordernum = atoi(data.data);
312 	req.map_parms.domain = yppush_domain;
313 	req.map_parms.peer = yppush_master;
314 	req.map_parms.map = job->map;
315 	req.transid = job->tid;
316 	req.prog = job->prognum;
317 	req.port = job->port;
318 
319 	/* Get a handle to the remote ypserv. */
320 	if ((clnt = clnt_create(job->server, YPPROG, YPVERS, "udp")) == NULL) {
321 		yp_error("%s: %s",job->server,clnt_spcreateerror("couldn't \
322 create udp handle to NIS server"));
323 		switch (rpc_createerr.cf_stat) {
324 			case RPC_UNKNOWNHOST:
325 				job->stat = YPPUSH_NOHOST;
326 				break;
327 			case RPC_PMAPFAILURE:
328 				job->stat = YPPUSH_PMAP;
329 				break;
330 			default:
331 				job->stat = YPPUSH_RPC;
332 				break;
333 			}
334 		return(1);
335 	}
336 
337 	/*
338 	 * Reduce timeout to nothing since we may not
339 	 * get a response from ypserv and we don't want to block.
340 	 */
341 	if (clnt_control(clnt, CLSET_TIMEOUT, (char *)&timeout) == FALSE)
342 		yp_error("failed to set timeout on ypproc_xfr call");
343 
344 	/* Invoke the ypproc_xfr service. */
345 	if (ypproc_xfr_2(&req, clnt) == NULL) {
346 		clnt_geterr(clnt, &err);
347 		if (err.re_status != RPC_SUCCESS &&
348 		    err.re_status != RPC_TIMEDOUT) {
349 			yp_error("%s: %s", job->server, clnt_sperror(clnt,
350 							"yp_xfr failed"));
351 			job->stat = YPPUSH_YPSERV;
352 			clnt_destroy(clnt);
353 			return(1);
354 		}
355 	}
356 
357 	clnt_destroy(clnt);
358 
359 	return(0);
360 }
361 
362 /*
363  * Main driver function. Register the callback service, add the transfer
364  * request to the internal list, send the YPPROC_XFR request to ypserv
365  * do other magic things.
366  */
367 static int
368 yp_push(char *server, char *map, unsigned long tid)
369 {
370 	unsigned long prognum;
371 	int sock = RPC_ANYSOCK;
372 	SVCXPRT *xprt;
373 	struct jobs *job;
374 
375 	/* Register the job in our linked list of jobs. */
376 
377 	/* First allocate job structure */
378 	if ((job = (struct jobs *)malloc(sizeof (struct jobs))) == NULL) {
379 		yp_error("malloc failed");
380 		yppush_exit (1);
381 	}
382 
383 	/*
384 	 * Register the callback service on the first free transient
385 	 * program number.
386 	 */
387 	xprt = svcudp_create(sock);
388 	for (prognum = 0x40000000; prognum < 0x5FFFFFFF; prognum++) {
389 		if (svc_register(xprt, prognum, 1,
390 		    yppush_xfrrespprog_1, IPPROTO_UDP) == TRUE)
391 			break;
392 	}
393 	if (prognum == 0x5FFFFFFF) {
394 		yp_error ("can't register yppush_xfrrespprog_1");
395 		yppush_exit (1);
396 	}
397 
398 	/* Initialize the info for this job. */
399 	job->stat = 0;
400 	job->tid = tid;
401 	job->port = xprt->xp_port;
402 	job->server = strdup(server);
403 	job->map = strdup(map);
404 	job->prognum = prognum;
405 	job->polled = 0;
406 	job->next = yppush_joblist;
407 	yppush_joblist = job;
408 
409 	if (verbose) {
410 		yp_error("initiating transfer: %s -> %s (transid = %lu)",
411 			yppush_mapname, server, tid);
412 	}
413 
414 	/*
415 	 * Send the XFR request to ypserv. We don't have to wait for
416 	 * a response here since we handle them asynchronously.
417 	 */
418 
419 	if (yppush_send_xfr(job)){
420 		/* Transfer request blew up. */
421 		yppush_show_status(job->stat ? job->stat :
422 			YPPUSH_YPSERV,job->tid);
423 	} else {
424 		if (verbose > 1)
425 			yp_error("%s has been called", server);
426 	}
427 
428 	return(0);
429 }
430 
431 /*
432  * Called for each entry in the ypservers map from yp_get_map(), which
433  * is our private yp_all() routine.
434  */
435 static int
436 yppush_foreach(int status, char *key, int keylen, char *val, int vallen,
437     char *data)
438 {
439 	char *server;
440 
441 	if (status != YP_TRUE)
442 		return (status);
443 
444 	asprintf(&server, "%.*s", vallen, val);
445 
446 	/*
447 	 * Do not stop the iteration on the allocation failure.  We
448 	 * cannot usefully react on low memory condition anyway, and
449 	 * the failure is more likely due to insane val.
450 	 */
451 	if (server == NULL)
452 		return (0);
453 
454 	if (skip_master && strcasecmp(server, yppush_master) == 0) {
455 		free(server);
456 		return (0);
457 	}
458 
459 	/*
460 	 * Restrict the number of concurrent jobs: if yppush_jobs number
461 	 * of jobs have already been dispatched and are still pending,
462 	 * wait for one of them to finish so we can reuse its slot.
463 	 */
464 	while (yppush_running_jobs >= yppush_jobs && (yppush_svc_run (yppush_timeout) > 0))
465 		;
466 
467 	/* Cleared for takeoff: set everything in motion. */
468 	if (yp_push(server, yppush_mapname, yppush_transid)) {
469 		free(server);
470 		return(yp_errno);
471 	}
472 
473 	/* Bump the job counter and transaction ID. */
474 	yppush_running_jobs++;
475 	yppush_transid++;
476 	free(server);
477 	return (0);
478 }
479 
480 static void
481 usage()
482 {
483 	fprintf (stderr, "%s\n%s\n",
484 	"usage: yppush [-d domain] [-t timeout] [-j #parallel jobs] [-h host]",
485 	"              [-p path] mapname");
486 	exit(1);
487 }
488 
489 /*
490  * Entry point. (About time!)
491  */
492 int
493 main(int argc, char *argv[])
494 {
495 	int ch;
496 	DBT key, data;
497 	char myname[MAXHOSTNAMELEN];
498 	struct hostlist {
499 		char *name;
500 		struct hostlist *next;
501 	};
502 	struct hostlist *yppush_hostlist = NULL;
503 	struct hostlist *tmp;
504 
505 	while ((ch = getopt(argc, argv, "d:j:p:h:t:v")) != -1) {
506 		switch (ch) {
507 		case 'd':
508 			yppush_domain = optarg;
509 			break;
510 		case 'j':
511 			yppush_jobs = atoi(optarg);
512 			if (yppush_jobs <= 0)
513 				yppush_jobs = 1;
514 			break;
515 		case 'p':
516 			yp_dir = optarg;
517 			break;
518 		case 'h': /* we can handle multiple hosts */
519 			if ((tmp = (struct hostlist *)malloc(sizeof(struct hostlist))) == NULL) {
520 				yp_error("malloc failed");
521 				yppush_exit(1);
522 			}
523 			tmp->name = strdup(optarg);
524 			tmp->next = yppush_hostlist;
525 			yppush_hostlist = tmp;
526 			break;
527 		case 't':
528 			yppush_timeout = atoi(optarg);
529 			break;
530 		case 'v':
531 			verbose++;
532 			break;
533 		default:
534 			usage();
535 			break;
536 		}
537 	}
538 
539 	argc -= optind;
540 	argv += optind;
541 
542 	yppush_mapname = argv[0];
543 
544 	if (yppush_mapname == NULL) {
545 	/* "No guts, no glory." */
546 		usage();
547 	}
548 
549 	/*
550 	 * If no domain was specified, try to find the default
551 	 * domain. If we can't find that, we're doomed and must bail.
552 	 */
553 	if (yppush_domain == NULL) {
554 		char *yppush_check_domain;
555 		if (!yp_get_default_domain(&yppush_check_domain) &&
556 			!_yp_check(&yppush_check_domain)) {
557 			yp_error("no domain specified and NIS not running");
558 			usage();
559 		} else
560 			yp_get_default_domain(&yppush_domain);
561 	}
562 
563 	/* Check to see that we are the master for this map. */
564 
565 	if (gethostname ((char *)&myname, sizeof(myname))) {
566 		yp_error("failed to get name of local host: %s",
567 			strerror(errno));
568 		yppush_exit(1);
569 	}
570 
571 	key.data = "YP_MASTER_NAME";
572 	key.size = sizeof("YP_MASTER_NAME") - 1;
573 
574 	if (yp_get_record(yppush_domain, yppush_mapname,
575 			  &key, &data, 1) != YP_TRUE) {
576 		yp_error("couldn't open %s map: %s", yppush_mapname,
577 			 strerror(errno));
578 		yppush_exit(1);
579 	}
580 
581 	if (strncasecmp(myname, data.data, data.size) == 0) {
582 		/* I am master server, and no explicit host list was
583 		   specified: do not push map to myself -- this will
584 		   fail with YPPUSH_AGE anyway. */
585 		if (yppush_hostlist == NULL)
586 			skip_master = 1;
587 	} else {
588 		yp_error("warning: this host is not the master for %s",
589 							yppush_mapname);
590 #ifdef NITPICKY
591 		yppush_exit(1);
592 #endif
593 	}
594 
595 	yppush_master = malloc(data.size + 1);
596 	strncpy(yppush_master, data.data, data.size);
597 	yppush_master[data.size] = '\0';
598 
599 	/* Install some handy handlers. */
600 	signal(SIGTERM, handler);
601 	signal(SIGINT, handler);
602 
603 	/* set initial transaction ID */
604 	yppush_transid = time((time_t *)NULL);
605 
606 	if (yppush_hostlist) {
607 	/*
608 	 * Host list was specified on the command line:
609 	 * kick off the transfers by hand.
610 	 */
611 		tmp = yppush_hostlist;
612 		while (tmp) {
613 			yppush_foreach(YP_TRUE, NULL, 0, tmp->name,
614 			    strlen(tmp->name), NULL);
615 			tmp = tmp->next;
616 		}
617 	} else {
618 	/*
619 	 * Do a yp_all() on the ypservers map and initiate a ypxfr
620 	 * for each one.
621 	 */
622 		ypxfr_get_map("ypservers", yppush_domain,
623 			      "localhost", yppush_foreach);
624 	}
625 
626 	if (verbose > 1)
627 		yp_error("all jobs dispatched");
628 
629 	/* All done -- normal exit. */
630 	yppush_exit(0);
631 
632 	/* Just in case. */
633 	exit(0);
634 }
635