Whamcloud - gitweb
LU-4629 libcfs: fix buffer overflow of string buffer
[fs/lustre-release.git] / lustre / utils / mount_utils.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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  * Copyright (c) 2012, 2013, Intel Corporation.
30  */
31 /*
32  * This file is part of Lustre, http://www.lustre.org/
33  * Lustre is a trademark of Sun Microsystems, Inc.
34  */
35
36 #if HAVE_CONFIG_H
37 #  include "config.h"
38 #endif /* HAVE_CONFIG_H */
39
40 #include "mount_utils.h"
41 #include <stdio.h>
42 #include <errno.h>
43 #include <string.h>
44 #include <config.h>
45 #include <lustre_disk.h>
46 #include <lustre_ver.h>
47 #include <sys/stat.h>
48 #include <sys/utsname.h>
49 #include <linux/loop.h>
50 #include <dlfcn.h>
51
52 extern char *progname;
53 extern int verbose;
54
55 #define vprint(fmt, arg...) if (verbose > 0) printf(fmt, ##arg)
56 #define verrprint(fmt, arg...) if (verbose >= 0) fprintf(stderr, fmt, ##arg)
57
58 static struct module_backfs_ops *backfs_ops[LDD_MT_LAST];
59
60 void fatal(void)
61 {
62         verbose = 0;
63         fprintf(stderr, "\n%s FATAL: ", progname);
64 }
65
66 int run_command(char *cmd, int cmdsz)
67 {
68         char log[] = "/tmp/run_command_logXXXXXX";
69         int fd = -1, rc;
70
71         if ((cmdsz - strlen(cmd)) < 6) {
72                 fatal();
73                 fprintf(stderr, "Command buffer overflow: %.*s...\n",
74                         cmdsz, cmd);
75                 return ENOMEM;
76         }
77
78         if (verbose > 1) {
79                 printf("cmd: %s\n", cmd);
80         } else {
81                 if ((fd = mkstemp(log)) >= 0) {
82                         close(fd);
83                         strcat(cmd, " >");
84                         strcat(cmd, log);
85                 }
86         }
87         strcat(cmd, " 2>&1");
88
89         /* Can't use popen because we need the rv of the command */
90         rc = system(cmd);
91         if (rc && (fd >= 0)) {
92                 char buf[128];
93                 FILE *fp;
94                 fp = fopen(log, "r");
95                 if (fp) {
96                         while (fgets(buf, sizeof(buf), fp) != NULL) {
97                                 printf("   %s", buf);
98                         }
99                         fclose(fp);
100                 }
101         }
102         if (fd >= 0)
103                 remove(log);
104         return rc;
105 }
106
107 int add_param(char *buf, char *key, char *val)
108 {
109         int end = sizeof(((struct lustre_disk_data *)0)->ldd_params);
110         int start = strlen(buf);
111         int keylen = 0;
112
113         if (key)
114                 keylen = strlen(key);
115         if (start + 1 + keylen + strlen(val) >= end) {
116                 fprintf(stderr, "%s: params are too long-\n%s %s%s\n",
117                         progname, buf, key ? key : "", val);
118                 return 1;
119         }
120
121         sprintf(buf + start, " %s%s", key ? key : "", val);
122         return 0;
123 }
124
125 int get_param(char *buf, char *key, char **val)
126 {
127         int i, key_len = strlen(key);
128         char *ptr;
129
130         ptr = strstr(buf, key);
131         if (ptr) {
132                 *val = strdup(ptr + key_len);
133                 if (*val == NULL)
134                         return ENOMEM;
135
136                 for (i = 0; i < strlen(*val); i++)
137                         if (((*val)[i] == ' ') || ((*val)[i] == '\0'))
138                                 break;
139
140                 (*val)[i] = '\0';
141                 return 0;
142         }
143
144         return ENOENT;
145 }
146
147 char *strscat(char *dst, char *src, int buflen)
148 {
149         dst[buflen - 1] = 0;
150         if (strlen(dst) + strlen(src) >= buflen) {
151                 fprintf(stderr, "string buffer overflow (max %d): '%s' + '%s'"
152                         "\n", buflen, dst, src);
153                 exit(EOVERFLOW);
154         }
155         return strcat(dst, src);
156 }
157
158 char *strscpy(char *dst, char *src, int buflen)
159 {
160         dst[0] = 0;
161         return strscat(dst, src, buflen);
162 }
163
164 int check_mtab_entry(char *spec1, char *spec2, char *mtpt, char *type)
165 {
166         FILE *fp;
167         struct mntent *mnt;
168
169         fp = setmntent(MOUNTED, "r");
170         if (fp == NULL)
171                 return 0;
172
173         while ((mnt = getmntent(fp)) != NULL) {
174                 if ((strcmp(mnt->mnt_fsname, spec1) == 0 ||
175                      strcmp(mnt->mnt_fsname, spec2) == 0) &&
176                     (mtpt == NULL || strcmp(mnt->mnt_dir, mtpt) == 0) &&
177                     (type == NULL || strcmp(mnt->mnt_type, type) == 0)) {
178                         endmntent(fp);
179                         return(EEXIST);
180                 }
181         }
182         endmntent(fp);
183
184         return 0;
185 }
186
187 #define PROC_DIR        "/proc/"
188 static int mtab_is_proc(const char *mtab)
189 {
190         char path[16];
191
192         if (readlink(mtab, path, sizeof(path)) < 0)
193                 return 0;
194
195         if (strncmp(path, PROC_DIR, strlen(PROC_DIR)))
196                 return 0;
197
198         return 1;
199 }
200
201 int update_mtab_entry(char *spec, char *mtpt, char *type, char *opts,
202                 int flags, int freq, int pass)
203 {
204         FILE *fp;
205         struct mntent mnt;
206         int rc = 0;
207
208         /* Don't update mtab if it is linked to any file in /proc direcotry.*/
209         if (mtab_is_proc(MOUNTED))
210                 return 0;
211
212         mnt.mnt_fsname = spec;
213         mnt.mnt_dir = mtpt;
214         mnt.mnt_type = type;
215         mnt.mnt_opts = opts ? opts : "";
216         mnt.mnt_freq = freq;
217         mnt.mnt_passno = pass;
218
219         fp = setmntent(MOUNTED, "a+");
220         if (fp == NULL) {
221                 fprintf(stderr, "%s: setmntent(%s): %s:",
222                         progname, MOUNTED, strerror (errno));
223                 rc = 16;
224         } else {
225                 if ((addmntent(fp, &mnt)) == 1) {
226                         fprintf(stderr, "%s: addmntent: %s:",
227                                 progname, strerror (errno));
228                         rc = 16;
229                 }
230                 endmntent(fp);
231         }
232
233         return rc;
234 }
235
236 /* Search for opt in mntlist, returning true if found.
237  */
238 static int in_mntlist(char *opt, char *mntlist)
239 {
240         char *ml, *mlp, *item, *ctx = NULL;
241
242         if (!(ml = strdup(mntlist))) {
243                 fprintf(stderr, "%s: out of memory\n", progname);
244                 exit(1);
245         }
246         mlp = ml;
247         while ((item = strtok_r(mlp, ",", &ctx))) {
248                 if (!strcmp(opt, item))
249                         break;
250                 mlp = NULL;
251         }
252         free(ml);
253         return (item != NULL);
254 }
255
256 /* Issue a message on stderr for every item in wanted_mountopts that is not
257  * present in mountopts.  The justwarn boolean toggles between error and
258  * warning message.  Return an error count.
259  */
260 int check_mountfsoptions(char *mountopts, char *wanted_mountopts,
261                          int justwarn)
262 {
263         char *ml, *mlp, *item, *ctx = NULL;
264         int errors = 0;
265
266         if (!(ml = strdup(wanted_mountopts))) {
267                 fprintf(stderr, "%s: out of memory\n", progname);
268                 exit(1);
269         }
270         mlp = ml;
271         while ((item = strtok_r(mlp, ",", &ctx))) {
272                 if (!in_mntlist(item, mountopts)) {
273                         fprintf(stderr, "%s: %s mount option `%s' is missing\n",
274                                 progname, justwarn ? "Warning: default"
275                                 : "Error: mandatory", item);
276                         errors++;
277                 }
278                 mlp = NULL;
279         }
280         free(ml);
281         return errors;
282 }
283
284 /* Trim embedded white space, leading and trailing commas from string s.
285  */
286 void trim_mountfsoptions(char *s)
287 {
288         char *p;
289
290         for (p = s; *p; ) {
291                 if (isspace(*p)) {
292                         memmove(p, p + 1, strlen(p + 1) + 1);
293                         continue;
294                 }
295                 p++;
296         }
297
298         while (s[0] == ',')
299                 memmove(&s[0], &s[1], strlen(&s[1]) + 1);
300
301         p = s + strlen(s) - 1;
302         while (p >= s && *p == ',')
303                 *p-- = '\0';
304 }
305
306 /* Setup a file in the first unused loop_device */
307 int loop_setup(struct mkfs_opts *mop)
308 {
309         char loop_base[20];
310         char l_device[64];
311         int i, ret = 0;
312
313         /* Figure out the loop device names */
314         if (!access("/dev/loop0", F_OK | R_OK) ||
315             !access("/dev/loop-control", F_OK | R_OK)) {
316                 strcpy(loop_base, "/dev/loop\0");
317         } else if (!access("/dev/loop/0", F_OK | R_OK)) {
318                 strcpy(loop_base, "/dev/loop/\0");
319         } else {
320                 fprintf(stderr, "%s: can't access loop devices\n", progname);
321                 return EACCES;
322         }
323
324         /* Find unused loop device */
325         for (i = 0; i < MAX_LOOP_DEVICES; i++) {
326                 char cmd[PATH_MAX];
327                 int cmdsz = sizeof(cmd);
328
329 #ifdef LOOP_CTL_GET_FREE
330                 ret = open("/dev/loop-control", O_RDWR);
331                 if (ret < 0) {
332                         fprintf(stderr, "%s: can't access loop control\n", progname);
333                         return EACCES;
334                 }
335                 /* find or allocate a free loop device to use */
336                 i = ioctl(ret, LOOP_CTL_GET_FREE);
337                 if (i < 0) {
338                         fprintf(stderr, "%s: access loop control error\n", progname);
339                         return EACCES;
340                 }
341                 sprintf(l_device, "%s%d", loop_base, i);
342 #else
343                 sprintf(l_device, "%s%d", loop_base, i);
344                 if (access(l_device, F_OK | R_OK))
345                         break;
346 #endif
347                 snprintf(cmd, cmdsz, "losetup %s > /dev/null 2>&1", l_device);
348                 ret = system(cmd);
349
350                 /* losetup gets 1 (ret=256) for non-set-up device */
351                 if (ret) {
352                         /* Set up a loopback device to our file */
353                         snprintf(cmd, cmdsz, "losetup %s %s", l_device,
354                                  mop->mo_device);
355                         ret = run_command(cmd, cmdsz);
356                         if (ret == 256)
357                                 /* someone else picked up this loop device
358                                  * behind our back */
359                                 continue;
360                         if (ret) {
361                                 fprintf(stderr, "%s: error %d on losetup: %s\n",
362                                         progname, ret,
363                                         ret >= 0 ? strerror(ret) : "");
364                                 return ret;
365                         }
366                         strscpy(mop->mo_loopdev, l_device,
367                                 sizeof(mop->mo_loopdev));
368                         return ret;
369                 }
370         }
371
372         fprintf(stderr, "%s: out of loop devices!\n", progname);
373         return EMFILE;
374 }
375
376 int loop_cleanup(struct mkfs_opts *mop)
377 {
378         char cmd[150];
379         int ret = 0;
380
381         if ((mop->mo_flags & MO_IS_LOOP) && *mop->mo_loopdev) {
382                 int tries;
383
384                 sprintf(cmd, "losetup -d %s", mop->mo_loopdev);
385                 for (tries = 0; tries < 3; tries++) {
386                         ret = run_command(cmd, sizeof(cmd));
387                         if (ret == 0)
388                                 break;
389                         sleep(1);
390                 }
391         }
392
393         if (ret != 0)
394                 fprintf(stderr, "cannot cleanup %s: rc = %d\n",
395                         mop->mo_loopdev, ret);
396         return ret;
397 }
398
399 int loop_format(struct mkfs_opts *mop)
400 {
401         int fd;
402
403         if (mop->mo_device_kb == 0) {
404                 fatal();
405                 fprintf(stderr, "loop device requires a --device-size= "
406                         "param\n");
407                 return EINVAL;
408         }
409
410         fd = creat(mop->mo_device, S_IRUSR|S_IWUSR);
411         if (fd < 0) {
412                 fatal();
413                 fprintf(stderr, "%s: Unable to create backing store: %s\n",
414                         progname, strerror(errno));
415                 return errno;
416         }
417
418         if (ftruncate(fd, mop->mo_device_kb * 1024) != 0) {
419                 close(fd);
420                 fatal();
421                 fprintf(stderr, "%s: Unable to truncate backing store: %s\n",
422                         progname, strerror(errno));
423                 return errno;
424         }
425
426         close(fd);
427         return 0;
428 }
429
430 #define DLSYM(prefix, sym, func)                                        \
431         do {                                                            \
432                 char _fname[64];                                        \
433                 snprintf(_fname, sizeof(_fname), "%s_%s", prefix, #func); \
434                 sym->func = (typeof(sym->func))dlsym(sym->dl_handle, _fname); \
435         } while (0)
436
437 /**
438  * Load plugin for a given mount_type from ${pkglibdir}/mount_osd_FSTYPE.so and
439  * return struct of function pointers (will be freed in unloack_backfs_module).
440  *
441  * \param[in] mount_type        Mount type to load module for.
442  * \retval Value of backfs_ops struct
443  * \retval NULL if no module exists
444  */
445 struct module_backfs_ops *load_backfs_module(enum ldd_mount_type mount_type)
446 {
447         void *handle;
448         char *error, filename[512], fsname[512], *name;
449         struct module_backfs_ops *ops;
450
451         /* This deals with duplicate ldd_mount_types resolving to same OSD layer
452          * plugin (e.g. ext3/ldiskfs/ldiskfs2 all being ldiskfs) */
453         strlcpy(fsname, mt_type(mount_type), sizeof(fsname));
454         name = fsname + sizeof("osd-") - 1;
455
456         /* change osd- to osd_ */
457         fsname[sizeof("osd-") - 2] = '_';
458
459         snprintf(filename, sizeof(filename), PLUGIN_DIR"/mount_%s.so", fsname);
460
461         handle = dlopen(filename, RTLD_LAZY);
462
463         /* Check for $LUSTRE environment variable from test-framework.
464          * This allows using locally built modules to be used.
465          */
466         if (handle == NULL) {
467                 char *dirname;
468                 dirname = getenv("LUSTRE");
469                 if (dirname) {
470                         snprintf(filename, sizeof(filename),
471                                  "%s/utils/.libs/mount_%s.so",
472                                  dirname, fsname);
473                         handle = dlopen(filename, RTLD_LAZY);
474                 }
475         }
476
477         /* Do not clutter up console with missing types */
478         if (handle == NULL)
479                 return NULL;
480
481         ops = malloc(sizeof(*ops));
482         if (ops == NULL) {
483                 dlclose(handle);
484                 return NULL;
485         }
486
487         ops->dl_handle = handle;
488         dlerror(); /* Clear any existing error */
489
490         DLSYM(name, ops, init);
491         DLSYM(name, ops, fini);
492         DLSYM(name, ops, read_ldd);
493         DLSYM(name, ops, write_ldd);
494         DLSYM(name, ops, is_lustre);
495         DLSYM(name, ops, make_lustre);
496         DLSYM(name, ops, prepare_lustre);
497         DLSYM(name, ops, tune_lustre);
498         DLSYM(name, ops, label_lustre);
499         DLSYM(name, ops, enable_quota);
500
501         error = dlerror();
502         if (error != NULL) {
503                 fatal();
504                 fprintf(stderr, "%s\n", error);
505                 dlclose(handle);
506                 free(ops);
507                 return NULL;
508         }
509         return ops;
510 }
511
512 /**
513  * Unload plugin and free backfs_ops structure. Must be called the same number
514  * of times as load_backfs_module is.
515  */
516 void unload_backfs_module(struct module_backfs_ops *ops)
517 {
518         if (ops == NULL)
519                 return;
520
521         dlclose(ops->dl_handle);
522         free(ops);
523 }
524
525 /* Return true if backfs_ops has operations for the given mount_type. */
526 int backfs_mount_type_okay(enum ldd_mount_type mount_type)
527 {
528         if (unlikely(mount_type >= LDD_MT_LAST || mount_type < 0)) {
529                 fatal();
530                 fprintf(stderr, "fs type out of range %d\n", mount_type);
531                 return 0;
532         }
533         if (backfs_ops[mount_type] == NULL) {
534                 fatal();
535                 fprintf(stderr, "unhandled fs type %d '%s'\n",
536                         mount_type, mt_str(mount_type));
537                 return 0;
538         }
539         return 1;
540 }
541
542 /* Write the server config files */
543 int osd_write_ldd(struct mkfs_opts *mop)
544 {
545         struct lustre_disk_data *ldd = &mop->mo_ldd;
546         int ret;
547
548         if (backfs_mount_type_okay(ldd->ldd_mount_type))
549                 ret = backfs_ops[ldd->ldd_mount_type]->write_ldd(mop);
550
551         else
552                 ret = EINVAL;
553
554         return ret;
555 }
556
557 /* Read the server config files */
558 int osd_read_ldd(char *dev, struct lustre_disk_data *ldd)
559 {
560         int ret;
561
562         if (backfs_mount_type_okay(ldd->ldd_mount_type))
563                 ret = backfs_ops[ldd->ldd_mount_type]->read_ldd(dev, ldd);
564
565         else
566                 ret = EINVAL;
567
568         return ret;
569 }
570
571 /* Was this device formatted for Lustre */
572 int osd_is_lustre(char *dev, unsigned *mount_type)
573 {
574         int i;
575
576         vprint("checking for existing Lustre data: ");
577
578         for (i = 0; i < LDD_MT_LAST; ++i) {
579                 if (backfs_ops[i] != NULL &&
580                     backfs_ops[i]->is_lustre(dev, mount_type)) {
581                         vprint("found\n");
582                         return 1;
583                 }
584         }
585
586         vprint("not found\n");
587         return 0;
588 }
589
590 /* Build fs according to type */
591 int osd_make_lustre(struct mkfs_opts *mop)
592 {
593         struct lustre_disk_data *ldd = &mop->mo_ldd;
594         int ret;
595
596         if (backfs_mount_type_okay(ldd->ldd_mount_type))
597                 ret = backfs_ops[ldd->ldd_mount_type]->make_lustre(mop);
598
599         else
600                 ret = EINVAL;
601
602         return ret;
603 }
604
605 int osd_prepare_lustre(struct mkfs_opts *mop,
606                 char *default_mountopts, int default_len,
607                 char *always_mountopts, int always_len)
608 {
609         struct lustre_disk_data *ldd = &mop->mo_ldd;
610         int ret;
611
612         if (backfs_mount_type_okay(ldd->ldd_mount_type))
613                 ret = backfs_ops[ldd->ldd_mount_type]->prepare_lustre(mop,
614                         default_mountopts, default_len,
615                         always_mountopts, always_len);
616
617         else
618                 ret = EINVAL;
619
620         return ret;
621 }
622
623 int osd_tune_lustre(char *dev, struct mount_opts *mop)
624 {
625         struct lustre_disk_data *ldd = &mop->mo_ldd;
626         int ret;
627
628         if (backfs_mount_type_okay(ldd->ldd_mount_type))
629                 ret = backfs_ops[ldd->ldd_mount_type]->tune_lustre(dev, mop);
630
631         else
632                 ret = EINVAL;
633
634         return ret;
635 }
636
637 int osd_label_lustre(struct mount_opts *mop)
638 {
639         struct lustre_disk_data *ldd = &mop->mo_ldd;
640         int ret;
641
642         if (backfs_mount_type_okay(ldd->ldd_mount_type))
643                 ret = backfs_ops[ldd->ldd_mount_type]->label_lustre(mop);
644
645         else
646                 ret = EINVAL;
647
648         return ret;
649 }
650
651 /* Enable quota accounting */
652 int osd_enable_quota(struct mkfs_opts *mop)
653 {
654         struct lustre_disk_data *ldd = &mop->mo_ldd;
655         int ret;
656
657         if (backfs_mount_type_okay(ldd->ldd_mount_type))
658                 ret = backfs_ops[ldd->ldd_mount_type]->enable_quota(mop);
659
660         else
661                 ret = EINVAL;
662
663         return ret;
664 }
665
666 int osd_init(void)
667 {
668         int i, ret = 0;
669
670         for (i = 0; i < LDD_MT_LAST; ++i) {
671                 backfs_ops[i] = load_backfs_module(i);
672                 if (backfs_ops[i] != NULL)
673                         ret = backfs_ops[i]->init();
674                 if (ret)
675                         break;
676         }
677
678         return ret;
679 }
680
681 void osd_fini(void)
682 {
683         int i;
684
685         for (i = 0; i < LDD_MT_LAST; ++i) {
686                 if (backfs_ops[i] != NULL) {
687                         backfs_ops[i]->fini();
688                         unload_backfs_module(backfs_ops[i]);
689                         backfs_ops[i] = NULL;
690                 }
691         }
692 }
693
694 __u64 get_device_size(char* device)
695 {
696         int ret, fd;
697         __u64 size = 0;
698
699         fd = open(device, O_RDONLY);
700         if (fd < 0) {
701                 fprintf(stderr, "%s: cannot open %s: %s\n",
702                         progname, device, strerror(errno));
703                 return 0;
704         }
705
706 #ifdef BLKGETSIZE64
707         /* size in bytes. bz5831 */
708         ret = ioctl(fd, BLKGETSIZE64, (void*)&size);
709 #else
710         {
711                 __u32 lsize = 0;
712                 /* size in blocks */
713                 ret = ioctl(fd, BLKGETSIZE, (void*)&lsize);
714                 size = (__u64)lsize * 512;
715         }
716 #endif
717         close(fd);
718         if (ret < 0) {
719                 fprintf(stderr, "%s: size ioctl failed: %s\n",
720                         progname, strerror(errno));
721                 return 0;
722         }
723
724         vprint("device size = "LPU64"MB\n", size >> 20);
725         /* return value in KB */
726         return size >> 10;
727 }
728
729 int file_create(char *path, __u64 size)
730 {
731         __u64 size_max;
732         int ret;
733         int fd;
734
735         /*
736          * Since "size" is in KB, the file offset it represents could overflow
737          * off_t.
738          */
739         size_max = (off_t)1 << (_FILE_OFFSET_BITS - 1 - 10);
740         if (size >= size_max) {
741                 fprintf(stderr, "%s: "LPU64" KB: Backing store size must be "
742                         "smaller than "LPU64" KB\n", progname, size, size_max);
743                 return EFBIG;
744         }
745
746         ret = access(path, F_OK);
747         if (ret == 0) {
748                 ret = unlink(path);
749                 if (ret != 0)
750                         return errno;
751         }
752
753         fd = creat(path, S_IRUSR|S_IWUSR);
754         if (fd < 0) {
755                 fatal();
756                 fprintf(stderr, "%s: Unable to create backing store: %s\n",
757                         progname, strerror(errno));
758                 return errno;
759         }
760
761         ret = ftruncate(fd, size * 1024);
762         close(fd);
763         if (ret != 0) {
764                 fatal();
765                 fprintf(stderr, "%s: Unable to truncate backing store: %s\n",
766                         progname, strerror(errno));
767                 return errno;
768         }
769
770         return 0;
771 }