]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mount/mount.c
mount.nfs: Replace fork() with daemon() for backgrounding mounts
[nfs-utils.git] / utils / mount / mount.c
1 /*
2  * mount.c -- Linux NFS mount
3  *
4  * Copyright (C) 2006 Amit Gud <agud@redhat.com>
5  *
6  * - Basic code and wrapper around mount and umount code of NFS.
7  *   Based on util-linux/mount/mount.c.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2, or (at your option)
12  * any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  */
20
21 #include "config.h"
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <sys/mount.h>
29 #include <sys/utsname.h>
30 #include <getopt.h>
31 #include <mntent.h>
32 #include <pwd.h>
33
34 #include "fstab.h"
35 #include "xcommon.h"
36 #include "nls.h"
37 #include "mount_constants.h"
38 #include "nfs_paths.h"
39
40 #include "nfs_mount.h"
41 #include "nfs4_mount.h"
42 #include "mount.h"
43 #include "error.h"
44 #include "network.h"
45 #include "stropts.h"
46
47 char *progname;
48 int nfs_mount_data_version;
49 int nomtab;
50 int verbose;
51 int sloppy;
52 int string;
53
54 #define FOREGROUND      (0)
55 #define BACKGROUND      (1)
56
57 static struct option longopts[] = {
58   { "fake", 0, 0, 'f' },
59   { "help", 0, 0, 'h' },
60   { "no-mtab", 0, 0, 'n' },
61   { "read-only", 0, 0, 'r' },
62   { "ro", 0, 0, 'r' },
63   { "verbose", 0, 0, 'v' },
64   { "version", 0, 0, 'V' },
65   { "read-write", 0, 0, 'w' },
66   { "rw", 0, 0, 'w' },
67   { "string", 0, 0, 'i' },
68   { "options", 1, 0, 'o' },
69   { NULL, 0, 0, 0 }
70 };
71
72 /*
73  * Map from -o and fstab option strings to the flag argument to mount(2).
74  */
75 struct opt_map {
76         const char *opt;        /* option name */
77         int skip;               /* skip in mtab option string */
78         int inv;                /* true if flag value should be inverted */
79         int mask;               /* flag mask value */
80 };
81
82 static const struct opt_map opt_map[] = {
83   { "defaults", 0, 0, 0         },      /* default options */
84   { "ro",       1, 0, MS_RDONLY },      /* read-only */
85   { "rw",       1, 1, MS_RDONLY },      /* read-write */
86   { "exec",     0, 1, MS_NOEXEC },      /* permit execution of binaries */
87   { "noexec",   0, 0, MS_NOEXEC },      /* don't execute binaries */
88   { "suid",     0, 1, MS_NOSUID },      /* honor suid executables */
89   { "nosuid",   0, 0, MS_NOSUID },      /* don't honor suid executables */
90   { "dev",      0, 1, MS_NODEV  },      /* interpret device files  */
91   { "nodev",    0, 0, MS_NODEV  },      /* don't interpret devices */
92   { "sync",     0, 0, MS_SYNCHRONOUS},  /* synchronous I/O */
93   { "async",    0, 1, MS_SYNCHRONOUS},  /* asynchronous I/O */
94   { "dirsync",  0, 0, MS_DIRSYNC},      /* synchronous directory modifications */
95   { "remount",  0, 0, MS_REMOUNT},      /* Alter flags of mounted FS */
96   { "bind",     0, 0, MS_BIND   },      /* Remount part of tree elsewhere */
97   { "rbind",    0, 0, MS_BIND|MS_REC }, /* Idem, plus mounted subtrees */
98   { "auto",     0, 0, MS_DUMMY },       /* Can be mounted using -a */
99   { "noauto",   0, 0, MS_DUMMY },       /* Can  only be mounted explicitly */
100   { "users",    1, 0, MS_USERS },       /* Allow ordinary user to mount */
101   { "nousers",  0, 1, MS_DUMMY  },      /* Forbid ordinary user to mount */
102   { "user",     1, 0, MS_USER  },       /* Allow ordinary user to mount */
103   { "nouser",   0, 1, MS_DUMMY   },     /* Forbid ordinary user to mount */
104   { "owner",    0, 0, MS_DUMMY  },      /* Let the owner of the device mount */
105   { "noowner",  0, 0, MS_DUMMY  },      /* Device owner has no special privs */
106   { "group",    0, 0, MS_DUMMY  },      /* Let the group of the device mount */
107   { "nogroup",  0, 0, MS_DUMMY  },      /* Device group has no special privs */
108   { "_netdev",  0, 0, MS_DUMMY},        /* Device requires network */
109   { "comment",  0, 0, MS_DUMMY},        /* fstab comment only (kudzu,_netdev)*/
110
111   /* add new options here */
112 #ifdef MS_NOSUB
113   { "sub",      0, 1, MS_NOSUB  },      /* allow submounts */
114   { "nosub",    0, 0, MS_NOSUB  },      /* don't allow submounts */
115 #endif
116 #ifdef MS_SILENT
117   { "quiet",    0, 0, MS_SILENT    },   /* be quiet  */
118   { "loud",     0, 1, MS_SILENT    },   /* print out messages. */
119 #endif
120 #ifdef MS_MANDLOCK
121   { "mand",     0, 0, MS_MANDLOCK },    /* Allow mandatory locks on this FS */
122   { "nomand",   0, 1, MS_MANDLOCK },    /* Forbid mandatory locks on this FS */
123 #endif
124   { "loop",     1, 0, MS_DUMMY   },      /* use a loop device */
125 #ifdef MS_NOATIME
126   { "atime",    0, 1, MS_NOATIME },     /* Update access time */
127   { "noatime",  0, 0, MS_NOATIME },     /* Do not update access time */
128 #endif
129 #ifdef MS_NODIRATIME
130   { "diratime", 0, 1, MS_NODIRATIME },  /* Update dir access times */
131   { "nodiratime", 0, 0, MS_NODIRATIME },/* Do not update dir access times */
132 #endif
133   { NULL,       0, 0, 0         }
134 };
135
136 #define MAKE_VERSION(p,q,r)     (65536 * (p) + 256 * (q) + (r))
137
138 int linux_version_code(void)
139 {
140         struct utsname my_utsname;
141         int p, q, r;
142
143         if (uname(&my_utsname) == 0) {
144                 p = atoi(strtok(my_utsname.release, "."));
145                 q = atoi(strtok(NULL, "."));
146                 r = atoi(strtok(NULL, "."));
147                 return MAKE_VERSION(p,q,r);
148         }
149         return 0;
150 }
151
152 /*
153  * Choose the version of the nfs_mount_data structure that is appropriate
154  * for the kernel that is doing the mount.
155  *
156  * NFS_MOUNT_VERSION:           maximum version supported by these sources
157  * nfs_mount_data_version:      maximum version supported by the running kernel
158  */
159 static void discover_nfs_mount_data_version(void)
160 {
161         int kernel_version = linux_version_code();
162
163         if (kernel_version) {
164                 if (kernel_version < MAKE_VERSION(2, 1, 32))
165                         nfs_mount_data_version = 1;
166                 else if (kernel_version < MAKE_VERSION(2, 2, 18))
167                         nfs_mount_data_version = 3;
168                 else if (kernel_version < MAKE_VERSION(2, 3, 0))
169                         nfs_mount_data_version = 4;
170                 else if (kernel_version < MAKE_VERSION(2, 3, 99))
171                         nfs_mount_data_version = 3;
172                 else if (kernel_version < MAKE_VERSION(2, 6, 3))
173                         nfs_mount_data_version = 4;
174                 else
175                         nfs_mount_data_version = 6;
176         }
177         if (nfs_mount_data_version > NFS_MOUNT_VERSION)
178                 nfs_mount_data_version = NFS_MOUNT_VERSION;
179 }
180
181 static void print_one(char *spec, char *node, char *type, char *opts)
182 {
183         if (!verbose)
184                 return;
185
186         if (opts)
187                 printf(_("%s on %s type %s (%s)\n"), spec, node, type, opts);
188         else
189                 printf(_("%s on %s type %s\n"), spec, node, type);
190 }
191
192 /*
193  * Build a canonical mount option string for /etc/mtab.
194  */
195 static char *fix_opts_string(int flags, const char *extra_opts)
196 {
197         const struct opt_map *om;
198         char *new_opts;
199
200         new_opts = xstrdup((flags & MS_RDONLY) ? "ro" : "rw");
201         if (flags & MS_USER) {
202                 /* record who mounted this so they can unmount */
203                 struct passwd *pw = getpwuid(getuid());
204                 if(pw)
205                         new_opts = xstrconcat3(new_opts, ",user=", pw->pw_name);
206         }
207         if (flags & MS_USERS)
208                 new_opts = xstrconcat3(new_opts, ",users", "");
209         
210         for (om = opt_map; om->opt != NULL; om++) {
211                 if (om->skip)
212                         continue;
213                 if (om->inv || !om->mask || (flags & om->mask) != om->mask)
214                         continue;
215                 new_opts = xstrconcat3(new_opts, ",", om->opt);
216                 flags &= ~om->mask;
217         }
218         if (extra_opts && *extra_opts) {
219                 new_opts = xstrconcat3(new_opts, ",", extra_opts);
220         }
221         return new_opts;
222 }
223
224 static int add_mtab(char *spec, char *mount_point, char *fstype,
225                         int flags, char *opts, int freq, int pass)
226 {
227         struct mntent ment;
228         FILE *mtab;
229         int result = EX_FILEIO;
230
231         ment.mnt_fsname = spec;
232         ment.mnt_dir = mount_point;
233         ment.mnt_type = fstype;
234         ment.mnt_opts = fix_opts_string(flags, opts);
235         ment.mnt_freq = freq;
236         ment.mnt_passno = pass;
237
238         if (flags & MS_REMOUNT) {
239                 update_mtab(ment.mnt_dir, &ment);
240                 return 0;
241         }
242
243         lock_mtab();
244
245         if ((mtab = setmntent(MOUNTED, "a+")) == NULL) {
246                 unlock_mtab();
247                 nfs_error(_("Can't open mtab: %s"),
248                                 strerror(errno));
249                 goto fail_unlock;
250         }
251
252         if (addmntent(mtab, &ment) == 1) {
253                 nfs_error(_("Can't write mount entry to mtab: %s"),
254                                 strerror(errno));
255                 goto fail_close;
256         }
257
258         if (fchmod(fileno(mtab), 0644) == -1) {
259                 nfs_error(_("Can't set permissions on mtab: %s"),
260                                 strerror(errno));
261                 goto fail_close;
262         }
263
264         result = 0;
265
266 fail_close:
267         endmntent(mtab);
268 fail_unlock:
269         unlock_mtab();
270
271         return result;
272 }
273
274 void mount_usage(void)
275 {
276         printf(_("usage: %s remotetarget dir [-rvVwfnsih] [-o nfsoptions]\n"),
277                 progname);
278         printf(_("options:\n"));
279         printf(_("\t-r\t\tMount file system readonly\n"));
280         printf(_("\t-v\t\tVerbose\n"));
281         printf(_("\t-V\t\tPrint version\n"));
282         printf(_("\t-w\t\tMount file system read-write\n"));
283         printf(_("\t-f\t\tFake mount, do not actually mount\n"));
284         printf(_("\t-n\t\tDo not update /etc/mtab\n"));
285         printf(_("\t-s\t\tTolerate sloppy mount options rather than fail\n"));
286         printf(_("\t-i\t\tPass mount options to the kernel via a string\n"));
287         printf(_("\t-h\t\tPrint this help\n"));
288         printf(_("\tnfsoptions\tRefer to mount.nfs(8) or nfs(5)\n\n"));
289 }
290
291 static void parse_opt(const char *opt, int *mask, char *extra_opts, int len)
292 {
293         const struct opt_map *om;
294
295         for (om = opt_map; om->opt != NULL; om++) {
296                 if (!strcmp (opt, om->opt)) {
297                         if (om->inv)
298                                 *mask &= ~om->mask;
299                         else
300                                 *mask |= om->mask;
301                         return;
302                 }
303         }
304
305         len -= strlen(extra_opts);
306
307         if (*extra_opts && --len > 0)
308                 strcat(extra_opts, ",");
309
310         if ((len -= strlen(opt)) > 0)
311                 strcat(extra_opts, opt);
312 }
313
314 /*
315  * Convert the provided mount command-line options into the 4th &
316  * 5th arguments to mount(2).  Output parameter "@flags" gets the
317  * standard options (indicated by MS_ bits), and output parameter
318  * "@extra_opts" gets all the filesystem-specific options.
319  */
320 static void parse_opts(const char *options, int *flags, char **extra_opts)
321 {
322         if (options != NULL) {
323                 char *opts = xstrdup(options);
324                 char *opt, *p;
325                 int len = strlen(opts) + 1;     /* include room for a null */
326                 int open_quote = 0;
327
328                 *extra_opts = xmalloc(len);
329                 **extra_opts = '\0';
330
331                 for (p = opts, opt = NULL; p && *p; p++) {
332                         if (!opt)
333                                 opt = p;        /* begin of the option item */
334                         if (*p == '"')
335                                 open_quote ^= 1; /* reverse the status */
336                         if (open_quote)
337                                 continue;       /* still in a quoted block */
338                         if (*p == ',')
339                                 *p = '\0';      /* terminate the option item */
340
341                         /* end of option item or last item */
342                         if (*p == '\0' || *(p + 1) == '\0') {
343                                 parse_opt(opt, flags, *extra_opts, len);
344                                 opt = NULL;
345                         }
346                 }
347                 free(opts);
348         }
349 }
350
351 static int chk_mountpoint(char *mount_point)
352 {
353         struct stat sb;
354
355         if (stat(mount_point, &sb) < 0){
356                 mount_error(NULL, mount_point, errno);
357                 return 1;
358         }
359         if (S_ISDIR(sb.st_mode) == 0){
360                 mount_error(NULL, mount_point, ENOTDIR);
361                 return 1;
362         }
363         if (access(mount_point, X_OK) < 0) {
364                 mount_error(NULL, mount_point, errno);
365                 return 1;
366         }
367
368         return 0;
369 }
370
371 static int try_mount(char *spec, char *mount_point, int flags,
372                         char *fs_type, char **extra_opts, char *mount_opts,
373                         int fake, int nomtab, int bg)
374 {
375         int ret;
376
377         if (string) {
378                 if (strcmp(fs_type, "nfs4") == 0)
379                         ret = nfs4mount_s(spec, mount_point, flags,
380                                                 extra_opts, fake, bg);
381                 else
382                         ret = nfsmount_s(spec, mount_point, flags,
383                                                 extra_opts, fake, bg);
384         } else {
385                 if (strcmp(fs_type, "nfs4") == 0)
386                         ret = nfs4mount(spec, mount_point, flags,
387                                         extra_opts, fake, bg);
388                 else
389                         ret = nfsmount(spec, mount_point, flags,
390                                         extra_opts, fake, bg);
391         }
392
393         if (ret)
394                 return ret;
395
396         if (!fake)
397                 print_one(spec, mount_point, fs_type, mount_opts);
398
399         if (!nomtab)
400                 ret = add_mtab(spec, mount_point, fs_type, flags, *extra_opts,
401                                 0, 0 /* these are always zero for NFS */ );
402         return ret;
403 }
404
405 int main(int argc, char *argv[])
406 {
407         int c, flags = 0, mnt_err = 1, fake = 0;
408         char *spec, *mount_point, *fs_type = "nfs";
409         char *extra_opts = NULL, *mount_opts = NULL;
410         uid_t uid = getuid();
411
412         progname = basename(argv[0]);
413
414         discover_nfs_mount_data_version();
415
416         if(!strncmp(progname, "umount", strlen("umount")))
417                 exit(nfsumount(argc, argv));
418
419         if (argv[1] && argv[1][0] == '-') {
420                 if(argv[1][1] == 'V')
421                         printf("%s ("PACKAGE_STRING")\n", progname);
422                 else
423                         mount_usage();
424                 exit(0);
425         }
426
427         if ((argc < 3)) {
428                 mount_usage();
429                 exit(EX_USAGE);
430         }
431
432         spec = argv[1];
433         mount_point = argv[2];
434
435         argv[2] = argv[0]; /* so that getopt error messages are correct */
436         while ((c = getopt_long(argc - 2, argv + 2, "rvVwfno:hsi",
437                                 longopts, NULL)) != -1) {
438                 switch (c) {
439                 case 'r':
440                         flags |= MS_RDONLY;
441                         break;
442                 case 'v':
443                         ++verbose;
444                         break;
445                 case 'V':
446                         printf("%s: ("PACKAGE_STRING")\n", progname);
447                         exit(0);
448                 case 'w':
449                         flags &= ~MS_RDONLY;
450                         break;
451                 case 'f':
452                         ++fake;
453                         break;
454                 case 'n':
455                         ++nomtab;
456                         break;
457                 case 'o':              /* specify mount options */
458                         if (mount_opts)
459                                 mount_opts = xstrconcat3(mount_opts, ",", optarg);
460                         else
461                                 mount_opts = xstrdup(optarg);
462                         break;
463                 case 's':
464                         ++sloppy;
465                         break;
466                 case 'i':
467                         if (linux_version_code() < MAKE_VERSION(2, 6, 23)) {
468                                 nfs_error(_("%s: Passing mount options via a"
469                                         " string is unsupported by this"
470                                         " kernel\n"), progname);
471                                 exit(EX_USAGE);
472                         }
473                         if (uid != 0) {
474                                 nfs_error(_("%s: -i option is restricted to 'root'\n"),
475                                         progname);
476                                 exit(EX_USAGE);
477                         }
478                         ++string;
479                         break;
480                 case 'h':
481                 default:
482                         mount_usage();
483                         exit(EX_USAGE);
484                 }
485         }
486
487         /*
488          * Extra non-option words at the end are bogus...
489          */
490         if (optind != argc - 2) {
491                 mount_usage();
492                 exit(EX_USAGE);
493         }
494
495         if (strcmp(progname, "mount.nfs4") == 0)
496                 fs_type = "nfs4";
497
498         /*
499          * If a non-root user is attempting to mount, make sure the
500          * user's requested options match the options specified in
501          * /etc/fstab; otherwise, don't allow the mount.
502          */
503         if (uid != 0) {
504                 struct mntentchn *mc;
505
506                 if ((mc = getfsfile(mount_point)) == NULL ||
507                     strcmp(mc->m.mnt_fsname, spec) != 0 ||
508                     strcmp(mc->m.mnt_type, fs_type) != 0) {
509                         nfs_error(_("%s: permission denied: no match for %s "
510                                 "found in /etc/fstab"), progname, mount_point);
511                         exit(EX_USAGE);
512                 }
513
514                 /*
515                  * 'mount' munges the options from fstab before passing them
516                  * to us, so it is non-trivial to test that we have the correct
517                  * set of options and we don't want to trust what the user
518                  * gave us, so just take whatever is in /etc/fstab.
519                  */
520                 mount_opts = strdup(mc->m.mnt_opts);
521         }
522
523         mount_point = canonicalize(mount_point);
524         if (!mount_point) {
525                 nfs_error(_("%s: no mount point provided"), progname);
526                 exit(EX_USAGE);
527         }
528         if (mount_point[0] != '/') {
529                 nfs_error(_("%s: unrecognized mount point %s"),
530                         progname, mount_point);
531                 mnt_err = EX_USAGE;
532                 goto out;
533         }
534
535         parse_opts(mount_opts, &flags, &extra_opts);
536
537         if (uid != 0) {
538                 if (!(flags & (MS_USERS|MS_USER))) {
539                         nfs_error(_("%s: permission denied"), progname);
540                         mnt_err = EX_USAGE;
541                         goto out;
542                 }
543         }
544
545         if (chk_mountpoint(mount_point)) {
546                 mnt_err = EX_USAGE;
547                 goto out;
548         }
549
550         mnt_err = try_mount(spec, mount_point, flags, fs_type, &extra_opts,
551                                 mount_opts, fake, nomtab, FOREGROUND);
552         if (mnt_err == EX_BG) {
553                 printf(_("%s: backgrounding \"%s\"\n"),
554                         progname, spec);
555                 fflush(stdout);
556
557                 /*
558                  * Parent exits immediately with success.
559                  */
560                 if (daemon(0, 0)) {
561                         nfs_error(_("%s: failed to start "
562                                         "background process: %s\n"),
563                                                 progname, strerror(errno));
564                         exit(EX_FAIL);
565                 }
566
567                 mnt_err = try_mount(spec, mount_point, flags, fs_type,
568                                         &extra_opts, mount_opts, fake,
569                                         nomtab, BACKGROUND);
570                 if (verbose && mnt_err)
571                         printf(_("%s: giving up \"%s\"\n"),
572                                 progname, spec);
573         }
574
575 out:
576         free(mount_point);
577         exit(mnt_err);
578 }