]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mount/mount.c
mount.nfs: Always preset nfs_mount_version
[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 "nfsumount.h"
43 #include "mount.h"
44 #include "error.h"
45
46 char *progname;
47 int nfs_mount_data_version;
48 int nomtab;
49 int verbose;
50 int sloppy;
51
52 static struct option longopts[] = {
53   { "fake", 0, 0, 'f' },
54   { "help", 0, 0, 'h' },
55   { "no-mtab", 0, 0, 'n' },
56   { "read-only", 0, 0, 'r' },
57   { "ro", 0, 0, 'r' },
58   { "verbose", 0, 0, 'v' },
59   { "version", 0, 0, 'V' },
60   { "read-write", 0, 0, 'w' },
61   { "rw", 0, 0, 'w' },
62   { "options", 1, 0, 'o' },
63   { NULL, 0, 0, 0 }
64 };
65
66 /* Map from -o and fstab option strings to the flag argument to mount(2).  */
67 struct opt_map {
68   const char *opt;              /* option name */
69   int  skip;                    /* skip in mtab option string */
70   int  inv;                     /* true if flag value should be inverted */
71   int  mask;                    /* flag mask value */
72 };
73
74 /* Custom mount options for our own purposes.  */
75 #define MS_DUMMY        0x00000000
76 #define MS_USERS        0x40000000
77 #define MS_USER         0x80000000
78
79 static const struct opt_map opt_map[] = {
80   { "defaults", 0, 0, 0         },      /* default options */
81   { "ro",       1, 0, MS_RDONLY },      /* read-only */
82   { "rw",       1, 1, MS_RDONLY },      /* read-write */
83   { "exec",     0, 1, MS_NOEXEC },      /* permit execution of binaries */
84   { "noexec",   0, 0, MS_NOEXEC },      /* don't execute binaries */
85   { "suid",     0, 1, MS_NOSUID },      /* honor suid executables */
86   { "nosuid",   0, 0, MS_NOSUID },      /* don't honor suid executables */
87   { "dev",      0, 1, MS_NODEV  },      /* interpret device files  */
88   { "nodev",    0, 0, MS_NODEV  },      /* don't interpret devices */
89   { "sync",     0, 0, MS_SYNCHRONOUS},  /* synchronous I/O */
90   { "async",    0, 1, MS_SYNCHRONOUS},  /* asynchronous I/O */
91   { "dirsync",  0, 0, MS_DIRSYNC},      /* synchronous directory modifications */
92   { "remount",  0, 0, MS_REMOUNT},      /* Alter flags of mounted FS */
93   { "bind",     0, 0, MS_BIND   },      /* Remount part of tree elsewhere */
94   { "rbind",    0, 0, MS_BIND|MS_REC }, /* Idem, plus mounted subtrees */
95   { "auto",     0, 0, MS_DUMMY },       /* Can be mounted using -a */
96   { "noauto",   0, 0, MS_DUMMY },       /* Can  only be mounted explicitly */
97   { "users",    1, 0, MS_USERS },       /* Allow ordinary user to mount */
98   { "nousers",  0, 1, MS_DUMMY  },      /* Forbid ordinary user to mount */
99   { "user",     1, 0, MS_USER  },       /* Allow ordinary user to mount */
100   { "nouser",   0, 1, MS_DUMMY   },     /* Forbid ordinary user to mount */
101   { "owner",    0, 0, MS_DUMMY  },      /* Let the owner of the device mount */
102   { "noowner",  0, 0, MS_DUMMY  },      /* Device owner has no special privs */
103   { "group",    0, 0, MS_DUMMY  },      /* Let the group of the device mount */
104   { "nogroup",  0, 0, MS_DUMMY  },      /* Device group has no special privs */
105   { "_netdev",  0, 0, MS_DUMMY},        /* Device requires network */
106   { "comment",  0, 0, MS_DUMMY},        /* fstab comment only (kudzu,_netdev)*/
107
108   /* add new options here */
109 #ifdef MS_NOSUB
110   { "sub",      0, 1, MS_NOSUB  },      /* allow submounts */
111   { "nosub",    0, 0, MS_NOSUB  },      /* don't allow submounts */
112 #endif
113 #ifdef MS_SILENT
114   { "quiet",    0, 0, MS_SILENT    },   /* be quiet  */
115   { "loud",     0, 1, MS_SILENT    },   /* print out messages. */
116 #endif
117 #ifdef MS_MANDLOCK
118   { "mand",     0, 0, MS_MANDLOCK },    /* Allow mandatory locks on this FS */
119   { "nomand",   0, 1, MS_MANDLOCK },    /* Forbid mandatory locks on this FS */
120 #endif
121   { "loop",     1, 0, MS_DUMMY   },      /* use a loop device */
122 #ifdef MS_NOATIME
123   { "atime",    0, 1, MS_NOATIME },     /* Update access time */
124   { "noatime",  0, 0, MS_NOATIME },     /* Do not update access time */
125 #endif
126 #ifdef MS_NODIRATIME
127   { "diratime", 0, 1, MS_NODIRATIME },  /* Update dir access times */
128   { "nodiratime", 0, 0, MS_NODIRATIME },/* Do not update dir access times */
129 #endif
130   { NULL,       0, 0, 0         }
131 };
132
133 #define MAKE_VERSION(p,q,r)     (65536 * (p) + 256 * (q) + (r))
134
135 int linux_version_code(void)
136 {
137         struct utsname my_utsname;
138         int p, q, r;
139
140         if (uname(&my_utsname) == 0) {
141                 p = atoi(strtok(my_utsname.release, "."));
142                 q = atoi(strtok(NULL, "."));
143                 r = atoi(strtok(NULL, "."));
144                 return MAKE_VERSION(p,q,r);
145         }
146         return 0;
147 }
148
149 /*
150  * Choose the version of the nfs_mount_data structure that is appropriate
151  * for the kernel that is doing the mount.
152  *
153  * NFS_MOUNT_VERSION:           maximum version supported by these sources
154  * nfs_mount_data_version:      maximum version supported by the running kernel
155  */
156 static void discover_nfs_mount_data_version(void)
157 {
158         int kernel_version = linux_version_code();
159
160         if (kernel_version) {
161                 if (kernel_version < MAKE_VERSION(2, 1, 32))
162                         nfs_mount_data_version = 1;
163                 else if (kernel_version < MAKE_VERSION(2, 2, 18))
164                         nfs_mount_data_version = 3;
165                 else if (kernel_version < MAKE_VERSION(2, 3, 0))
166                         nfs_mount_data_version = 4;
167                 else if (kernel_version < MAKE_VERSION(2, 3, 99))
168                         nfs_mount_data_version = 3;
169                 else if (kernel_version < MAKE_VERSION(2, 6, 3))
170                         nfs_mount_data_version = 4;
171                 else
172                         nfs_mount_data_version = 6;
173         }
174         if (nfs_mount_data_version > NFS_MOUNT_VERSION)
175                 nfs_mount_data_version = NFS_MOUNT_VERSION;
176 }
177
178 /* Try to build a canonical options string.  */
179 static char * fix_opts_string (int flags, const char *extra_opts) {
180         const struct opt_map *om;
181         char *new_opts;
182
183         new_opts = xstrdup((flags & MS_RDONLY) ? "ro" : "rw");
184         if (flags & MS_USER) {
185                 /* record who mounted this so they can unmount */
186                 struct passwd *pw = getpwuid(getuid());
187                 if(pw)
188                         new_opts = xstrconcat3(new_opts, ",user=", pw->pw_name);
189         }
190         if (flags & MS_USERS)
191                 new_opts = xstrconcat3(new_opts, ",users", "");
192         
193         for (om = opt_map; om->opt != NULL; om++) {
194                 if (om->skip)
195                         continue;
196                 if (om->inv || !om->mask || (flags & om->mask) != om->mask)
197                         continue;
198                 new_opts = xstrconcat3(new_opts, ",", om->opt);
199                 flags &= ~om->mask;
200         }
201         if (extra_opts && *extra_opts) {
202                 new_opts = xstrconcat3(new_opts, ",", extra_opts);
203         }
204         return new_opts;
205 }
206
207 static int add_mtab(char *spec, char *mount_point, char *fstype,
208                         int flags, char *opts, int freq, int pass)
209 {
210         struct mntent ment;
211         FILE *mtab;
212         int result = EX_FILEIO;
213
214         ment.mnt_fsname = spec;
215         ment.mnt_dir = mount_point;
216         ment.mnt_type = fstype;
217         ment.mnt_opts = fix_opts_string(flags, opts);
218         ment.mnt_freq = freq;
219         ment.mnt_passno = pass;
220
221         if (flags & MS_REMOUNT) {
222                 update_mtab(ment.mnt_dir, &ment);
223                 return 0;
224         }
225
226         lock_mtab();
227
228         if ((mtab = setmntent(MOUNTED, "a+")) == NULL) {
229                 unlock_mtab();
230                 nfs_error(_("Can't open mtab: %s"),
231                                 strerror(errno));
232                 goto fail_unlock;
233         }
234
235         if (addmntent(mtab, &ment) == 1) {
236                 nfs_error(_("Can't write mount entry to mtab: %s"),
237                                 strerror(errno));
238                 goto fail_close;
239         }
240
241         if (fchmod(fileno(mtab), 0644) == -1) {
242                 nfs_error(_("Can't set permissions on mtab: %s"),
243                                 strerror(errno));
244                 goto fail_close;
245         }
246
247         result = 0;
248
249 fail_close:
250         endmntent(mtab);
251 fail_unlock:
252         unlock_mtab();
253
254         return result;
255 }
256
257 int do_mount_syscall(char *spec, char *node, char *type, int flags, void *data)
258 {
259         return mount(spec, node, type, flags, data);
260 }
261
262 void mount_usage()
263 {
264         printf("usage: %s remotetarget dir [-rvVwfnh] [-o nfsoptions]\n",
265                 progname);
266         printf("options:\n");
267         printf("\t-r\t\tMount file system readonly\n");
268         printf("\t-v\t\tVerbose\n");
269         printf("\t-V\t\tPrint version\n");
270         printf("\t-w\t\tMount file system read-write\n");
271         printf("\t-f\t\tFake mount, do not actually mount\n");
272         printf("\t-n\t\tDo not update /etc/mtab\n");
273         printf("\t-s\t\tTolerate sloppy mount options rather than failing.\n");
274         printf("\t-h\t\tPrint this help\n");
275         printf("\tnfsoptions\tRefer to mount.nfs(8) or nfs(5)\n\n");
276 }
277
278 static inline void
279 parse_opt(const char *opt, int *mask, char *extra_opts, int len) {
280         const struct opt_map *om;
281
282         for (om = opt_map; om->opt != NULL; om++) {
283                 if (!strcmp (opt, om->opt)) {
284                         if (om->inv)
285                                 *mask &= ~om->mask;
286                         else
287                                 *mask |= om->mask;
288                         return;
289                 }
290         }
291
292         len -= strlen(extra_opts);
293
294         if (*extra_opts && --len > 0)
295                 strcat(extra_opts, ",");
296
297         if ((len -= strlen(opt)) > 0)
298                 strcat(extra_opts, opt);
299 }
300
301 /* Take -o options list and compute 4th and 5th args to mount(2).  flags
302    gets the standard options (indicated by bits) and extra_opts all the rest */
303 static void parse_opts (const char *options, int *flags, char **extra_opts)
304 {
305         if (options != NULL) {
306                 char *opts = xstrdup(options);
307                 char *opt, *p;
308                 int len = strlen(opts) + 1;             /* include room for a null */
309                 int open_quote = 0;
310
311                 *extra_opts = xmalloc(len);
312                 **extra_opts = '\0';
313
314                 for (p=opts, opt=NULL; p && *p; p++) {
315                         if (!opt)
316                                 opt = p;                /* begin of the option item */
317                         if (*p == '"')
318                                 open_quote ^= 1;        /* reverse the status */
319                         if (open_quote)
320                                 continue;               /* still in a quoted block */
321                         if (*p == ',')
322                                 *p = '\0';              /* terminate the option item */
323                         /* end of option item or last item */
324                         if (*p == '\0' || *(p+1) == '\0') {
325                                 parse_opt(opt, flags, *extra_opts, len);
326                                 opt = NULL;
327                         }
328                 }
329                 free(opts);
330         }
331 }
332
333 static int chk_mountpoint(char *mount_point)
334 {
335         struct stat sb;
336
337         if (stat(mount_point, &sb) < 0){
338                 mount_error(NULL, mount_point, errno);
339                 return 1;
340         }
341         if (S_ISDIR(sb.st_mode) == 0){
342                 mount_error(NULL, mount_point, ENOTDIR);
343                 return 1;
344         }
345         if (access(mount_point, X_OK) < 0) {
346                 mount_error(NULL, mount_point, errno);
347                 return 1;
348         }
349
350         return 0;
351 }
352
353 extern u_short getport(
354         struct sockaddr_in *saddr,
355         u_long prog,
356         u_long vers,
357         u_int prot);
358
359 static int probe_statd()
360 {
361         struct sockaddr_in addr;
362         u_short port;
363
364         memset(&addr, 0, sizeof(addr));
365         addr.sin_family = AF_INET;
366         addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
367         port = getport(&addr, 100024, 1, IPPROTO_UDP);
368
369         if (port == 0)
370                 return 0;
371         addr.sin_port = htons(port);
372
373         if (clnt_ping(&addr, 100024, 1, IPPROTO_UDP, NULL) <= 0)
374                 return 0;
375
376         return 1;
377 }
378
379 static int start_statd()
380 {
381         /* If /var/run/rpc.statd.pid exists and is non-empty,
382          * assume statd already running.
383          * If START_STATD not defined, or defined to a non-existent file,
384          * don't bother,
385          * else run that file (typically a shell script)
386          */
387         struct stat stb;
388
389         if (probe_statd())
390                 return 1;
391 #ifdef START_STATD
392         if (stat(START_STATD, &stb) ==0 &&
393             S_ISREG(stb.st_mode) &&
394             (stb.st_mode & S_IXUSR)) {
395                 system(START_STATD);
396                 if (probe_statd())
397                         return 1;
398         }
399 #endif
400         return 0;
401 }
402
403 int main(int argc, char *argv[])
404 {
405         int c, flags = 0, mnt_err = 1, fake = 0;
406         char *spec, *mount_point, *fs_type = "nfs";
407         char *extra_opts = NULL, *mount_opts = NULL;
408         uid_t uid = getuid();
409
410         progname = basename(argv[0]);
411
412         discover_nfs_mount_data_version();
413
414         if(!strncmp(progname, "umount", strlen("umount"))) {
415                 if(argc < 2) {
416                         umount_usage();
417                         exit(1);
418                 }
419                 exit(nfsumount(argc, argv));
420         }
421
422         if(argv[1] && argv[1][0] == '-') {
423                 if(argv[1][1] == 'V')
424                         printf("%s ("PACKAGE_STRING")\n", progname);
425                 else
426                         mount_usage();
427                 return 0;
428         }
429
430         if ((argc < 3)) {
431                 mount_usage();
432                 exit(1);
433         }
434
435         spec = argv[1];
436         mount_point = argv[2];
437
438         argv[2] = argv[0]; /* so that getopt error messages are correct */
439         while ((c = getopt_long(argc - 2, argv + 2, "rvVwfno:hs",
440                                 longopts, NULL)) != -1) {
441                 switch (c) {
442                 case 'r':
443                         flags |= MS_RDONLY;
444                         break;
445                 case 'v':
446                         ++verbose;
447                         break;
448                 case 'V':
449                         printf("%s: ("PACKAGE_STRING")\n", progname);
450                         return 0;
451                 case 'w':
452                         flags &= ~MS_RDONLY;
453                         break;
454                 case 'f':
455                         ++fake;
456                         break;
457                 case 'n':
458                         ++nomtab;
459                         break;
460                 case 'o':              /* specify mount options */
461                         if (mount_opts)
462                                 mount_opts = xstrconcat3(mount_opts, ",", optarg);
463                         else
464                                 mount_opts = xstrdup(optarg);
465                         break;
466                 case 's':
467                         ++sloppy;
468                         break;
469                 case 'h':
470                 default:
471                         mount_usage();
472                         exit(1);
473                 }
474         }
475         if (optind != argc-2) {
476                 /* Extra non-option words at the end... */
477                 mount_usage();
478                 exit(1);
479         }
480
481         if (strcmp(progname, "mount.nfs4") == 0)
482                 fs_type = "nfs4";
483
484         /*
485          * If a non-root user is attempting to mount, make sure the
486          * user's requested options match the options specified in
487          * /etc/fstab; otherwise, don't allow the mount.
488          */
489         if (uid != 0) {
490                 struct mntentchn *mc;
491
492                 if ((mc = getfsfile(mount_point)) == NULL ||
493                     strcmp(mc->m.mnt_fsname, spec) != 0 ||
494                     strcmp(mc->m.mnt_type, fs_type) != 0) {
495                         fprintf(stderr, "%s: permission denied: no match for %s "
496                                 "found in /etc/fstab\n", progname, mount_point);
497                         exit(1);
498                 }
499
500                 /*
501                  * 'mount' munges the options from fstab before passing them
502                  * to us, so it is non-trivial to test that we have the correct
503                  * set of options and we don't want to trust what the user
504                  * gave us, so just take whatever is in /etc/fstab.
505                  */
506                 mount_opts = strdup(mc->m.mnt_opts);
507         }
508
509         mount_point = canonicalize(mount_point);
510         if (mount_point == NULL ||
511             mount_point[0] != '/') {
512                 fprintf(stderr, "%s: unknown mount point %s\n",
513                         progname, mount_point ? : "");
514                 exit(1);
515         }
516         
517         parse_opts(mount_opts, &flags, &extra_opts);
518
519         if (uid != 0) {
520             if (! (flags & (MS_USERS | MS_USER))) {
521                     fprintf(stderr, "%s: permission denied\n", progname);
522                     exit(1);
523             }
524         }
525
526         if (chk_mountpoint(mount_point))
527                 exit(EX_FAIL);
528
529         if (strcmp(fs_type, "nfs4") == 0)
530                 mnt_err = nfs4mount(spec, mount_point, &flags, &extra_opts, &mount_opts, 0);
531         else {
532                 int need_statd = 0;
533                 mnt_err = nfsmount(spec, mount_point, &flags,
534                                    &extra_opts, &mount_opts,
535                                    0, &need_statd);
536                 if (!mnt_err && !fake && need_statd) {
537                         if (!start_statd()) {
538                                 fprintf(stderr,
539                                         "%s: rpc.statd is not running but is "
540                                         "required for remote locking\n"
541                                         "   Either use \"-o nolocks\" to keep "
542                                         "locks local, or start statd.\n",
543                                         progname);
544                                 exit(1);
545                         }
546                 }
547         }
548
549         if (mnt_err)
550                 exit(EX_FAIL);
551
552         if (!fake) {
553                 mnt_err = do_mount_syscall(spec, mount_point, fs_type,
554                                            flags & ~(MS_USER|MS_USERS) ,
555                                            mount_opts);
556
557                 if (mnt_err) {
558                         mount_error(spec, mount_point, errno);
559                         exit(EX_FAIL);
560                 }
561         }
562
563         if (!nomtab)
564                 mnt_err = add_mtab(spec, mount_point, fs_type, flags, extra_opts,
565                                 0, 0 /* these are always zero for NFS */ );
566
567         exit(mnt_err);
568 }
569