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