Whamcloud - gitweb
LU-7919 mount: Buffer overflow issue while parsing mount
[fs/lustre-release.git] / lustre / utils / mount_lustre.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/mount_lustre.c
37  *
38  * Author: Robert Read <rread@clusterfs.com>
39  * Author: Nathan Rutman <nathan@clusterfs.com>
40  */
41
42 #ifndef _GNU_SOURCE
43 #define _GNU_SOURCE
44 #endif
45 #include <getopt.h>
46 #include <mntent.h>
47 #include <stdbool.h>
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <errno.h>
53 #include <string.h>
54 #include <sys/mount.h>
55 #include <lustre_ver.h>
56 #include <ctype.h>
57 #include <limits.h>
58 #include <lnet/nidstr.h>
59 #include <lustre/lustre_idl.h>
60 #include <libcfs/util/string.h>
61
62 #include "obdctl.h"
63 #include "mount_utils.h"
64
65 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 10, 53, 0)
66 /*
67  * LU-1783
68  * We only #include a kernel level include file here because
69  * important MS_ flag #defines are missing from the SLES version
70  * of sys/mount.h
71  * In the future if SLES updates sys/mount.h to have a more complete
72  * set of flag #defines we should stop including linux/fs.h
73  */
74 #if !defined(MS_RDONLY)
75 #include <linux/fs.h>
76 #endif
77 #endif
78
79 #ifdef HAVE_LIBMOUNT
80 # define WITH_LIBMOUNT  "(libmount)"
81 #else
82 # define WITH_LIBMOUNT  ""
83 #endif
84
85 #define MAX_RETRIES 99
86
87 int     verbose;
88 int     version;
89 char    *progname;
90
91 void usage(FILE *out)
92 {
93         fprintf(out, "\nThis mount helper should only be invoked via the "
94                 "mount (8) command,\ne.g. mount -t lustre dev dir\n\n");
95         fprintf(out, "usage: %s [-fhnvV] [-o <mntopt>] <device> <mountpt>\n",
96                 progname);
97         fprintf(out,
98                 "\t<device>: the disk device, or for a client:\n"
99                 "\t\t<mgsnid>[:<altmgsnid>...]:/<filesystem>[/<subdir>]\n"
100                 "\t<filesystem>: name of the Lustre filesystem (e.g. lustre1)\n"
101                 "\t<mountpt>: filesystem mountpoint (e.g. /mnt/lustre)\n"
102                 "\t-f|--fake: fake mount (updates /etc/mtab)\n"
103                 "\t-o force|--force: force mount even if already in /etc/mtab\n"
104                 "\t-h|--help: print this usage message\n"
105                 "\t-n|--nomtab: do not update /etc/mtab after mount\n"
106                 "\t-v|--verbose: print verbose config settings\n"
107                 "\t-V|--version: output build version of the utility and exit\n"
108                 "\t<mntopt>: one or more comma separated of:\n"
109                 "\t\t(no)flock,(no)user_xattr,(no)acl\n"
110                 "\t\tabort_recov: abort server recovery handling\n"
111                 "\t\tnosvc: only start MGC/MGS obds\n"
112                 "\t\tnomgs: only start target obds, using existing MGS\n"
113                 "\t\tnoscrub: NOT auto start OI scrub unless start explicitly\n"
114                 "\t\tskip_lfsck: NOT auto resume the paused/crashed LFSCK\n"
115                 "\t\texclude=<ostname>[:<ostname>] : colon-separated list of "
116                 "inactive OSTs (e.g. lustre-OST0001)\n"
117 #ifdef HAVE_GSS
118                 "\t\tskpath=<file|directory>: Path to a file or directory of"
119                 "key configuration files to load into the kernel keyring\n"
120 #endif
121                 "\t\tretry=<num>: number of times mount is retried by client\n"
122                 "\t\tmd_stripe_cache_size=<num>: set the raid stripe cache "
123                 "size for the underlying raid if present\n");
124         exit((out != stdout) ? EINVAL : 0);
125 }
126
127 /* Get rid of symbolic hostnames for tcp, since kernel can't do lookups */
128 #define MAXNIDSTR 1024
129 static char *convert_hostnames(char *s1)
130 {
131         char *converted, *s2 = 0, *c;
132         char sep;
133         int left = MAXNIDSTR;
134         lnet_nid_t nid;
135
136         converted = malloc(left);
137         if (converted == NULL) {
138                 fprintf(stderr, "out of memory: needed %d bytes\n",
139                         MAXNIDSTR);
140                 return NULL;
141         }
142         c = converted;
143         while ((left > 0) && (*s1 != '/')) {
144                 s2 = strpbrk(s1, ",:");
145                 if (!s2)
146                         goto out_free;
147                 sep = *s2;
148                 *s2 = '\0';
149                 nid = libcfs_str2nid(s1);
150                 *s2 = sep;                      /* back to original string */
151                 if (nid == LNET_NID_ANY)
152                         goto out_free;
153                 c += snprintf(c, left, "%s%c", libcfs_nid2str(nid), sep);
154                 left = converted + MAXNIDSTR - c;
155                 s1 = s2 + 1;
156         }
157         snprintf(c, left, "%s", s1);
158         return converted;
159 out_free:
160         fprintf(stderr, "%s: Can't parse NID '%s'\n", progname, s1);
161         free(converted);
162         return NULL;
163 }
164
165 /*****************************************************************************
166  *
167  * This part was cribbed from util-linux/mount/mount.c.  There was no clear
168  * license information, but many other files in the package are identified as
169  * GNU GPL, so it's a pretty safe bet that was their intent.
170  *
171  ****************************************************************************/
172 struct opt_map {
173         const char *opt;        /* option name */
174         int inv;                /* true if flag value should be inverted */
175         int mask;               /* flag mask value */
176 };
177
178 static const struct opt_map opt_map[] = {
179   /*"optname", inv,ms_mask */
180   /* These flags are parsed by mount, not lustre */
181   { "defaults", 0, 0         },      /* default options */
182   { "remount",  0, MS_REMOUNT},      /* remount with different options */
183   { "rw",       1, MS_RDONLY },      /* read-write */
184   { "ro",       0, MS_RDONLY },      /* read-only */
185   { "exec",     1, MS_NOEXEC },      /* permit execution of binaries */
186   { "noexec",   0, MS_NOEXEC },      /* don't execute binaries */
187   { "suid",     1, MS_NOSUID },      /* honor suid executables */
188   { "nosuid",   0, MS_NOSUID },      /* don't honor suid executables */
189   { "dev",      1, MS_NODEV  },      /* interpret device files  */
190   { "nodev",    0, MS_NODEV  },      /* don't interpret devices */
191   { "sync",     0, MS_SYNCHRONOUS},  /* synchronous I/O */
192   { "async",    1, MS_SYNCHRONOUS},  /* asynchronous I/O */
193   { "atime",    1, MS_NOATIME  },    /* set file access time on read */
194   { "noatime",  0, MS_NOATIME  },    /* do not set file access time on read */
195 #ifdef MS_NODIRATIME
196   { "diratime", 1, MS_NODIRATIME },  /* set file access time on read */
197   { "nodiratime",0,MS_NODIRATIME },  /* do not set file access time on read */
198 #endif
199 #ifdef MS_RELATIME
200   { "relatime", 0, MS_RELATIME },  /* set file access time on read */
201   { "norelatime",1,MS_RELATIME },  /* do not set file access time on read */
202 #endif
203 #ifdef MS_STRICTATIME
204   { "strictatime",0,MS_STRICTATIME },  /* update access time strictly */
205 #endif
206   { "auto",     0, 0         },      /* Can be mounted using -a */
207   { "noauto",   0, 0         },      /* Can only be mounted explicitly */
208   { "nousers",  1, 0         },      /* Forbid ordinary user to mount */
209   { "nouser",   1, 0         },      /* Forbid ordinary user to mount */
210   { "noowner",  1, 0         },      /* Device owner has no special privs */
211   { "_netdev",  0, 0         },      /* Device accessible only via network */
212   { "loop",     0, 0         },
213   { NULL,       0, 0         }
214 };
215 /****************************************************************************/
216
217 /* 1  = don't pass on to lustre
218    0  = pass on to lustre */
219 static int parse_one_option(const char *check, int *flagp)
220 {
221         const struct opt_map *opt;
222
223         for (opt = &opt_map[0]; opt->opt != NULL; opt++) {
224                 if (strncmp(check, opt->opt, strlen(opt->opt)) == 0) {
225                         if (opt->mask) {
226                                 if (opt->inv)
227                                         *flagp &= ~(opt->mask);
228                                 else
229                                         *flagp |= opt->mask;
230                         }
231                         return 1;
232                 }
233         }
234         /* Assume any unknown options are valid and pass them on.  The mount
235            will fail if lmd_parse, ll_options or ldiskfs doesn't recognize it.*/
236         return 0;
237 }
238
239 static int append_option(char *options, size_t options_len,
240                          const char *param, const char *value)
241 {
242         int rc;
243         if (options[0] != '\0') {
244                 rc = strlcat(options, ",", options_len);
245                 if (rc >= options_len)
246                         goto out_err;
247         }
248         rc = strlcat(options, param, options_len);
249         if (rc >= options_len)
250                 goto out_err;
251         if (value != NULL) {
252                 rc = strlcat(options, value, options_len);
253                 if (rc >= options_len)
254                         goto out_err;
255         }
256         return 0;
257 out_err:
258         fprintf(stderr, "error: mount options %s%s too long\n", param, value);
259         return E2BIG;
260 }
261
262 /* Replace options with subset of Lustre-specific options, and
263    fill in mount flags */
264 int parse_options(struct mount_opts *mop, char *orig_options,
265                   int *flagp, size_t options_len)
266 {
267         char *options, *opt, *nextopt, *arg, *val;
268         int rc = 0;
269
270         options = calloc(strlen(orig_options) + 1, 1);
271         *flagp = 0;
272         nextopt = orig_options;
273         while ((opt = strsep(&nextopt, ","))) {
274                 if (!*opt)
275                         /* empty option */
276                         continue;
277
278                 /* Handle retries in a slightly different
279                  * manner */
280                 arg = opt;
281                 val = strchr(opt, '=');
282                 /* please note that some ldiskfs mount options are also in
283                  * the form of param=value. We should pay attention not to
284                  * remove those mount options, see bug 22097. */
285                 if (val && strncmp(arg, "md_stripe_cache_size", 20) == 0) {
286                         mop->mo_md_stripe_cache_size = atoi(val + 1);
287                 } else if (val && strncmp(arg, "retry", 5) == 0) {
288                         mop->mo_retry = atoi(val + 1);
289                         if (mop->mo_retry > MAX_RETRIES)
290                                 mop->mo_retry = MAX_RETRIES;
291                         else if (mop->mo_retry < 0)
292                                 mop->mo_retry = 0;
293                 } else if (val && strncmp(arg, "mgssec", 6) == 0) {
294                         rc = append_option(options, options_len, opt, NULL);
295                         if (rc != 0)
296                                 goto out_options;
297                 } else if (strncmp(arg, "nosvc", 5) == 0) {
298                         mop->mo_nosvc = 1;
299                         rc = append_option(options, options_len, opt, NULL);
300                         if (rc != 0)
301                                 goto out_options;
302                 } else if (strcmp(opt, "force") == 0) {
303                         /* XXX special check for 'force' option */
304                         ++mop->mo_force;
305                         printf("force: %d\n", mop->mo_force);
306 #ifdef HAVE_GSS
307                 } else if (val && strncmp(opt, "skpath=", 7) == 0) {
308                         if (strlen(val) + 1 >= sizeof(mop->mo_skpath)) {
309                                 fprintf(stderr,
310                                         "%s: shared key path too long\n",
311                                         progname);
312                                 free(options);
313                                 return -1;
314                         }
315                         strncpy(mop->mo_skpath, val + 1, strlen(val + 1));
316 #endif
317                 } else if (parse_one_option(opt, flagp) == 0) {
318                         /* pass this on as an option */
319                         rc = append_option(options, options_len, opt, NULL);
320                         if (rc != 0)
321                                 goto out_options;
322                 }
323         }
324 #ifdef MS_STRICTATIME
325 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(3, 2, 53, 0)
326         /*
327          * LU-1783
328          * In the future when upstream fixes land in all supported kernels
329          * we should stop forcing MS_STRICTATIME in lustre mounts.
330          * We override the kernel level default of MS_RELATIME for now
331          * due to a kernel vfs level bug in atime updates that fails
332          * to reset timestamps from the future.
333          */
334 #warn "remove MS_STRICTATIME override if kernel updates atime from the future"
335 #endif
336         /* set strictatime to default if NOATIME or RELATIME
337            not given explicit */
338         if (!(*flagp & (MS_NOATIME | MS_RELATIME)))
339                 *flagp |= MS_STRICTATIME;
340 #endif
341         strcpy(orig_options, options);
342
343 out_options:
344         free(options);
345         return rc;
346 }
347
348 /* Add mgsnids from ldd params */
349 static int add_mgsnids(struct mount_opts *mop, char *options,
350                        const char *params, size_t options_len)
351 {
352         char *ptr = (char *)params;
353         char tmp, *sep;
354         int rc = 0;
355
356         while ((ptr = strstr(ptr, PARAM_MGSNODE)) != NULL) {
357                 sep = strchr(ptr, ' ');
358                 if (sep != NULL) {
359                         tmp = *sep;
360                         *sep = '\0';
361                 }
362                 rc = append_option(options, options_len, ptr, NULL);
363                 if (rc != 0)
364                         goto out;
365                 mop->mo_have_mgsnid++;
366                 if (sep) {
367                         *sep = tmp;
368                         ptr = sep;
369                 } else {
370                         break;
371                 }
372         }
373
374 out:
375         return rc;
376 }
377
378 static int clear_update_ondisk(char *source, struct lustre_disk_data *ldd)
379 {
380         char wanted_mountopts[512] = "";
381         struct mkfs_opts mkop;
382         int ret;
383         int ret2;
384
385         memset(&mkop, 0, sizeof(mkop));
386         mkop.mo_ldd = *ldd;
387         mkop.mo_ldd.ldd_flags &= ~LDD_F_UPDATE;
388         mkop.mo_flags = MO_NOHOSTID_CHECK; /* Ignore missing hostid */
389         if (strlen(source) > sizeof(mkop.mo_device)-1) {
390                 fatal();
391                 fprintf(stderr, "Device name too long: %s\n", source);
392                 return -E2BIG;
393         }
394         strncpy(mkop.mo_device, source, sizeof(mkop.mo_device));
395
396         ret = osd_prepare_lustre(&mkop,
397                                  wanted_mountopts, sizeof(wanted_mountopts));
398         if (ret) {
399                 fatal();
400                 fprintf(stderr, "Can't prepare device %s: %s\n",
401                         source, strerror(ret));
402                 return ret;
403         }
404
405         /* Create the loopback file */
406         if (mkop.mo_flags & MO_IS_LOOP) {
407                 ret = access(mkop.mo_device, F_OK);
408                 if (ret) {
409                         ret = errno;
410                         fatal();
411                         fprintf(stderr, "Can't access device %s: %s\n",
412                                         source, strerror(ret));
413                         return ret;
414                 }
415
416                 ret = loop_setup(&mkop);
417                 if (ret) {
418                         fatal();
419                         fprintf(stderr, "Loop device setup for %s failed: %s\n",
420                                         mkop.mo_device, strerror(ret));
421                         return ret;
422                 }
423         }
424         ret = osd_write_ldd(&mkop);
425         if (ret != 0) {
426                 fatal();
427                 fprintf(stderr, "failed to write local files: %s\n",
428                         strerror(ret));
429         }
430
431         ret2 = loop_cleanup(&mkop);
432         if (ret == 0)
433                 ret = ret2;
434
435         return ret;
436 }
437
438 static int parse_ldd(char *source, struct mount_opts *mop,
439                      char *options, size_t options_len)
440 {
441         struct lustre_disk_data *ldd = &mop->mo_ldd;
442         char *cur, *start;
443         int rc = 0;
444
445         rc = osd_is_lustre(source, &ldd->ldd_mount_type);
446         if (rc == 0) {
447                 fprintf(stderr, "%s: %s has not been formatted with mkfs.lustre"
448                         " or the backend filesystem type is not supported by "
449                         "this tool\n", progname, source);
450                 return ENODEV;
451         }
452
453         rc = osd_read_ldd(source, ldd);
454         if (rc) {
455                 fprintf(stderr, "%s: %s failed to read permanent mount"
456                         " data: %s\n", progname, source,
457                         rc >= 0 ? strerror(rc) : "");
458                 return rc;
459         }
460
461         if ((IS_MDT(ldd) || IS_OST(ldd)) &&
462             (ldd->ldd_flags & LDD_F_NEED_INDEX)) {
463                 fprintf(stderr, "%s: %s has no index assigned "
464                         "(probably formatted with old mkfs)\n",
465                         progname, source);
466                 return EINVAL;
467         }
468
469         if (ldd->ldd_flags & LDD_F_UPGRADE14) {
470                 fprintf(stderr, "%s: we cannot upgrade %s from this (very old) "
471                         "Lustre version\n", progname, source);
472                 return EINVAL;
473         }
474
475         if (ldd->ldd_flags & LDD_F_UPDATE)
476                 clear_update_ondisk(source, ldd);
477
478         /* Since we never rewrite ldd, ignore temp flags */
479         ldd->ldd_flags &= ~(LDD_F_VIRGIN | LDD_F_WRITECONF);
480
481         /* svname of the form lustre:OST1234 means never registered */
482         rc = strlen(ldd->ldd_svname);
483         if (strcmp(ldd->ldd_svname, "MGS") != 0) {
484                 if (rc < 8) {
485                         fprintf(stderr, "%s: invalid name '%s'\n",
486                                 progname, ldd->ldd_svname);
487                         return EINVAL;
488                 } else if (ldd->ldd_svname[rc - 8] == ':') {
489                         ldd->ldd_svname[rc - 8] = '-';
490                         ldd->ldd_flags |= LDD_F_VIRGIN;
491                 } else if (ldd->ldd_svname[rc - 8] == '=') {
492                         ldd->ldd_svname[rc - 8] = '-';
493                         ldd->ldd_flags |= LDD_F_WRITECONF;
494                 }
495         }
496         /* backend osd type */
497         rc = append_option(options, options_len, "osd=",
498                            mt_type(ldd->ldd_mount_type));
499         if (rc != 0)
500                 return rc;
501
502         rc = append_option(options, options_len, ldd->ldd_mount_opts, NULL);
503         if (rc != 0)
504                 return rc;
505
506         if (!mop->mo_have_mgsnid) {
507                 /* Only use disk data if mount -o mgsnode=nid wasn't
508                  * specified */
509                 if (ldd->ldd_flags & LDD_F_SV_TYPE_MGS) {
510                         rc = append_option(options, options_len, "mgs", NULL);
511                         if (rc != 0)
512                                 return rc;
513                         mop->mo_have_mgsnid++;
514                 } else {
515                         if (add_mgsnids(mop, options, ldd->ldd_params,
516                                         options_len))
517                                 return E2BIG;
518                 }
519         }
520         /* Better have an mgsnid by now */
521         if (!mop->mo_have_mgsnid) {
522                 fprintf(stderr, "%s: missing option mgsnode=<nid>\n",
523                         progname);
524                 return EINVAL;
525         }
526
527         if (ldd->ldd_flags & LDD_F_VIRGIN) {
528                 rc = append_option(options, options_len, "virgin", NULL);
529                 if (rc != 0)
530                         return rc;
531         }
532         if (ldd->ldd_flags & LDD_F_UPDATE) {
533                 rc = append_option(options, options_len, "update", NULL);
534                 if (rc != 0)
535                         return rc;
536         }
537         if (ldd->ldd_flags & LDD_F_WRITECONF) {
538                 rc = append_option(options, options_len, "writeconf", NULL);
539                 if (rc != 0)
540                         return rc;
541         }
542         if (ldd->ldd_flags & LDD_F_NO_PRIMNODE) {
543                 rc = append_option(options, options_len, "noprimnode", NULL);
544                 if (rc != 0)
545                         return rc;
546         }
547
548         /* prefix every lustre parameter with param= so that in-kernel
549          * mount can recognize them properly and send to MGS at registration */
550         start = ldd->ldd_params;
551         while (start && *start != '\0') {
552                 while (*start == ' ') start++;
553                 if (*start == '\0')
554                         break;
555                 cur = start;
556                 start = strchr(cur, ' ');
557                 if (start) {
558                         *start = '\0';
559                         start++;
560                 }
561                 rc = append_option(options, options_len, "param=", cur);
562                 if (rc != 0)
563                         return rc;
564         }
565
566         /* svname must be last option */
567         rc = append_option(options, options_len, "svname=", ldd->ldd_svname);
568
569         return rc;
570 }
571
572 static void set_defaults(struct mount_opts *mop)
573 {
574         memset(mop, 0, sizeof(*mop));
575         mop->mo_usource = NULL;
576         mop->mo_source = NULL;
577         mop->mo_nomtab = 0;
578         mop->mo_fake = 0;
579         mop->mo_force = 0;
580         mop->mo_retry = 0;
581         mop->mo_have_mgsnid = 0;
582         mop->mo_md_stripe_cache_size = 16384;
583         mop->mo_orig_options = "";
584         mop->mo_nosvc = 0;
585 }
586
587 static int parse_opts(int argc, char *const argv[], struct mount_opts *mop)
588 {
589         static struct option long_opt[] = {
590                 {"fake", 0, 0, 'f'},
591                 {"force", 0, 0, 1},
592                 {"help", 0, 0, 'h'},
593                 {"nomtab", 0, 0, 'n'},
594                 {"options", 1, 0, 'o'},
595                 {"verbose", 0, 0, 'v'},
596                 {"version", 0, 0, 'V'},
597                 {0, 0, 0, 0}
598         };
599         char real_path[PATH_MAX] = {'\0'};
600         FILE *f;
601         char path[256], name[256];
602         size_t sz;
603         char *ptr;
604         int opt, rc;
605
606         while ((opt = getopt_long(argc, argv, "fhno:vV",
607                                   long_opt, NULL)) != EOF){
608                 switch (opt) {
609                 case 1:
610                         ++mop->mo_force;
611                         printf("force: %d\n", mop->mo_force);
612                         break;
613                 case 'f':
614                         ++mop->mo_fake;
615                         printf("fake: %d\n", mop->mo_fake);
616                         break;
617                 case 'h':
618                         usage(stdout);
619                         break;
620                 case 'n':
621                         ++mop->mo_nomtab;
622                         printf("nomtab: %d\n", mop->mo_nomtab);
623                         break;
624                 case 'o':
625                         mop->mo_orig_options = optarg;
626                         break;
627                 case 'v':
628                         ++verbose;
629                         break;
630                 case 'V':
631                         ++version;
632                         fprintf(stdout, "%s %s %s\n", progname,
633                                 LUSTRE_VERSION_STRING, WITH_LIBMOUNT);
634                         return 0;
635                 default:
636                         fprintf(stderr, "%s: unknown option '%c'\n",
637                                         progname, opt);
638                         usage(stderr);
639                         break;
640                 }
641         }
642
643         if (optind + 2 > argc) {
644                 fprintf(stderr, "%s: too few arguments\n", progname);
645                 usage(stderr);
646         }
647
648         mop->mo_usource = argv[optind];
649         if (!mop->mo_usource) {
650                 usage(stderr);
651         }
652
653         /**
654          * Try to get the real path to the device, in case it is a
655          * symbolic link for instance
656          */
657         if (realpath(mop->mo_usource, real_path) != NULL) {
658                 ptr = strrchr(real_path, '/');
659                 if (ptr && strncmp(ptr, "/dm-", 4) == 0 && isdigit(*(ptr + 4))) {
660                         snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptr+1);
661                         if ((f = fopen(path, "r"))) {
662                                 /* read "<name>\n" from sysfs */
663                                 if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
664                                         name[sz - 1] = '\0';
665                                         snprintf(real_path, sizeof(real_path), "/dev/mapper/%s", name);
666                                 }
667                                 fclose(f);
668                         }
669                 }
670                 mop->mo_usource = strdup(real_path);
671         }
672
673         ptr = strstr(mop->mo_usource, ":/");
674         if (ptr != NULL) {
675                 mop->mo_source = convert_hostnames(mop->mo_usource);
676                 if (!mop->mo_source)
677                         usage(stderr);
678         } else {
679                 mop->mo_source = strdup(mop->mo_usource);
680         }
681
682         if (realpath(argv[optind + 1], mop->mo_target) == NULL) {
683                 rc = errno;
684                 fprintf(stderr, "warning: %s: cannot resolve: %s\n",
685                                 argv[optind + 1], strerror(errno));
686                 return rc;
687         }
688
689         return 0;
690 }
691
692 int main(int argc, char *const argv[])
693 {
694         struct mount_opts mop;
695         char *options;
696         int i, flags;
697         int rc;
698         bool client;
699         size_t maxopt_len;
700         size_t g_pagesize;
701
702         progname = strrchr(argv[0], '/');
703         progname = progname ? progname + 1 : argv[0];
704
705         set_defaults(&mop);
706
707         g_pagesize = sysconf(_SC_PAGESIZE);
708         if (g_pagesize == -1) {
709                 rc = errno;
710                 printf("error: %d failed to get page size.\n", rc);
711                 return rc;
712         }
713         maxopt_len = MIN(g_pagesize, 64 * 1024);
714
715         rc = parse_opts(argc, argv, &mop);
716         if (rc || version)
717                 return rc;
718
719         if (verbose) {
720                 for (i = 0; i < argc; i++)
721                         printf("arg[%d] = %s\n", i, argv[i]);
722                 printf("source = %s (%s), target = %s\n", mop.mo_usource,
723                        mop.mo_source, mop.mo_target);
724                 printf("options = %s\n", mop.mo_orig_options);
725         }
726
727         options = malloc(maxopt_len);
728         if (options == NULL) {
729                 fprintf(stderr, "can't allocate memory for options\n");
730                 rc = ENOMEM;
731                 goto out_mo_source;
732         }
733
734         if (strlen(mop.mo_orig_options) >= maxopt_len) {
735                 fprintf(stderr, "error: mount options too long\n");
736                 rc = E2BIG;
737                 goto out_options;
738         }
739
740         strcpy(options, mop.mo_orig_options);
741         rc = parse_options(&mop, options, &flags, maxopt_len);
742         if (rc) {
743                 fprintf(stderr, "%s: can't parse options: %s\n",
744                         progname, options);
745                 rc = EINVAL;
746                 goto out_options;
747         }
748
749         if (!mop.mo_force) {
750                 rc = check_mtab_entry(mop.mo_usource, mop.mo_source,
751                                       mop.mo_target, "lustre");
752                 if (rc && !(flags & MS_REMOUNT)) {
753                         fprintf(stderr, "%s: according to %s %s is "
754                                 "already mounted on %s\n", progname, MOUNTED,
755                                 mop.mo_usource, mop.mo_target);
756                         rc = EEXIST;
757                         goto out_options;
758                 }
759                 if (!rc && (flags & MS_REMOUNT)) {
760                         fprintf(stderr, "%s: according to %s %s is "
761                                 "not already mounted on %s\n", progname, MOUNTED,
762                                 mop.mo_usource, mop.mo_target);
763                         rc = ENOENT;
764                         goto out_options;
765                 }
766         }
767         if (flags & MS_REMOUNT)
768                 mop.mo_nomtab++;
769
770         rc = access(mop.mo_target, F_OK);
771         if (rc) {
772                 rc = errno;
773                 fprintf(stderr, "%s: %s inaccessible: %s\n", progname,
774                         mop.mo_target, strerror(errno));
775                 goto out_options;
776         }
777
778         client = (strstr(mop.mo_usource, ":/") != NULL);
779         if (!client) {
780                 rc = osd_init();
781                 if (rc)
782                         goto out_options;
783
784                 rc = parse_ldd(mop.mo_source, &mop, options, maxopt_len);
785                 if (rc)
786                         goto out_osd;
787         }
788
789         /* In Linux 2.4, the target device doesn't get passed to any of our
790            functions.  So we'll stick it on the end of the options. */
791         rc = append_option(options, maxopt_len, "device=", mop.mo_source);
792         if (rc != 0)
793                 goto out_osd;
794
795         if (verbose)
796                 printf("mounting device %s at %s, flags=%#x options=%s\n",
797                        mop.mo_source, mop.mo_target, flags, options);
798
799         if (!client && osd_tune_lustre(mop.mo_source, &mop)) {
800                 if (verbose)
801                         fprintf(stderr, "%s: unable to set tunables for %s"
802                                         " (may cause reduced IO performance)\n",
803                                         argv[0], mop.mo_source);
804         }
805
806 #ifdef HAVE_GSS
807         if (mop.mo_skpath[0] != '\0') {
808                 /* Treat shared key failures as fatal */
809                 rc = load_shared_keys(&mop);
810                 if (rc) {
811                         fprintf(stderr,
812                                 "%s: Error loading shared keys: %s\n",
813                                 progname, strerror(rc));
814                         goto out_osd;
815                 }
816         }
817 #endif /* HAVE_GSS */
818
819         if (!mop.mo_fake) {
820                 /* flags and target get to lustre_get_sb(), but not
821                  * lustre_fill_super().  Lustre ignores the flags, but mount
822                  * does not. */
823                 for (i = 0, rc = -EAGAIN; i <= mop.mo_retry && rc != 0; i++) {
824                         rc = mount(mop.mo_source, mop.mo_target, "lustre",
825                                    flags, (void *)options);
826                         if (rc == 0) {
827                                 /* change label from <fsname>:<index> to
828                                  * <fsname>-<index> to indicate the device has
829                                  *  been registered. only if the label is
830                                  *  supposed to be changed and target service
831                                  *  is supposed to start */
832                                 if (mop.mo_ldd.ldd_flags &
833                                    (LDD_F_VIRGIN | LDD_F_WRITECONF)) {
834                                         if (mop.mo_nosvc == 0)
835                                                 (void)osd_label_lustre(&mop);
836                                 }
837                         } else {
838                                 if (verbose) {
839                                         fprintf(stderr, "%s: mount %s at %s "
840                                                 "failed: %s retries left: "
841                                                 "%d\n", basename(progname),
842                                                 mop.mo_usource, mop.mo_target,
843                                                 strerror(errno),
844                                                 mop.mo_retry - i);
845                                 }
846
847                                 if (mop.mo_retry) {
848                                         int limit = i/2 > 5 ? i/2 : 5;
849
850                                         sleep(1 << limit);
851                                 } else {
852                                         rc = errno;
853                                 }
854                         }
855                 }
856         }
857
858         if (rc) {
859                 char *cli;
860
861                 rc = errno;
862
863                 cli = strrchr(mop.mo_usource, ':');
864                 if (cli && (strlen(cli) > 2))
865                         cli += 2;
866                 else
867                         cli = NULL;
868
869                 fprintf(stderr, "%s: mount %s at %s failed: %s\n", progname,
870                         mop.mo_usource, mop.mo_target, strerror(errno));
871                 if (errno == EBUSY)
872                         fprintf(stderr, "Is the backend filesystem mounted?\n"
873                                         "Check /etc/mtab and /proc/mounts\n");
874                 if (errno == ENODEV)
875                         fprintf(stderr, "Are the lustre modules loaded?\n"
876                                 "Check /etc/modprobe.conf and "
877                                 "/proc/filesystems\n");
878                 if (errno == ENOTBLK)
879                         fprintf(stderr, "Do you need -o loop?\n");
880                 if (errno == ENOMEDIUM)
881                         fprintf(stderr,
882                                 "This filesystem needs at least 1 OST\n");
883                 if (errno == ENOENT) {
884                         fprintf(stderr, "Is the MGS specification correct?\n");
885                         fprintf(stderr, "Is the filesystem name correct?\n");
886                         fprintf(stderr, "If upgrading, is the copied client log"
887                                 " valid? (see upgrade docs)\n");
888                 }
889                 if (errno == EALREADY)
890                         fprintf(stderr, "The target service is already running."
891                                 " (%s)\n", mop.mo_usource);
892                 if (errno == ENXIO)
893                         fprintf(stderr, "The target service failed to start "
894                                 "(bad config log?) (%s).  "
895                                 "See /var/log/messages.\n", mop.mo_usource);
896                 if (errno == EIO)
897                         fprintf(stderr, "Is the MGS running?\n");
898                 if (errno == EADDRINUSE)
899                         fprintf(stderr, "The target service's index is already "
900                                 "in use. (%s)\n", mop.mo_usource);
901                 if (errno == EINVAL) {
902                         fprintf(stderr, "This may have multiple causes.\n");
903                         if (cli)
904                                 fprintf(stderr, "Is '%s' the correct filesystem"
905                                         " name?\n", cli);
906                         fprintf(stderr, "Are the mount options correct?\n");
907                         fprintf(stderr, "Check the syslog for more info.\n");
908                 }
909
910                 /* May as well try to clean up loop devs */
911                 if (strncmp(mop.mo_usource, "/dev/loop", 9) == 0) {
912                         char cmd[256];
913                         int ret;
914                         sprintf(cmd, "/sbin/losetup -d %s", mop.mo_usource);
915                         if ((ret = system(cmd)) < 0)
916                                 rc = errno;
917                         else if (ret > 0)
918                                 rc = WEXITSTATUS(ret);
919                 }
920
921         } else {
922                 /* Deal with utab just for client. Note that we ignore
923                  * the return value here since it is not worth to fail
924                  * mount by prevent some rare cases */
925                 if (strstr(mop.mo_usource, ":/") != NULL)
926                         update_utab_entry(&mop);
927                 if (!mop.mo_nomtab) {
928                         rc = update_mtab_entry(mop.mo_usource, mop.mo_target,
929                                                "lustre", mop.mo_orig_options,
930                                                0, 0, 0);
931                 }
932         }
933
934 out_osd:
935         if (!client)
936                 osd_fini();
937
938 out_options:
939         free(options);
940
941 out_mo_source:
942         /* mo_usource should be freed, but we can rely on the kernel */
943         free(mop.mo_source);
944         return rc;
945 }