9c47cc6a10ef7048323e6c8a728d3779836489ea
[project/ubox.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 <stdio.h>
17 #include <unistd.h>
18 #include <syslog.h>
19 #include <libgen.h>
20 #include <glob.h>
21
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <sys/swap.h>
25 #include <sys/mount.h>
26 #include <sys/wait.h>
27
28 #include <uci.h>
29 #include <uci_blob.h>
30
31 #include <libubox/list.h>
32 #include <libubox/vlist.h>
33 #include <libubox/blobmsg_json.h>
34 #include <libubox/avl-cmp.h>
35
36 #include "libblkid-tiny/libblkid-tiny.h"
37
38 enum {
39         TYPE_MOUNT,
40         TYPE_SWAP,
41 };
42
43 struct mount {
44         struct vlist_node node;
45         int type;
46
47         char *target;
48         char *path;
49         char *options;
50         uint32_t flags;
51         char *uuid;
52         char *label;
53         char *device;
54         int extroot;
55         int overlay;
56         int disabled_fsck;
57         unsigned int prio;
58 };
59
60 static struct vlist_tree mounts;
61 static struct blob_buf b;
62 static LIST_HEAD(devices);
63 static int anon_mount, anon_swap, auto_mount, auto_swap, check_fs;
64 static unsigned int delay_root;
65
66 enum {
67         CFG_ANON_MOUNT,
68         CFG_ANON_SWAP,
69         CFG_AUTO_MOUNT,
70         CFG_AUTO_SWAP,
71         CFG_DELAY_ROOT,
72         CFG_CHECK_FS,
73         __CFG_MAX
74 };
75
76 static const struct blobmsg_policy config_policy[__CFG_MAX] = {
77         [CFG_ANON_SWAP] = { .name = "anon_swap", .type = BLOBMSG_TYPE_INT32 },
78         [CFG_ANON_MOUNT] = { .name = "anon_mount", .type = BLOBMSG_TYPE_INT32 },
79         [CFG_AUTO_SWAP] = { .name = "auto_swap", .type = BLOBMSG_TYPE_INT32 },
80         [CFG_AUTO_MOUNT] = { .name = "auto_mount", .type = BLOBMSG_TYPE_INT32 },
81         [CFG_DELAY_ROOT] = { .name = "delay_root", .type = BLOBMSG_TYPE_INT32 },
82         [CFG_CHECK_FS] = { .name = "check_fs", .type = BLOBMSG_TYPE_INT32 },
83 };
84
85 enum {
86         MOUNT_UUID,
87         MOUNT_LABEL,
88         MOUNT_ENABLE,
89         MOUNT_TARGET,
90         MOUNT_DEVICE,
91         MOUNT_OPTIONS,
92         __MOUNT_MAX
93 };
94
95 static const struct uci_blob_param_list config_attr_list = {
96         .n_params = __CFG_MAX,
97         .params = config_policy,
98 };
99
100 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
101         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
102         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
103         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
104         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
105         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
106         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
107 };
108
109 static const struct uci_blob_param_list mount_attr_list = {
110         .n_params = __MOUNT_MAX,
111         .params = mount_policy,
112 };
113
114 enum {
115         SWAP_ENABLE,
116         SWAP_UUID,
117         SWAP_DEVICE,
118         SWAP_PRIO,
119         __SWAP_MAX
120 };
121
122 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
123         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
124         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
125         [SWAP_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
126         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
127 };
128
129 static const struct uci_blob_param_list swap_attr_list = {
130         .n_params = __SWAP_MAX,
131         .params = swap_policy,
132 };
133
134 struct mount_flag {
135         const char *name;
136         int32_t flag;
137 };
138
139 #ifndef MS_DIRSYNC
140 #       define MS_DIRSYNC               (1 << 7)
141 #endif
142
143 #ifndef MS_RELATIME
144 #       define MS_RELATIME              (1 << 21)
145 #endif
146
147 #ifndef MS_STRICTATIME
148 #       define MS_STRICTATIME   (1 << 24)
149 #endif
150
151 static const struct mount_flag mount_flags[] = {
152         { "sync",                       MS_SYNCHRONOUS  },
153         { "async",                      ~MS_SYNCHRONOUS },
154         { "dirsync",            MS_DIRSYNC              },
155         { "mand",                       MS_MANDLOCK             },
156         { "nomand",                     ~MS_MANDLOCK    },
157         { "atime",                      ~MS_NOATIME             },
158         { "noatime",            MS_NOATIME              },
159         { "dev",                        ~MS_NODEV               },
160         { "nodev",                      MS_NODEV                },
161         { "diratime",           ~MS_NODIRATIME  },
162         { "nodiratime",         MS_NODIRATIME   },
163         { "exec",                       ~MS_NOEXEC              },
164         { "noexec",                     MS_NOEXEC               },
165         { "suid",                       ~MS_NOSUID              },
166         { "nosuid",                     MS_NOSUID               },
167         { "rw",                         ~MS_RDONLY              },
168         { "ro",                         MS_RDONLY               },
169         { "relatime",           MS_RELATIME             },
170         { "norelatime",         ~MS_RELATIME    },
171         { "strictatime",        MS_STRICTATIME  },
172 };
173
174 static char *blobmsg_get_strdup(struct blob_attr *attr)
175 {
176         if (!attr)
177                 return NULL;
178
179         return strdup(blobmsg_get_string(attr));
180 }
181
182 static char *blobmsg_get_basename(struct blob_attr *attr)
183 {
184         if (!attr)
185                 return NULL;
186
187         return strdup(basename(blobmsg_get_string(attr)));
188 }
189
190 static void parse_mount_options(struct mount *m, char *optstr)
191 {
192         int i;
193         bool is_flag;
194         char *p, *opts, *last;
195
196         m->flags = 0;
197         m->options = NULL;
198
199         if (!optstr || !*optstr)
200                 return;
201
202         m->options = opts = calloc(1, strlen(optstr) + 1);
203
204         if (!m->options)
205                 return;
206
207         p = last = optstr;
208
209         do {
210                 p = strchr(p, ',');
211
212                 if (p)
213                         *p++ = 0;
214
215                 for (i = 0, is_flag = false; i < ARRAY_SIZE(mount_flags); i++) {
216                         if (!strcmp(last, mount_flags[i].name)) {
217                                 if (mount_flags[i].flag < 0)
218                                         m->flags &= (uint32_t)mount_flags[i].flag;
219                                 else
220                                         m->flags |= (uint32_t)mount_flags[i].flag;
221                                 is_flag = true;
222                                 break;
223                         }
224                 }
225
226                 if (!is_flag)
227                         opts += sprintf(opts, "%s%s", (opts > m->options) ? "," : "", last);
228
229                 last = p;
230
231         } while (p);
232
233         free(optstr);
234 }
235
236 static int mount_add(struct uci_section *s)
237 {
238         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
239         struct mount *m;
240
241         blob_buf_init(&b, 0);
242         uci_to_blob(&b, s, &mount_attr_list);
243         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
244
245         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID] && !tb[MOUNT_DEVICE])
246                 return -1;
247
248         if (tb[MOUNT_ENABLE] && !blobmsg_get_u32(tb[MOUNT_ENABLE]))
249                 return -1;
250
251         m = malloc(sizeof(struct mount));
252         m->type = TYPE_MOUNT;
253         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
254         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
255         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
256         m->device = blobmsg_get_basename(tb[MOUNT_DEVICE]);
257
258         parse_mount_options(m, blobmsg_get_strdup(tb[MOUNT_OPTIONS]));
259
260         m->overlay = m->extroot = 0;
261         if (m->target && !strcmp(m->target, "/"))
262                 m->extroot = 1;
263         if (m->target && !strcmp(m->target, "/overlay"))
264                 m->extroot = m->overlay = 1;
265
266         if (m->uuid)
267                 vlist_add(&mounts, &m->node, m->uuid);
268         else if (m->label)
269                 vlist_add(&mounts, &m->node, m->label);
270         else if (m->device)
271                 vlist_add(&mounts, &m->node, m->device);
272
273         return 0;
274 }
275
276 static int swap_add(struct uci_section *s)
277 {
278         struct blob_attr *tb[__SWAP_MAX] = { 0 };
279         struct mount *m;
280
281         blob_buf_init(&b, 0);
282         uci_to_blob(&b, s, &swap_attr_list);
283         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
284
285         if (!tb[SWAP_UUID] && !tb[SWAP_DEVICE])
286                 return -1;
287
288         m = malloc(sizeof(struct mount));
289         memset(m, 0, sizeof(struct mount));
290         m->type = TYPE_SWAP;
291         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
292         m->device = blobmsg_get_basename(tb[SWAP_DEVICE]);
293         if (tb[SWAP_PRIO])
294                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
295         if (m->prio)
296                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
297
298         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE])) {
299                 /* store complete swap path */
300                 if (tb[SWAP_DEVICE])
301                         m->target = blobmsg_get_strdup(tb[SWAP_DEVICE]);
302                 vlist_add(&mounts, &m->node, (m->uuid) ? (m->uuid) : (m->device));
303         }
304
305         return 0;
306 }
307
308 static int global_add(struct uci_section *s)
309 {
310         struct blob_attr *tb[__CFG_MAX] = { 0 };
311
312         blob_buf_init(&b, 0);
313         uci_to_blob(&b, s, &config_attr_list);
314         blobmsg_parse(config_policy, __CFG_MAX, tb, blob_data(b.head), blob_len(b.head));
315
316         if ((tb[CFG_ANON_MOUNT]) && blobmsg_get_u32(tb[CFG_ANON_MOUNT]))
317                 anon_mount = 1;
318         if ((tb[CFG_ANON_SWAP]) && blobmsg_get_u32(tb[CFG_ANON_SWAP]))
319                 anon_swap = 1;
320
321         if ((tb[CFG_AUTO_MOUNT]) && blobmsg_get_u32(tb[CFG_AUTO_MOUNT]))
322                 auto_mount = 1;
323         if ((tb[CFG_AUTO_SWAP]) && blobmsg_get_u32(tb[CFG_AUTO_SWAP]))
324                 auto_swap = 1;
325
326         if (tb[CFG_DELAY_ROOT])
327                 delay_root = blobmsg_get_u32(tb[CFG_DELAY_ROOT]);
328
329         if ((tb[CFG_CHECK_FS]) && blobmsg_get_u32(tb[CFG_CHECK_FS]))
330                 check_fs = 1;
331
332         return 0;
333 }
334
335 static struct mount* find_swap(const char *uuid, const char *device)
336 {
337         struct mount *m;
338
339         vlist_for_each_element(&mounts, m, node) {
340                 if (m->type != TYPE_SWAP)
341                         continue;
342                 if (uuid && m->uuid && !strcmp(m->uuid, uuid))
343                         return m;
344                 if (device && m->device && !strcmp(m->device, device))
345                         return m;
346         }
347
348         return NULL;
349 }
350
351 static struct mount* find_block(const char *uuid, const char *label, const char *device,
352                                 const char *target)
353 {
354         struct mount *m;
355
356         vlist_for_each_element(&mounts, m, node) {
357                 if (m->type != TYPE_MOUNT)
358                         continue;
359                 if (m->uuid && uuid && !strcmp(m->uuid, uuid))
360                         return m;
361                 if (m->label && label && !strcmp(m->label, label))
362                         return m;
363                 if (m->target && target && !strcmp(m->target, target))
364                         return m;
365                 if (m->device && device && !strcmp(m->device, device))
366                         return m;
367         }
368
369         return NULL;
370 }
371
372 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
373                           struct vlist_node *node_old)
374 {
375 }
376
377 static int config_load(char *cfg)
378 {
379         struct uci_context *ctx;
380         struct uci_package *pkg;
381         struct uci_element *e;
382
383         vlist_init(&mounts, avl_strcmp, mounts_update);
384
385         ctx = uci_alloc_context();
386         if (cfg) {
387                 char path[32];
388                 snprintf(path, 32, "%s/etc/config", cfg);
389                 uci_set_confdir(ctx, path);
390         }
391
392         if (uci_load(ctx, "fstab", &pkg))
393                 return -1;
394
395         vlist_update(&mounts);
396         uci_foreach_element(&pkg->sections, e) {
397                 struct uci_section *s = uci_to_section(e);
398
399                 if (!strcmp(s->type, "mount"))
400                         mount_add(s);
401                 if (!strcmp(s->type, "swap"))
402                         swap_add(s);
403                 if (!strcmp(s->type, "global"))
404                         global_add(s);
405         }
406         vlist_flush(&mounts);
407
408         return 0;
409 }
410
411 static struct blkid_struct_probe* _probe_path(char *path)
412 {
413         struct blkid_struct_probe *pr;
414
415         pr = malloc(sizeof(*pr));
416
417         if (!pr)
418                 return NULL;
419
420         memset(pr, 0, sizeof(*pr));
421         probe_block(path, pr);
422
423         if (pr->err || !pr->id) {
424                 free(pr);
425                 return NULL;
426         }
427
428         return pr;
429 }
430
431 static int _cache_load(const char *path)
432 {
433         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
434         int j;
435         glob_t gl;
436
437         if (glob(path, gl_flags, NULL, &gl) < 0)
438                 return -1;
439
440         for (j = 0; j < gl.gl_pathc; j++) {
441                 struct blkid_struct_probe *pr = _probe_path(gl.gl_pathv[j]);
442                 if (pr)
443                         list_add_tail(&pr->list, &devices);
444         }
445
446         globfree(&gl);
447
448         return 0;
449 }
450
451 static void cache_load(int mtd)
452 {
453         if (mtd)
454                 _cache_load("/dev/mtdblock*");
455         _cache_load("/dev/mmcblk*");
456         _cache_load("/dev/sd*");
457         _cache_load("/dev/sdc*");
458         _cache_load("/dev/hd*");
459         _cache_load("/dev/md*");
460         _cache_load("/dev/mapper/*");
461 }
462
463 static int print_block_info(struct blkid_struct_probe *pr)
464 {
465         printf("%s:", pr->dev);
466         if (pr->uuid[0])
467                 printf(" UUID=\"%s\"", pr->uuid);
468
469         if (pr->label[0])
470                 printf(" LABEL=\"%s\"", pr->label);
471
472         if (pr->name[0])
473                 printf(" NAME=\"%s\"", pr->name);
474
475         if (pr->version[0])
476                 printf(" VERSION=\"%s\"", pr->version);
477
478         printf(" TYPE=\"%s\"\n", pr->id->name);
479
480         return 0;
481 }
482
483 static int print_block_uci(struct blkid_struct_probe *pr)
484 {
485         if (!strcmp(pr->id->name, "swap")) {
486                 printf("config 'swap'\n");
487         } else {
488                 printf("config 'mount'\n");
489                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
490         }
491         if (pr->uuid[0])
492                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
493         else
494                 printf("\toption\tdevice\t'%s'\n", pr->dev);
495         printf("\toption\tenabled\t'0'\n\n");
496
497         return 0;
498 }
499
500 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
501 {
502         struct blkid_struct_probe *pr = NULL;
503
504         if (uuid)
505                 list_for_each_entry(pr, &devices, list)
506                         if (!strcmp(pr->uuid, uuid))
507                                 return pr;
508
509         if (label)
510                 list_for_each_entry(pr, &devices, list)
511                         if (strcmp(pr->label, label))
512                                 return pr;
513
514         if (path)
515                 list_for_each_entry(pr, &devices, list)
516                         if (!strcmp(pr->dev, path))
517                                 return pr;
518
519         return NULL;
520 }
521
522 static char* find_mount_point(char *block)
523 {
524         FILE *fp = fopen("/proc/mounts", "r");
525         static char line[256];
526         int len = strlen(block);
527         char *point = NULL;
528
529         if(!fp)
530                 return NULL;
531
532         while (fgets(line, sizeof(line), fp)) {
533                 if (!strncmp(line, block, len)) {
534                         char *p = &line[len + 1];
535                         char *t = strstr(p, " ");
536
537                         if (!t)
538                                 return NULL;
539                         *t = '\0';
540                         point = p;
541                         break;
542                 }
543         }
544
545         fclose(fp);
546
547         return point;
548 }
549
550 static void mkdir_p(char *dir)
551 {
552         char *l = strrchr(dir, '/');
553
554         if (l) {
555                 *l = '\0';
556                 mkdir_p(dir);
557                 *l = '/';
558                 mkdir(dir, 0755);
559         }
560 }
561
562 static void check_filesystem(struct blkid_struct_probe *pr)
563 {
564         pid_t pid;
565         struct stat statbuf;
566         char *e2fsck = "/usr/sbin/e2fsck";
567
568         if (strncmp(pr->id->name, "ext", 3)) {
569                 fprintf(stderr, "check_filesystem: %s is not supported\n", pr->id->name);
570                 return;
571         }
572
573         if (stat(e2fsck, &statbuf) < 0) {
574                 fprintf(stderr, "check_filesystem: %s not found\n", e2fsck);
575                 return;
576         }
577
578         pid = fork();
579         if (!pid) {
580                 execl(e2fsck, e2fsck, "-p", pr->dev, NULL);
581                 exit(-1);
582         } else if (pid > 0) {
583                 int status;
584
585                 waitpid(pid, &status, 0);
586                 if (WEXITSTATUS(status))
587                         fprintf(stderr, "check_filesystem: %s returned %d\n", e2fsck, WEXITSTATUS(status));
588         }
589 }
590
591 static void handle_swapfiles(bool on)
592 {
593         struct stat s;
594         struct mount *m;
595         struct blkid_struct_probe *pr;
596
597         vlist_for_each_element(&mounts, m, node)
598         {
599                 if (m->type != TYPE_SWAP || !m->target)
600                         continue;
601
602                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
603                         continue;
604
605                 pr = _probe_path(m->target);
606
607                 if (!pr)
608                         continue;
609
610                 if (!strcmp(pr->id->name, "swap")) {
611                         if (on)
612                                 swapon(pr->dev, m->prio);
613                         else
614                                 swapoff(pr->dev);
615                 }
616
617                 free(pr);
618         }
619 }
620
621 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
622 {
623         struct mount *m;
624         char *device;
625
626         if (!pr)
627                 return -1;
628
629         device = basename(pr->dev);
630
631         if (!strcmp(pr->id->name, "swap")) {
632                 if (hotplug && !auto_swap)
633                         return -1;
634                 m = find_swap(pr->uuid, device);
635                 if (m || anon_swap)
636                         swapon(pr->dev, (m) ? (m->prio) : (0));
637
638                 return 0;
639         }
640
641         if (hotplug && !auto_mount)
642                 return -1;
643
644         if (find_mount_point(pr->dev)) {
645                 fprintf(stderr, "%s is already mounted\n", pr->dev);
646                 return -1;
647         }
648
649         m = find_block(pr->uuid, pr->label, device, NULL);
650         if (m && m->extroot)
651                 return -1;
652
653         if (m) {
654                 char *target = m->target;
655                 char _target[32];
656                 int err = 0;
657
658                 if (!target) {
659                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
660                         target = _target;
661                 }
662                 mkdir_p(target);
663
664                 if (check_fs)
665                         check_filesystem(pr);
666
667                 err = mount(pr->dev, target, pr->id->name, m->flags,
668                             (m->options) ? (m->options) : (""));
669                 if (err)
670                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
671                                         pr->dev, pr->id->name, target, err, strerror(err));
672                 else
673                         handle_swapfiles(true);
674                 return err;
675         }
676
677         if (anon_mount) {
678                 char target[] = "/mnt/mmcblk123";
679                 int err = 0;
680
681                 snprintf(target, sizeof(target), "/mnt/%s", device);
682                 mkdir_p(target);
683
684                 if (check_fs)
685                         check_filesystem(pr);
686
687                 err = mount(pr->dev, target, pr->id->name, 0, "");
688                 if (err)
689                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
690                                         pr->dev, pr->id->name, target, err, strerror(err));
691                 else
692                         handle_swapfiles(true);
693                 return err;
694         }
695
696         return 0;
697 }
698
699 static int umount_device(struct blkid_struct_probe *pr)
700 {
701         struct mount *m;
702         char *device = basename(pr->dev);
703         char *mp;
704         int err;
705
706         if (!pr)
707                 return -1;
708
709         if (!strcmp(pr->id->name, "swap"))
710                 return -1;
711
712         mp = find_mount_point(pr->dev);
713         if (!mp)
714                 return -1;
715
716         m = find_block(pr->uuid, pr->label, device, NULL);
717         if (m && m->extroot)
718                 return -1;
719
720         err = umount2(mp, MNT_DETACH);
721         if (err)
722                 fprintf(stderr, "unmounting %s (%s)  failed (%d) - %s\n",
723                         pr->dev, mp, err, strerror(err));
724         else
725                 fprintf(stderr, "unmounted %s (%s)\n",
726                         pr->dev, mp);
727
728         return err;
729 }
730
731 static int main_hotplug(int argc, char **argv)
732 {
733         char path[32];
734         char *action, *device, *mount_point;
735
736         action = getenv("ACTION");
737         device = getenv("DEVNAME");
738
739         if (!action || !device)
740                 return -1;
741         snprintf(path, sizeof(path), "/dev/%s", device);
742
743         if (!strcmp(action, "remove")) {
744                 int err = 0;
745                 mount_point = find_mount_point(path);
746                 if (mount_point)
747                         err = umount2(mount_point, MNT_DETACH);
748
749                 if (err)
750                         fprintf(stderr, "umount of %s failed (%d) - %s\n",
751                                         mount_point, err, strerror(err));
752
753                 return 0;
754         } else if (strcmp(action, "add")) {
755                 fprintf(stderr, "Unkown action %s\n", action);
756
757                 return -1;
758         }
759
760         if (config_load(NULL))
761                 return -1;
762         cache_load(0);
763
764         return mount_device(find_block_info(NULL, NULL, path), 1);
765 }
766
767 static int find_block_mtd(char *name, char *part, int plen)
768 {
769         FILE *fp = fopen("/proc/mtd", "r");
770         static char line[256];
771         char *index = NULL;
772
773         if(!fp)
774                 return -1;
775
776         while (!index && fgets(line, sizeof(line), fp)) {
777                 if (strstr(line, name)) {
778                         char *eol = strstr(line, ":");
779
780                         if (!eol)
781                                 continue;
782
783                         *eol = '\0';
784                         index = &line[3];
785                 }
786         }
787
788         fclose(fp);
789
790         if (!index)
791                 return -1;
792
793         snprintf(part, plen, "/dev/mtdblock%s", index);
794
795         return 0;
796 }
797
798 static int check_extroot(char *path)
799 {
800         struct blkid_struct_probe *pr = NULL;
801         char fs[32];
802
803         if (find_block_mtd("rootfs", fs, sizeof(fs)))
804                 return -1;
805
806         list_for_each_entry(pr, &devices, list) {
807                 if (!strcmp(pr->dev, fs)) {
808                         struct stat s;
809                         FILE *fp = NULL;
810                         char tag[64];
811                         char uuid[64] = { 0 };
812
813                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
814                         if (stat(tag, &s)) {
815                                 fp = fopen(tag, "w+");
816                                 if (!fp) {
817                                         fprintf(stderr, "extroot: failed to write uuid tag file\n");
818                                         /* return 0 to continue boot regardless of error */
819                                         return 0;
820                                 }
821                                 fputs(pr->uuid, fp);
822                                 fclose(fp);
823                                 return 0;
824                         }
825
826                         fp = fopen(tag, "r");
827                         if (!fp) {
828                                 fprintf(stderr, "extroot: failed to open uuid tag file\n");
829                                 return -1;
830                         }
831
832                         fgets(uuid, sizeof(uuid), fp);
833                         fclose(fp);
834                         if (!strcmp(uuid, pr->uuid))
835                                 return 0;
836                         fprintf(stderr, "extroot: uuid tag does not match rom uuid\n");
837                 }
838         }
839         return -1;
840 }
841
842 static int mount_extroot(char *cfg)
843 {
844         char overlay[] = "/tmp/extroot/overlay";
845         char mnt[] = "/tmp/extroot/mnt";
846         char *path = mnt;
847         struct blkid_struct_probe *pr;
848         struct mount *m;
849         int err = -1;
850
851         if (config_load(cfg))
852                 return -2;
853
854         m = find_block(NULL, NULL, NULL, "/");
855         if (!m)
856                 m = find_block(NULL, NULL, NULL, "/overlay");
857
858         if (!m || !m->extroot)
859                 return -1;
860
861         pr = find_block_info(m->uuid, m->label, NULL);
862
863         if (!pr && delay_root){
864                 fprintf(stderr, "extroot: is not ready yet, retrying in %u seconds\n", delay_root);
865                 sleep(delay_root);
866                 mkblkdev();
867                 cache_load(0);
868                 pr = find_block_info(m->uuid, m->label, NULL);
869         }
870         if (pr) {
871                 if (strncmp(pr->id->name, "ext", 3)) {
872                         fprintf(stderr, "extroot: %s is not supported, try ext4\n", pr->id->name);
873                         return -1;
874                 }
875                 if (m->overlay)
876                         path = overlay;
877                 mkdir_p(path);
878
879                 if (check_fs)
880                         check_filesystem(pr);
881
882                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
883
884                 if (err) {
885                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
886                                         pr->dev, pr->id->name, path, err, strerror(err));
887                 } else if (m->overlay) {
888                         err = check_extroot(path);
889                         if (err)
890                                 umount(path);
891                 }
892         }
893
894         return err;
895 }
896
897 static int main_extroot(int argc, char **argv)
898 {
899         struct blkid_struct_probe *pr;
900         char fs[32] = { 0 };
901         char fs_data[32] = { 0 };
902         int err = -1;
903
904         if (!getenv("PREINIT"))
905                 return -1;
906
907         if (argc != 2) {
908                 fprintf(stderr, "Usage: block extroot mountpoint\n");
909                 return -1;
910         }
911
912         mkblkdev();
913         cache_load(1);
914
915         find_block_mtd("rootfs", fs, sizeof(fs));
916         if (!fs[0])
917                 return -2;
918
919         pr = find_block_info(NULL, NULL, fs);
920         if (!pr)
921                 return -3;
922
923         find_block_mtd("rootfs_data", fs_data, sizeof(fs_data));
924         if (fs_data[0]) {
925                 pr = find_block_info(NULL, NULL, fs_data);
926                 if (pr && !strcmp(pr->id->name, "jffs2")) {
927                         char cfg[] = "/tmp/jffs_cfg";
928
929                         mkdir_p(cfg);
930                         if (!mount(fs_data, cfg, "jffs2", MS_NOATIME, NULL)) {
931                                 err = mount_extroot(cfg);
932                                 umount2(cfg, MNT_DETACH);
933                         }
934                         if (err < 0)
935                                 rmdir("/tmp/overlay");
936                         rmdir(cfg);
937                         return err;
938                 }
939         }
940
941         return mount_extroot(NULL);
942 }
943
944 static int main_mount(int argc, char **argv)
945 {
946         struct blkid_struct_probe *pr;
947
948         if (config_load(NULL))
949                 return -1;
950
951         cache_load(1);
952         list_for_each_entry(pr, &devices, list)
953                 mount_device(pr, 0);
954
955         return 0;
956 }
957
958 static int main_umount(int argc, char **argv)
959 {
960         struct blkid_struct_probe *pr;
961
962         if (config_load(NULL))
963                 return -1;
964
965         handle_swapfiles(false);
966
967         cache_load(0);
968         list_for_each_entry(pr, &devices, list)
969                 umount_device(pr);
970
971         return 0;
972 }
973
974 static int main_detect(int argc, char **argv)
975 {
976         struct blkid_struct_probe *pr;
977
978         cache_load(0);
979         printf("config 'global'\n");
980         printf("\toption\tanon_swap\t'0'\n");
981         printf("\toption\tanon_mount\t'0'\n");
982         printf("\toption\tauto_swap\t'1'\n");
983         printf("\toption\tauto_mount\t'1'\n");
984         printf("\toption\tdelay_root\t'5'\n");
985         printf("\toption\tcheck_fs\t'0'\n\n");
986         list_for_each_entry(pr, &devices, list)
987                 print_block_uci(pr);
988
989         return 0;
990 }
991
992 static int main_info(int argc, char **argv)
993 {
994         int i;
995         struct blkid_struct_probe *pr;
996
997         cache_load(1);
998         if (argc == 2) {
999                 list_for_each_entry(pr, &devices, list)
1000                         print_block_info(pr);
1001
1002                 return 0;
1003         };
1004
1005         for (i = 2; i < argc; i++) {
1006                 struct stat s;
1007
1008                 if (stat(argv[i], &s)) {
1009                         fprintf(stderr, "failed to stat %s\n", argv[i]);
1010                         continue;
1011                 }
1012                 if (!S_ISBLK(s.st_mode)) {
1013                         fprintf(stderr, "%s is not a block device\n", argv[i]);
1014                         continue;
1015                 }
1016                 pr = find_block_info(NULL, NULL, argv[i]);
1017                 if (pr)
1018                         print_block_info(pr);
1019         }
1020
1021         return 0;
1022 }
1023
1024 static int main_swapon(int argc, char **argv)
1025 {
1026         if (argc != 2) {
1027                 fprintf(stderr, "Usage: swapon <-s> <-a> [DEVICE]\n\n\tStart swapping on [DEVICE]\n -a\tStart swapping on all swap devices\n -s\tShow summary\n");
1028                 return -1;
1029         }
1030
1031         if (!strcmp(argv[1], "-s")) {
1032                 FILE *fp = fopen("/proc/swaps", "r");
1033                 char *lineptr = NULL;
1034                 size_t s;
1035
1036                 if (!fp) {
1037                         fprintf(stderr, "failed to open /proc/swaps\n");
1038                         return -1;
1039                 }
1040                 while (getline(&lineptr, &s, fp) > 0)
1041                         printf(lineptr);
1042                 if (lineptr)
1043                         free(lineptr);
1044                 fclose(fp);
1045         } else if (!strcmp(argv[1], "-a")) {
1046                 struct blkid_struct_probe *pr;
1047
1048                 cache_load(0);
1049                 list_for_each_entry(pr, &devices, list) {
1050                         if (strcmp(pr->id->name, "swap"))
1051                                 continue;
1052                         if (swapon(pr->dev, 0))
1053                                 fprintf(stderr, "failed to swapon %s\n", pr->dev);
1054                 }
1055         } else {
1056                 struct stat s;
1057                 int err;
1058
1059                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1060                         fprintf(stderr, "%s is not a block device or file\n", argv[1]);
1061                         return -1;
1062                 }
1063                 err = swapon(argv[1], 0);
1064                 if (err) {
1065                         fprintf(stderr, "failed to swapon %s (%d)\n", argv[1], err);
1066                         return err;
1067                 }
1068         }
1069
1070         return 0;
1071 }
1072
1073 static int main_swapoff(int argc, char **argv)
1074 {
1075         if (argc != 2) {
1076                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\n\tStop swapping on DEVICE\n -a\tStop swapping on all swap devices\n");
1077                 return -1;
1078         }
1079
1080         if (!strcmp(argv[1], "-a")) {
1081                 FILE *fp = fopen("/proc/swaps", "r");
1082                 char line[256];
1083
1084                 if (!fp) {
1085                         fprintf(stderr, "failed to open /proc/swaps\n");
1086                         return -1;
1087                 }
1088                 fgets(line, sizeof(line), fp);
1089                 while (fgets(line, sizeof(line), fp)) {
1090                         char *end = strchr(line, ' ');
1091                         int err;
1092
1093                         if (!end)
1094                                 continue;
1095                         *end = '\0';
1096                         err = swapoff(line);
1097                         if (err)
1098                                 fprintf(stderr, "failed to swapoff %s (%d)\n", line, err);
1099                 }
1100                 fclose(fp);
1101         } else {
1102                 struct stat s;
1103                 int err;
1104
1105                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1106                         fprintf(stderr, "%s is not a block device or file\n", argv[1]);
1107                         return -1;
1108                 }
1109                 err = swapoff(argv[1]);
1110                 if (err) {
1111                         fprintf(stderr, "fsiled to swapoff %s (%d)\n", argv[1], err);
1112                         return err;
1113                 }
1114         }
1115
1116         return 0;
1117 }
1118
1119 int main(int argc, char **argv)
1120 {
1121         char *base = basename(*argv);
1122
1123         umask(0);
1124
1125         if (!strcmp(base, "swapon"))
1126                 return main_swapon(argc, argv);
1127
1128         if (!strcmp(base, "swapoff"))
1129                 return main_swapoff(argc, argv);
1130
1131         if ((argc > 1) && !strcmp(base, "block")) {
1132                 if (!strcmp(argv[1], "info"))
1133                         return main_info(argc, argv);
1134
1135                 if (!strcmp(argv[1], "detect"))
1136                         return main_detect(argc, argv);
1137
1138                 if (!strcmp(argv[1], "hotplug"))
1139                         return main_hotplug(argc, argv);
1140
1141                 if (!strcmp(argv[1], "extroot"))
1142                         return main_extroot(argc, argv);
1143
1144                 if (!strcmp(argv[1], "mount"))
1145                         return main_mount(argc, argv);
1146
1147                 if (!strcmp(argv[1], "umount"))
1148                         return main_umount(argc, argv);
1149         }
1150
1151         fprintf(stderr, "Usage: block <info|mount|umount|detect>\n");
1152
1153         return -1;
1154 }