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