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