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