block.c: Add support for checking vfat filesystems
[project/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
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/swap.h>
29 #include <sys/mount.h>
30 #include <sys/wait.h>
31
32 #include <uci.h>
33 #include <uci_blob.h>
34
35 #include <libubox/ulog.h>
36 #include <libubox/list.h>
37 #include <libubox/vlist.h>
38 #include <libubox/blobmsg_json.h>
39 #include <libubox/avl-cmp.h>
40
41 #include "libblkid-tiny/libblkid-tiny.h"
42
43 #ifdef UBIFS_EXTROOT
44 #include "libubi/libubi.h"
45 #endif
46
47 enum {
48         TYPE_MOUNT,
49         TYPE_SWAP,
50 };
51
52 struct mount {
53         struct vlist_node node;
54         int type;
55
56         char *target;
57         char *path;
58         char *options;
59         uint32_t flags;
60         char *uuid;
61         char *label;
62         char *device;
63         int extroot;
64         int overlay;
65         int disabled_fsck;
66         unsigned int prio;
67 };
68
69 static struct vlist_tree mounts;
70 static struct blob_buf b;
71 static LIST_HEAD(devices);
72 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
73 static unsigned int delay_root;
74
75 enum {
76         CFG_ANON_MOUNT,
77         CFG_ANON_SWAP,
78         CFG_AUTO_MOUNT,
79         CFG_AUTO_SWAP,
80         CFG_DELAY_ROOT,
81         CFG_CHECK_FS,
82         __CFG_MAX
83 };
84
85 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
86         [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
87         [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
88         [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
89         [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
90         [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
91         [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
92 };
93
94 enum {
95         MOUNT_UUID,
96         MOUNT_LABEL,
97         MOUNT_ENABLE,
98         MOUNT_TARGET,
99         MOUNT_DEVICE,
100         MOUNT_OPTIONS,
101         __MOUNT_MAX
102 };
103
104 static const struct uci_blob_param_list config_attr_list = {
105         .n_params = __CFG_MAX,
106         .params = config_policy,
107 };
108
109 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
110         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
111         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
112         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
113         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
114         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
115         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
116 };
117
118 static const struct uci_blob_param_list mount_attr_list = {
119         .n_params = __MOUNT_MAX,
120         .params = mount_policy,
121 };
122
123 enum {
124         SWAP_ENABLE,
125         SWAP_UUID,
126         SWAP_LABEL,
127         SWAP_DEVICE,
128         SWAP_PRIO,
129         __SWAP_MAX
130 };
131
132 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
133         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
134         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
135         [SWAP_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
136         [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
137         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
138 };
139
140 static const struct uci_blob_param_list swap_attr_list = {
141         .n_params = __SWAP_MAX,
142         .params = swap_policy,
143 };
144
145 struct mount_flag {
146         const char *name;
147         int32_t flag;
148 };
149
150 #ifndef MS_DIRSYNC
151 #       define MS_DIRSYNC               (1 << 7)
152 #endif
153
154 #ifndef MS_RELATIME
155 #       define MS_RELATIME              (1 << 21)
156 #endif
157
158 #ifndef MS_STRICTATIME
159 #       define MS_STRICTATIME   (1 << 24)
160 #endif
161
162 static const struct mount_flag mount_flags[] = {
163         { "sync",               MS_SYNCHRONOUS  },
164         { "async",              ~MS_SYNCHRONOUS },
165         { "dirsync",            MS_DIRSYNC      },
166         { "mand",               MS_MANDLOCK     },
167         { "nomand",             ~MS_MANDLOCK    },
168         { "atime",              ~MS_NOATIME     },
169         { "noatime",            MS_NOATIME      },
170         { "dev",                ~MS_NODEV       },
171         { "nodev",              MS_NODEV        },
172         { "diratime",           ~MS_NODIRATIME  },
173         { "nodiratime",         MS_NODIRATIME   },
174         { "exec",               ~MS_NOEXEC      },
175         { "noexec",             MS_NOEXEC       },
176         { "suid",               ~MS_NOSUID      },
177         { "nosuid",             MS_NOSUID       },
178         { "rw",                 ~MS_RDONLY      },
179         { "ro",                 MS_RDONLY       },
180         { "relatime",           MS_RELATIME     },
181         { "norelatime",         ~MS_RELATIME    },
182         { "strictatime",        MS_STRICTATIME  },
183 };
184
185 static char *blobmsg_get_strdup(struct blob_attr *attr)
186 {
187         if (!attr)
188                 return NULL;
189
190         return strdup(blobmsg_get_string(attr));
191 }
192
193 static char *blobmsg_get_basename(struct blob_attr *attr)
194 {
195         if (!attr)
196                 return NULL;
197
198         return strdup(basename(blobmsg_get_string(attr)));
199 }
200
201 static void parse_mount_options(struct mount *m, char *optstr)
202 {
203         int i;
204         bool is_flag;
205         char *p, *opts, *last;
206
207         m->flags = 0;
208         m->options = NULL;
209
210         if (!optstr || !*optstr)
211                 return;
212
213         m->options = opts = calloc(1, strlen(optstr) + 1);
214
215         if (!m->options)
216                 return;
217
218         p = last = optstr;
219
220         do {
221                 p = strchr(p, ',');
222
223                 if (p)
224                         *p++ = 0;
225
226                 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
227                         if (!strcmp(last, mount_flags[i].name)) {
228                                 if (mount_flags[i].flag < 0)
229                                         m->flags &= (uint32_t)mount_flags[i].flag;
230                                 else
231                                         m->flags |= (uint32_t)mount_flags[i].flag;
232                                 is_flag = true;
233                                 break;
234                         }
235                 }
236
237                 if (!is_flag)
238                         opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
239
240                 last = p;
241
242         } while (p);
243
244         free(optstr);
245 }
246
247 static int mount_add(struct uci_section *s)
248 {
249         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
250         struct mount *m;
251
252         blob_buf_init(&b, 0);
253         uci_to_blob(&b, s, &mount_attr_list);
254         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
255
256         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
257                 return -1;
258
259         if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
260                 return -1;
261
262         m = malloc(sizeof(struct mount));
263         m->type = TYPE_MOUNT;
264         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
265         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
266         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
267         m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
268
269         parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
270
271         m->overlay = m->extroot = 0;
272         if (m->target && !strcmp(m->target, "/"))
273                 m->extroot = 1;
274         if (m->target && !strcmp(m->target, "/overlay"))
275                 m->extroot = m->overlay = 1;
276
277         if (m->target && *m->target != '/') {
278                 ULOG_WARN("ignoring mount section %s due to invalid target '%s'\n",
279                           s->e.name, m->target);
280                 free(m);
281                 return -1;
282         }
283
284         if (m->uuid)
285                 vlist_add(&mounts, &m->node, m->uuid);
286         else if (m->label)
287                 vlist_add(&mounts, &m->node, m->label);
288         else if (m->device)
289                 vlist_add(&mounts, &m->node, m->device);
290
291         return 0;
292 }
293
294 static int swap_add(struct uci_section *s)
295 {
296         struct blob_attr *tb[__SWAP_MAX] = { 0 };
297         struct mount *m;
298
299         blob_buf_init(&b, 0);
300         uci_to_blob(&b, s, &swap_attr_list);
301         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
302
303         if (!tb[SWAP_UUID] && !tb[SWAP_LABEL] && !tb[SWAP_DEVICE])
304                 return -1;
305
306         m = malloc(sizeof(struct mount));
307         memset(m, 0, sizeof(struct mount));
308         m->type = TYPE_SWAP;
309         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
310         m->label = blobmsg_get_strdup(tb[SWAP_LABEL]);
311         m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
312         if (tb[SWAP_PRIO])
313                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
314         if (m->prio)
315                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
316
317         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
318                 /* store complete swap path */
319                 if (tb[SWAP_DEVICE])
320                         m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
321
322                 if (m->uuid)
323                         vlist_add(&mounts, &m->node, m->uuid);
324                 else if (m->label)
325                         vlist_add(&mounts, &m->node, m->label);
326                 else if (m->device)
327                         vlist_add(&mounts, &m->node, m->device);
328         }
329
330         return 0;
331 }
332
333 static int global_add(struct uci_section *s)
334 {
335         struct blob_attr *tb[__CFG_MAX] = { 0 };
336
337         blob_buf_init(&b, 0);
338         uci_to_blob(&b, s, &config_attr_list);
339         blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
340
341         if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
342                 anon_mount = 1;
343         if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
344                 anon_swap = 1;
345
346         if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
347                 auto_mount = 1;
348         if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
349                 auto_swap = 1;
350
351         if (tb[CFG_DELAY_ROOT])
352                 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
353
354         if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
355                 check_fs = 1;
356
357         return 0;
358 }
359
360 static struct mount* find_swap(const char *uuid, const char *label, const char *device)
361 {
362         struct mount *m;
363
364         vlist_for_each_element(&mounts, m, node) {
365                 if (m->type != TYPE_SWAP)
366                         continue;
367                 if (uuid && m->uuid && !strcasecmp(m->uuid, uuid))
368                         return m;
369                 if (label && m->label && !strcmp(m->label, label))
370                         return m;
371                 if (device && m->device && !strcmp(m->device, device))
372                         return m;
373         }
374
375         return NULL;
376 }
377
378 static struct mount* find_block(const char *uuid, const char *label, const char *device,
379                                 const char *target)
380 {
381         struct mount *m;
382
383         vlist_for_each_element(&mounts, m, node) {
384                 if (m->type != TYPE_MOUNT)
385                         continue;
386                 if (m->uuid && uuid && !strcasecmp(m->uuid, uuid))
387                         return m;
388                 if (m->label && label && !strcmp(m->label, label))
389                         return m;
390                 if (m->target && target && !strcmp(m->target, target))
391                         return m;
392                 if (m->device && device && !strcmp(m->device, device))
393                         return m;
394         }
395
396         return NULL;
397 }
398
399 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
400                           struct vlist_node *node_old)
401 {
402 }
403
404 static struct uci_package * config_try_load(struct uci_context *ctx, char *path)
405 {
406         char *file = basename(path);
407         char *dir = dirname(path);
408         char *err;
409         struct uci_package *pkg;
410
411         uci_set_confdir(ctx, dir);
412         ULOG_INFO("attempting to load %s/%s\n", dir, file);
413
414         if (uci_load(ctx, file, &pkg)) {
415                 uci_get_errorstr(ctx, &err, file);
416                 ULOG_ERR("unable to load configuration (%s)\n", err);
417
418                 free(err);
419                 return NULL;
420         }
421
422         return pkg;
423 }
424
425 static int config_load(char *cfg)
426 {
427         struct uci_context *ctx = uci_alloc_context();
428         struct uci_package *pkg = NULL;
429         struct uci_element *e;
430         char path[64];
431
432         vlist_init(&mounts, avl_strcmp, mounts_update);
433
434         if (cfg) {
435                 snprintf(path, sizeof(path), "%s/upper/etc/config/fstab", cfg);
436                 pkg = config_try_load(ctx, path);
437
438                 if (!pkg) {
439                         snprintf(path, sizeof(path), "%s/etc/config/fstab", cfg);
440                         pkg = config_try_load(ctx, path);
441                 }
442         }
443
444         if (!pkg) {
445                 snprintf(path, sizeof(path), "/etc/config/fstab");
446                 pkg = config_try_load(ctx, path);
447         }
448
449         if (!pkg) {
450                 ULOG_ERR("no usable configuration\n");
451                 return -1;
452         }
453
454         vlist_update(&mounts);
455         uci_foreach_element(&pkg->sections, e) {
456                 struct uci_section *s = uci_to_section(e);
457
458                 if (!strcmp(s->type, "mount"))
459                         mount_add(s);
460                 if (!strcmp(s->type, "swap"))
461                         swap_add(s);
462                 if (!strcmp(s->type, "global"))
463                         global_add(s);
464         }
465         vlist_flush(&mounts);
466
467         return 0;
468 }
469
470 static struct blkid_struct_probe* _probe_path(char *path)
471 {
472         struct blkid_struct_probe *pr;
473
474         pr = malloc(sizeof(*pr));
475
476         if (!pr)
477                 return NULL;
478
479         memset(pr, 0, sizeof(*pr));
480         probe_block(path, pr);
481
482         if (pr->err || !pr->id) {
483                 free(pr);
484                 return NULL;
485         }
486
487         return pr;
488 }
489
490 static int _cache_load(const char *path)
491 {
492         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
493         int j;
494         glob_t gl;
495
496         if (glob(path, gl_flags, NULL, &gl) < 0)
497                 return -1;
498
499         for (j = 0; j < gl.gl_pathc; j++) {
500                 struct blkid_struct_probe *pr = _probe_path(gl.gl_pathv[j]);
501                 if (pr)
502                         list_add_tail(&pr->list, &devices);
503         }
504
505         globfree(&gl);
506
507         return 0;
508 }
509
510 static void cache_load(int mtd)
511 {
512         if (mtd) {
513                 _cache_load("/dev/mtdblock*");
514                 _cache_load("/dev/ubiblock*");
515                 _cache_load("/dev/ubi?*_?*");
516         }
517         _cache_load("/dev/mmcblk*");
518         _cache_load("/dev/sd*");
519         _cache_load("/dev/hd*");
520         _cache_load("/dev/md*");
521         _cache_load("/dev/vd*");
522         _cache_load("/dev/mapper/*");
523 }
524
525 static int print_block_info(struct blkid_struct_probe *pr)
526 {
527         printf("%s:", pr->dev);
528         if (pr->uuid[0])
529                 printf(" UUID=\"%s\"", pr->uuid);
530
531         if (pr->label[0])
532                 printf(" LABEL=\"%s\"", pr->label);
533
534         if (pr->name[0])
535                 printf(" NAME=\"%s\"", pr->name);
536
537         if (pr->version[0])
538                 printf(" VERSION=\"%s\"", pr->version);
539
540         printf(" TYPE=\"%s\"\n", pr->id->name);
541
542         return 0;
543 }
544
545 static int print_block_uci(struct blkid_struct_probe *pr)
546 {
547         if (!strcmp(pr->id->name, "swap")) {
548                 printf("config 'swap'\n");
549         } else {
550                 printf("config 'mount'\n");
551                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
552         }
553         if (pr->uuid[0])
554                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
555         else
556                 printf("\toption\tdevice\t'%s'\n", pr->dev);
557         printf("\toption\tenabled\t'0'\n\n");
558
559         return 0;
560 }
561
562 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
563 {
564         struct blkid_struct_probe *pr = NULL;
565
566         if (uuid)
567                 list_for_each_entry(pr, &devices, list)
568                         if (!strcasecmp(pr->uuid, uuid))
569                                 return pr;
570
571         if (label)
572                 list_for_each_entry(pr, &devices, list)
573                         if (!strcmp(pr->label, label))
574                                 return pr;
575
576         if (path)
577                 list_for_each_entry(pr, &devices, list)
578                         if (!strcmp(basename(pr->dev), basename(path)))
579                                 return pr;
580
581         return NULL;
582 }
583
584 static char* find_mount_point(char *block)
585 {
586         FILE *fp = fopen("/proc/mounts", "r");
587         static char line[256];
588         int len = strlen(block);
589         char *point = NULL;
590
591         if(!fp)
592                 return NULL;
593
594         while (fgets(line, sizeof(line), fp)) {
595                 if (!strncmp(line, block, len)) {
596                         char *p = &line[len + 1];
597                         char *t = strstr(p, " ");
598
599                         if (!t) {
600                                 fclose(fp);
601                                 return NULL;
602                         }
603                         *t = '\0';
604                         point = p;
605                         break;
606                 }
607         }
608
609         fclose(fp);
610
611         return point;
612 }
613
614 static void mkdir_p(char *dir)
615 {
616         char *l = strrchr(dir, '/');
617
618         if (l) {
619                 *l = '\0';
620                 mkdir_p(dir);
621                 *l = '/';
622                 mkdir(dir, 0755);
623         }
624 }
625
626 static void check_filesystem(struct blkid_struct_probe *pr)
627 {
628         pid_t pid;
629         struct stat statbuf;
630         const char *e2fsck = "/usr/sbin/e2fsck";
631         const char *dosfsck = "/usr/sbin/dosfsck";
632         const char *ckfs;
633
634         /* UBIFS does not need stuff like fsck */
635         if (!strncmp(pr->id->name, "ubifs", 5))
636                 return;
637
638         if (!strncmp(pr->id->name, "vfat", 4)) {
639                 ckfs = dosfsck;
640         } else if (!strncmp(pr->id->name, "ext", 3)) {
641                 ckfs = e2fsck;
642         } else {
643                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->id->name);
644                 return;
645         }
646
647         if (stat(ckfs, &statbuf) < 0) {
648                 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
649                 return;
650         }
651
652         pid = fork();
653         if (!pid) {
654                 execl(ckfs, ckfs, "-p", pr->dev, NULL);
655                 exit(-1);
656         } else if (pid > 0) {
657                 int status;
658
659                 waitpid(pid, &status, 0);
660                 if (WEXITSTATUS(status))
661                         ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
662         }
663 }
664
665 static void handle_swapfiles(bool on)
666 {
667         struct stat s;
668         struct mount *m;
669         struct blkid_struct_probe *pr;
670
671         vlist_for_each_element(&mounts, m, node)
672         {
673                 if (m->type != TYPE_SWAP || !m->target)
674                         continue;
675
676                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
677                         continue;
678
679                 pr = _probe_path(m->target);
680
681                 if (!pr)
682                         continue;
683
684                 if (!strcmp(pr->id->name, "swap")) {
685                         if (on)
686                                 swapon(pr->dev, m->prio);
687                         else
688                                 swapoff(pr->dev);
689                 }
690
691                 free(pr);
692         }
693 }
694
695 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
696 {
697         struct mount *m;
698         char *device;
699
700         if (!pr)
701                 return -1;
702
703         device = basename(pr->dev);
704
705         if (!strcmp(pr->id->name, "swap")) {
706                 if (hotplug && !auto_swap)
707                         return -1;
708                 m = find_swap(pr->uuid, pr->label, device);
709                 if (m || anon_swap)
710                         swapon(pr->dev, (m) ? (m->prio) : (0));
711
712                 return 0;
713         }
714
715         if (hotplug && !auto_mount)
716                 return -1;
717
718         if (find_mount_point(pr->dev)) {
719                 ULOG_ERR("%s is already mounted\n", pr->dev);
720                 return -1;
721         }
722
723         m = find_block(pr->uuid, pr->label, device, NULL);
724         if (m && m->extroot)
725                 return -1;
726
727         if (m) {
728                 char *target = m->target;
729                 char _target[32];
730                 int err = 0;
731
732                 if (!target) {
733                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
734                         target = _target;
735                 }
736                 mkdir_p(target);
737
738                 if (check_fs)
739                         check_filesystem(pr);
740
741                 err = mount(pr->dev, target, pr->id->name, m->flags,
742                             (m->options) ? (m->options) : (""));
743                 if (err)
744                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
745                                  pr->dev, pr->id->name, target, err, strerror(err));
746                 else
747                         handle_swapfiles(true);
748                 return err;
749         }
750
751         if (anon_mount) {
752                 char target[] = "/mnt/mmcblk123";
753                 int err = 0;
754
755                 snprintf(target, sizeof(target), "/mnt/%s", device);
756                 mkdir_p(target);
757
758                 if (check_fs)
759                         check_filesystem(pr);
760
761                 err = mount(pr->dev, target, pr->id->name, 0, "");
762                 if (err)
763                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
764                                  pr->dev, pr->id->name, target, err, strerror(err));
765                 else
766                         handle_swapfiles(true);
767                 return err;
768         }
769
770         return 0;
771 }
772
773 static int umount_device(struct blkid_struct_probe *pr)
774 {
775         struct mount *m;
776         char *device = basename(pr->dev);
777         char *mp;
778         int err;
779
780         if (!pr)
781                 return -1;
782
783         if (!strcmp(pr->id->name, "swap"))
784                 return -1;
785
786         mp = find_mount_point(pr->dev);
787         if (!mp)
788                 return -1;
789
790         m = find_block(pr->uuid, pr->label, device, NULL);
791         if (m && m->extroot)
792                 return -1;
793
794         err = umount2(mp, MNT_DETACH);
795         if (err)
796                 ULOG_ERR("unmounting %s (%s)  failed (%d) - %s\n",
797                          pr->dev, mp, err, strerror(err));
798         else
799                 ULOG_INFO("unmounted %s (%s)\n",
800                           pr->dev, mp);
801
802         return err;
803 }
804
805 static int main_hotplug(int argc, char **argv)
806 {
807         char path[32];
808         char *action, *device, *mount_point;
809
810         action = getenv("ACTION");
811         device = getenv("DEVNAME");
812
813         if (!action || !device)
814                 return -1;
815         snprintf(path, sizeof(path), "/dev/%s", device);
816
817         if (!strcmp(action, "remove")) {
818                 int err = 0;
819                 mount_point = find_mount_point(path);
820                 if (mount_point)
821                         err = umount2(mount_point, MNT_DETACH);
822
823                 if (err)
824                         ULOG_ERR("umount of %s failed (%d) - %s\n",
825                                  mount_point, err, strerror(err));
826
827                 return 0;
828         } else if (strcmp(action, "add")) {
829                 ULOG_ERR("Unkown action %s\n", action);
830
831                 return -1;
832         }
833
834         if (config_load(NULL))
835                 return -1;
836         cache_load(0);
837
838         return mount_device(find_block_info(NULL, NULL, path), 1);
839 }
840
841 static int find_block_mtd(char *name, char *part, int plen)
842 {
843         FILE *fp = fopen("/proc/mtd", "r");
844         static char line[256];
845         char *index = NULL;
846
847         if(!fp)
848                 return -1;
849
850         while (!index && fgets(line, sizeof(line), fp)) {
851                 if (strstr(line, name)) {
852                         char *eol = strstr(line, ":");
853
854                         if (!eol)
855                                 continue;
856
857                         *eol = '\0';
858                         index = &line[3];
859                 }
860         }
861
862         fclose(fp);
863
864         if (!index)
865                 return -1;
866
867         snprintf(part, plen, "/dev/mtdblock%s", index);
868
869         return 0;
870 }
871
872 #ifdef UBIFS_EXTROOT
873 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
874 {
875         int dev = 0;
876
877         while (ubi_dev_present(libubi, dev))
878         {
879                 struct ubi_dev_info dev_info;
880                 struct ubi_vol_info vol_info;
881
882                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
883                         continue;
884                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
885                         continue;
886
887                 *dev_num = dev_info.dev_num;
888                 *vol_id = vol_info.vol_id;
889
890                 return 0;
891         }
892
893         return -1;
894 }
895
896 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
897 {
898         int dev_num;
899         int vol_id;
900         int err = -1;
901
902         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
903         if (!err)
904                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
905
906         return err;
907 }
908
909 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
910 {
911         int dev_num;
912         int vol_id;
913         int err = -1;
914
915         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
916         if (!err)
917                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
918
919         return err;
920 }
921
922 #else
923
924 static int find_root_dev(char *buf, int len)
925 {
926         DIR *d;
927         dev_t root;
928         struct stat s;
929         struct dirent *e;
930
931         if (stat("/", &s))
932                 return -1;
933
934         if (!(d = opendir("/dev")))
935                 return -1;
936
937         root = s.st_dev;
938
939         while ((e = readdir(d)) != NULL) {
940                 snprintf(buf, len, "/dev/%s", e->d_name);
941
942                 if (stat(buf, &s) || s.st_rdev != root)
943                         continue;
944
945                 closedir(d);
946                 return 0;
947         }
948
949         closedir(d);
950         return -1;
951 }
952
953 #endif
954
955 static int test_fs_support(const char *name)
956 {
957         char line[128], *p;
958         int rv = -1;
959         FILE *f;
960
961         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
962                 while (fgets(line, sizeof(line), f)) {
963                         p = strtok(line, "\t\n");
964
965                         if (p && !strcmp(p, "nodev"))
966                                 p = strtok(NULL, "\t\n");
967
968                         if (p && !strcmp(p, name)) {
969                                 rv = 0;
970                                 break;
971                         }
972                 }
973                 fclose(f);
974         }
975
976         return rv;
977 }
978
979 static int check_extroot(char *path)
980 {
981         struct blkid_struct_probe *pr = NULL;
982         char devpath[32];
983
984 #ifdef UBIFS_EXTROOT
985         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
986                 int err = -1;
987                 libubi_t libubi;
988
989                 libubi = libubi_open();
990                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
991                 libubi_close(libubi);
992                 if (err)
993                         return -1;
994         }
995 #else
996         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
997                 if (find_root_dev(devpath, sizeof(devpath))) {
998                         ULOG_ERR("extroot: unable to determine root device\n");
999                         return -1;
1000                 }
1001         }
1002 #endif
1003
1004         list_for_each_entry(pr, &devices, list) {
1005                 if (!strcmp(pr->dev, devpath)) {
1006                         struct stat s;
1007                         FILE *fp = NULL;
1008                         char tag[64];
1009                         char uuid[64] = { 0 };
1010
1011                         snprintf(tag, sizeof(tag), "%s/etc", path);
1012                         if (stat(tag, &s))
1013                                 mkdir_p(tag);
1014
1015                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1016                         if (stat(tag, &s)) {
1017                                 fp = fopen(tag, "w+");
1018                                 if (!fp) {
1019                                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%s)\n",
1020                                                  tag, errno, strerror(errno));
1021                                         /* return 0 to continue boot regardless of error */
1022                                         return 0;
1023                                 }
1024                                 fputs(pr->uuid, fp);
1025                                 fclose(fp);
1026                                 return 0;
1027                         }
1028
1029                         fp = fopen(tag, "r");
1030                         if (!fp) {
1031                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1032                                          tag, errno, strerror(errno));
1033                                 return -1;
1034                         }
1035
1036                         if (!fgets(uuid, sizeof(uuid), fp))
1037                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1038                                          tag, errno, strerror(errno));
1039                         fclose(fp);
1040
1041                         if (*uuid || !strcasecmp(uuid, pr->uuid))
1042                                 return 0;
1043
1044                         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1045                                  pr->uuid, basename(path), uuid);
1046                         return -1;
1047                 }
1048         }
1049
1050         ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1051         return -1;
1052 }
1053
1054 /*
1055  * Read info about extroot from UCI (using prefix) and mount it.
1056  */
1057 static int mount_extroot(char *cfg)
1058 {
1059         char overlay[] = "/tmp/extroot/overlay";
1060         char mnt[] = "/tmp/extroot/mnt";
1061         char *path = mnt;
1062         struct blkid_struct_probe *pr;
1063         struct mount *m;
1064         int err = -1;
1065
1066         /* Load @cfg/etc/config/fstab */
1067         if (config_load(cfg))
1068                 return -2;
1069
1070         /* See if there is extroot-specific mount config */
1071         m = find_block(NULL, NULL, NULL, "/");
1072         if (!m)
1073                 m = find_block(NULL, NULL, NULL, "/overlay");
1074
1075         if (!m || !m->extroot)
1076         {
1077                 ULOG_INFO("extroot: not configured\n");
1078                 return -1;
1079         }
1080
1081         /* Find block device pointed by the mount config */
1082         pr = find_block_info(m->uuid, m->label, m->device);
1083
1084         if (!pr && delay_root){
1085                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1086                 sleep(delay_root);
1087                 mkblkdev();
1088                 cache_load(0);
1089                 pr = find_block_info(m->uuid, m->label, m->device);
1090         }
1091         if (pr) {
1092                 if (strncmp(pr->id->name, "ext", 3) &&
1093                     strncmp(pr->id->name, "ubifs", 5)) {
1094                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4\n", pr->id->name);
1095                         return -1;
1096                 }
1097
1098                 if (test_fs_support(pr->id->name)) {
1099                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->id->name);
1100                         return -1;
1101                 }
1102
1103                 if (m->overlay)
1104                         path = overlay;
1105                 mkdir_p(path);
1106
1107                 if (check_fs)
1108                         check_filesystem(pr);
1109
1110                 err = mount(pr->dev, path, pr->id->name, m->flags,
1111                             (m->options) ? (m->options) : (""));
1112
1113                 if (err) {
1114                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%s)\n",
1115                                  pr->dev, pr->id->name, path, err, strerror(err));
1116                 } else if (m->overlay) {
1117                         err = check_extroot(path);
1118                         if (err)
1119                                 umount(path);
1120                 }
1121         } else {
1122                 ULOG_ERR("extroot: cannot find device %s%s\n",
1123                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1124                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1125         }
1126
1127         return err;
1128 }
1129
1130 static int main_extroot(int argc, char **argv)
1131 {
1132         struct blkid_struct_probe *pr;
1133         char blkdev_path[32] = { 0 };
1134         int err = -1;
1135 #ifdef UBIFS_EXTROOT
1136         libubi_t libubi;
1137 #endif
1138
1139         if (!getenv("PREINIT"))
1140                 return -1;
1141
1142         if (argc != 2) {
1143                 ULOG_ERR("Usage: block extroot\n");
1144                 return -1;
1145         }
1146
1147         mkblkdev();
1148         cache_load(1);
1149
1150         /* enable LOG_INFO messages */
1151         ulog_threshold(LOG_INFO);
1152
1153         /*
1154          * Look for "rootfs_data". We will want to mount it and check for
1155          * extroot configuration.
1156          */
1157
1158         /* Start with looking for MTD partition */
1159         find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1160         if (blkdev_path[0]) {
1161                 pr = find_block_info(NULL, NULL, blkdev_path);
1162                 if (pr && !strcmp(pr->id->name, "jffs2")) {
1163                         char cfg[] = "/tmp/jffs_cfg";
1164
1165                         /*
1166                          * Mount MTD part and try extroot (using
1167                          * /etc/config/fstab from that partition)
1168                          */
1169                         mkdir_p(cfg);
1170                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1171                                 err = mount_extroot(cfg);
1172                                 umount2(cfg, MNT_DETACH);
1173                         }
1174                         if (err < 0)
1175                                 rmdir("/tmp/overlay");
1176                         rmdir(cfg);
1177                         return err;
1178                 }
1179         }
1180
1181 #ifdef UBIFS_EXTROOT
1182         /* ... but it also could be an UBI volume */
1183         memset(blkdev_path, 0, sizeof(blkdev_path));
1184         libubi = libubi_open();
1185         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1186         libubi_close(libubi);
1187         if (blkdev_path[0]) {
1188                 char cfg[] = "/tmp/ubifs_cfg";
1189
1190                 /* Mount volume and try extroot (using fstab from that vol) */
1191                 mkdir_p(cfg);
1192                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1193                         err = mount_extroot(cfg);
1194                         umount2(cfg, MNT_DETACH);
1195                 }
1196                 if (err < 0)
1197                         rmdir("/tmp/overlay");
1198                 rmdir(cfg);
1199                 return err;
1200        }
1201 #endif
1202
1203         return mount_extroot(NULL);
1204 }
1205
1206 static int main_mount(int argc, char **argv)
1207 {
1208         struct blkid_struct_probe *pr;
1209
1210         if (config_load(NULL))
1211                 return -1;
1212
1213         cache_load(1);
1214         list_for_each_entry(pr, &devices, list)
1215                 mount_device(pr, 0);
1216
1217         handle_swapfiles(true);
1218
1219         return 0;
1220 }
1221
1222 static int main_umount(int argc, char **argv)
1223 {
1224         struct blkid_struct_probe *pr;
1225
1226         if (config_load(NULL))
1227                 return -1;
1228
1229         handle_swapfiles(false);
1230
1231         cache_load(0);
1232         list_for_each_entry(pr, &devices, list)
1233                 umount_device(pr);
1234
1235         return 0;
1236 }
1237
1238 static int main_detect(int argc, char **argv)
1239 {
1240         struct blkid_struct_probe *pr;
1241
1242         cache_load(0);
1243         printf("config 'global'\n");
1244         printf("\toption\tanon_swap\t'0'\n");
1245         printf("\toption\tanon_mount\t'0'\n");
1246         printf("\toption\tauto_swap\t'1'\n");
1247         printf("\toption\tauto_mount\t'1'\n");
1248         printf("\toption\tdelay_root\t'5'\n");
1249         printf("\toption\tcheck_fs\t'0'\n\n");
1250         list_for_each_entry(pr, &devices, list)
1251                 print_block_uci(pr);
1252
1253         return 0;
1254 }
1255
1256 static int main_info(int argc, char **argv)
1257 {
1258         int i;
1259         struct blkid_struct_probe *pr;
1260
1261         cache_load(1);
1262         if (argc == 2) {
1263                 list_for_each_entry(pr, &devices, list)
1264                         print_block_info(pr);
1265
1266                 return 0;
1267         };
1268
1269         for (i = 2; i < argc; i++) {
1270                 struct stat s;
1271
1272                 if (stat(argv[i], &s)) {
1273                         ULOG_ERR("failed to stat %s\n", argv[i]);
1274                         continue;
1275                 }
1276                 if (!S_ISBLK(s.st_mode)) {
1277                         ULOG_ERR("%s is not a block device\n", argv[i]);
1278                         continue;
1279                 }
1280                 pr = find_block_info(NULL, NULL, argv[i]);
1281                 if (pr)
1282                         print_block_info(pr);
1283         }
1284
1285         return 0;
1286 }
1287
1288 static int swapon_usage(void)
1289 {
1290         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1291                 "\tStart swapping on [DEVICE]\n"
1292                 " -a\tStart swapping on all swap devices\n"
1293                 " -p pri\tSet priority of swap device\n"
1294                 " -s\tShow summary\n");
1295         return -1;
1296 }
1297
1298 static int main_swapon(int argc, char **argv)
1299 {
1300         int ch;
1301         FILE *fp;
1302         char *lineptr;
1303         size_t s;
1304         struct blkid_struct_probe *pr;
1305         int flags = 0;
1306         int pri;
1307         struct stat st;
1308         int err;
1309
1310         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1311                 switch(ch) {
1312                 case 's':
1313                         fp = fopen("/proc/swaps", "r");
1314                         lineptr = NULL;
1315
1316                         if (!fp) {
1317                                 ULOG_ERR("failed to open /proc/swaps\n");
1318                                 return -1;
1319                         }
1320                         while (getline(&lineptr, &s, fp) > 0)
1321                                 printf("%s", lineptr);
1322                         if (lineptr)
1323                                 free(lineptr);
1324                         fclose(fp);
1325                         return 0;
1326                 case 'a':
1327                         cache_load(0);
1328                         list_for_each_entry(pr, &devices, list) {
1329                                 if (strcmp(pr->id->name, "swap"))
1330                                         continue;
1331                                 if (swapon(pr->dev, 0))
1332                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1333                         }
1334                         return 0;
1335                 case 'p':
1336                         pri = atoi(optarg);
1337                         if (pri >= 0)
1338                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1339                         break;
1340                 default:
1341                         return swapon_usage();
1342                 }
1343
1344         }
1345
1346         if (optind != (argc - 1))
1347                 return swapon_usage();
1348
1349         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1350                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1351                 return -1;
1352         }
1353         err = swapon(argv[optind], flags);
1354         if (err) {
1355                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1356                 return err;
1357         }
1358
1359         return 0;
1360 }
1361
1362 static int main_swapoff(int argc, char **argv)
1363 {
1364         if (argc != 2) {
1365                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1366                         "\tStop swapping on DEVICE\n"
1367                         " -a\tStop swapping on all swap devices\n");
1368                 return -1;
1369         }
1370
1371         if (!strcmp(argv[1], "-a")) {
1372                 FILE *fp = fopen("/proc/swaps", "r");
1373                 char line[256];
1374
1375                 if (!fp) {
1376                         ULOG_ERR("failed to open /proc/swaps\n");
1377                         return -1;
1378                 }
1379                 if (fgets(line, sizeof(line), fp))
1380                         while (fgets(line, sizeof(line), fp)) {
1381                                 char *end = strchr(line, ' ');
1382                                 int err;
1383
1384                                 if (!end)
1385                                         continue;
1386                                 *end = '\0';
1387                                 err = swapoff(line);
1388                                 if (err)
1389                                         ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1390                         }
1391                 fclose(fp);
1392         } else {
1393                 struct stat s;
1394                 int err;
1395
1396                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1397                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1398                         return -1;
1399                 }
1400                 err = swapoff(argv[1]);
1401                 if (err) {
1402                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1403                         return err;
1404                 }
1405         }
1406
1407         return 0;
1408 }
1409
1410 int main(int argc, char **argv)
1411 {
1412         char *base = basename(*argv);
1413
1414         umask(0);
1415
1416         ulog_open(-1, -1, "block");
1417         ulog_threshold(LOG_NOTICE);
1418
1419         if (!strcmp(base, "swapon"))
1420                 return main_swapon(argc, argv);
1421
1422         if (!strcmp(base, "swapoff"))
1423                 return main_swapoff(argc, argv);
1424
1425         if ((argc > 1) && !strcmp(base, "block")) {
1426                 if (!strcmp(argv[1], "info"))
1427                         return main_info(argc, argv);
1428
1429                 if (!strcmp(argv[1], "detect"))
1430                         return main_detect(argc, argv);
1431
1432                 if (!strcmp(argv[1], "hotplug"))
1433                         return main_hotplug(argc, argv);
1434
1435                 if (!strcmp(argv[1], "extroot"))
1436                         return main_extroot(argc, argv);
1437
1438                 if (!strcmp(argv[1], "mount"))
1439                         return main_mount(argc, argv);
1440
1441                 if (!strcmp(argv[1], "umount"))
1442                         return main_umount(argc, argv);
1443
1444                 if (!strcmp(argv[1], "remount")) {
1445                         int ret = main_umount(argc, argv);
1446
1447                         if (!ret)
1448                                 ret = main_mount(argc, argv);
1449                         return ret;
1450                 }
1451         }
1452
1453         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1454
1455         return -1;
1456 }