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