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