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