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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt