• 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 }
597 
598 
599 static struct probe_info* find_block_info(char *uuid, char *label, char *path)
600 {
601         struct probe_info *pr = NULL;
602 
603         if (uuid)
604                 list_for_each_entry(pr, &devices, list)
605                         if (pr->uuid && !strcasecmp(pr->uuid, uuid))
606                                 return pr;
607 
608         if (label)
609                 list_for_each_entry(pr, &devices, list)
610                         if (pr->label && !strcmp(pr->label, label))
611                                 return pr;
612 
613         if (path)
614                 list_for_each_entry(pr, &devices, list)
615                         if (pr->dev && !strcmp(basename(pr->dev), basename(path)))
616                                 return pr;
617 
618         return NULL;
619 }
620 
621 static char* find_mount_point(char *block)
622 {
623         FILE *fp = fopen("/proc/self/mountinfo", "r");
624         static char line[256];
625         char *point = NULL, *pos, *tmp, *cpoint, *devname;
626         struct stat s;
627         int rstat;
628         unsigned int minor, major;
629 
630         if (!fp)
631                 return NULL;
632 
633         rstat = stat(block, &s);
634 
635         while (fgets(line, sizeof(line), fp)) {
636                 pos = strchr(line, ' ');
637                 if (!pos)
638                         continue;
639 
640                 pos = strchr(pos + 1, ' ');
641                 if (!pos)
642                         continue;
643 
644                 tmp = ++pos;
645                 pos = strchr(pos, ':');
646                 if (!pos)
647                         continue;
648 
649                 *pos = '\0';
650                 major = atoi(tmp);
651                 tmp = ++pos;
652                 pos = strchr(pos, ' ');
653                 if (!pos)
654                         continue;
655 
656                 *pos = '\0';
657                 minor = atoi(tmp);
658                 pos = strchr(pos + 1, ' ');
659                 if (!pos)
660                         continue;
661                 tmp = ++pos;
662 
663                 pos = strchr(pos, ' ');
664                 if (!pos)
665                         continue;
666                 *pos = '\0';
667                 cpoint = tmp;
668 
669                 pos = strchr(pos + 1, ' ');
670                 if (!pos)
671                         continue;
672 
673                 pos = strchr(pos + 1, ' ');
674                 if (!pos)
675                         continue;
676 
677                 pos = strchr(pos + 1, ' ');
678                 if (!pos)
679                         continue;
680 
681                 tmp = ++pos;
682                 pos = strchr(pos, ' ');
683                 if (!pos)
684                         continue;
685 
686                 *pos = '\0';
687                 devname = tmp;
688                 if (!strcmp(block, devname)) {
689                         point = strdup(cpoint);
690                         break;
691                 }
692 
693                 if (rstat)
694                         continue;
695 
696                 if (!S_ISBLK(s.st_mode))
697                         continue;
698 
699                 if (major == major(s.st_rdev) &&
700                     minor == minor(s.st_rdev)) {
701                         point = strdup(cpoint);
702                         break;
703                 }
704         }
705 
706         fclose(fp);
707 
708         return point;
709 }
710 
711 static int print_block_uci(struct probe_info *pr)
712 {
713         if (!strcmp(pr->type, "swap")) {
714                 printf("config 'swap'\n");
715         } else {
716                 char *mp = find_mount_point(pr->dev);
717 
718                 printf("config 'mount'\n");
719                 if (mp) {
720                         printf("\toption\ttarget\t'%s'\n", mp);
721                         free(mp);
722                 } else {
723                         printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
724                 }
725         }
726         if (pr->uuid)
727                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
728         else
729                 printf("\toption\tdevice\t'%s'\n", pr->dev);
730         printf("\toption\tenabled\t''\n\n");
731 
732         return 0;
733 }
734 
735 static int print_block_info(struct probe_info *pr)
736 {
737         static char *mp;
738 
739         mp = find_mount_point(pr->dev);
740         printf("%s:", pr->dev);
741         if (pr->uuid)
742                 printf(" UUID=\"%s\"", pr->uuid);
743 
744         if (pr->label)
745                 printf(" LABEL=\"%s\"", pr->label);
746 
747         if (pr->version)
748                 printf(" VERSION=\"%s\"", pr->version);
749 
750         if (mp) {
751                 printf(" MOUNT=\"%s\"", mp);
752                 free(mp);
753         }
754 
755         printf(" TYPE=\"%s\"\n", pr->type);
756 
757         return 0;
758 }
759 
760 static void check_filesystem(struct probe_info *pr)
761 {
762         pid_t pid;
763         struct stat statbuf;
764         const char *e2fsck = "/usr/sbin/e2fsck";
765         const char *f2fsck = "/usr/sbin/fsck.f2fs";
766         const char *fatfsck = "/usr/sbin/fsck.fat";
767         const char *btrfsck = "/usr/bin/btrfsck";
768         const char *ntfsck = "/usr/bin/ntfsfix";
769         const char *ckfs;
770 
771         /* UBIFS does not need stuff like fsck */
772         if (!strncmp(pr->type, "ubifs", 5))
773                 return;
774 
775         if (!strncmp(pr->type, "vfat", 4)) {
776                 ckfs = fatfsck;
777         } else if (!strncmp(pr->type, "f2fs", 4)) {
778                 ckfs = f2fsck;
779         } else if (!strncmp(pr->type, "ext", 3)) {
780                 ckfs = e2fsck;
781         } else if (!strncmp(pr->type, "btrfs", 5)) {
782                 ckfs = btrfsck;
783         } else if (!strncmp(pr->type, "ntfs", 4)) {
784                 ckfs = ntfsck;
785         } else {
786                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->type);
787                 return;
788         }
789 
790         if (stat(ckfs, &statbuf) < 0) {
791                 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
792                 return;
793         }
794 
795         pid = fork();
796         if (!pid) {
797                 if(!strncmp(pr->type, "f2fs", 4)) {
798                         execl(ckfs, ckfs, "-f", pr->dev, NULL);
799                         exit(EXIT_FAILURE);
800                 } else if(!strncmp(pr->type, "btrfs", 5)) {
801                         execl(ckfs, ckfs, "--repair", pr->dev, NULL);
802                         exit(EXIT_FAILURE);
803                 } else if(!strncmp(pr->type, "ntfs", 4)) {
804                         execl(ckfs, ckfs, "-b", pr->dev, NULL);
805                         exit(EXIT_FAILURE);
806                 } else {
807                         execl(ckfs, ckfs, "-p", pr->dev, NULL);
808                         exit(EXIT_FAILURE);
809                 }
810         } else if (pid > 0) {
811                 int status;
812 
813                 waitpid(pid, &status, 0);
814                 if (WIFEXITED(status) && WEXITSTATUS(status))
815                         ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
816                 if (WIFSIGNALED(status))
817                         ULOG_ERR("check_filesystem: %s terminated by %s\n", ckfs, strsignal(WTERMSIG(status)));
818         }
819 }
820 
821 static void handle_swapfiles(bool on)
822 {
823         struct stat s;
824         struct mount *m;
825         struct probe_info *pr;
826 
827         vlist_for_each_element(&mounts, m, node)
828         {
829                 if (m->type != TYPE_SWAP || !m->target)
830                         continue;
831 
832                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
833                         continue;
834 
835                 pr = _probe_path(m->target);
836 
837                 if (!pr)
838                         continue;
839 
840                 if (!strcmp(pr->type, "swap")) {
841                         if (on)
842                                 swapon(pr->dev, m->prio);
843                         else
844                                 swapoff(pr->dev);
845                 }
846 
847                 free(pr);
848         }
849 }
850 
851 static void to_devnull(int fd)
852 {
853         int devnull = open("/dev/null", fd ? O_WRONLY : O_RDONLY);
854 
855         if (devnull >= 0)
856                 dup2(devnull, fd);
857 
858         if (devnull > STDERR_FILENO)
859                 close(devnull);
860 }
861 
862 static int exec_mount(const char *source, const char *target,
863                       const char *fstype, const char *options)
864 {
865         pid_t pid;
866         struct stat s;
867         FILE *mount_fd;
868         int err, status, pfds[2];
869         char errmsg[128], cmd[sizeof("/sbin/mount.XXXXXXXXXXXXXXXX\0")];
870 
871         snprintf(cmd, sizeof(cmd), "/sbin/mount.%s", fstype);
872 
873         if (stat(cmd, &s) < 0 || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR)) {
874                 ULOG_ERR("No \"mount.%s\" utility available\n", fstype);
875                 return -1;
876         }
877 
878         if (pipe(pfds) < 0)
879                 return -1;
880 
881         fcntl(pfds[0], F_SETFD, fcntl(pfds[0], F_GETFD) | FD_CLOEXEC);
882         fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
883 
884         pid = vfork();
885 
886         switch (pid) {
887         case -1:
888                 close(pfds[0]);
889                 close(pfds[1]);
890 
891                 return -1;
892 
893         case 0:
894                 to_devnull(STDIN_FILENO);
895                 to_devnull(STDOUT_FILENO);
896 
897                 dup2(pfds[1], STDERR_FILENO);
898                 close(pfds[0]);
899                 close(pfds[1]);
900 
901                 if (options && *options)
902                         execl(cmd, cmd, "-o", options, source, target, NULL);
903                 else
904                         execl(cmd, cmd, source, target, NULL);
905 
906                 return -1;
907 
908         default:
909                 close(pfds[1]);
910 
911                 mount_fd = fdopen(pfds[0], "r");
912 
913                 while (fgets(errmsg, sizeof(errmsg), mount_fd))
914                         ULOG_ERR("mount.%s: %s", fstype, errmsg);
915 
916                 fclose(mount_fd);
917 
918                 err = waitpid(pid, &status, 0);
919 
920                 if (err != -1) {
921                         if (status != 0) {
922                                 ULOG_ERR("mount.%s: failed with status %d\n", fstype, status);
923                                 errno = EINVAL;
924                                 err = -1;
925                         } else {
926                                 errno = 0;
927                                 err = 0;
928                         }
929                 }
930 
931                 break;
932         }
933 
934         return err;
935 }
936 
937 static int handle_mount(const char *source, const char *target,
938                         const char *fstype, struct mount *m)
939 {
940         int i, err;
941         size_t mount_opts_len;
942         char *mount_opts = NULL, *ptr;
943 
944         err = mount(source, target, fstype, m ? m->flags : 0,
945                     (m && m->options) ? m->options : "");
946 
947         /* Requested file system type is not available in kernel,
948            attempt to call mount helper. */
949         if (err == -1 && errno == ENODEV) {
950                 if (m) {
951                         /* Convert mount flags back into string representation,
952                            first calculate needed length of string buffer... */
953                         mount_opts_len = 1 + (m->options ? strlen(m->options) : 0);
954 
955                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
956                                 if ((mount_flags[i].flag > 0) &&
957                                     (mount_flags[i].flag < INT_MAX) &&
958                                     (m->flags & (uint32_t)mount_flags[i].flag))
959                                         mount_opts_len += strlen(mount_flags[i].name) + 1;
960 
961                         /* ... then now allocate and fill it ... */
962                         ptr = mount_opts = calloc(1, mount_opts_len);
963 
964                         if (!ptr) {
965                                 errno = ENOMEM;
966                                 return -1;
967                         }
968 
969                         if (m->options)
970                                 ptr += sprintf(ptr, "%s,", m->options);
971 
972                         for (i = 0; i < ARRAY_SIZE(mount_flags); i++)
973                                 if ((mount_flags[i].flag > 0) &&
974                                     (mount_flags[i].flag < INT_MAX) &&
975                                     (m->flags & (uint32_t)mount_flags[i].flag))
976                                         ptr += sprintf(ptr, "%s,", mount_flags[i].name);
977 
978                         mount_opts[mount_opts_len - 1] = 0;
979                 }
980 
981                 /* ... and now finally invoke the external mount program */
982                 err = exec_mount(source, target, fstype, mount_opts);
983         }
984 
985         free(mount_opts);
986 
987         return err;
988 }
989 
990 static int blockd_notify(const char *method, char *device, struct mount *m,
991                          struct probe_info *pr)
992 {
993         struct ubus_context *ctx = ubus_connect(NULL);
994         uint32_t id;
995         int err;
996 
997         if (!ctx)
998                 return -ENXIO;
999 
1000         if (!ubus_lookup_id(ctx, "block", &id)) {
1001                 struct blob_buf buf = { 0 };
1002                 char *d = strrchr(device, '/');
1003 
1004                 if (d)
1005                         d++;
1006                 else
1007                         d = device;
1008 
1009                 blob_buf_init(&buf, 0);
1010 
1011                 if (m) {
1012 
1013                         blobmsg_add_string(&buf, "device", d);
1014                         if (m->uuid)
1015                                 blobmsg_add_string(&buf, "uuid", m->uuid);
1016                         if (m->label)
1017                                 blobmsg_add_string(&buf, "label", m->label);
1018                         if (m->target)
1019                                 blobmsg_add_string(&buf, "target", m->target);
1020                         if (m->options)
1021                                 blobmsg_add_string(&buf, "options", m->options);
1022                         if (m->autofs)
1023                                 blobmsg_add_u32(&buf, "autofs", m->autofs);
1024                         if (pr->type)
1025                                 blobmsg_add_string(&buf, "type", pr->type);
1026                         if (pr->version)
1027                                 blobmsg_add_string(&buf, "version", pr->version);
1028                 } else if (pr) {
1029                         blobmsg_add_string(&buf, "device", d);
1030                         if (pr->uuid)
1031                                 blobmsg_add_string(&buf, "uuid", pr->uuid);
1032                         if (pr->label)
1033                                 blobmsg_add_string(&buf, "label", pr->label);
1034                         if (pr->type)
1035                                 blobmsg_add_string(&buf, "type", pr->type);
1036                         if (pr->version)
1037                                 blobmsg_add_string(&buf, "version", pr->version);
1038                         blobmsg_add_u32(&buf, "anon", 1);
1039                 } else {
1040                         blobmsg_add_string(&buf, "device", d);
1041                         blobmsg_add_u32(&buf, "remove", 1);
1042                 }
1043 
1044                 err = ubus_invoke(ctx, id, method, buf.head, NULL, NULL, 3000);
1045         } else {
1046                 err = -ENOENT;
1047         }
1048 
1049         ubus_free(ctx);
1050 
1051         return err;
1052 }
1053 
1054 static int mount_device(struct probe_info *pr, int type)
1055 {
1056         struct mount *m;
1057         struct stat st;
1058         char *_target = NULL;
1059         char *target;
1060         char *device;
1061         char *mp;
1062         int err;
1063 
1064         if (!pr)
1065                 return -1;
1066 
1067         device = basename(pr->dev);
1068 
1069         if (!strcmp(pr->type, "swap")) {
1070                 if ((type == TYPE_HOTPLUG) && !auto_swap)
1071                         return -1;
1072                 m = find_swap(pr->uuid, pr->label, device);
1073                 if (m || anon_swap)
1074                         swapon(pr->dev, (m) ? (m->prio) : (0));
1075 
1076                 return 0;
1077         }
1078 
1079         m = find_block(pr->uuid, pr->label, device, NULL);
1080         if (m && m->extroot)
1081                 return -1;
1082 
1083         mp = find_mount_point(pr->dev);
1084         if (mp) {
1085                 if (m && m->type == TYPE_MOUNT && m->target && strcmp(m->target, mp)) {
1086                         ULOG_ERR("%s is already mounted on %s\n", pr->dev, mp);
1087                         err = -1;
1088                 } else
1089                         err = 0;
1090                 free(mp);
1091                 return err;
1092         }
1093 
1094         if (type == TYPE_HOTPLUG)
1095                 blockd_notify("hotplug", device, m, pr);
1096 
1097         /* Check if device should be mounted & set the target directory */
1098         if (m) {
1099                 switch (type) {
1100                 case TYPE_HOTPLUG:
1101                         if (m->autofs)
1102                                 return 0;
1103                         if (!auto_mount)
1104                                 return -1;
1105                         break;
1106                 case TYPE_AUTOFS:
1107                         if (!m->autofs)
1108                                 return -1;
1109                         break;
1110                 case TYPE_DEV:
1111                         if (m->autofs)
1112                                 return -1;
1113                         break;
1114                 }
1115 
1116                 if (m->autofs) {
1117                         if (asprintf(&_target, "/tmp/run/blockd/%s", device) == -1)
1118                                 exit(ENOMEM);
1119 
1120                         target = _target;
1121                 } else if (m->target) {
1122                         target = m->target;
1123                 } else {
1124                         if (asprintf(&_target, "/mnt/%s", device) == -1)
1125                                 exit(ENOMEM);
1126 
1127                         target = _target;
1128                 }
1129         } else if (anon_mount) {
1130                 if (asprintf(&_target, "/mnt/%s", device) == -1)
1131                         exit(ENOMEM);
1132 
1133                 target = _target;
1134         } else {
1135                 /* No reason to mount this device */
1136                 return 0;
1137         }
1138 
1139         /* Mount the device */
1140 
1141         if (check_fs)
1142                 check_filesystem(pr);
1143 
1144         mkdir_p(target, 0755);
1145         if (!lstat(target, &st) && S_ISLNK(st.st_mode))
1146                 unlink(target);
1147 
1148         err = handle_mount(pr->dev, target, pr->type, m);
1149         if (err) {
1150                 ULOG_ERR("mounting %s (%s) as %s failed (%d) - %m\n",
1151                                 pr->dev, pr->type, target, errno);
1152 
1153                 if (_target)
1154                         free(_target);
1155 
1156                 return err;
1157         }
1158 
1159         if (_target)
1160                 free(_target);
1161 
1162         handle_swapfiles(true);
1163 
1164         if (type != TYPE_AUTOFS)
1165                 blockd_notify("mount", device, NULL, NULL);
1166 
1167         return 0;
1168 }
1169 
1170 static int umount_device(char *path, int type, bool all)
1171 {
1172         char *mp, *devpath;
1173         int err;
1174 
1175         if (strlen(path) > 5 && !strncmp("/dev/", path, 5)) {
1176                 mp = find_mount_point(path);
1177         } else {
1178                 devpath = malloc(strlen(path) + 6);
1179                 strcpy(devpath, "/dev/");
1180                 strcat(devpath, path);
1181                 mp = find_mount_point(devpath);
1182                 free(devpath);
1183         }
1184 
1185         if (!mp)
1186                 return -1;
1187         if (!strcmp(mp, "/") && !all) {
1188                 free(mp);
1189                 return 0;
1190         }
1191         if (type != TYPE_AUTOFS)
1192                 blockd_notify("umount", basename(path), NULL, NULL);
1193 
1194         err = umount2(mp, MNT_DETACH);
1195         if (err) {
1196                 ULOG_ERR("unmounting %s (%s) failed (%d) - %m\n", path, mp,
1197                          errno);
1198         } else {
1199                 ULOG_INFO("unmounted %s (%s)\n", path, mp);
1200                 rmdir(mp);
1201         }
1202 
1203         free(mp);
1204         return err;
1205 }
1206 
1207 static int mount_action(char *action, char *device, int type)
1208 {
1209         char *path = NULL;
1210         struct probe_info *pr;
1211 
1212         if (!action || !device)
1213                 return -1;
1214 
1215         if (!strcmp(action, "remove")) {
1216                 if (type == TYPE_HOTPLUG)
1217                         blockd_notify("hotplug", device, NULL, NULL);
1218 
1219                 umount_device(device, type, true);
1220 
1221                 return 0;
1222         } else if (strcmp(action, "add")) {
1223                 ULOG_ERR("Unkown action %s\n", action);
1224 
1225                 return -1;
1226         }
1227 
1228         if (config_load(NULL))
1229                 return -1;
1230 
1231         cache_load(1);
1232 
1233         list_for_each_entry(pr, &devices, list)
1234                 if (!strcmp(basename(pr->dev), device))
1235                         path = pr->dev;
1236 
1237         if (!path)
1238                 return -1;
1239 
1240         return mount_device(find_block_info(NULL, NULL, path), type);
1241 }
1242 
1243 static int main_hotplug(int argc, char **argv)
1244 {
1245         return mount_action(getenv("ACTION"), getenv("DEVNAME"), TYPE_HOTPLUG);
1246 }
1247 
1248 static int main_autofs(int argc, char **argv)
1249 {
1250         int err = 0;
1251 
1252         if (argc < 3)
1253                 return -1;
1254 
1255         if (!strcmp(argv[2], "start")) {
1256                 struct probe_info *pr;
1257 
1258                 if (config_load(NULL))
1259                         return -1;
1260 
1261                 cache_load(1);
1262                 list_for_each_entry(pr, &devices, list) {
1263                         struct mount *m;
1264                         char *mp;
1265 
1266                         if (!strcmp(pr->type, "swap"))
1267                                 continue;
1268 
1269                         m = find_block(pr->uuid, pr->label, NULL, NULL);
1270                         if (m && m->extroot)
1271                                 continue;
1272 
1273                         blockd_notify("hotplug", pr->dev, m, pr);
1274                         if ((!m || !m->autofs) && (mp = find_mount_point(pr->dev))) {
1275                                 blockd_notify("mount", pr->dev, NULL, NULL);
1276                                 free(mp);
1277                         }
1278                 }
1279         } else {
1280                 if (argc < 4)
1281                         return -EINVAL;
1282 
1283                 err = mount_action(argv[2], argv[3], TYPE_AUTOFS);
1284         }
1285 
1286         if (err) {
1287                 ULOG_ERR("autofs: \"%s\" action has failed: %d\n", argv[2], err);
1288         }
1289 
1290         return err;
1291 }
1292 
1293 static int find_block_mtd(char *name, char *part, int plen)
1294 {
1295         FILE *fp = fopen("/proc/mtd", "r");
1296         static char line[256];
1297         char *index = NULL;
1298 
1299         if(!fp)
1300                 return -1;
1301 
1302         while (!index && fgets(line, sizeof(line), fp)) {
1303                 if (strstr(line, name)) {
1304                         char *eol = strstr(line, ":");
1305 
1306                         if (!eol)
1307                                 continue;
1308 
1309                         *eol = '\0';
1310                         index = &line[3];
1311                 }
1312         }
1313 
1314         fclose(fp);
1315 
1316         if (!index)
1317                 return -1;
1318 
1319         snprintf(part, plen, "/dev/mtdblock%s", index);
1320 
1321         return 0;
1322 }
1323 
1324 #ifdef UBIFS_EXTROOT
1325 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
1326 {
1327         int dev = 0;
1328 
1329         while (ubi_dev_present(libubi, dev))
1330         {
1331                 struct ubi_dev_info dev_info;
1332                 struct ubi_vol_info vol_info;
1333 
1334                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
1335                         continue;
1336                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
1337                         continue;
1338 
1339                 *dev_num = dev_info.dev_num;
1340                 *vol_id = vol_info.vol_id;
1341 
1342                 return 0;
1343         }
1344 
1345         return -1;
1346 }
1347 
1348 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
1349 {
1350         int dev_num;
1351         int vol_id;
1352         int err = -1;
1353 
1354         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1355         if (!err)
1356                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
1357 
1358         return err;
1359 }
1360 
1361 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
1362 {
1363         int dev_num;
1364         int vol_id;
1365         int err = -1;
1366 
1367         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
1368         if (!err)
1369                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
1370 
1371         return err;
1372 }
1373 #endif
1374 
1375 static int find_root_dev(char *buf, int len)
1376 {
1377         DIR *d;
1378         dev_t root;
1379         struct stat s;
1380         struct dirent *e;
1381 
1382         if (stat("/", &s))
1383                 return -1;
1384 
1385         if (!(d = opendir("/dev")))
1386                 return -1;
1387 
1388         root = s.st_dev;
1389 
1390         while ((e = readdir(d)) != NULL) {
1391                 snprintf(buf, len, "/dev/%s", e->d_name);
1392 
1393                 if (stat(buf, &s) || s.st_rdev != root)
1394                         continue;
1395 
1396                 closedir(d);
1397                 return 0;
1398         }
1399 
1400         closedir(d);
1401         return -1;
1402 }
1403 
1404 static int test_fs_support(const char *name)
1405 {
1406         char line[128], *p;
1407         int rv = -1;
1408         FILE *f;
1409 
1410         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
1411                 while (fgets(line, sizeof(line), f)) {
1412                         p = strtok(line, "\t\n");
1413 
1414                         if (p && !strcmp(p, "nodev"))
1415                                 p = strtok(NULL, "\t\n");
1416 
1417                         if (p && !strcmp(p, name)) {
1418                                 rv = 0;
1419                                 break;
1420                         }
1421                 }
1422                 fclose(f);
1423         }
1424 
1425         return rv;
1426 }
1427 
1428 /**
1429  * Check if mounted partition is a valid extroot
1430  *
1431  * @path target mount point
1432  *
1433  * Valid extroot partition has to contain /etc/.extroot-uuid with UUID of root
1434  * device. This function reads UUID and verifies it OR writes UUID to
1435  * .extroot-uuid if it doesn't exist yet (first extroot usage).
1436  */
1437 static int check_extroot(char *path)
1438 {
1439         struct probe_info *pr = NULL;
1440         struct probe_info *tmp;
1441         struct stat s;
1442         char uuid[64] = { 0 };
1443         char devpath[32];
1444         char tag[64];
1445         FILE *fp;
1446         int err;
1447 
1448         err = find_block_mtd("\"rootfs\"", devpath, sizeof(devpath));
1449 #ifdef UBIFS_EXTROOT
1450         if (err) {
1451                 libubi_t libubi;
1452 
1453                 libubi = libubi_open();
1454                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1455                 libubi_close(libubi);
1456         }
1457 #endif
1458         if (err) {
1459                 err = find_root_dev(devpath, sizeof(devpath));
1460         }
1461         if (err) {
1462                 ULOG_ERR("extroot: unable to determine root device\n");
1463                 return -1;
1464         }
1465 
1466         /* Find root device probe_info so we know its UUID */
1467         list_for_each_entry(tmp, &devices, list) {
1468                 if (!strcmp(tmp->dev, devpath)) {
1469                         pr = tmp;
1470                         break;
1471                 }
1472         }
1473         if (!pr) {
1474                 ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1475                 return -1;
1476         }
1477 
1478         snprintf(tag, sizeof(tag), "%s/etc", path);
1479         if (stat(tag, &s))
1480                 mkdir_p(tag, 0755);
1481 
1482         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1483         if (stat(tag, &s)) {
1484                 fp = fopen(tag, "w+");
1485                 if (!fp) {
1486                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%m)\n",
1487                                  tag, errno);
1488                         /* return 0 to continue boot regardless of error */
1489                         return 0;
1490                 }
1491                 fputs(pr->uuid, fp);
1492                 fclose(fp);
1493                 return 0;
1494         }
1495 
1496         fp = fopen(tag, "r");
1497         if (!fp) {
1498                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n", tag,
1499                          errno);
1500                 return -1;
1501         }
1502 
1503         if (!fgets(uuid, sizeof(uuid), fp))
1504                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%m)\n", tag,
1505                          errno);
1506         fclose(fp);
1507 
1508         if (*uuid && !strcasecmp(uuid, pr->uuid))
1509                 return 0;
1510 
1511         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n", pr->uuid,
1512                  basename(path), uuid);
1513         return -1;
1514 }
1515 
1516 /*
1517  * Read info about extroot from UCI (using prefix) and mount it.
1518  */
1519 static int mount_extroot(char *cfg)
1520 {
1521         char overlay[] = "/tmp/extroot/overlay";
1522         char mnt[] = "/tmp/extroot/mnt";
1523         char *path = mnt;
1524         struct probe_info *pr;
1525         struct mount *m;
1526         int err = -1;
1527 
1528         /* Load @cfg/etc/config/fstab */
1529         if (config_load(cfg))
1530                 return -2;
1531 
1532         /* See if there is extroot-specific mount config */
1533         m = find_block(NULL, NULL, NULL, "/");
1534         if (!m)
1535                 m = find_block(NULL, NULL, NULL, "/overlay");
1536 
1537         if (!m || !m->extroot)
1538         {
1539                 ULOG_INFO("extroot: not configured\n");
1540                 return -1;
1541         }
1542 
1543         /* Find block device pointed by the mount config */
1544         pr = find_block_info(m->uuid, m->label, m->device);
1545 
1546         if (!pr && delay_root){
1547                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1548                 sleep(delay_root);
1549                 make_devs();
1550                 cache_load(1);
1551                 pr = find_block_info(m->uuid, m->label, m->device);
1552         }
1553         if (pr) {
1554                 if (strncmp(pr->type, "ext", 3) &&
1555                     strncmp(pr->type, "f2fs", 4) &&
1556                     strncmp(pr->type, "btrfs", 5) &&
1557                     strncmp(pr->type, "ntfs", 4) &&
1558                     strncmp(pr->type, "ubifs", 5)) {
1559                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4, f2fs, btrfs, ntfs or ubifs\n", pr->type);
1560                         return -1;
1561                 }
1562 
1563                 if (test_fs_support(pr->type)) {
1564                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->type);
1565                         return -1;
1566                 }
1567 
1568                 if (m->overlay)
1569                         path = overlay;
1570                 mkdir_p(path, 0755);
1571 
1572                 if (check_fs)
1573                         check_filesystem(pr);
1574 
1575                 err = mount(pr->dev, path, pr->type, m->flags,
1576                             (m->options) ? (m->options) : (""));
1577 
1578                 if (err) {
1579                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%m)\n",
1580                                  pr->dev, pr->type, path, errno);
1581                 } else if (m->overlay) {
1582                         err = check_extroot(path);
1583                         if (err)
1584                                 umount(path);
1585                 }
1586         } else {
1587                 ULOG_ERR("extroot: cannot find device %s%s\n",
1588                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1589                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1590         }
1591 
1592         return err;
1593 }
1594 
1595 /**
1596  * Look for extroot config and mount it if present
1597  *
1598  * Look for /etc/config/fstab on all supported partitions and use it for
1599  * mounting extroot if specified.
1600  */
1601 static int main_extroot(int argc, char **argv)
1602 {
1603         struct probe_info *pr;
1604         char blkdev_path[32] = { 0 };
1605         int err = -1;
1606 #ifdef UBIFS_EXTROOT
1607         libubi_t libubi;
1608 #endif
1609 
1610         if (!getenv("PREINIT"))
1611                 return -1;
1612 
1613         if (argc != 2) {
1614                 ULOG_ERR("Usage: block extroot\n");
1615                 return -1;
1616         }
1617 
1618         make_devs();
1619         cache_load(1);
1620 
1621         /* enable LOG_INFO messages */
1622         ulog_threshold(LOG_INFO);
1623 
1624         /*
1625          * Look for "rootfs_data". We will want to mount it and check for
1626          * extroot configuration.
1627          */
1628 
1629         /* Start with looking for MTD partition */
1630         find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1631         if (blkdev_path[0]) {
1632                 pr = find_block_info(NULL, NULL, blkdev_path);
1633                 if (pr && !strcmp(pr->type, "jffs2")) {
1634                         char cfg[] = "/tmp/jffs_cfg";
1635 
1636                         /*
1637                          * Mount MTD part and try extroot (using
1638                          * /etc/config/fstab from that partition)
1639                          */
1640                         mkdir_p(cfg, 0755);
1641                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1642                                 err = mount_extroot(cfg);
1643                                 umount2(cfg, MNT_DETACH);
1644                         }
1645                         if (err < 0)
1646                                 rmdir("/tmp/overlay");
1647                         rmdir(cfg);
1648                         return err;
1649                 }
1650         }
1651 
1652 #ifdef UBIFS_EXTROOT
1653         /* ... but it also could be an UBI volume */
1654         memset(blkdev_path, 0, sizeof(blkdev_path));
1655         libubi = libubi_open();
1656         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1657         libubi_close(libubi);
1658         if (blkdev_path[0]) {
1659                 char cfg[] = "/tmp/ubifs_cfg";
1660 
1661                 /* Mount volume and try extroot (using fstab from that vol) */
1662                 mkdir_p(cfg, 0755);
1663                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1664                         err = mount_extroot(cfg);
1665                         umount2(cfg, MNT_DETACH);
1666                 }
1667                 if (err < 0)
1668                         rmdir("/tmp/overlay");
1669                 rmdir(cfg);
1670                 return err;
1671        }
1672 #endif
1673 
1674         /* As a last resort look for /etc/config/fstab on "rootfs" partition */
1675         return mount_extroot(NULL);
1676 }
1677 
1678 static int main_mount(int argc, char **argv)
1679 {
1680         struct probe_info *pr;
1681 
1682         if (config_load(NULL))
1683                 return -1;
1684 
1685         cache_load(1);
1686         list_for_each_entry(pr, &devices, list)
1687                 mount_device(pr, TYPE_DEV);
1688 
1689         handle_swapfiles(true);
1690 
1691         return 0;
1692 }
1693 
1694 static int main_umount(int argc, char **argv)
1695 {
1696         struct probe_info *pr;
1697         bool all = false;
1698 
1699         if (config_load(NULL))
1700                 return -1;
1701 
1702         handle_swapfiles(false);
1703 
1704         cache_load(1);
1705 
1706         if (argc == 3)
1707                 all = !strcmp(argv[2], "-a");
1708 
1709         list_for_each_entry(pr, &devices, list) {
1710                 struct mount *m;
1711 
1712                 if (!strcmp(pr->type, "swap"))
1713                         continue;
1714 
1715                 m = find_block(pr->uuid, pr->label, basename(pr->dev), NULL);
1716                 if (m && m->extroot)
1717                         continue;
1718 
1719                 umount_device(pr->dev, TYPE_DEV, all);
1720         }
1721 
1722         return 0;
1723 }
1724 
1725 static int main_detect(int argc, char **argv)
1726 {
1727         struct probe_info *pr;
1728 
1729         cache_load(0);
1730         printf("config 'global'\n");
1731         printf("\toption\tanon_swap\t''\n");
1732         printf("\toption\tanon_mount\t''\n");
1733         printf("\toption\tauto_swap\t'1'\n");
1734         printf("\toption\tauto_mount\t'1'\n");
1735         printf("\toption\tdelay_root\t'5'\n");
1736         printf("\toption\tcheck_fs\t''\n\n");
1737         list_for_each_entry(pr, &devices, list)
1738                 print_block_uci(pr);
1739 
1740         return 0;
1741 }
1742 
1743 static int main_info(int argc, char **argv)
1744 {
1745         int i;
1746         struct probe_info *pr;
1747 
1748         cache_load(1);
1749         if (argc == 2) {
1750                 list_for_each_entry(pr, &devices, list)
1751                         print_block_info(pr);
1752 
1753                 return 0;
1754         };
1755 
1756         for (i = 2; i < argc; i++) {
1757                 struct stat s;
1758 
1759                 if (stat(argv[i], &s)) {
1760                         ULOG_ERR("failed to stat %s\n", argv[i]);
1761                         continue;
1762                 }
1763                 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1764                         ULOG_ERR("%s is not a block device\n", argv[i]);
1765                         continue;
1766                 }
1767                 pr = find_block_info(NULL, NULL, argv[i]);
1768                 if (pr)
1769                         print_block_info(pr);
1770         }
1771 
1772         return 0;
1773 }
1774 
1775 static int swapon_usage(void)
1776 {
1777         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1778                 "\tStart swapping on [DEVICE]\n"
1779                 " -a\tStart swapping on all swap devices\n"
1780                 " -p pri\tSet priority of swap device\n"
1781                 " -s\tShow summary\n");
1782         return -1;
1783 }
1784 
1785 static int main_swapon(int argc, char **argv)
1786 {
1787         int ch;
1788         FILE *fp;
1789         char *lineptr;
1790         size_t s;
1791         struct probe_info *pr;
1792         int flags = 0;
1793         int pri;
1794         struct stat st;
1795         int err;
1796 
1797         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1798                 switch(ch) {
1799                 case 's':
1800                         fp = fopen("/proc/swaps", "r");
1801                         lineptr = NULL;
1802 
1803                         if (!fp) {
1804                                 ULOG_ERR("failed to open /proc/swaps\n");
1805                                 return -1;
1806                         }
1807                         while (getline(&lineptr, &s, fp) > 0)
1808                                 printf("%s", lineptr);
1809                         if (lineptr)
1810                                 free(lineptr);
1811                         fclose(fp);
1812                         return 0;
1813                 case 'a':
1814                         cache_load(0);
1815                         list_for_each_entry(pr, &devices, list) {
1816                                 if (strcmp(pr->type, "swap"))
1817                                         continue;
1818                                 if (swapon(pr->dev, 0))
1819                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1820                         }
1821                         return 0;
1822                 case 'p':
1823                         pri = atoi(optarg);
1824                         if (pri >= 0)
1825                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1826                         break;
1827                 default:
1828                         return swapon_usage();
1829                 }
1830         }
1831 
1832         if (optind != (argc - 1))
1833                 return swapon_usage();
1834 
1835         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1836                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1837                 return -1;
1838         }
1839         err = swapon(argv[optind], flags);
1840         if (err) {
1841                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1842                 return err;
1843         }
1844 
1845         return 0;
1846 }
1847 
1848 static int main_swapoff(int argc, char **argv)
1849 {
1850         if (argc != 2) {
1851                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1852                         "\tStop swapping on DEVICE\n"
1853                         " -a\tStop swapping on all swap devices\n");
1854                 return -1;
1855         }
1856 
1857         if (!strcmp(argv[1], "-a")) {
1858                 FILE *fp = fopen("/proc/swaps", "r");
1859                 char line[256];
1860 
1861                 if (!fp) {
1862                         ULOG_ERR("failed to open /proc/swaps\n");
1863                         return -1;
1864                 }
1865                 if (fgets(line, sizeof(line), fp))
1866                         while (fgets(line, sizeof(line), fp)) {
1867                                 char *end = strchr(line, ' ');
1868                                 int err;
1869 
1870                                 if (!end)
1871                                         continue;
1872                                 *end = '\0';
1873                                 err = swapoff(line);
1874                                 if (err)
1875                                         ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1876                         }
1877                 fclose(fp);
1878         } else {
1879                 struct stat s;
1880                 int err;
1881 
1882                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1883                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1884                         return -1;
1885                 }
1886                 err = swapoff(argv[1]);
1887                 if (err) {
1888                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1889                         return err;
1890                 }
1891         }
1892 
1893         return 0;
1894 }
1895 
1896 int main(int argc, char **argv)
1897 {
1898         char *base = basename(*argv);
1899 
1900         umask(0);
1901 
1902         ulog_open(-1, -1, "block");
1903         ulog_threshold(LOG_NOTICE);
1904 
1905         if (!strcmp(base, "swapon"))
1906                 return main_swapon(argc, argv);
1907 
1908         if (!strcmp(base, "swapoff"))
1909                 return main_swapoff(argc, argv);
1910 
1911         if ((argc > 1) && !strcmp(base, "block")) {
1912                 if (!strcmp(argv[1], "info"))
1913                         return main_info(argc, argv);
1914 
1915                 if (!strcmp(argv[1], "detect"))
1916                         return main_detect(argc, argv);
1917 
1918                 if (!strcmp(argv[1], "hotplug"))
1919                         return main_hotplug(argc, argv);
1920 
1921                 if (!strcmp(argv[1], "autofs"))
1922                         return main_autofs(argc, argv);
1923 
1924                 if (!strcmp(argv[1], "extroot"))
1925                         return main_extroot(argc, argv);
1926 
1927                 if (!strcmp(argv[1], "mount"))
1928                         return main_mount(argc, argv);
1929 
1930                 if (!strcmp(argv[1], "umount"))
1931                         return main_umount(argc, argv);
1932 
1933                 if (!strcmp(argv[1], "remount")) {
1934                         int ret = main_umount(argc, argv);
1935 
1936                         if (!ret)
1937                                 ret = main_mount(argc, argv);
1938                         return ret;
1939                 }
1940         }
1941 
1942         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1943 
1944         return -1;
1945 }
1946 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt