whitespace cleanups
[util-vserver.git] / src / secure-mount.c
1 // $Id$    --*- c++ -*--
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; version 2 of the License.
8 //  
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //  
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18
19   // secure-mount <general mount(8) options> [--chroot]
20   //              [--mtab <mtabfile>] [--fstab <fstabfile>]
21   //
22   // Executes mount-operations under the current directory: it assumes sources
23   // in the current root-dir while destinations are expected in the chroot
24   // environment.
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include "util.h"
32 #include "pathconfig.h"
33
34 #include <lib/internal.h>
35
36 #include <getopt.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <strings.h>
43 #include <unistd.h>
44 #include <stdbool.h>
45 #include <sys/mount.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <sys/file.h>
49 #include <linux/fs.h>
50 #include <assert.h>
51 #include <ctype.h>
52 #include <sys/wait.h>
53 #include <libgen.h>
54 #include <signal.h>
55 #include <stdlib.h>
56
57 #define ENSC_WRAPPERS_FCNTL     1
58 #define ENSC_WRAPPERS_UNISTD    1
59 #include <wrappers.h>
60
61 #define MNTPOINT        "/etc"
62
63 typedef enum { rfsYES, rfsNO, rfsONLY }         RootFsOption;
64
65 struct MountInfo {
66     char *              src;
67     char *              dst;
68     char *              name;
69     char *              type;
70     unsigned long       flag;
71     unsigned long       xflag;
72     unsigned long       mask;
73     char *              data;
74     char *              data_parsed;
75 };
76
77 struct Options {
78     char const *        mtab;
79     char const *        fstab;
80     bool                do_chroot;
81     bool                ignore_mtab;
82     bool                mount_all;
83     RootFsOption        rootfs;
84
85     int                 cur_dir_fd;
86     int                 cur_rootdir_fd;
87 };
88
89 #define OPTION_BIND     1024
90 #define OPTION_MOVE     1025
91 #define OPTION_MTAB     1026
92 #define OPTION_FSTAB    1027
93 #define OPTION_CHROOT   1028
94 #define OPTION_SECURE   1029
95 #define OPTION_RBIND    1030
96 #define OPTION_ROOTFS   1031
97
98 #define XFLAG_NOAUTO    0x01
99 #define XFLAG_FILE      0x02
100
101 static struct option const
102 CMDLINE_OPTIONS[] = {
103   { "help",    no_argument,       0, 'h' },
104   { "version", no_argument,       0, 'v' },
105   { "bind",    no_argument,       0, OPTION_BIND },
106   { "move",    no_argument,       0, OPTION_MOVE },
107   { "mtab",    required_argument, 0, OPTION_MTAB },
108   { "fstab",   required_argument, 0, OPTION_FSTAB },
109   { "rootfs",  required_argument, 0, OPTION_ROOTFS },
110   { "chroot",  no_argument,       0, OPTION_CHROOT },
111   { "secure",  no_argument,       0, OPTION_SECURE },
112   { "rbind",   no_argument,       0, OPTION_RBIND },
113   { 0, 0, 0, 0 }
114 };
115
116 #ifndef MS_REC
117 #define MS_REC          0x4000
118 #endif
119 #ifndef MS_UNBINDABLE
120 #define MS_UNBINDABLE   (1<<17)
121 #endif
122 #ifndef MS_PRIVATE
123 #define MS_PRIVATE      (1<<18)
124 #endif
125 #ifndef MS_SLAVE
126 #define MS_SLAVE        (1<<19)
127 #endif
128 #ifndef MS_SHARED
129 #define MS_SHARED       (1<<20)
130 #endif
131
132 static struct FstabOption {
133     char const * const  opt;
134     unsigned long const         flag;
135     unsigned long const         mask;
136     unsigned long const         xflag;
137     bool const                  is_dflt;
138 } const FSTAB_OPTIONS[] = {
139   { "defaults",   MS_NODEV,      (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|
140                                   MS_SYNCHRONOUS), 0, false },
141   { "rbind",      MS_BIND|MS_REC, MS_BIND|MS_REC,  0, false },
142   { "bind",       MS_BIND,        MS_BIND,         0, false },
143   { "move",       MS_MOVE,        MS_MOVE,         0, false },
144   { "async",      0,              MS_SYNCHRONOUS,  0, false },
145   { "sync",       MS_SYNCHRONOUS, MS_SYNCHRONOUS,  0, false },
146   { "atime",      0,              MS_NOATIME,      0, false },
147   { "noatime",    MS_NOATIME,     MS_NOATIME,      0, false },
148   { "dev",        0,              MS_NODEV,        0, false },
149   { "nodev",      MS_NODEV,       MS_NODEV,        0, false },
150   { "exec",       0,              MS_NOEXEC,       0, false },
151   { "noexec",     MS_NOEXEC,      MS_NOEXEC,       0, false },
152   { "suid",       0,              MS_NOSUID,       0, false },
153   { "nosuid",     MS_NOSUID,      MS_NOSUID,       0, false },
154   { "ro",         MS_RDONLY,      MS_RDONLY,       0, false },
155   { "rw",         0,              MS_RDONLY,       0, false },
156   
157   { "remount",    MS_REMOUNT,     MS_REMOUNT,      0, false },
158   { "users",      MS_NOEXEC|MS_NOSUID|MS_NODEV,
159                   MS_NOEXEC|MS_NOSUID|MS_NODEV,    0, false },
160   { "mandlock",   MS_MANDLOCK,    MS_MANDLOCK,     0, false },
161   { "nodiratime", MS_NODIRATIME,  MS_NODIRATIME,   0, false },
162 #ifdef MS_DIRSYNC  
163   { "dirsync",    MS_DIRSYNC,     MS_DIRSYNC,      0, false },
164 #endif
165   { "_netdev",    0,              0,               0, false },
166   { "auto",       0,              0,               0, false },
167   { "noauto",     0,              0,               XFLAG_NOAUTO, false },
168   { "user",       0,              0,               0, false },
169   { "nouser",     0,              0,               0, false },
170   { "rec",        MS_REC,         MS_REC,          0, false },
171   { "unbindable", MS_UNBINDABLE,  MS_UNBINDABLE,   0, false },
172   { "private",    MS_PRIVATE,     MS_PRIVATE,      0, false },
173   { "slave",      MS_SLAVE,       MS_SLAVE,        0, false },
174   { "shared",     MS_SHARED,      MS_SHARED,       0, false },
175 };
176
177 int                     wrapper_exit_code = 1;
178
179 static void
180 showHelp(int fd, char const *cmd, int res)
181 {
182   VSERVER_DECLARE_CMD(cmd);
183   
184   WRITE_MSG(fd, "Usage:  ");
185   WRITE_STR(fd, cmd);
186   WRITE_MSG(fd,
187             " [--help] [--version] [--bind] [--move] [--rbind] [-t <type>] [--chroot]\n"
188             "            [--mtab <filename>] [--fstab <filename>] [--rootfs yes|no|only]\n"
189             "            [-n] -a|([-o <options>] [--] <src> <dst>)\n\n"
190             "Executes mount-operations under the current directory: it assumes sources in\n"
191             "the current root-dir while destinations are expected in the chroot environment.\n\n"
192             "For non-trivial mount-operations it uses the external 'mount' program which\n"
193             "can be overridden by the $MOUNT environment variable.\n\n"
194             "Options:\n"
195             "  --bind|move|rbind        ...  set the correspond flags; with this options\n"
196             "                                the mount will be executed internally without\n"
197             "                                calling an external mount program.\n"
198             "  -t <type>                ...  assume the given filesystem type\n"
199             "  -o <options>             ...  set additional options; see mount(2) for details\n"
200             "  -n                       ...  do not update the mtab-file\n"
201             "  --mtab <filename>        ...  use <filename> as an alternative mtab file\n"
202             "                                [default: /etc/mtab]\n"
203             "  --chroot                 ...  chroot into the current directory before\n"
204             "                                mounting the filesystem\n"
205             "  --fstab <filename>       ...  use <filename> as an alternative fstab file;\n"
206             "                                this option has an effect only with the '-a'\n"
207             "                                option [default: /etc/fstab]\n"
208             "  --rootfs yes|no|only     ...  specifies how to handle an entry for a rootfs\n"
209             "                                ('/') when processing an fstab file. 'yes' will\n"
210             "                                mount it among the other entries, 'only' will\n"
211             "                                mount only the rootfs entry, and 'no' will ignore\n"
212             "                                it and mount only the other entries [default: yes]\n"
213             "  -a                       ...  mount everything listed in the fstab-file\n\n"
214             "  <src>                    ...  the source-filesystem; this path is absolute\n"
215             "                                to the current root-filesystem. Only valid\n"
216             "                                without the '-a' option.\n"
217             "  <dst>                    ...  the destination mount-point; when used with\n"
218             "                                '--chroot', this path is relative to the current\n"
219             "                                directory. Only valid without the '-a' option\n\n"
220             "Please report bugs to " PACKAGE_BUGREPORT "\n");
221
222   exit(res);
223 }
224
225 static void
226 showVersion()
227 {
228   WRITE_MSG(1,
229             "secure-mount " VERSION " -- secure mounting of directories\n"
230             "This program is part of " PACKAGE_STRING "\n\n"
231             "Copyright (C) 2003 Enrico Scholz\n"
232             VERSION_COPYRIGHT_DISCLAIMER);
233   exit(0);
234 }
235
236 inline static bool
237 isSameObject(struct stat const *lhs,
238              struct stat const *rhs)
239 {
240   return (lhs->st_dev==rhs->st_dev &&
241           lhs->st_ino==rhs->st_ino);
242 }
243
244 static int
245 fchroot(int fd)
246 {
247   if (fchdir(fd)==-1 || chroot(".")==-1) return -1;
248   return 0;
249 }
250
251 static int
252 writeX(int fd, void const *buf, size_t len)
253 {
254   if ((size_t)(write(fd, buf, len))!=len) return -1;
255   return 0;
256 }
257
258 static int
259 writeStrX(int fd, char const *str)
260 {
261   return writeX(fd, str, strlen(str));
262 }
263
264 static inline char const *
265 getType(struct MountInfo const *mnt)
266 {
267   if (mnt->type==0)                         return "none";
268   else if (strncmp(mnt->type, "ext", 3)==0) return "ufs";
269   else                                      return mnt->type;
270 }
271
272 inline static void
273 restoreRoot(struct Options const *opt)
274 {
275   if (opt->do_chroot!=0 && fchroot(opt->cur_rootdir_fd)==-1) {
276     perror("secure-mount: fchdir(\"/\")");
277     WRITE_MSG(2, "Failed to restore root-directory; aborting\n");
278     exit(1);
279   }
280 }
281
282 static int
283 updateMtab(struct MountInfo const *mnt, struct Options const *opt)
284 {
285   int           res = -1;
286   int           fd;
287   assert(opt->mtab!=0);
288
289   if (opt->do_chroot && fchroot(opt->cur_dir_fd)==-1) {
290       perror("secure-mount: fchroot(\".\")");
291       return -1;
292   }
293
294   fd=open(opt->mtab, O_CREAT|O_APPEND|O_WRONLY, 0644);
295   
296   if (fd==-1) {
297     perror("secure-mount: open(<mtab>)");
298     goto err0;
299   }
300
301   if (lockf(fd, F_LOCK, 0)==-1) {
302     perror("secure-mount: lockf()");
303     goto err1;
304   }
305
306   if (writeStrX(fd, mnt->src)==-1 ||
307       writeStrX(fd, " ")==-1 ||
308       writeStrX(fd, mnt->dst)==-1 ||
309       writeStrX(fd, mnt->xflag & XFLAG_FILE ? "/" : "")==-1 ||
310       writeStrX(fd, mnt->xflag & XFLAG_FILE ? mnt->name : "")==-1 ||
311       writeStrX(fd, " ")==-1 ||
312       writeStrX(fd, getType(mnt))==-1 ||
313       writeStrX(fd, " ")==-1 ||
314       writeStrX(fd, mnt->data ? mnt->data : "defaults")==-1 ||
315       writeStrX(fd, " 0 0\n")==-1) {
316     perror("secure-mount: write()");
317     goto err1;
318   }
319
320   res = 0;
321
322   err1: close(fd);
323   err0:
324   restoreRoot(opt);
325   return res;
326 }
327
328 static bool
329 callExternalMount(struct MountInfo const *mnt)
330 {
331   char const *  argv[10];
332   size_t        idx = 0;
333   pid_t         pid;
334   int           status;
335   char const *  mount_prog = getenv("MOUNT");
336
337   if (mount_prog==0) mount_prog = MOUNT_PROG;
338
339   argv[idx++] = mount_prog;
340   argv[idx++] = "-n";
341   if      (mnt->flag & MS_BIND) argv[idx++] = "--bind";
342   else if (mnt->flag & MS_MOVE) argv[idx++] = "--move";
343
344   argv[idx++] = "-o";
345   if (mnt->data && *mnt->data &&
346       strcmp(mnt->data, "defaults")!=0) {
347     if (mnt->mask & MS_NODEV)
348       argv[idx++] = mnt->data;
349     else {
350       char *    tmp = alloca(strlen(mnt->data) + sizeof("nodev,"));
351       strcpy(tmp, "nodev,");
352       strcat(tmp, mnt->data);
353       argv[idx++] = tmp;
354     }
355   }
356   else
357     argv[idx++] = "nodev";
358
359   if (mnt->type) {
360     argv[idx++] = "-t";
361     argv[idx++] = mnt->type;
362   }
363
364   argv[idx++] = mnt->src;
365   argv[idx++] = mnt->name;
366   argv[idx]   = 0;
367
368   pid = fork();
369   if (pid==-1) {
370     perror("secure-mount: fork()");
371     return false;
372   }
373
374   if (pid==0) {
375     execv(mount_prog, const_cast(char **)(argv));
376     PERROR_Q("secure-mount: execv", mount_prog);
377     exit(1);
378   }
379
380   if (wait4(pid, &status, 0, 0)==-1) {
381     perror("secure-mount: wait4()");
382     return false;
383   }
384
385   return (WIFEXITED(status)) && (WEXITSTATUS(status)==0);
386 }
387
388 inline static bool
389 secureChdir(char const *dir, struct Options const *opt)
390 {
391   int           dir_fd;
392   bool          res = false;
393   
394   if (opt->do_chroot!=0 && fchroot(opt->cur_dir_fd)==-1) {
395     perror("secure-mount: fchroot(\".\")");
396     return false;
397   }
398
399   if (chdir(dir)==-1) {
400     PERROR_Q("secure-mount: chdir", dir);
401     goto err;
402   }
403
404   dir_fd = open(".", O_RDONLY|O_DIRECTORY);
405   if (dir_fd==-1) {
406     perror("secure-mount: open(\".\")");
407     goto err;
408   }
409
410   restoreRoot(opt);
411   if (fchdir(dir_fd)==-1)
412     PERROR_Q("secure-mount: fchdir", dir);
413   else
414     res = true;
415   
416   close(dir_fd);
417   return res;
418
419   err:
420   restoreRoot(opt);
421   return false;
422 }
423
424 static bool
425 canHandleInternal(struct MountInfo const *mnt)
426 {
427   static char const *   FS[] = {
428     "tmpfs", "sysfs", "proc", "sockfs", "pipefs", "futexfs",
429     "inotifyfs", "devpts", "ext3", "ext2", "ramfs",
430     "hugetlbfs", "usbfs", "binfmt_misc",
431     0
432   };
433   char const **         i;
434   
435   if (!mnt)                                 return false;
436   else if ((mnt->flag & (MS_BIND|MS_MOVE))) return true;
437   else if ((mnt->flag & (MS_SHARED|MS_SLAVE|MS_PRIVATE|
438                          MS_UNBINDABLE)))   return true;
439   else if (mnt->type==0)                    return false;
440
441   for (i=FS+0; *i!=0; ++i)
442     if (strcmp(mnt->type, *i)==0) return true;
443
444   return false;
445 }
446
447 static bool
448 mountSingle(struct MountInfo const *mnt, struct Options const *opt)
449 {
450   assert(mnt->dst!=0);
451   
452   if (!secureChdir(mnt->dst, opt))
453     return false;
454
455   if (canHandleInternal(mnt)) {
456     if (mount(mnt->src, mnt->name,
457               mnt->type ? mnt->type : "",
458               mnt->flag,  mnt->data_parsed)==-1) {
459       perror("secure-mount: mount()");
460       return false;
461     }
462     if ((mnt->flag & MS_BIND) &&
463         (mnt->mask & ~(MS_BIND|MS_REC))) {
464       /* This is needed to put us in the new mountpoint */
465       if (!secureChdir(mnt->dst, opt))
466         return false;
467       if (mount(mnt->src, mnt->name,
468                 mnt->type ? mnt->type : "",
469                 (mnt->flag | MS_REMOUNT), NULL) == -1 &&
470           errno != EBUSY) { /* Returned on older kernels */
471         perror("secure-mount: mount()");
472         return false;
473       }
474     }
475   }
476   else if (!callExternalMount(mnt))
477     return false;
478
479   if (!opt->ignore_mtab &&
480       updateMtab(mnt, opt)==-1) {
481     WRITE_MSG(2, "Failed to update mtab-file\n");
482       // no error
483   }
484   
485   return true;
486 }
487
488 static struct FstabOption const *
489 searchOption(char const *opt, size_t len)
490 {
491   struct FstabOption const *            i;
492   for (i=FSTAB_OPTIONS+0; i<FSTAB_OPTIONS+DIM_OF(FSTAB_OPTIONS); ++i)
493     if (strncmp(i->opt, opt, len)==0) return i;
494
495   return 0;
496 }
497
498 static bool
499 transformOptionList(struct MountInfo *info, size_t UNUSED *col)
500 {
501   char const *                  ptr = info->data;
502   char *                        data = malloc(strlen(info->data));
503   char *                        dst = data;
504
505   do {
506     char const *                pos = strchr(ptr, ',');
507     struct FstabOption const *  opt;
508     
509     if (pos==0) pos = ptr+strlen(ptr);
510     opt = searchOption(ptr, pos-ptr);
511
512     if (opt!=0) {
513       info->flag  &= ~opt->mask;
514       info->flag  |=  opt->flag;
515       info->mask  |=  opt->mask;
516       info->xflag |=  opt->xflag;
517     }
518     else {
519       if (dst != data)
520         *(dst++) = ',';
521       strncpy(dst, ptr, pos-ptr);
522       dst += pos - ptr;
523       *dst = '\0';
524     }
525
526     if (*pos!='\0')
527       ptr = pos+1;
528     else
529       ptr = pos;
530
531   } while (*ptr!='\0');
532
533   info->data_parsed = data;
534   return true;
535 }
536
537 #define MOVE_TO_NEXT_FIELD(PTR,ALLOW_EOL)               \
538   while (!isspace(*PTR) && *PTR!='\0') ++PTR;           \
539   if (col) *col = buf-start_buf+1;                      \
540   if (!(ALLOW_EOL) && *PTR=='\0') return prFAIL;        \
541   *PTR++ = '\0';                                        \
542   while (isspace(*PTR)) ++PTR
543
544 static enum {prDOIT, prFAIL, prIGNORE}
545   parseFstabLine(struct MountInfo *info, char *buf, size_t *col)
546 {
547   char const * const    start_buf = buf;
548   size_t                err_col;
549
550   while (isspace(*buf)) ++buf;
551   if (*buf=='#' || *buf=='\0')  return prIGNORE;
552
553   info->src  = buf;
554   MOVE_TO_NEXT_FIELD(buf, false);
555   info->dst  = buf;
556   MOVE_TO_NEXT_FIELD(buf, false);
557   info->type = buf;
558   MOVE_TO_NEXT_FIELD(buf, false);
559   err_col    = buf-start_buf+1;
560   info->data = buf;
561   MOVE_TO_NEXT_FIELD(buf, true);
562
563   info->flag  = MS_NODEV;
564   info->mask  = 0;
565   info->xflag = 0;
566   info->name = ".";
567
568   if      (strcmp(info->type, "swap")  ==0) return prIGNORE;
569   else if (strcmp(info->type, "none")  ==0) info->type  = 0;
570   else if (strcmp(info->type, "devpts")==0) {
571     info->mask |=  MS_NODEV;
572     info->flag &= ~MS_NODEV;
573   }
574
575   if (col) *col = err_col;
576   if (!transformOptionList(info,col)) return prFAIL;
577   if (info->xflag & XFLAG_NOAUTO)     return prIGNORE;
578
579   return prDOIT;
580 }
581
582 #undef MOVE_TO_NEXT_FIELD
583
584 static void
585 showFstabPosition(int fd, char const *fname, size_t line_nr, size_t col_nr)
586 {
587   char          buf[3*sizeof(line_nr)*2 + 4];
588   size_t        len = utilvserver_fmt_uint(buf+1, line_nr)+1;
589   
590   buf[0]     = ':';
591   buf[len++] = ':';
592   len += utilvserver_fmt_uint(buf+len, col_nr);
593   WRITE_STR(fd, fname);
594   Vwrite(fd, buf, len);
595 }
596
597 static void
598 adjustFileMount(struct MountInfo *mnt)
599 {
600   char *buf = strrchr(mnt->dst, '/');
601
602   if (buf)
603     *buf++ = 0;
604
605   mnt->name = buf;
606   mnt->xflag |= XFLAG_FILE;
607 }
608
609 static bool
610 mountFstab(struct Options const *opt)
611 {
612   bool          res = false;
613   int           fd;
614   off_t         len;
615
616   assert(opt->fstab!=0);
617   fd = open(opt->fstab, O_RDONLY);
618   if (fd==-1) {
619     perror("secure-mount: open(<fstab>)");
620     goto err0;
621   }
622
623   len = lseek(fd, 0, SEEK_END); 
624   if (len==-1 ||
625       lseek(fd, 0, SEEK_SET)==-1) {
626     perror("secure-mount: lseek(<fstab>)");
627     goto err1;
628   }
629
630   {
631     char        buf[len+2];
632     char        *ptr, *ptrptr;
633     size_t      line_nr=0, col_nr;
634
635     if (read(fd, buf, len+1)!=len) {
636       perror("secure-mount: read()");
637       goto err1;
638     }
639     buf[len]   = '#';   // workaround for broken dietlibc strtok_r()
640                         // implementation
641     buf[len+1] = '\0';
642     ptrptr     = buf;
643
644     while ((ptr=strsep(&ptrptr, "\n")) != 0) {
645       struct MountInfo  mnt;
646       ++line_nr;
647
648       switch (parseFstabLine(&mnt, ptr, &col_nr)) {
649         case prFAIL     :
650           showFstabPosition(2, opt->fstab, line_nr, col_nr);
651           WRITE_MSG(2, ": syntax error\n");
652           goto err1;
653
654         case prIGNORE   :  break;
655         case prDOIT     : {
656           bool          is_rootfs = (strcmp(mnt.dst, "/")==0);
657           Echdir("/");
658           if (( is_rootfs && opt->rootfs==rfsNO) ||
659               (!is_rootfs && opt->rootfs==rfsONLY)) { /* ignore the entry */ }
660           else {
661             if (utilvserver_isFile(mnt.dst, 0))
662               adjustFileMount(&mnt);
663             if (!mountSingle(&mnt, opt)) {
664               showFstabPosition(2, opt->fstab, line_nr, 1);
665               WRITE_MSG(2, ": failed to mount fstab-entry\n");
666             }
667           }
668           break;
669         }
670         default         :
671           assert(false);
672       }
673     }
674   }
675
676   res = true;
677
678   err1: close(fd);
679   err0: return res;
680 }
681
682 static void
683 initFDs(struct Options *opt)
684 {
685   opt->cur_dir_fd     = Eopen(".", O_RDONLY|O_DIRECTORY, 0);
686   opt->cur_rootdir_fd = Eopen("/", O_RDONLY|O_DIRECTORY, 0);
687
688   Efcntl(opt->cur_dir_fd,     F_SETFD, FD_CLOEXEC);
689   Efcntl(opt->cur_rootdir_fd, F_SETFD, FD_CLOEXEC);
690 }
691
692 static RootFsOption
693 parseRootFS(char const *str)
694 {
695   if      (strcasecmp(str, "yes")==0)  return rfsYES;
696   else if (strcasecmp(str, "no")==0)   return rfsNO;
697   else if (strcasecmp(str, "only")==0) return rfsONLY;
698   else {
699     WRITE_MSG(2, "secure-mount: invalid option for '--rootfs': '");
700     WRITE_STR(2, str);
701     WRITE_MSG(2, "'\n");
702     exit(wrapper_exit_code);
703   }
704 }
705
706 int main(int argc, char *argv[])
707 {
708   struct MountInfo      mnt = {
709     .src         = 0,
710     .dst         = 0,
711     .name        = ".",
712     .type        = 0,
713     .flag        = MS_NODEV,
714     .xflag       = 0,
715     .data        = 0,
716   };
717
718   struct Options        opt = {
719     .mtab           = "/etc/mtab",
720     .fstab          = "/etc/fstab",
721     .do_chroot      = 0,
722     .ignore_mtab    = false,
723     .mount_all      = false,
724     .cur_dir_fd     = -1,
725     .cur_rootdir_fd = -1,
726     .rootfs         = rfsYES
727   };
728
729   while (1) {
730     int         c = getopt_long(argc, argv, "ht:nao:", CMDLINE_OPTIONS, 0);
731     if (c==-1) break;
732     
733     switch (c) {
734       case 'h'          :  showHelp(1, argv[0], 0);
735       case 'v'          :  showVersion();
736       case 't'          :  mnt.type = optarg;         break;
737       case 'n'          :  opt.ignore_mtab = true;    break;
738       case 'a'          :  opt.mount_all   = true;    break;
739       case 'o'          :  mnt.data        = optarg;  break;
740       case OPTION_RBIND :  mnt.flag       |= MS_REC;  /*@fallthrough@*/
741       case OPTION_BIND  :  mnt.flag       |= MS_BIND; break;
742       case OPTION_MOVE  :  mnt.flag       |= MS_MOVE; break;
743       case OPTION_MTAB  :  opt.mtab        = optarg;  break;
744       case OPTION_FSTAB :  opt.fstab       = optarg;  break;
745       case OPTION_CHROOT:  opt.do_chroot   = true;    break;
746       case OPTION_ROOTFS:  opt.rootfs      = parseRootFS(optarg); break;
747       case OPTION_SECURE:
748         WRITE_MSG(2, "secure-mount: The '--secure' option is deprecated...\n");
749         break;
750       default           :
751         WRITE_MSG(2, "Try '");
752         WRITE_STR(2, argv[0]);
753         WRITE_MSG(2, " --help' for more information.\n");
754         return EXIT_FAILURE;
755         break;
756     }
757   }
758
759
760   if (opt.mount_all && optind<argc) {
761     WRITE_MSG(2, "Can not specify <src> and '-a' at the same time\n");
762     return EXIT_FAILURE;
763   }
764
765   initFDs(&opt);
766   signal(SIGCHLD, SIG_DFL);
767   
768   if (opt.mount_all) {
769     if (!mountFstab(&opt)) return EXIT_FAILURE;
770     else                   return EXIT_SUCCESS;
771   }
772
773   if (optind+2!=argc) {
774     WRITE_MSG(2, "Invalid <src> <dst> pair specified\n");
775     return EXIT_FAILURE;
776   }
777
778   if (mnt.data) {
779     mnt.data = strdup(mnt.data);
780     if (!transformOptionList(&mnt, 0)) {
781       WRITE_MSG(2, "Invalid options specified\n");
782       return EXIT_FAILURE;
783     }
784   }
785     
786   mnt.src  = argv[optind++];
787   mnt.dst  = argv[optind++];
788
789   if (utilvserver_isFile(mnt.dst, 0))
790     adjustFileMount(&mnt);
791   if (!mountSingle(&mnt, &opt))
792     return EXIT_FAILURE;
793     
794   return EXIT_SUCCESS;
795 }