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