• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/fstools/block.c

  1 /*
  2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
  3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
  4  *
  5  * This program is free software; you can redistribute it and/or modify
  6  * it under the terms of the GNU Lesser General Public License version 2.1
  7  * as published by the Free Software Foundation
  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 
 15 #define _GNU_SOURCE
 16 #include <getopt.h>
 17 #include <stdio.h>
 18 #include <unistd.h>
 19 #include <syslog.h>
 20 #include <libgen.h>
 21 #include <glob.h>
 22 #include <dirent.h>
 23 #include <stdarg.h>
 24 #include <string.h>
 25 #include <errno.h>
 26 #include <fcntl.h>
 27 #include <limits.h>
 28 
 29 #include <sys/stat.h>
 30 #include <sys/types.h>
 31 #include <sys/swap.h>
 32 #include <sys/mount.h>
 33 #include <sys/wait.h>
 34 #include <sys/sysmacros.h>
 35 
 36 #include <linux/fs.h>
 37 
 38 #include <uci.h>
 39 #include <uci_blob.h>
 40 
 41 #include <libubox/avl-cmp.h>
 42 #include <libubox/blobmsg_json.h>
 43 #include <libubox/list.h>
 44 #include <libubox/ulog.h>
 45 #include <libubox/utils.h>
 46 #include <libubox/vlist.h>
 47 #include <libubus.h>
 48 
 49 #include "probe.h"
 50 
 51 #define AUTOFS_MOUNT_PATH       "/tmp/run/blockd/"
 52 
 53 #ifdef UBIFS_EXTROOT
 54 #include "libubi/libubi.h"
 55 #endif
 56 
 57 enum {
 58         TYPE_MOUNT,
 59         TYPE_SWAP,
 60 };
 61 
 62 enum {
 63         TYPE_DEV,
 64         TYPE_HOTPLUG,
 65         TYPE_AUTOFS,
 66 };
 67 
 68 struct mount {
 69         struct vlist_node node;
 70         int type;
 71 
 72         char *target;
 73         char *path;
 74         char *options;
 75         uint32_t flags;
 76         char *uuid;
 77         char *label;
 78         char *device;
 79         int extroot;
 80         int autofs;
 81         int overlay;
 82         int disabled_fsck;
 83         unsigned int prio;
 84 };
 85 
 86 static struct vlist_tree mounts;
 87 static struct blob_buf b;
 88 static LIST_HEAD(devices);
 89 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
 90 static unsigned int delay_root;
 91 
 92 enum {
 93         CFG_ANON_MOUNT,
 94         CFG_ANON_SWAP,
 95         CFG_AUTO_MOUNT,
 96         CFG_AUTO_SWAP,
 97         CFG_DELAY_ROOT,
 98         CFG_CHECK_FS,
 99         __CFG_MAX
100 };
101 
102 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
103         [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
104         [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
105         [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
106         [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
107         [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
108         [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
109 };
110 
111 enum {
112         MOUNT_UUID,
113         MOUNT_LABEL,
114         MOUNT_ENABLE,
115         MOUNT_TARGET,
116         MOUNT_DEVICE,
117         MOUNT_OPTIONS,
118         MOUNT_AUTOFS,
119         __MOUNT_MAX
120 };
121 
122 static const struct uci_blob_param_list config_attr_list = {
123         .n_params = __CFG_MAX,
124         .params = config_policy,
125 };
126 
127 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
128         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
129         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
130         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
131         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
132         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
133         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
134         [MOUNT_AUTOFS] = { .name = "autofs", .type = BLOBMSG_TYPE_INT32 },
135 };
136 
137 static const struct uci_blob_param_list mount_attr_list = {
138         .n_params = __MOUNT_MAX,
139         .params = mount_policy,
140 };
141 
142 enum {
143         SWAP_ENABLE,
144         SWAP_UUID,
145         SWAP_LABEL,
146         SWAP_DEVICE,
147         SWAP_PRIO,
148         __SWAP_MAX
149 };
150 
151 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
152         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
153         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
154         [SWAP_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
155         [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
156         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
157 };
158 
159 static const struct uci_blob_param_list swap_attr_list = {
160         .n_params = __SWAP_MAX,
161         .params = swap_policy,
162 };
163 
164 struct mount_flag {
165         const char *name;
166         int32_t flag;
167 };
168 
169 static const struct mount_flag mount_flags[] = {
170         { "sync",               MS_SYNCHRONOUS  },
171         { "async",              ~MS_SYNCHRONOUS },
172         { "dirsync",            MS_DIRSYNC      },
173         { "mand",               MS_MANDLOCK     },
174         { "nomand",             ~MS_MANDLOCK    },
175         { "atime",              ~MS_NOATIME     },
176         { "noatime",            MS_NOATIME      },
177         { "dev",                ~MS_NODEV       },
178         { "nodev",              MS_NODEV        },
179         { "diratime",           ~MS_NODIRATIME  },
180         { "nodiratime",         MS_NODIRATIME   },
181         { "exec",               ~MS_NOEXEC      },
182         { "noexec",             MS_NOEXEC       },
183         { "suid",               ~MS_NOSUID      },
184         { "nosuid",             MS_NOSUID       },
185         { "rw",                 ~MS_RDONLY      },
186         { "ro",                 MS_RDONLY       },
187         { "relatime",           MS_RELATIME     },
188         { "norelatime",         ~MS_RELATIME    },
189         { "strictatime",        MS_STRICTATIME  },
190         { "acl",                MS_POSIXACL     },
191         { "noacl",              ~MS_POSIXACL    },
192         { "nouser_xattr",       MS_NOUSER       },
193         { "user_xattr",         ~MS_NOUSER      },
194 };
195 
196 static char *blobmsg_get_strdup(struct blob_attr *attr)
197 {
198         if (!attr)
199                 return NULL;
200 
201         return strdup(blobmsg_get_string(attr));
202 }
203 
204 static char *blobmsg_get_basename(struct blob_attr *attr)
205 {
206         if (!attr)
207                 return NULL;
208 
209         return strdup(basename(blobmsg_get_string(attr)));
210 }
211 
212 static void parse_mount_options(struct mount *m, char *optstr)
213 {
214         int i;
215         bool is_flag;
216         char *p, *opts, *last;
217 
218         m->flags = 0;
219         m->options = NULL;
220 
221         if (!optstr || !*optstr)
222                 return;
223 
224         m->options = opts = calloc(1, strlen(optstr) + 1);
225 
226         if (!m->options)
227                 return;
228 
229         p = last = optstr;
230 
231         do {
232                 p = strchr(p, ',');
233 
234                 if (p)
235                         *p++ = 0;
236 
237                 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
238                         if (!strcmp(last, mount_flags[i].name)) {
239                                 if (mount_flags[i].flag < 0)
240                                         m->flags &= (uint32_t)mount_flags[i].flag;
241                                 else
242                                         m->flags |= (uint32_t)mount_flags[i].flag;
243                                 is_flag = true;
244                                 break;
245                         }
246                 }
247 
248                 if (!is_flag)
249                         opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
250 
251                 last = p;
252 
253         } while (p);
254 
255         free(optstr);
256 }
257 
258 static int mount_add(struct uci_section *s)
259 {
260         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
261         struct mount *m;
262 
263         blob_buf_init(&b, 0);
264         uci_to_blob(&b, s, &mount_attr_list);
265         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
266 
267         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
268                 return -1;
269 
270         if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
271                 return -1;
272 
273         m = malloc(sizeof(struct mount));
274         m->type = TYPE_MOUNT;
275         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
276         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
277         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
278         m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
279         if (tb[MOUNT_AUTOFS])
280                 m->autofs = blobmsg_get_u32(tb[MOUNT_AUTOFS]);
281         else
282                 m->autofs = 0;
283         parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
284 
285         m->overlay = m->extroot = 0;
286         if (m->target && !strcmp(m->target, "/"))
287                 m->extroot = 1;
288         if (m->target && !strcmp(m->target, "/overlay"))
289                 m->extroot = m->overlay = 1;
290 
291         if (m->target && *m->target != '/') {
292                 ULOG_WARN("ignoring mount section %s due to invalid target '%s'\n",
293                           s->e.name, m->target);
294                 free(m);
295                 return -1;
296         }
297 
298         if (m->uuid)
299                 vlist_add(&mounts, &m->node, m->uuid);
300         else if (m->label)
301                 vlist_add(&mounts, &m->node, m->label);
302         else if (m->device)
303                 vlist_add(&mounts, &m->node, m->device);
304 
305         return 0;
306 }
307 
308 static int swap_add(struct uci_section *s)
309 {
310         struct blob_attr *tb[__SWAP_MAX] = { 0 };
311         struct mount *m;
312 
313         blob_buf_init(&b, 0);
314         uci_to_blob(&b, s, &swap_attr_list);
315         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
316 
317         if (!tb[SWAP_UUID] && !tb[SWAP_LABEL] && !tb[SWAP_DEVICE])
318                 return -1;
319 
320         m = malloc(sizeof(struct mount));
321         memset(m, 0, sizeof(struct mount));
322         m->type = TYPE_SWAP;
323         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
324         m->label = blobmsg_get_strdup(tb[SWAP_LABEL]);
325         m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
326         if (tb[SWAP_PRIO])
327                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
328         if (m->prio)
329                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
330 
331         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
332                 /* store complete swap path */
333                 if (tb[SWAP_DEVICE])
334                         m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
335 
336                 if (m->uuid)
337                         vlist_add(&mounts, &m->node, m->uuid);
338                 else if (m->label)
339                         vlist_add(&mounts, &m->node, m->label);
340                 else if (m->device)
341                         vlist_add(&mounts, &m->node, m->device);
342         }
343 
344         return 0;
345 }
346 
347 static int global_add(struct uci_section *s)
348 {
349         struct blob_attr *tb[__CFG_MAX] = { 0 };
350 
351         blob_buf_init(&b, 0);
352         uci_to_blob(&b, s, &config_attr_list);
353         blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
354 
355         if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
356                 anon_mount = 1;
357         if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
358                 anon_swap = 1;
359 
360         if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
361                 auto_mount = 1;
362         if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
363                 auto_swap = 1;
364 
365         if (tb[CFG_DELAY_ROOT])
366                 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
367 
368         if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
369                 check_fs = 1;
370 
371         return 0;
372 }
373 
374 static struct mount* find_swap(const char *uuid, const char *label, const char *device)
375 {
376         struct mount *m;
377 
378         vlist_for_each_element(&mounts, m, node) {
379                 if (m->type != TYPE_SWAP)
380                         continue;
381                 if (uuid && m->uuid && !strcasecmp(m->uuid, uuid))
382                         return m;
383                 if (label && m->label && !strcmp(m->label, label))
384                         return m;
385                 if (device && m->device && !strcmp(m->device, device))
386                         return m;
387         }
388 
389         return NULL;
390 }
391 
392 static struct mount* find_block(const char *uuid, const char *label, const char *device,
393                                 const char *target)
394 {
395         struct mount *m;
396 
397         vlist_for_each_element(&mounts, m, node) {
398                 if (m->type != TYPE_MOUNT)
399                         continue;
400                 if (m->uuid && uuid && !strcasecmp(m->uuid, uuid))
401                         return m;
402                 if (m->label && label && !strcmp(m->label, label))
403                         return m;
404                 if (m->target && target && !strcmp(m->target, target))
405                         return m;
406                 if (m->device && device && !strcmp(m->device, device))
407                         return m;
408         }
409 
410         return NULL;
411 }
412 
413 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
414                           struct vlist_node *node_old)
415 {
416 }
417 
418 static struct uci_package * config_try_load(struct uci_context *ctx, char *path)
419 {
420         char *file = basename(path);
421         char *dir = dirname(path);
422         char *err;
423         struct uci_package *pkg;
424 
425         uci_set_confdir(ctx, dir);
426         ULOG_INFO("attempting to load %s/%s\n", dir, file);
427 
428         if (uci_load(ctx, file, &pkg)) {
429                 uci_get_errorstr(ctx, &err, file);
430                 ULOG_ERR("unable to load configuration (%s)\n", err);
431 
432                 free(err);
433                 return NULL;
434         }
435 
436         return pkg;
437 }
438 
439 static int config_load(char *cfg)
440 {
441         struct uci_context *ctx = uci_alloc_context();
442         struct uci_package *pkg = NULL;
443         struct uci_element *e;
444         char path[64];
445 
446         vlist_init(&mounts, avl_strcmp, mounts_update);
447 
448         if (cfg) {
449                 snprintf(path, sizeof(path), "%s/upper/etc/config/fstab", cfg);
450                 pkg = config_try_load(ctx, path);
451 
452                 if (!pkg) {
453                         snprintf(path, sizeof(path), "%s/etc/config/fstab", cfg);
454                         pkg = config_try_load(ctx, path);
455                 }
456         }
457 
458         if (!pkg) {
459                 snprintf(path, sizeof(path), "/etc/config/fstab");
460                 pkg = config_try_load(ctx, path);
461         }
462 
463         if (!pkg) {
464                 ULOG_ERR("no usable configuration\n");
465                 return -1;
466         }
467 
468         vlist_update(&mounts);
469         uci_foreach_element(&pkg->sections, e) {
470                 struct uci_section *s = uci_to_section(e);
471 
472                 if (!strcmp(s->type, "mount"))
473                         mount_add(s);
474                 if (!strcmp(s->type, "swap"))
475                         swap_add(s);
476                 if (!strcmp(s->type, "global"))
477                         global_add(s);
478         }
479         vlist_flush(&mounts);
480 
481         return 0;
482 }
483 
484 static struct probe_info* _probe_path(char *path)
485 {
486         struct probe_info *pr, *epr;
487         char tmppath[64];
488 
489         pr = probe_path(path);
490         if (!pr)
491                 return NULL;
492 
493         if (path[5] == 'u' && path[6] == 'b' && path[7] == 'i' &&
494             path[8] >= '' && path[8] <= '9' ) {
495                 /* skip ubi device if not UBIFS (as it requires ubiblock) */
496                 if (strcmp("ubifs", pr->type))
497                         return NULL;
498 
499                 /* skip ubi device if ubiblock device is present */
500                 snprintf(tmppath, sizeof(tmppath), "/dev/ubiblock%s", path + 8);
501                 list_for_each_entry(epr, &devices, list)
502                         if (!strcmp(epr->dev, tmppath))
503                                 return NULL;
504         }
505 
506         return pr;
507 }
508 
509 static int _cache_load(const char *path)
510 {
511         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
512         int j;
513         glob_t gl;
514 
515         if (glob(path, gl_flags, NULL, &gl) < 0)
516                 return -1;
517 
518         for (j = 0; j < gl.gl_pathc; j++) {
519                 struct probe_info *pr = _probe_path(gl.gl_pathv[j]);
520                 if (pr)
521                         list_add_tail(&pr->list, &devices);
522         }
523 
524         globfree(&gl);
525 
526         return 0;
527 }
528 
529 static void cache_load(int mtd)
530 {
531         if (mtd) {
532                 _cache_load("/dev/mtdblock*");
533                 _cache_load("/dev/ubiblock*");
534                 _cache_load("/dev/ubi[0-9]*");
535         }
536         _cache_load("/dev/loop*");
537         _cache_load("/dev/mmcblk*");
538         _cache_load("/dev/sd*");
539         _cache_load("/dev/hd*");
540         _cache_load("/dev/md*");
541         _cache_load("/dev/nvme*");
542         _cache_load("/dev/vd*");
543         _cache_load("/dev/xvd*");
544         _cache_load("/dev/dm-*");
545 }
546 
547 
548 static struct probe_info* find_block_info(char *uuid, char *label, char *path)
549 {
550         struct probe_info *pr = NULL;
551 
552         if (uuid)
553                 list_for_each_entry(pr, &devices, list)
554                         if (pr->uuid && !strcasecmp(pr->uuid, uuid))
555                                 return pr;
556 
557         if (label)
558                 list_for_each_entry(pr, &devices, list)
559                         if (pr->label && !strcmp(pr->label, label))
560                                 return pr;
561 
562         if (path)
563                 list_for_each_entry(pr, &devices, list)
564                         if (pr->dev && !strcmp(basename(pr->dev), basename(path)))
565                                 return pr;
566 
567         return NULL;
568 }
569 
570 static char* find_mount_point(char *block)
571 {
572         FILE *fp = fopen("/proc/self/mountinfo", "r");
573         static char line[256];
574         char *point = NULL, *pos, *tmp, *cpoint, *devname;
575         struct stat s;
576         int rstat;
577         unsigned int minor, major;
578 
579         if (!fp)
580                 return NULL;
581 
582         rstat = stat(block, &s);
583 
584         while (fgets(line, sizeof(line), fp)) {
585                 pos = strchr(line, ' ');
586                 if (!pos)
587                         continue;
588 
589                 pos = strchr(pos + 1, ' ');
590                 if (!pos)
591                         continue;
592 
593                 tmp = ++pos;
594                 pos = strchr(pos, ':');
595                 if (!pos)
596                         continue;
597 
598                 *pos = '\0';
599                 major = atoi(tmp);
600                 tmp = ++pos;
601                 pos = strchr(pos, ' ');
602                 if (!pos)
603                         continue;
604 
605                 *pos = '\0';
606                 minor = atoi(tmp);
607                 pos = strchr(pos + 1, ' ');
608                 if (!pos)
609                         continue;
610                 tmp = ++pos;
611 
612                 pos = strchr(pos, ' ');
613                 if (!pos)
614                         continue;
615                 *pos = '\0';
616                 cpoint = tmp;
617 
618                 pos = strchr(pos + 1, ' ');
619                 if (!pos)
620                         continue;
621 
622                 pos = strchr(pos + 1, ' ');
623                 if (!pos)
624                         continue;
625 
626                 pos = strchr(pos + 1, ' ');
627                 if (!pos)
628                         continue;
629 
630                 tmp = ++pos;
631                 pos = strchr(pos, ' ');
632                 if (!pos)
633                         continue;
634 
635                 *pos = '\0';
636                 devname = tmp;
637                 if (!strcmp(block, devname)) {
638                         point = strdup(cpoint);
639                         break;
640                 }
641 
642                 if (rstat)
643                         continue;
644 
645                 if (!S_ISBLK(s.st_mode))
646                         continue;
647 
648                 if (major == major(s.st_rdev) &&
649                     minor == minor(s.st_rdev)) {
650                         point = strdup(cpoint);
651                         break;
652                 }
653         }
654 
655         fclose(fp);
656 
657         return point;
658 }
659 
660 static int print_block_uci(struct probe_info *pr)
661 {
662         if (!strcmp(pr->type, "swap")) {
663                 printf("config 'swap'\n");
664         } else {
665                 char *mp = find_mount_point(pr->dev);
666 
667                 printf("config 'mount'\n");
668                 if (mp) {
669                         printf("\toption\ttarget\t'%s'\n", mp);
670                         free(mp);
671                 } else {
672                         printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
673                 }
674         }
675         if (pr->uuid)
676                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
677         else
678                 printf("\toption\tdevice\t'%s'\n", pr->dev);
679         printf("\toption\tenabled\t''\n\n");
680 
681         return 0;
682 }
683 
684 static int print_block_info(struct probe_info *pr)
685 {
686         static char *mp;
687 
688         mp = find_mount_point(pr->dev);
689         printf("%s:", pr->dev);
690         if (pr->uuid)
691                 printf(" UUID=\"%s\"", pr->uuid);
692 
693         if (pr->label)
694                 printf(" LABEL=\"%s\"", pr->label);
695 
696         if (pr->version)
697                 printf(" VERSION=\"%s\"", pr->version);
698 
699         if (mp) {
700                 printf(" MOUNT=\"%s\"", mp);
701                 free(mp);
702         }
703 
704         printf(" TYPE=\"%s\"\n", pr->type);
705 
706         return 0;
707 }
708 
709 static void check_filesystem(struct probe_info *pr)
710 {
711         pid_t pid;
712         struct stat statbuf;
713         const char *e2fsck = "/usr/sbin/e2fsck";
714         const char *f2fsck = "/usr/sbin/fsck.f2fs";
715         const char *fatfsck = "/usr/sbin/fsck.fat";
716         const char *btrfsck = "/usr/bin/btrfsck";
717         const char *ntfsck = "/usr/bin/ntfsfix";
718         const char *ckfs;
719 
720         /* UBIFS does not need stuff like fsck */
721         if (!strncmp(pr->type, "ubifs", 5))
722                 return;
723 
724         if (!strncmp(pr->type, "vfat", 4)) {
725                 ckfs = fatfsck;
726         } else if (!strncmp(pr->type, "f2fs", 4)) {
727                 ckfs = f2fsck;
728         } else if (!strncmp(pr->type, "ext", 3)) {
729                 ckfs = e2fsck;
730         } else if (!strncmp(pr->type, "btrfs", 5)) {
731                 ckfs = btrfsck;
732         } else if (!strncmp(pr->type, "ntfs", 4)) {
733                 ckfs = ntfsck;
734         } else {
735                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->type);
736                 return;
737         }
738 
739         if (stat(ckfs, &statbuf) < 0) {
740                 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
741                 return;
742         }
743 
744         pid = fork();
745         if (!pid) {
746                 if(!strncmp(pr->type, "f2fs", 4)) {
747                         execl(ckfs, ckfs, "-f", pr->dev, NULL);
748                         exit(EXIT_FAILURE);
749                 } else if(!strncmp(pr->type, "btrfs", 5)) {
750                         execl(ckfs, ckfs, "--repair", pr->dev, NULL);
751                         exit(EXIT_FAILURE);
752                 } else if(!strncmp(pr->type, "ntfs", 4)) {
753                         execl(ckfs, ckfs, "-b", pr->dev, NULL);
754                         exit(EXIT_FAILURE);
755                 } else {
756                         execl(ckfs, ckfs, "-p", pr->dev, NULL);
757                         exit(EXIT_FAILURE);
758                 }
759         } else if (pid > 0) {
760                 int status;
761 
762                 waitpid(pid, &status, 0);
763                 if (WIFEXITED(status) && WEXITSTATUS(status))
764                         ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
765                 if (WIFSIGNALED(status))
766                         ULOG_ERR("check_filesystem: %s terminated by %s\n", ckfs, strsignal(WTERMSIG(status)));
767         }
768 }
769 
770 static void handle_swapfiles(bool on)
771 {
772         struct stat s;
773         struct mount *m;
774         struct probe_info *pr;
775 
776         vlist_for_each_element(&mounts, m, node)
777         {
778                 if (m->type != TYPE_SWAP || !m->target)
779                         continue;
780 
781                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
782                         continue;
783 
784                 pr = _probe_path(m->target);
785 
786                 if (!pr)
787                         continue;
788 
789                 if (!strcmp(pr->type, "swap")) {
790                         if (on)
791                                 swapon(pr->dev, m->prio);
792                         else
793                                 swapoff(pr->dev);
794                 }
795 
796                 free(pr);
797         }
798 }
799 
800 static void to_devnull(int fd)
801 {
802         int devnull = open("/dev/null", fd ? O_WRONLY : O_RDONLY);
803 
804         if (devnull >= 0)
805                 dup2(devnull, fd);
806 
807         if (devnull > STDERR_FILENO)
808                 close(devnull);
809 }
810 
811 static int exec_mount(const char *source, const char *target,
812                       const char *fstype, const char *options)
813 {
814         pid_t pid;
815         struct stat s;
816         FILE *mount_fd;
817         int err, status, pfds[2];
818         char errmsg[128], cmd[sizeof("/sbin/mount.XXXXXXXXXXXXXXXX\0")];
819 
820         snprintf(cmd, sizeof(cmd), "/sbin/mount.%s", fstype);
821 
822         if (stat(cmd, &s) < 0 || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR)) {
823                 ULOG_ERR("No \"mount.%s\" utility available\n", fstype);
824                 return -1;
825         }
826 
827         if (pipe(pfds) < 0)
828                 return -1;
829 
830         fcntl(pfds[0], F_SETFD, fcntl(pfds[0], F_GETFD) | FD_CLOEXEC);
831         fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
832 
833         pid = vfork();
834 
835         switch (pid) {
836         case -1:
837                 close(pfds[0]);
838                 close(pfds[1]);
839 
840                 return -1;
841 
842         case 0:
843                 to_devnull(STDIN_FILENO);
844                 to_devnull(STDOUT_FILENO);
845 
846                 dup2(pfds[1], STDERR_FILENO);
847                 close(pfds[0]);
848                 close(pfds[1]);
849 
850                 if (options && *options)
851                         execl(cmd, cmd, "-o", options, source, target, NULL);
852                 else
853                         execl(cmd, cmd, source, target, NULL);
854 
855                 return -1;
856 
857         default:
858                 close(pfds[1]);
859 
860                 mount_fd = fdopen(pfds[0], "r");
861 
862                 while (fgets(errmsg, sizeof(errmsg), mount_fd))
863                         ULOG_ERR("mount.%s: %s", fstype, errmsg);
864 
865                 fclose(mount_fd);
866 
867                 err = waitpid(pid, &status, 0);
868 
869                 if (err != -1) {
870                         if (status != 0) {
871                                 ULOG_ERR("mount.%s: failed with status %d\n", fstype, status);
872                                 errno = EINVAL;
873                                 err = -1;
874                         } else {
875                                 errno = 0;
876                                 err = 0;
877                         }
878                 }
879 
880                 break;
881         }
882 
883         return err;
884 }
885 
886 static int handle_mount(const char *source, const char *target,
887                         const char *fstype, struct mount *m)
888 {
889         int i, err;
890         size_t mount_opts_len;
891         char *mount_opts = NULL, *ptr;
892 
893         err = mount(source, target, fstype, m ? m->flags : 0,
894                     (m && m->options) ? m->options : "");
895 
896         /* Requested file system type is not available in kernel,
897            attempt to call mount helper. */
898         if (err == -1 && errno == ENODEV) {
899                 if (m) {
900                         /* Convert mount flags back into string representation,
901                            first calculate needed length of string buffer... */
902                         mount_opts_len = 1 + (m->options ? strlen(m->options) : 0);
903 
904                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
905                                 if ((mount_flags[i].flag > 0) &&
906                                     (mount_flags[i].flag < INT_MAX) &&
907                                     (m->flags & (uint32_t)mount_flags[i].flag))
908                                         mount_opts_len += strlen(mount_flags[i].name) + 1;
909 
910                         /* ... then now allocate and fill it ... */
911                         ptr = mount_opts = calloc(1, mount_opts_len);
912 
913                         if (!ptr) {
914                                 errno = ENOMEM;
915                                 return -1;
916                         }
917 
918                         if (m->options)
919                                 ptr += sprintf(ptr, "%s,", m->options);
920 
921                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
922                                 if ((mount_flags[i].flag > 0) &&
923                                     (mount_flags[i].flag < INT_MAX) &&
924                                     (m->flags & (uint32_t)mount_flags[i].flag))
925                                         ptr += sprintf(ptr, "%s,", mount_flags[i].name);
926 
927                         mount_opts[mount_opts_len - 1] = 0;
928                 }
929 
930                 /* ... and now finally invoke the external mount program */
931                 err = exec_mount(source, target, fstype, mount_opts);
932         }
933 
934         free(mount_opts);
935 
936         return err;
937 }
938 
939 static int blockd_notify(const char *method, char *device, struct mount *m,
940                          struct probe_info *pr)
941 {
942         struct ubus_context *ctx = ubus_connect(NULL);
943         uint32_t id;
944         int err;
945 
946         if (!ctx)
947                 return -ENXIO;
948 
949         if (!ubus_lookup_id(ctx, "block", &id)) {
950                 struct blob_buf buf = { 0 };
951                 char *d = strrchr(device, '/');
952 
953                 if (d)
954                         d++;
955                 else
956                         d = device;
957 
958                 blob_buf_init(&buf, 0);
959 
960                 if (m) {
961 
962                         blobmsg_add_string(&buf, "device", d);
963                         if (m->uuid)
964                                 blobmsg_add_string(&buf, "uuid", m->uuid);
965                         if (m->label)
966                                 blobmsg_add_string(&buf, "label", m->label);
967                         if (m->target)
968                                 blobmsg_add_string(&buf, "target", m->target);
969                         if (m->options)
970                                 blobmsg_add_string(&buf, "options", m->options);
971                         if (m->autofs)
972                                 blobmsg_add_u32(&buf, "autofs", m->autofs);
973                         if (pr->type)
974                                 blobmsg_add_string(&buf, "type", pr->type);
975                         if (pr->version)
976                                 blobmsg_add_string(&buf, "version", pr->version);
977                 } else if (pr) {
978                         blobmsg_add_string(&buf, "device", d);
979                         if (pr->uuid)
980                                 blobmsg_add_string(&buf, "uuid", pr->uuid);
981                         if (pr->label)
982                                 blobmsg_add_string(&buf, "label", pr->label);
983                         if (pr->type)
984                                 blobmsg_add_string(&buf, "type", pr->type);
985                         if (pr->version)
986                                 blobmsg_add_string(&buf, "version", pr->version);
987                         blobmsg_add_u32(&buf, "anon", 1);
988                 } else {
989                         blobmsg_add_string(&buf, "device", d);
990                         blobmsg_add_u32(&buf, "remove", 1);
991                 }
992 
993                 err = ubus_invoke(ctx, id, method, buf.head, NULL, NULL, 3000);
994         } else {
995                 err = -ENOENT;
996         }
997 
998         ubus_free(ctx);
999 
1000         return err;
1001 }
1002 
1003 static int mount_device(struct probe_info *pr, int type)
1004 {
1005         struct mount *m;
1006         struct stat st;
1007         char *_target = NULL;
1008         char *target;
1009         char *device;
1010         char *mp;
1011         int err;
1012 
1013         if (!pr)
1014                 return -1;
1015 
1016         device = basename(pr->dev);
1017 
1018         if (!strcmp(pr->type, "swap")) {
1019                 if ((type == TYPE_HOTPLUG) && !auto_swap)
1020                         return -1;
1021                 m = find_swap(pr->uuid, pr->label, device);
1022                 if (m || anon_swap)
1023                         swapon(pr->dev, (m) ? (m->prio) : (0));
1024 
1025                 return 0;
1026         }
1027 
1028         m = find_block(pr->uuid, pr->label, device, NULL);
1029         if (m && m->extroot)
1030                 return -1;
1031 
1032         mp = find_mount_point(pr->dev);
1033         if (mp) {
1034                 if (m && m->type == TYPE_MOUNT && m->target && strcmp(m->target, mp)) {
1035                         ULOG_ERR("%s is already mounted on %s\n", pr->dev, mp);
1036                         err = -1;
1037                 } else
1038                         err = 0;
1039                 free(mp);
1040                 return err;
1041         }
1042 
1043         if (type == TYPE_HOTPLUG)
1044                 blockd_notify("hotplug", device, m, pr);
1045 
1046         /* Check if device should be mounted & set the target directory */
1047         if (m) {
1048                 switch (type) {
1049                 case TYPE_HOTPLUG:
1050                         if (m->autofs)
1051                                 return 0;
1052                         if (!auto_mount)
1053                                 return -1;
1054                         break;
1055                 case TYPE_AUTOFS:
1056                         if (!m->autofs)
1057                                 return -1;
1058                         break;
1059                 case TYPE_DEV:
1060                         if (m->autofs)
1061                                 return -1;
1062                         break;
1063                 }
1064 
1065                 if (m->autofs) {
1066                         if (asprintf(&_target, "/tmp/run/blockd/%s", device) == -1)
1067                                 exit(ENOMEM);
1068 
1069                         target = _target;
1070                 } else if (m->target) {
1071                         target = m->target;
1072                 } else {
1073                         if (asprintf(&_target, "/mnt/%s", device) == -1)
1074                                 exit(ENOMEM);
1075 
1076                         target = _target;
1077                 }
1078         } else if (anon_mount) {
1079                 if (asprintf(&_target, "/mnt/%s", device) == -1)
1080                         exit(ENOMEM);
1081 
1082                 target = _target;
1083         } else {
1084                 /* No reason to mount this device */
1085                 return 0;
1086         }
1087 
1088         /* Mount the device */
1089 
1090         if (check_fs)
1091                 check_filesystem(pr);
1092 
1093         mkdir_p(target, 0755);
1094         if (!lstat(target, &st) && S_ISLNK(st.st_mode))
1095                 unlink(target);
1096 
1097         err = handle_mount(pr->dev, target, pr->type, m);
1098         if (err) {
1099                 ULOG_ERR("mounting %s (%s) as %s failed (%d) - %m\n",
1100                                 pr->dev, pr->type, target, errno);
1101 
1102                 if (_target)
1103                         free(_target);
1104 
1105                 return err;
1106         }
1107 
1108         if (_target)
1109                 free(_target);
1110 
1111         handle_swapfiles(true);
1112 
1113         if (type != TYPE_AUTOFS)
1114                 blockd_notify("mount", device, NULL, NULL);
1115 
1116         return 0;
1117 }
1118 
1119 static int umount_device(char *path, int type, bool all)
1120 {
1121         char *mp, *devpath;
1122         int err;
1123 
1124         if (strlen(path) > 5 && !strncmp("/dev/", path, 5)) {
1125                 mp = find_mount_point(path);
1126         } else {
1127                 devpath = malloc(strlen(path) + 6);
1128                 strcpy(devpath, "/dev/");
1129                 strcat(devpath, path);
1130                 mp = find_mount_point(devpath);
1131                 free(devpath);
1132         }
1133 
1134         if (!mp)
1135                 return -1;
1136         if (!strcmp(mp, "/") && !all) {
1137                 free(mp);
1138                 return 0;
1139         }
1140         if (type != TYPE_AUTOFS)
1141                 blockd_notify("umount", basename(path), NULL, NULL);
1142 
1143         err = umount2(mp, MNT_DETACH);
1144         if (err) {
1145                 ULOG_ERR("unmounting %s (%s) failed (%d) - %m\n", path, mp,
1146                          errno);
1147         } else {
1148                 ULOG_INFO("unmounted %s (%s)\n", path, mp);
1149                 rmdir(mp);
1150         }
1151 
1152         free(mp);
1153         return err;
1154 }
1155 
1156 static int mount_action(char *action, char *device, int type)
1157 {
1158         char *path = NULL;
1159         struct probe_info *pr;
1160 
1161         if (!action || !device)
1162                 return -1;
1163 
1164         if (!strcmp(action, "remove")) {
1165                 if (type == TYPE_HOTPLUG)
1166                         blockd_notify("hotplug", device, NULL, NULL);
1167 
1168                 umount_device(device, type, true);
1169 
1170                 return 0;
1171         } else if (strcmp(action, "add")) {
1172                 ULOG_ERR("Unkown action %s\n", action);
1173 
1174                 return -1;
1175         }
1176 
1177         if (config_load(NULL))
1178                 return -1;
1179 
1180         cache_load(1);
1181 
1182         list_for_each_entry(pr, &devices, list)
1183                 if (!strcmp(basename(pr->dev), device))
1184                         path = pr->dev;
1185 
1186         if (!path)
1187                 return -1;
1188 
1189         return mount_device(find_block_info(NULL, NULL, path), type);
1190 }
1191 
1192 static int main_hotplug(int argc, char **argv)
1193 {
1194         return mount_action(getenv("ACTION"), getenv("DEVNAME"), TYPE_HOTPLUG);
1195 }
1196 
1197 static int main_autofs(int argc, char **argv)
1198 {
1199         int err = 0;
1200 
1201         if (argc < 3)
1202                 return -1;
1203 
1204         if (!strcmp(argv[2], "start")) {
1205                 struct probe_info *pr;
1206 
1207                 if (config_load(NULL))
1208                         return -1;
1209 
1210                 cache_load(1);
1211                 list_for_each_entry(pr, &devices, list) {
1212                         struct mount *m;
1213                         char *mp;
1214 
1215                         if (!strcmp(pr->type, "swap"))
1216                                 continue;
1217 
1218                         m = find_block(pr->uuid, pr->label, NULL, NULL);
1219                         if (m && m->extroot)
1220                                 continue;
1221 
1222                         blockd_notify("hotplug", pr->dev, m, pr);
1223                         if ((!m || !m->autofs) && (mp = find_mount_point(pr->dev))) {
1224                                 blockd_notify("mount", pr->dev, NULL, NULL);
1225                                 free(mp);
1226                         }
1227                 }
1228         } else {
1229                 if (argc < 4)
1230                         return -EINVAL;
1231 
1232                 err = mount_action(argv[2], argv[3], TYPE_AUTOFS);
1233         }
1234 
1235         if (err) {
1236                 ULOG_ERR("autofs: \"%s\" action has failed: %d\n", argv[2], err);
1237         }
1238 
1239         return err;
1240 }
1241 
1242 static int find_block_mtd(char *name, char *part, int plen)
1243 {
1244         FILE *fp = fopen("/proc/mtd", "r");
1245         static char line[256];
1246         char *index = NULL;
1247 
1248         if(!fp)
1249                 return -1;
1250 
1251         while (!index && fgets(line, sizeof(line), fp)) {
1252                 if (strstr(line, name)) {
1253                         char *eol = strstr(line, ":");
1254 
1255                         if (!eol)
1256                                 continue;
1257 
1258                         *eol = '\0';
1259                         index = &line[3];
1260                 }
1261         }
1262 
1263         fclose(fp);
1264 
1265         if (!index)
1266                 return -1;
1267 
1268         snprintf(part, plen, "/dev/mtdblock%s", index);
1269 
1270         return 0;
1271 }
1272 
1273 #ifdef UBIFS_EXTROOT
1274 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
1275 {
1276         int dev = 0;
1277 
1278         while (ubi_dev_present(libubi, dev))
1279         {
1280                 struct ubi_dev_info dev_info;
1281                 struct ubi_vol_info vol_info;
1282 
1283                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
1284                         continue;
1285                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
1286                         continue;
1287 
1288                 *dev_num = dev_info.dev_num;
1289                 *vol_id = vol_info.vol_id;
1290 
1291                 return 0;
1292         }
1293 
1294         return -1;
1295 }
1296 
1297 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
1298 {
1299         int dev_num;
1300         int vol_id;
1301         int err = -1;
1302 
1303         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1304         if (!err)
1305                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
1306 
1307         return err;
1308 }
1309 
1310 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
1311 {
1312         int dev_num;
1313         int vol_id;
1314         int err = -1;
1315 
1316         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1317         if (!err)
1318                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
1319 
1320         return err;
1321 }
1322 #endif
1323 
1324 static int find_root_dev(char *buf, int len)
1325 {
1326         DIR *d;
1327         dev_t root;
1328         struct stat s;
1329         struct dirent *e;
1330 
1331         if (stat("/", &s))
1332                 return -1;
1333 
1334         if (!(d = opendir("/dev")))
1335                 return -1;
1336 
1337         root = s.st_dev;
1338 
1339         while ((e = readdir(d)) != NULL) {
1340                 snprintf(buf, len, "/dev/%s", e->d_name);
1341 
1342                 if (stat(buf, &s) || s.st_rdev != root)
1343                         continue;
1344 
1345                 closedir(d);
1346                 return 0;
1347         }
1348 
1349         closedir(d);
1350         return -1;
1351 }
1352 
1353 static int test_fs_support(const char *name)
1354 {
1355         char line[128], *p;
1356         int rv = -1;
1357         FILE *f;
1358 
1359         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
1360                 while (fgets(line, sizeof(line), f)) {
1361                         p = strtok(line, "\t\n");
1362 
1363                         if (p && !strcmp(p, "nodev"))
1364                                 p = strtok(NULL, "\t\n");
1365 
1366                         if (p && !strcmp(p, name)) {
1367                                 rv = 0;
1368                                 break;
1369                         }
1370                 }
1371                 fclose(f);
1372         }
1373 
1374         return rv;
1375 }
1376 
1377 /**
1378  * Check if mounted partition is a valid extroot
1379  *
1380  * @path target mount point
1381  *
1382  * Valid extroot partition has to contain /etc/.extroot-uuid with UUID of root
1383  * device. This function reads UUID and verifies it OR writes UUID to
1384  * .extroot-uuid if it doesn't exist yet (first extroot usage).
1385  */
1386 static int check_extroot(char *path)
1387 {
1388         struct probe_info *pr = NULL;
1389         struct probe_info *tmp;
1390         struct stat s;
1391         char uuid[64] = { 0 };
1392         char devpath[32];
1393         char tag[64];
1394         FILE *fp;
1395         int err;
1396 
1397         err = find_block_mtd("\"rootfs\"", devpath, sizeof(devpath));
1398 #ifdef UBIFS_EXTROOT
1399         if (err) {
1400                 libubi_t libubi;
1401 
1402                 libubi = libubi_open();
1403                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1404                 libubi_close(libubi);
1405         }
1406 #endif
1407         if (err) {
1408                 err = find_root_dev(devpath, sizeof(devpath));
1409         }
1410         if (err) {
1411                 ULOG_ERR("extroot: unable to determine root device\n");
1412                 return -1;
1413         }
1414 
1415         /* Find root device probe_info so we know its UUID */
1416         list_for_each_entry(tmp, &devices, list) {
1417                 if (!strcmp(tmp->dev, devpath)) {
1418                         pr = tmp;
1419                         break;
1420                 }
1421         }
1422         if (!pr) {
1423                 ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1424                 return -1;
1425         }
1426 
1427         snprintf(tag, sizeof(tag), "%s/etc", path);
1428         if (stat(tag, &s))
1429                 mkdir_p(tag, 0755);
1430 
1431         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1432         if (stat(tag, &s)) {
1433                 fp = fopen(tag, "w+");
1434                 if (!fp) {
1435                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%m)\n",
1436                                  tag, errno);
1437                         /* return 0 to continue boot regardless of error */
1438                         return 0;
1439                 }
1440                 fputs(pr->uuid, fp);
1441                 fclose(fp);
1442                 return 0;
1443         }
1444 
1445         fp = fopen(tag, "r");
1446         if (!fp) {
1447                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n", tag,
1448                          errno);
1449                 return -1;
1450         }
1451 
1452         if (!fgets(uuid, sizeof(uuid), fp))
1453                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n", tag,
1454                          errno);
1455         fclose(fp);
1456 
1457         if (*uuid && !strcasecmp(uuid, pr->uuid))
1458                 return 0;
1459 
1460         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n", pr->uuid,
1461                  basename(path), uuid);
1462         return -1;
1463 }
1464 
1465 /*
1466  * Read info about extroot from UCI (using prefix) and mount it.
1467  */
1468 static int mount_extroot(char *cfg)
1469 {
1470         char overlay[] = "/tmp/extroot/overlay";
1471         char mnt[] = "/tmp/extroot/mnt";
1472         char *path = mnt;
1473         struct probe_info *pr;
1474         struct mount *m;
1475         int err = -1;
1476 
1477         /* Load @cfg/etc/config/fstab */
1478         if (config_load(cfg))
1479                 return -2;
1480 
1481         /* See if there is extroot-specific mount config */
1482         m = find_block(NULL, NULL, NULL, "/");
1483         if (!m)
1484                 m = find_block(NULL, NULL, NULL, "/overlay");
1485 
1486         if (!m || !m->extroot)
1487         {
1488                 ULOG_INFO("extroot: not configured\n");
1489                 return -1;
1490         }
1491 
1492         /* Find block device pointed by the mount config */
1493         pr = find_block_info(m->uuid, m->label, m->device);
1494 
1495         if (!pr && delay_root){
1496                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1497                 sleep(delay_root);
1498                 make_devs();
1499                 cache_load(1);
1500                 pr = find_block_info(m->uuid, m->label, m->device);
1501         }
1502         if (pr) {
1503                 if (strncmp(pr->type, "ext", 3) &&
1504                     strncmp(pr->type, "f2fs", 4) &&
1505                     strncmp(pr->type, "btrfs", 5) &&
1506                     strncmp(pr->type, "ntfs", 4) &&
1507                     strncmp(pr->type, "ubifs", 5)) {
1508                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4, f2fs, btrfs, ntfs or ubifs\n", pr->type);
1509                         return -1;
1510                 }
1511 
1512                 if (test_fs_support(pr->type)) {
1513                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->type);
1514                         return -1;
1515                 }
1516 
1517                 if (m->overlay)
1518                         path = overlay;
1519                 mkdir_p(path, 0755);
1520 
1521                 if (check_fs)
1522                         check_filesystem(pr);
1523 
1524                 err = mount(pr->dev, path, pr->type, m->flags,
1525                             (m->options) ? (m->options) : (""));
1526 
1527                 if (err) {
1528                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%m)\n",
1529                                  pr->dev, pr->type, path, errno);
1530                 } else if (m->overlay) {
1531                         err = check_extroot(path);
1532                         if (err)
1533                                 umount(path);
1534                 }
1535         } else {
1536                 ULOG_ERR("extroot: cannot find device %s%s\n",
1537                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1538                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1539         }
1540 
1541         return err;
1542 }
1543 
1544 /**
1545  * Look for extroot config and mount it if present
1546  *
1547  * Look for /etc/config/fstab on all supported partitions and use it for
1548  * mounting extroot if specified.
1549  */
1550 static int main_extroot(int argc, char **argv)
1551 {
1552         struct probe_info *pr;
1553         char blkdev_path[32] = { 0 };
1554         int err = -1;
1555 #ifdef UBIFS_EXTROOT
1556         libubi_t libubi;
1557 #endif
1558 
1559         if (!getenv("PREINIT"))
1560                 return -1;
1561 
1562         if (argc != 2) {
1563                 ULOG_ERR("Usage: block extroot\n");
1564                 return -1;
1565         }
1566 
1567         make_devs();
1568         cache_load(1);
1569 
1570         /* enable LOG_INFO messages */
1571         ulog_threshold(LOG_INFO);
1572 
1573         /*
1574          * Look for "rootfs_data". We will want to mount it and check for
1575          * extroot configuration.
1576          */
1577 
1578         /* Start with looking for MTD partition */
1579         find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1580         if (blkdev_path[0]) {
1581                 pr = find_block_info(NULL, NULL, blkdev_path);
1582                 if (pr && !strcmp(pr->type, "jffs2")) {
1583                         char cfg[] = "/tmp/jffs_cfg";
1584 
1585                         /*
1586                          * Mount MTD part and try extroot (using
1587                          * /etc/config/fstab from that partition)
1588                          */
1589                         mkdir_p(cfg, 0755);
1590                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1591                                 err = mount_extroot(cfg);
1592                                 umount2(cfg, MNT_DETACH);
1593                         }
1594                         if (err < 0)
1595                                 rmdir("/tmp/overlay");
1596                         rmdir(cfg);
1597                         return err;
1598                 }
1599         }
1600 
1601 #ifdef UBIFS_EXTROOT
1602         /* ... but it also could be an UBI volume */
1603         memset(blkdev_path, 0, sizeof(blkdev_path));
1604         libubi = libubi_open();
1605         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1606         libubi_close(libubi);
1607         if (blkdev_path[0]) {
1608                 char cfg[] = "/tmp/ubifs_cfg";
1609 
1610                 /* Mount volume and try extroot (using fstab from that vol) */
1611                 mkdir_p(cfg, 0755);
1612                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1613                         err = mount_extroot(cfg);
1614                         umount2(cfg, MNT_DETACH);
1615                 }
1616                 if (err < 0)
1617                         rmdir("/tmp/overlay");
1618                 rmdir(cfg);
1619                 return err;
1620        }
1621 #endif
1622 
1623         /* As a last resort look for /etc/config/fstab on "rootfs" partition */
1624         return mount_extroot(NULL);
1625 }
1626 
1627 static int main_mount(int argc, char **argv)
1628 {
1629         struct probe_info *pr;
1630 
1631         if (config_load(NULL))
1632                 return -1;
1633 
1634         cache_load(1);
1635         list_for_each_entry(pr, &devices, list)
1636                 mount_device(pr, TYPE_DEV);
1637 
1638         handle_swapfiles(true);
1639 
1640         return 0;
1641 }
1642 
1643 static int main_umount(int argc, char **argv)
1644 {
1645         struct probe_info *pr;
1646         bool all = false;
1647 
1648         if (config_load(NULL))
1649                 return -1;
1650 
1651         handle_swapfiles(false);
1652 
1653         cache_load(1);
1654 
1655         if (argc == 3)
1656                 all = !strcmp(argv[2], "-a");
1657 
1658         list_for_each_entry(pr, &devices, list) {
1659                 struct mount *m;
1660 
1661                 if (!strcmp(pr->type, "swap"))
1662                         continue;
1663 
1664                 m = find_block(pr->uuid, pr->label, basename(pr->dev), NULL);
1665                 if (m && m->extroot)
1666                         continue;
1667 
1668                 umount_device(pr->dev, TYPE_DEV, all);
1669         }
1670 
1671         return 0;
1672 }
1673 
1674 static int main_detect(int argc, char **argv)
1675 {
1676         struct probe_info *pr;
1677 
1678         cache_load(0);
1679         printf("config 'global'\n");
1680         printf("\toption\tanon_swap\t''\n");
1681         printf("\toption\tanon_mount\t''\n");
1682         printf("\toption\tauto_swap\t'1'\n");
1683         printf("\toption\tauto_mount\t'1'\n");
1684         printf("\toption\tdelay_root\t'5'\n");
1685         printf("\toption\tcheck_fs\t''\n\n");
1686         list_for_each_entry(pr, &devices, list)
1687                 print_block_uci(pr);
1688 
1689         return 0;
1690 }
1691 
1692 static int main_info(int argc, char **argv)
1693 {
1694         int i;
1695         struct probe_info *pr;
1696 
1697         cache_load(1);
1698         if (argc == 2) {
1699                 list_for_each_entry(pr, &devices, list)
1700                         print_block_info(pr);
1701 
1702                 return 0;
1703         };
1704 
1705         for (i = 2; i < argc; i++) {
1706                 struct stat s;
1707 
1708                 if (stat(argv[i], &s)) {
1709                         ULOG_ERR("failed to stat %s\n", argv[i]);
1710                         continue;
1711                 }
1712                 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1713                         ULOG_ERR("%s is not a block device\n", argv[i]);
1714                         continue;
1715                 }
1716                 pr = find_block_info(NULL, NULL, argv[i]);
1717                 if (pr)
1718                         print_block_info(pr);
1719         }
1720 
1721         return 0;
1722 }
1723 
1724 static int swapon_usage(void)
1725 {
1726         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1727                 "\tStart swapping on [DEVICE]\n"
1728                 " -a\tStart swapping on all swap devices\n"
1729                 " -p pri\tSet priority of swap device\n"
1730                 " -s\tShow summary\n");
1731         return -1;
1732 }
1733 
1734 static int main_swapon(int argc, char **argv)
1735 {
1736         int ch;
1737         FILE *fp;
1738         char *lineptr;
1739         size_t s;
1740         struct probe_info *pr;
1741         int flags = 0;
1742         int pri;
1743         struct stat st;
1744         int err;
1745 
1746         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1747                 switch(ch) {
1748                 case 's':
1749                         fp = fopen("/proc/swaps", "r");
1750                         lineptr = NULL;
1751 
1752                         if (!fp) {
1753                                 ULOG_ERR("failed to open /proc/swaps\n");
1754                                 return -1;
1755                         }
1756                         while (getline(&lineptr, &s, fp) > 0)
1757                                 printf("%s", lineptr);
1758                         if (lineptr)
1759                                 free(lineptr);
1760                         fclose(fp);
1761                         return 0;
1762                 case 'a':
1763                         cache_load(0);
1764                         list_for_each_entry(pr, &devices, list) {
1765                                 if (strcmp(pr->type, "swap"))
1766                                         continue;
1767                                 if (swapon(pr->dev, 0))
1768                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1769                         }
1770                         return 0;
1771                 case 'p':
1772                         pri = atoi(optarg);
1773                         if (pri >= 0)
1774                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1775                         break;
1776                 default:
1777                         return swapon_usage();
1778                 }
1779         }
1780 
1781         if (optind != (argc - 1))
1782                 return swapon_usage();
1783 
1784         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1785                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1786                 return -1;
1787         }
1788         err = swapon(argv[optind], flags);
1789         if (err) {
1790                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1791                 return err;
1792         }
1793 
1794         return 0;
1795 }
1796 
1797 static int main_swapoff(int argc, char **argv)
1798 {
1799         if (argc != 2) {
1800                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1801                         "\tStop swapping on DEVICE\n"
1802                         " -a\tStop swapping on all swap devices\n");
1803                 return -1;
1804         }
1805 
1806         if (!strcmp(argv[1], "-a")) {
1807                 FILE *fp = fopen("/proc/swaps", "r");
1808                 char line[256];
1809 
1810                 if (!fp) {
1811                         ULOG_ERR("failed to open /proc/swaps\n");
1812                         return -1;
1813                 }
1814                 if (fgets(line, sizeof(line), fp))
1815                         while (fgets(line, sizeof(line), fp)) {
1816                                 char *end = strchr(line, ' ');
1817                                 int err;
1818 
1819                                 if (!end)
1820                                         continue;
1821                                 *end = '\0';
1822                                 err = swapoff(line);
1823                                 if (err)
1824                                         ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1825                         }
1826                 fclose(fp);
1827         } else {
1828                 struct stat s;
1829                 int err;
1830 
1831                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1832                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1833                         return -1;
1834                 }
1835                 err = swapoff(argv[1]);
1836                 if (err) {
1837                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1838                         return err;
1839                 }
1840         }
1841 
1842         return 0;
1843 }
1844 
1845 int main(int argc, char **argv)
1846 {
1847         char *base = basename(*argv);
1848 
1849         umask(0);
1850 
1851         ulog_open(-1, -1, "block");
1852         ulog_threshold(LOG_NOTICE);
1853 
1854         if (!strcmp(base, "swapon"))
1855                 return main_swapon(argc, argv);
1856 
1857         if (!strcmp(base, "swapoff"))
1858                 return main_swapoff(argc, argv);
1859 
1860         if ((argc > 1) && !strcmp(base, "block")) {
1861                 if (!strcmp(argv[1], "info"))
1862                         return main_info(argc, argv);
1863 
1864                 if (!strcmp(argv[1], "detect"))
1865                         return main_detect(argc, argv);
1866 
1867                 if (!strcmp(argv[1], "hotplug"))
1868                         return main_hotplug(argc, argv);
1869 
1870                 if (!strcmp(argv[1], "autofs"))
1871                         return main_autofs(argc, argv);
1872 
1873                 if (!strcmp(argv[1], "extroot"))
1874                         return main_extroot(argc, argv);
1875 
1876                 if (!strcmp(argv[1], "mount"))
1877                         return main_mount(argc, argv);
1878 
1879                 if (!strcmp(argv[1], "umount"))
1880                         return main_umount(argc, argv);
1881 
1882                 if (!strcmp(argv[1], "remount")) {
1883                         int ret = main_umount(argc, argv);
1884 
1885                         if (!ret)
1886                                 ret = main_mount(argc, argv);
1887                         return ret;
1888                 }
1889         }
1890 
1891         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1892 
1893         return -1;
1894 }
1895 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt