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