]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mountd/mountd.c
mountd: Unregister mountd if my_svc_run() returns
[nfs-utils.git] / utils / mountd / mountd.c
1 /*
2  * utils/mountd/mountd.c
3  *
4  * Authenticate mount requests and retrieve file handle.
5  *
6  * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
7  */
8
9 #ifdef HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <signal.h>
14 #include <sys/stat.h>
15 #include <netinet/in.h>
16 #include <arpa/inet.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <getopt.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <sys/resource.h>
24 #include <sys/wait.h>
25 #include "xmalloc.h"
26 #include "misc.h"
27 #include "mountd.h"
28 #include "rpcmisc.h"
29 #include "pseudoflavors.h"
30
31 extern void my_svc_run(void);
32
33 static void             usage(const char *, int exitcode);
34 static exports          get_exportlist(void);
35 static struct nfs_fh_len *get_rootfh(struct svc_req *, dirpath *, nfs_export **, mountstat3 *, int v3);
36
37 int reverse_resolve = 0;
38 int new_cache = 0;
39 int manage_gids;
40 int use_ipaddr = -1;
41
42 /* PRC: a high-availability callout program can be specified with -H
43  * When this is done, the program will receive callouts whenever clients
44  * send mount or unmount requests -- the callout is not needed for 2.6 kernel */
45 char *ha_callout_prog = NULL;
46
47 /* Number of mountd threads to start.   Default is 1 and
48  * that's probably enough unless you need hundreds of
49  * clients to be able to mount at once.  */
50 static int num_threads = 1;
51 /* Arbitrary limit on number of threads */
52 #define MAX_THREADS 64
53
54 static struct option longopts[] =
55 {
56         { "foreground", 0, 0, 'F' },
57         { "descriptors", 1, 0, 'o' },
58         { "debug", 1, 0, 'd' },
59         { "help", 0, 0, 'h' },
60         { "exports-file", 1, 0, 'f' },
61         { "nfs-version", 1, 0, 'V' },
62         { "no-nfs-version", 1, 0, 'N' },
63         { "version", 0, 0, 'v' },
64         { "port", 1, 0, 'p' },
65         { "no-tcp", 0, 0, 'n' },
66         { "ha-callout", 1, 0, 'H' },
67         { "state-directory-path", 1, 0, 's' },
68         { "num-threads", 1, 0, 't' },
69         { "reverse-lookup", 0, 0, 'r' },
70         { "manage-gids", 0, 0, 'g' },
71         { NULL, 0, 0, 0 }
72 };
73
74 #define NFSVERSBIT(vers)        (0x1 << (vers - 1))
75 #define NFSVERSBIT_ALL          (NFSVERSBIT(2) | NFSVERSBIT(3) | NFSVERSBIT(4))
76
77 static int nfs_version = NFSVERSBIT_ALL;
78
79 static int version2(void)
80 {
81         return nfs_version & NFSVERSBIT(2);
82 }
83
84 static int version3(void)
85 {
86         return nfs_version & NFSVERSBIT(3);
87 }
88
89 static int version23(void)
90 {
91         return nfs_version & (NFSVERSBIT(2) | NFSVERSBIT(3));
92 }
93
94 static int version_any(void)
95 {
96         return nfs_version & NFSVERSBIT_ALL;
97 }
98
99 static void
100 unregister_services (void)
101 {
102         if (version2()) {
103                 nfs_svc_unregister(MOUNTPROG, MOUNTVERS);
104                 nfs_svc_unregister(MOUNTPROG, MOUNTVERS_POSIX);
105         }
106         if (version3())
107                 nfs_svc_unregister(MOUNTPROG, MOUNTVERS_NFSV3);
108 }
109
110 static void
111 cleanup_lockfiles (void)
112 {
113         unlink(_PATH_XTABLCK);
114         unlink(_PATH_ETABLCK);
115         unlink(_PATH_RMTABLCK);
116 }
117
118 /* Wait for all worker child processes to exit and reap them */
119 static void
120 wait_for_workers (void)
121 {
122         int status;
123         pid_t pid;
124
125         for (;;) {
126
127                 pid = waitpid(0, &status, 0);
128
129                 if (pid < 0) {
130                         if (errno == ECHILD)
131                                 return; /* no more children */
132                         xlog(L_FATAL, "mountd: can't wait: %s\n",
133                                         strerror(errno));
134                 }
135
136                 /* Note: because we SIG_IGN'd SIGCHLD earlier, this
137                  * does not happen on 2.6 kernels, and waitpid() blocks
138                  * until all the children are dead then returns with
139                  * -ECHILD.  But, we don't need to do anything on the
140                  * death of individual workers, so we don't care. */
141                 xlog(L_NOTICE, "mountd: reaped child %d, status %d\n",
142                                 (int)pid, status);
143         }
144 }
145
146 /* Fork num_threads worker children and wait for them */
147 static void
148 fork_workers(void)
149 {
150         int i;
151         pid_t pid;
152
153         xlog(L_NOTICE, "mountd: starting %d threads\n", num_threads);
154
155         for (i = 0 ; i < num_threads ; i++) {
156                 pid = fork();
157                 if (pid < 0) {
158                         xlog(L_FATAL, "mountd: cannot fork: %s\n",
159                                         strerror(errno));
160                 }
161                 if (pid == 0) {
162                         /* worker child */
163
164                         /* Re-enable the default action on SIGTERM et al
165                          * so that workers die naturally when sent them.
166                          * Only the parent unregisters with pmap and
167                          * hence needs to do special SIGTERM handling. */
168                         struct sigaction sa;
169                         sa.sa_handler = SIG_DFL;
170                         sa.sa_flags = 0;
171                         sigemptyset(&sa.sa_mask);
172                         sigaction(SIGHUP, &sa, NULL);
173                         sigaction(SIGINT, &sa, NULL);
174                         sigaction(SIGTERM, &sa, NULL);
175
176                         /* fall into my_svc_run in caller */
177                         return;
178                 }
179         }
180
181         /* in parent */
182         wait_for_workers();
183         unregister_services();
184         cleanup_lockfiles();
185         xlog(L_NOTICE, "mountd: no more workers, exiting\n");
186         exit(0);
187 }
188
189 /*
190  * Signal handler.
191  */
192 static void 
193 killer (int sig)
194 {
195         unregister_services();
196         if (num_threads > 1) {
197                 /* play Kronos and eat our children */
198                 kill(0, SIGTERM);
199                 wait_for_workers();
200         }
201         cleanup_lockfiles();
202         xlog (L_FATAL, "Caught signal %d, un-registering and exiting.", sig);
203 }
204
205 static void
206 sig_hup (int sig)
207 {
208         /* don't exit on SIGHUP */
209         xlog (L_NOTICE, "Received SIGHUP... Ignoring.\n", sig);
210         return;
211 }
212
213 bool_t
214 mount_null_1_svc(struct svc_req *rqstp, void *UNUSED(argp), 
215         void *UNUSED(resp))
216 {
217         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
218         char buf[INET6_ADDRSTRLEN];
219
220         xlog(D_CALL, "Received NULL request from %s",
221                 host_ntop(sap, buf, sizeof(buf)));
222
223         return 1;
224 }
225
226 bool_t
227 mount_mnt_1_svc(struct svc_req *rqstp, dirpath *path, fhstatus *res)
228 {
229         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
230         char buf[INET6_ADDRSTRLEN];
231         struct nfs_fh_len *fh;
232
233         xlog(D_CALL, "Received MNT1(%s) request from %s", *path,
234                 host_ntop(sap, buf, sizeof(buf)));
235
236         fh = get_rootfh(rqstp, path, NULL, &res->fhs_status, 0);
237         if (fh)
238                 memcpy(&res->fhstatus_u.fhs_fhandle, fh->fh_handle, 32);
239         return 1;
240 }
241
242 bool_t
243 mount_dump_1_svc(struct svc_req *rqstp, void *UNUSED(argp), mountlist *res)
244 {
245         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
246         char buf[INET6_ADDRSTRLEN];
247
248         xlog(D_CALL, "Received DUMP request from %s",
249                 host_ntop(sap, buf, sizeof(buf)));
250
251         *res = mountlist_list();
252
253         return 1;
254 }
255
256 bool_t
257 mount_umnt_1_svc(struct svc_req *rqstp, dirpath *argp, void *UNUSED(resp))
258 {
259         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
260         nfs_export      *exp;
261         char            *p = *argp;
262         char            rpath[MAXPATHLEN+1];
263         char            buf[INET6_ADDRSTRLEN];
264
265         if (*p == '\0')
266                 p = "/";
267
268         if (realpath(p, rpath) != NULL) {
269                 rpath[sizeof (rpath) - 1] = '\0';
270                 p = rpath;
271         }
272
273         xlog(D_CALL, "Received UMNT(%s) request from %s", p,
274                 host_ntop(sap, buf, sizeof(buf)));
275
276         exp = auth_authenticate("unmount", sap, p);
277         if (exp == NULL)
278                 return 1;
279
280         mountlist_del(host_ntop(sap, buf, sizeof(buf)), p);
281         return 1;
282 }
283
284 bool_t
285 mount_umntall_1_svc(struct svc_req *rqstp, void *UNUSED(argp), 
286         void *UNUSED(resp))
287 {
288         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
289         char            buf[INET6_ADDRSTRLEN];
290
291         xlog(D_CALL, "Received UMNTALL request from %s",
292                 host_ntop(sap, buf, sizeof(buf)));
293
294         /* Reload /etc/xtab if necessary */
295         auth_reload();
296
297         mountlist_del_all(nfs_getrpccaller(rqstp->rq_xprt));
298         return 1;
299 }
300
301 bool_t
302 mount_export_1_svc(struct svc_req *rqstp, void *UNUSED(argp), exports *resp)
303 {
304         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
305         char buf[INET6_ADDRSTRLEN];
306
307         xlog(D_CALL, "Received EXPORT request from %s.",
308                 host_ntop(sap, buf, sizeof(buf)));
309
310         *resp = get_exportlist();
311                 
312         return 1;
313 }
314
315 bool_t
316 mount_exportall_1_svc(struct svc_req *rqstp, void *UNUSED(argp), exports *resp)
317 {
318         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
319         char buf[INET6_ADDRSTRLEN];
320
321         xlog(D_CALL, "Received EXPORTALL request from %s.",
322                 host_ntop(sap, buf, sizeof(buf)));
323
324         *resp = get_exportlist();
325
326         return 1;
327 }
328
329 /*
330  * MNTv2 pathconf procedure
331  *
332  * The protocol doesn't include a status field, so Sun apparently considers
333  * it good practice to let anyone snoop on your system, even if it's
334  * pretty harmless data such as pathconf. We don't.
335  *
336  * Besides, many of the pathconf values don't make much sense on NFS volumes.
337  * FIFOs and tty device files represent devices on the *client*, so there's
338  * no point in getting the server's buffer sizes etc.
339  */
340 bool_t
341 mount_pathconf_2_svc(struct svc_req *rqstp, dirpath *path, ppathcnf *res)
342 {
343         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
344         struct stat     stb;
345         nfs_export      *exp;
346         char            rpath[MAXPATHLEN+1];
347         char            *p = *path;
348         char buf[INET6_ADDRSTRLEN];
349
350         memset(res, 0, sizeof(*res));
351
352         if (*p == '\0')
353                 p = "/";
354
355         /* Reload /etc/xtab if necessary */
356         auth_reload();
357
358         /* Resolve symlinks */
359         if (realpath(p, rpath) != NULL) {
360                 rpath[sizeof (rpath) - 1] = '\0';
361                 p = rpath;
362         }
363
364         xlog(D_CALL, "Received PATHCONF(%s) request from %s", p,
365                 host_ntop(sap, buf, sizeof(buf)));
366
367         /* Now authenticate the intruder... */
368         exp = auth_authenticate("pathconf", sap, p);
369         if (exp == NULL)
370                 return 1;
371         else if (stat(p, &stb) < 0) {
372                 xlog(L_WARNING, "can't stat exported dir %s: %s",
373                                 p, strerror(errno));
374                 return 1;
375         }
376
377         res->pc_link_max  = pathconf(p, _PC_LINK_MAX);
378         res->pc_max_canon = pathconf(p, _PC_MAX_CANON);
379         res->pc_max_input = pathconf(p, _PC_MAX_INPUT);
380         res->pc_name_max  = pathconf(p, _PC_NAME_MAX);
381         res->pc_path_max  = pathconf(p, _PC_PATH_MAX);
382         res->pc_pipe_buf  = pathconf(p, _PC_PIPE_BUF);
383         res->pc_vdisable  = pathconf(p, _PC_VDISABLE);
384
385         /* Can't figure out what to do with pc_mask */
386         res->pc_mask[0]   = 0;
387         res->pc_mask[1]   = 0;
388
389         return 1;
390 }
391
392 /*
393  * We should advertise the preferred flavours first. (See RFC 2623
394  * section 2.7.)  We leave that to the administrator, by advertising
395  * flavours in the order they were listed in /etc/exports.  AUTH_NULL is
396  * dropped from the list to avoid backward compatibility issue with
397  * older Linux clients, who inspect the list in reversed order.
398  *
399  * XXX: It might be more helpful to rearrange these so that flavors
400  * giving more access (as determined from readonly and id-squashing
401  * options) come first.  (If we decide to do that we should probably do
402  * that when reading the exports rather than here.)
403  */
404 static void set_authflavors(struct mountres3_ok *ok, nfs_export *exp)
405 {
406         struct sec_entry *s;
407         static int flavors[SECFLAVOR_COUNT];
408         int i = 0;
409
410         for (s = exp->m_export.e_secinfo; s->flav; s++) {
411                 if (s->flav->fnum == AUTH_NULL)
412                         continue;
413                 flavors[i] = s->flav->fnum;
414                 i++;
415         }
416         if (i == 0) {
417                 /* default when there is no sec= option: */
418                 i = 1;
419                 flavors[0] = AUTH_UNIX;
420         }
421         ok->auth_flavors.auth_flavors_val = flavors;
422         ok->auth_flavors.auth_flavors_len = i;
423 }
424
425 /*
426  * NFSv3 MOUNT procedure
427  */
428 bool_t
429 mount_mnt_3_svc(struct svc_req *rqstp, dirpath *path, mountres3 *res)
430 {
431         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
432         struct mountres3_ok *ok = &res->mountres3_u.mountinfo;
433         char buf[INET6_ADDRSTRLEN];
434         nfs_export *exp;
435         struct nfs_fh_len *fh;
436
437         xlog(D_CALL, "Received MNT3(%s) request from %s", *path,
438                 host_ntop(sap, buf, sizeof(buf)));
439
440         fh = get_rootfh(rqstp, path, &exp, &res->fhs_status, 1);
441         if (!fh)
442                 return 1;
443
444         ok->fhandle.fhandle3_len = fh->fh_size;
445         ok->fhandle.fhandle3_val = (char *)fh->fh_handle;
446         set_authflavors(ok, exp);
447         return 1;
448 }
449
450 static struct nfs_fh_len *
451 get_rootfh(struct svc_req *rqstp, dirpath *path, nfs_export **expret,
452                 mountstat3 *error, int v3)
453 {
454         struct sockaddr *sap = nfs_getrpccaller(rqstp->rq_xprt);
455         struct stat     stb, estb;
456         nfs_export      *exp;
457         struct nfs_fh_len *fh;
458         char            rpath[MAXPATHLEN+1];
459         char            *p = *path;
460         char            buf[INET6_ADDRSTRLEN];
461
462         if (*p == '\0')
463                 p = "/";
464
465         /* Reload /var/lib/nfs/etab if necessary */
466         auth_reload();
467
468         /* Resolve symlinks */
469         if (realpath(p, rpath) != NULL) {
470                 rpath[sizeof (rpath) - 1] = '\0';
471                 p = rpath;
472         }
473
474         /* Now authenticate the intruder... */
475         exp = auth_authenticate("mount", sap, p);
476         if (exp == NULL) {
477                 *error = NFSERR_ACCES;
478                 return NULL;
479         }
480         if (stat(p, &stb) < 0) {
481                 xlog(L_WARNING, "can't stat exported dir %s: %s",
482                                 p, strerror(errno));
483                 if (errno == ENOENT)
484                         *error = NFSERR_NOENT;
485                 else
486                         *error = NFSERR_ACCES;
487                 return NULL;
488         }
489         if (!S_ISDIR(stb.st_mode) && !S_ISREG(stb.st_mode)) {
490                 xlog(L_WARNING, "%s is not a directory or regular file", p);
491                 *error = NFSERR_NOTDIR;
492                 return NULL;
493         }
494         if (stat(exp->m_export.e_path, &estb) < 0) {
495                 xlog(L_WARNING, "can't stat export point %s: %s",
496                      p, strerror(errno));
497                 *error = NFSERR_NOENT;
498                 return NULL;
499         }
500         if (estb.st_dev != stb.st_dev
501                    && (!new_cache
502                            || !(exp->m_export.e_flags & NFSEXP_CROSSMOUNT))) {
503                 xlog(L_WARNING, "request to export directory %s below nearest filesystem %s",
504                      p, exp->m_export.e_path);
505                 *error = NFSERR_ACCES;
506                 return NULL;
507         }
508         if (exp->m_export.e_mountpoint &&
509                    !is_mountpoint(exp->m_export.e_mountpoint[0]?
510                                   exp->m_export.e_mountpoint:
511                                   exp->m_export.e_path)) {
512                 xlog(L_WARNING, "request to export an unmounted filesystem: %s",
513                      p);
514                 *error = NFSERR_NOENT;
515                 return NULL;
516         }
517
518         if (new_cache) {
519                 /* This will be a static private nfs_export with just one
520                  * address.  We feed it to kernel then extract the filehandle,
521                  * 
522                  */
523
524                 if (cache_export(exp, p)) {
525                         *error = NFSERR_ACCES;
526                         return NULL;
527                 }
528                 fh = cache_get_filehandle(exp, v3?64:32, p);
529                 if (fh == NULL) {
530                         *error = NFSERR_ACCES;
531                         return NULL;
532                 }
533         } else {
534                 int did_export = 0;
535         retry:
536                 if (exp->m_exported<1) {
537                         export_export(exp);
538                         did_export = 1;
539                 }
540                 if (!exp->m_xtabent)
541                         xtab_append(exp);
542
543                 if (v3)
544                         fh = getfh_size((struct sockaddr_in *)sap, p, 64);
545                 if (!v3 || (fh == NULL && errno == EINVAL)) {
546                         /* We first try the new nfs syscall. */
547                         fh = getfh((struct sockaddr_in *)sap, p);
548                         if (fh == NULL && errno == EINVAL)
549                                 /* Let's try the old one. */
550                                 fh = getfh_old((struct sockaddr_in *)sap,
551                                                 stb.st_dev, stb.st_ino);
552                 }
553                 if (fh == NULL && !did_export) {
554                         exp->m_exported = 0;
555                         goto retry;
556                 }
557
558                 if (fh == NULL) {
559                         xlog(L_WARNING, "getfh failed: %s", strerror(errno));
560                         *error = NFSERR_ACCES;
561                         return NULL;
562                 }
563         }
564         *error = NFS_OK;
565         mountlist_add(host_ntop(sap, buf, sizeof(buf)), p);
566         if (expret)
567                 *expret = exp;
568         return fh;
569 }
570
571 static void remove_all_clients(exportnode *e)
572 {
573         struct groupnode *g, *ng;
574
575         for (g = e->ex_groups; g; g = ng) {
576                 ng = g->gr_next;
577                 xfree(g->gr_name);
578                 xfree(g);
579         }
580         e->ex_groups = NULL;
581 }
582
583 static void free_exportlist(exports *elist)
584 {
585         struct exportnode *e, *ne;
586
587         for (e = *elist; e != NULL; e = ne) {
588                 ne = e->ex_next;
589                 remove_all_clients(e);
590                 xfree(e->ex_dir);
591                 xfree(e);
592         }
593         *elist = NULL;
594 }
595
596 static void prune_clients(nfs_export *exp, struct exportnode *e)
597 {
598         struct addrinfo *ai = NULL;
599         struct groupnode *c, **cp;
600
601         cp = &e->ex_groups;
602         while ((c = *cp) != NULL) {
603                 if (client_gettype(c->gr_name) == MCL_FQDN
604                     && (ai = host_addrinfo(c->gr_name))) {
605                         if (client_check(exp->m_client, ai)) {
606                                 *cp = c->gr_next;
607                                 xfree(c->gr_name);
608                                 xfree(c);
609                                 freeaddrinfo(ai);
610                                 continue;
611                         }
612                         freeaddrinfo(ai);
613                 }
614                 cp = &(c->gr_next);
615         }
616 }
617
618 static exportnode *lookup_or_create_elist_entry(exports *elist, nfs_export *exp)
619 {
620         exportnode *e;
621
622         for (e = *elist; e != NULL; e = e->ex_next) {
623                 if (!strcmp(exp->m_export.e_path, e->ex_dir))
624                         return e;
625         }
626         e = xmalloc(sizeof(*e));
627         e->ex_next = *elist;
628         e->ex_groups = NULL;
629         e->ex_dir = xstrdup(exp->m_export.e_path);
630         *elist = e;
631         return e;
632 }
633
634 static void insert_group(struct exportnode *e, char *newname)
635 {
636         struct groupnode *g;
637
638         for (g = e->ex_groups; g; g = g->gr_next)
639                 if (strcmp(g->gr_name, newname))
640                         return;
641
642         g = xmalloc(sizeof(*g));
643         g->gr_name = xstrdup(newname);
644         g->gr_next = e->ex_groups;
645         e->ex_groups = g;
646 }
647
648 static exports
649 get_exportlist(void)
650 {
651         static exports          elist = NULL;
652         struct exportnode       *e;
653         nfs_export              *exp;
654         int                     i;
655         static unsigned int     ecounter;
656         unsigned int            acounter;
657
658         acounter = auth_reload();
659         if (elist && acounter == ecounter)
660                 return elist;
661
662         ecounter = acounter;
663
664         free_exportlist(&elist);
665
666         for (i = 0; i < MCL_MAXTYPES; i++) {
667                 for (exp = exportlist[i].p_head; exp; exp = exp->m_next) {
668                          /* Don't show pseudo exports */
669                         if (exp->m_export.e_flags & NFSEXP_V4ROOT)
670                                 continue;
671                         e = lookup_or_create_elist_entry(&elist, exp);
672
673                         /* exports to "*" absorb any others */
674                         if (i == MCL_ANONYMOUS && e->ex_groups) {
675                                 remove_all_clients(e);
676                                 continue;
677                         }
678                         /* non-FQDN's absorb FQDN's they contain: */
679                         if (i != MCL_FQDN && e->ex_groups)
680                                 prune_clients(exp, e);
681
682                         if (exp->m_export.e_hostname[0] != '\0')
683                                 insert_group(e, exp->m_export.e_hostname);
684                 }
685         }
686
687         return elist;
688 }
689
690 int
691 main(int argc, char **argv)
692 {
693         char    *export_file = _PATH_EXPORTS;
694         char    *state_dir = NFS_STATEDIR;
695         unsigned int listeners = 0;
696         int     foreground = 0;
697         int     port = 0;
698         int     descriptors = 0;
699         int     c;
700         int     vers;
701         struct sigaction sa;
702         struct rlimit rlim;
703
704         /* Parse the command line options and arguments. */
705         opterr = 0;
706         while ((c = getopt_long(argc, argv, "o:nFd:f:p:P:hH:N:V:vrs:t:g", longopts, NULL)) != EOF)
707                 switch (c) {
708                 case 'g':
709                         manage_gids = 1;
710                         break;
711                 case 'o':
712                         descriptors = atoi(optarg);
713                         if (descriptors <= 0) {
714                                 fprintf(stderr, "%s: bad descriptors: %s\n",
715                                         argv [0], optarg);
716                                 usage(argv [0], 1);
717                         }
718                         break;
719                 case 'F':
720                         foreground = 1;
721                         break;
722                 case 'd':
723                         xlog_sconfig(optarg, 1);
724                         break;
725                 case 'f':
726                         export_file = optarg;
727                         break;
728                 case 'H': /* PRC: specify a high-availability callout program */
729                         ha_callout_prog = optarg;
730                         break;
731                 case 'h':
732                         usage(argv [0], 0);
733                         break;
734                 case 'P':       /* XXX for nfs-server compatibility */
735                 case 'p':
736                         port = atoi(optarg);
737                         if (port <= 0 || port > 65535) {
738                                 fprintf(stderr, "%s: bad port number: %s\n",
739                                         argv [0], optarg);
740                                 usage(argv [0], 1);
741                         }
742                         break;
743                 case 'N':
744                         vers = atoi(optarg);
745                         if (vers < 2 || vers > 4) {
746                                 fprintf(stderr, "%s: bad version number: %s\n",
747                                         argv[0], optarg);
748                                 usage(argv[0], 1);
749                         }
750                         nfs_version &= ~NFSVERSBIT(vers);
751                         break;
752                 case 'n':
753                         _rpcfdtype = SOCK_DGRAM;
754                         break;
755                 case 'r':
756                         reverse_resolve = 1;
757                         break;
758                 case 's':
759                         if ((state_dir = xstrdup(optarg)) == NULL) {
760                                 fprintf(stderr, "%s: xstrdup(%s) failed!\n",
761                                         argv[0], optarg);
762                                 exit(1);
763                         }
764                         break;
765                 case 't':
766                         num_threads = atoi (optarg);
767                         break;
768                 case 'V':
769                         vers = atoi(optarg);
770                         if (vers < 2 || vers > 4) {
771                                 fprintf(stderr, "%s: bad version number: %s\n",
772                                         argv[0], optarg);
773                                 usage(argv[0], 1);
774                         }
775                         nfs_version |= NFSVERSBIT(vers);
776                         break;
777                 case 'v':
778                         printf("kmountd %s\n", VERSION);
779                         exit(0);
780                 case 0:
781                         break;
782                 case '?':
783                 default:
784                         usage(argv [0], 1);
785                 }
786
787         /* No more arguments allowed.
788          * Require at least one valid version (2, 3, or 4)
789          */
790         if (optind != argc || !version_any())
791                 usage(argv [0], 1);
792
793         if (chdir(state_dir)) {
794                 fprintf(stderr, "%s: chdir(%s) failed: %s\n",
795                         argv [0], state_dir, strerror(errno));
796                 exit(1);
797         }
798
799         if (getrlimit (RLIMIT_NOFILE, &rlim) != 0)
800                 fprintf(stderr, "%s: getrlimit (RLIMIT_NOFILE) failed: %s\n",
801                                 argv [0], strerror(errno));
802         else {
803                 /* glibc sunrpc code dies if getdtablesize > FD_SETSIZE */
804                 if ((descriptors == 0 && rlim.rlim_cur > FD_SETSIZE) ||
805                     descriptors > FD_SETSIZE)
806                         descriptors = FD_SETSIZE;
807                 if (descriptors) {
808                         rlim.rlim_cur = descriptors;
809                         if (setrlimit (RLIMIT_NOFILE, &rlim) != 0) {
810                                 fprintf(stderr, "%s: setrlimit (RLIMIT_NOFILE) failed: %s\n",
811                                         argv [0], strerror(errno));
812                                 exit(1);
813                         }
814                 }
815         }
816         /* Initialize logging. */
817         if (!foreground) xlog_stderr(0);
818         xlog_open("mountd");
819
820         sa.sa_handler = SIG_IGN;
821         sa.sa_flags = 0;
822         sigemptyset(&sa.sa_mask);
823         sigaction(SIGHUP, &sa, NULL);
824         sigaction(SIGINT, &sa, NULL);
825         sigaction(SIGTERM, &sa, NULL);
826         sigaction(SIGPIPE, &sa, NULL);
827         /* WARNING: the following works on Linux and SysV, but not BSD! */
828         sigaction(SIGCHLD, &sa, NULL);
829
830         /* Daemons should close all extra filehandles ... *before* RPC init. */
831         if (!foreground)
832                 closeall(3);
833
834         new_cache = check_new_cache();
835         if (new_cache)
836                 cache_open();
837
838         if (version2()) {
839                 listeners += nfs_svc_create("mountd", MOUNTPROG,
840                                         MOUNTVERS, mount_dispatch, port);
841                 listeners += nfs_svc_create("mountd", MOUNTPROG,
842                                         MOUNTVERS_POSIX, mount_dispatch, port);
843         }
844         if (version3())
845                 listeners += nfs_svc_create("mountd", MOUNTPROG,
846                                         MOUNTVERS_NFSV3, mount_dispatch, port);
847         if (version23() && listeners == 0)
848                 xlog(L_FATAL, "mountd: could not create listeners\n");
849
850         sa.sa_handler = killer;
851         sigaction(SIGINT, &sa, NULL);
852         sigaction(SIGTERM, &sa, NULL);
853         sa.sa_handler = sig_hup;
854         sigaction(SIGHUP, &sa, NULL);
855
856         auth_init(export_file);
857
858         if (!foreground) {
859                 /* We first fork off a child. */
860                 if ((c = fork()) > 0)
861                         exit(0);
862                 if (c < 0) {
863                         xlog(L_FATAL, "mountd: cannot fork: %s\n",
864                                                 strerror(errno));
865                 }
866                 /* Now we remove ourselves from the foreground.
867                    Redirect stdin/stdout/stderr first. */
868                 {
869                         int fd = open("/dev/null", O_RDWR);
870                         (void) dup2(fd, 0);
871                         (void) dup2(fd, 1);
872                         (void) dup2(fd, 2);
873                         if (fd > 2) (void) close(fd);
874                 }
875                 setsid();
876         }
877
878         /* silently bounds check num_threads */
879         if (foreground)
880                 num_threads = 1;
881         else if (num_threads < 1)
882                 num_threads = 1;
883         else if (num_threads > MAX_THREADS)
884                 num_threads = MAX_THREADS;
885
886         if (num_threads > 1)
887                 fork_workers();
888
889         my_svc_run();
890
891         xlog(L_ERROR, "RPC service loop terminated unexpectedly. Exiting...\n");
892         unregister_services();
893         exit(1);
894 }
895
896 static void
897 usage(const char *prog, int n)
898 {
899         fprintf(stderr,
900 "Usage: %s [-F|--foreground] [-h|--help] [-v|--version] [-d kind|--debug kind]\n"
901 "       [-o num|--descriptors num] [-f exports-file|--exports-file=file]\n"
902 "       [-p|--port port] [-V version|--nfs-version version]\n"
903 "       [-N version|--no-nfs-version version] [-n|--no-tcp]\n"
904 "       [-H ha-callout-prog] [-s|--state-directory-path path]\n"
905 "       [-g|--manage-gids] [-t num|--num-threads=num]\n", prog);
906         exit(n);
907 }