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