cosmetic: fix indentation
[project/fstools.git] / block.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #define _GNU_SOURCE
16 #include <getopt.h>
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <syslog.h>
20 #include <libgen.h>
21 #include <glob.h>
22
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/ubiblock*");
480         }
481         _cache_load("/dev/mmcblk*");
482         _cache_load("/dev/sd*");
483         _cache_load("/dev/hd*");
484         _cache_load("/dev/md*");
485         _cache_load("/dev/mapper/*");
486 }
487
488 static int print_block_info(struct blkid_struct_probe *pr)
489 {
490         printf("%s:", pr->dev);
491         if (pr->uuid[0])
492                 printf(" UUID=\"%s\"", pr->uuid);
493
494         if (pr->label[0])
495                 printf(" LABEL=\"%s\"", pr->label);
496
497         if (pr->name[0])
498                 printf(" NAME=\"%s\"", pr->name);
499
500         if (pr->version[0])
501                 printf(" VERSION=\"%s\"", pr->version);
502
503         printf(" TYPE=\"%s\"\n", pr->id->name);
504
505         return 0;
506 }
507
508 static int print_block_uci(struct blkid_struct_probe *pr)
509 {
510         if (!strcmp(pr->id->name, "swap")) {
511                 printf("config 'swap'\n");
512         } else {
513                 printf("config 'mount'\n");
514                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
515         }
516         if (pr->uuid[0])
517                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
518         else
519                 printf("\toption\tdevice\t'%s'\n", pr->dev);
520         printf("\toption\tenabled\t'0'\n\n");
521
522         return 0;
523 }
524
525 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
526 {
527         struct blkid_struct_probe *pr = NULL;
528
529         if (uuid)
530                 list_for_each_entry(pr, &devices, list)
531                         if (!strcmp(pr->uuid, uuid))
532                                 return pr;
533
534         if (label)
535                 list_for_each_entry(pr, &devices, list)
536                         if (!strcmp(pr->label, label))
537                                 return pr;
538
539         if (path)
540                 list_for_each_entry(pr, &devices, list)
541                         if (!strcmp(basename(pr->dev), basename(path)))
542                                 return pr;
543
544         return NULL;
545 }
546
547 static char* find_mount_point(char *block)
548 {
549         FILE *fp = fopen("/proc/mounts", "r");
550         static char line[256];
551         int len = strlen(block);
552         char *point = NULL;
553
554         if(!fp)
555                 return NULL;
556
557         while (fgets(line, sizeof(line), fp)) {
558                 if (!strncmp(line, block, len)) {
559                         char *p = &line[len + 1];
560                         char *t = strstr(p, " ");
561
562                         if (!t) {
563                                 fclose(fp);
564                                 return NULL;
565                         }
566                         *t = '\0';
567                         point = p;
568                         break;
569                 }
570         }
571
572         fclose(fp);
573
574         return point;
575 }
576
577 static void mkdir_p(char *dir)
578 {
579         char *l = strrchr(dir, '/');
580
581         if (l) {
582                 *l = '\0';
583                 mkdir_p(dir);
584                 *l = '/';
585                 mkdir(dir, 0755);
586         }
587 }
588
589 static void check_filesystem(struct blkid_struct_probe *pr)
590 {
591         pid_t pid;
592         struct stat statbuf;
593         char *e2fsck = "/usr/sbin/e2fsck";
594
595         if (strncmp(pr->id->name, "ext", 3)) {
596                 ERROR("check_filesystem: %s is not supported\n", pr->id->name);
597                 return;
598         }
599
600         if (stat(e2fsck, &statbuf) < 0) {
601                 ERROR("check_filesystem: %s not found\n", e2fsck);
602                 return;
603         }
604
605         pid = fork();
606         if (!pid) {
607                 execl(e2fsck, e2fsck, "-p", pr->dev, NULL);
608                 exit(-1);
609         } else if (pid > 0) {
610                 int status;
611
612                 waitpid(pid, &status, 0);
613                 if (WEXITSTATUS(status))
614                         ERROR("check_filesystem: %s returned %d\n", e2fsck, WEXITSTATUS(status));
615         }
616 }
617
618 static void handle_swapfiles(bool on)
619 {
620         struct stat s;
621         struct mount *m;
622         struct blkid_struct_probe *pr;
623
624         vlist_for_each_element(&mounts, m, node)
625         {
626                 if (m->type != TYPE_SWAP || !m->target)
627                         continue;
628
629                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
630                         continue;
631
632                 pr = _probe_path(m->target);
633
634                 if (!pr)
635                         continue;
636
637                 if (!strcmp(pr->id->name, "swap")) {
638                         if (on)
639                                 swapon(pr->dev, m->prio);
640                         else
641                                 swapoff(pr->dev);
642                 }
643
644                 free(pr);
645         }
646 }
647
648 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
649 {
650         struct mount *m;
651         char *device;
652
653         if (!pr)
654                 return -1;
655
656         device = basename(pr->dev);
657
658         if (!strcmp(pr->id->name, "swap")) {
659                 if (hotplug && !auto_swap)
660                         return -1;
661                 m = find_swap(pr->uuid, pr->label, device);
662                 if (m || anon_swap)
663                         swapon(pr->dev, (m) ? (m->prio) : (0));
664
665                 return 0;
666         }
667
668         if (hotplug && !auto_mount)
669                 return -1;
670
671         if (find_mount_point(pr->dev)) {
672                 ERROR("%s is already mounted\n", pr->dev);
673                 return -1;
674         }
675
676         m = find_block(pr->uuid, pr->label, device, NULL);
677         if (m && m->extroot)
678                 return -1;
679
680         if (m) {
681                 char *target = m->target;
682                 char _target[32];
683                 int err = 0;
684
685                 if (!target) {
686                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
687                         target = _target;
688                 }
689                 mkdir_p(target);
690
691                 if (check_fs)
692                         check_filesystem(pr);
693
694                 err = mount(pr->dev, target, pr->id->name, m->flags,
695                             (m->options) ? (m->options) : (""));
696                 if (err)
697                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
698                                         pr->dev, pr->id->name, target, err, strerror(err));
699                 else
700                         handle_swapfiles(true);
701                 return err;
702         }
703
704         if (anon_mount) {
705                 char target[] = "/mnt/mmcblk123";
706                 int err = 0;
707
708                 snprintf(target, sizeof(target), "/mnt/%s", device);
709                 mkdir_p(target);
710
711                 if (check_fs)
712                         check_filesystem(pr);
713
714                 err = mount(pr->dev, target, pr->id->name, 0, "");
715                 if (err)
716                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
717                                         pr->dev, pr->id->name, target, err, strerror(err));
718                 else
719                         handle_swapfiles(true);
720                 return err;
721         }
722
723         return 0;
724 }
725
726 static int umount_device(struct blkid_struct_probe *pr)
727 {
728         struct mount *m;
729         char *device = basename(pr->dev);
730         char *mp;
731         int err;
732
733         if (!pr)
734                 return -1;
735
736         if (!strcmp(pr->id->name, "swap"))
737                 return -1;
738
739         mp = find_mount_point(pr->dev);
740         if (!mp)
741                 return -1;
742
743         m = find_block(pr->uuid, pr->label, device, NULL);
744         if (m && m->extroot)
745                 return -1;
746
747         err = umount2(mp, MNT_DETACH);
748         if (err)
749                 ERROR("unmounting %s (%s)  failed (%d) - %s\n",
750                         pr->dev, mp, err, strerror(err));
751         else
752                 ERROR("unmounted %s (%s)\n",
753                         pr->dev, mp);
754
755         return err;
756 }
757
758 static int main_hotplug(int argc, char **argv)
759 {
760         char path[32];
761         char *action, *device, *mount_point;
762
763         action = getenv("ACTION");
764         device = getenv("DEVNAME");
765
766         if (!action || !device)
767                 return -1;
768         snprintf(path, sizeof(path), "/dev/%s", device);
769
770         if (!strcmp(action, "remove")) {
771                 int err = 0;
772                 mount_point = find_mount_point(path);
773                 if (mount_point)
774                         err = umount2(mount_point, MNT_DETACH);
775
776                 if (err)
777                         ERROR("umount of %s failed (%d) - %s\n",
778                                         mount_point, err, strerror(err));
779
780                 return 0;
781         } else if (strcmp(action, "add")) {
782                 ERROR("Unkown action %s\n", action);
783
784                 return -1;
785         }
786
787         if (config_load(NULL))
788                 return -1;
789         cache_load(0);
790
791         return mount_device(find_block_info(NULL, NULL, path), 1);
792 }
793
794 static int find_block_mtd(char *name, char *part, int plen)
795 {
796         FILE *fp = fopen("/proc/mtd", "r");
797         static char line[256];
798         char *index = NULL;
799
800         if(!fp)
801                 return -1;
802
803         while (!index && fgets(line, sizeof(line), fp)) {
804                 if (strstr(line, name)) {
805                         char *eol = strstr(line, ":");
806
807                         if (!eol)
808                                 continue;
809
810                         *eol = '\0';
811                         index = &line[3];
812                 }
813         }
814
815         fclose(fp);
816
817         if (!index)
818                 return -1;
819
820         snprintf(part, plen, "/dev/mtdblock%s", index);
821
822         return 0;
823 }
824
825 static int check_extroot(char *path)
826 {
827         struct blkid_struct_probe *pr = NULL;
828         char fs[32];
829
830         if (find_block_mtd("rootfs", fs, sizeof(fs)))
831                 return -1;
832
833         list_for_each_entry(pr, &devices, list) {
834                 if (!strcmp(pr->dev, fs)) {
835                         struct stat s;
836                         FILE *fp = NULL;
837                         char tag[64];
838                         char uuid[64] = { 0 };
839
840                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
841                         if (stat(tag, &s)) {
842                                 fp = fopen(tag, "w+");
843                                 if (!fp) {
844                                         ERROR("extroot: failed to write uuid tag file\n");
845                                         /* return 0 to continue boot regardless of error */
846                                         return 0;
847                                 }
848                                 fputs(pr->uuid, fp);
849                                 fclose(fp);
850                                 return 0;
851                         }
852
853                         fp = fopen(tag, "r");
854                         if (!fp) {
855                                 ERROR("extroot: failed to open uuid tag file\n");
856                                 return -1;
857                         }
858
859                         fgets(uuid, sizeof(uuid), fp);
860                         fclose(fp);
861                         if (!strcmp(uuid, pr->uuid))
862                                 return 0;
863                         ERROR("extroot: uuid tag does not match rom uuid\n");
864                 }
865         }
866         return -1;
867 }
868
869 static int mount_extroot(char *cfg)
870 {
871         char overlay[] = "/tmp/extroot/overlay";
872         char mnt[] = "/tmp/extroot/mnt";
873         char *path = mnt;
874         struct blkid_struct_probe *pr;
875         struct mount *m;
876         int err = -1;
877
878         if (config_load(cfg))
879                 return -2;
880
881         m = find_block(NULL, NULL, NULL, "/");
882         if (!m)
883                 m = find_block(NULL, NULL, NULL, "/overlay");
884
885         if (!m || !m->extroot)
886         {
887                 ERROR("extroot: no root or overlay mount defined\n");
888                 return -1;
889         }
890
891         pr = find_block_info(m->uuid, m->label, m->device);
892
893         if (!pr && delay_root){
894                 ERROR("extroot: is not ready yet, retrying in %u seconds\n", delay_root);
895                 sleep(delay_root);
896                 mkblkdev();
897                 cache_load(0);
898                 pr = find_block_info(m->uuid, m->label, m->device);
899         }
900         if (pr) {
901                 if (strncmp(pr->id->name, "ext", 3)) {
902                         ERROR("extroot: %s is not supported, try ext4\n", pr->id->name);
903                         return -1;
904                 }
905                 if (m->overlay)
906                         path = overlay;
907                 mkdir_p(path);
908
909                 if (check_fs)
910                         check_filesystem(pr);
911
912                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
913
914                 if (err) {
915                         ERROR("mounting %s (%s) as %s failed (%d) - %s\n",
916                                         pr->dev, pr->id->name, path, err, strerror(err));
917                 } else if (m->overlay) {
918                         err = check_extroot(path);
919                         if (err)
920                                 umount(path);
921                 }
922         } else {
923                 ERROR("extroot: cannot find block device\n");
924         }
925
926         return err;
927 }
928
929 static int main_extroot(int argc, char **argv)
930 {
931         struct blkid_struct_probe *pr;
932         char fs[32] = { 0 };
933         char fs_data[32] = { 0 };
934         int err = -1;
935
936         if (!getenv("PREINIT"))
937                 return -1;
938
939         if (argc != 2) {
940                 fprintf(stderr, "Usage: block extroot mountpoint\n");
941                 return -1;
942         }
943
944         mkblkdev();
945         cache_load(1);
946
947         find_block_mtd("rootfs", fs, sizeof(fs));
948         if (!fs[0]) {
949                 ERROR("extroot: unable to locate rootfs mtdblock\n");
950                 return -2;
951         }
952
953         pr = find_block_info(NULL, NULL, fs);
954         if (!pr) {
955                 ERROR("extroot: unable to retrieve rootfs information\n");
956                 return -3;
957         }
958
959         find_block_mtd("rootfs_data", fs_data, sizeof(fs_data));
960         if (fs_data[0]) {
961                 pr = find_block_info(NULL, NULL, fs_data);
962                 if (pr && !strcmp(pr->id->name, "jffs2")) {
963                         char cfg[] = "/tmp/jffs_cfg";
964
965                         mkdir_p(cfg);
966                         if (!mount(fs_data, cfg, "jffs2", MS_NOATIME, NULL)) {
967                                 err = mount_extroot(cfg);
968                                 umount2(cfg, MNT_DETACH);
969                         }
970                         if (err < 0)
971                                 rmdir("/tmp/overlay");
972                         rmdir(cfg);
973                         return err;
974                 }
975         }
976
977         return mount_extroot(NULL);
978 }
979
980 static int main_mount(int argc, char **argv)
981 {
982         struct blkid_struct_probe *pr;
983
984         if (config_load(NULL))
985                 return -1;
986
987         cache_load(1);
988         list_for_each_entry(pr, &devices, list)
989                 mount_device(pr, 0);
990
991         handle_swapfiles(true);
992
993         return 0;
994 }
995
996 static int main_umount(int argc, char **argv)
997 {
998         struct blkid_struct_probe *pr;
999
1000         if (config_load(NULL))
1001                 return -1;
1002
1003         handle_swapfiles(false);
1004
1005         cache_load(0);
1006         list_for_each_entry(pr, &devices, list)
1007                 umount_device(pr);
1008
1009         return 0;
1010 }
1011
1012 static int main_detect(int argc, char **argv)
1013 {
1014         struct blkid_struct_probe *pr;
1015
1016         cache_load(0);
1017         printf("config 'global'\n");
1018         printf("\toption\tanon_swap\t'0'\n");
1019         printf("\toption\tanon_mount\t'0'\n");
1020         printf("\toption\tauto_swap\t'1'\n");
1021         printf("\toption\tauto_mount\t'1'\n");
1022         printf("\toption\tdelay_root\t'5'\n");
1023         printf("\toption\tcheck_fs\t'0'\n\n");
1024         list_for_each_entry(pr, &devices, list)
1025                 print_block_uci(pr);
1026
1027         return 0;
1028 }
1029
1030 static int main_info(int argc, char **argv)
1031 {
1032         int i;
1033         struct blkid_struct_probe *pr;
1034
1035         cache_load(1);
1036         if (argc == 2) {
1037                 list_for_each_entry(pr, &devices, list)
1038                         print_block_info(pr);
1039
1040                 return 0;
1041         };
1042
1043         for (i = 2; i < argc; i++) {
1044                 struct stat s;
1045
1046                 if (stat(argv[i], &s)) {
1047                         ERROR("failed to stat %s\n", argv[i]);
1048                         continue;
1049                 }
1050                 if (!S_ISBLK(s.st_mode)) {
1051                         ERROR("%s is not a block device\n", argv[i]);
1052                         continue;
1053                 }
1054                 pr = find_block_info(NULL, NULL, argv[i]);
1055                 if (pr)
1056                         print_block_info(pr);
1057         }
1058
1059         return 0;
1060 }
1061
1062 static int swapon_usage(void)
1063 {
1064         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1065                 "\tStart swapping on [DEVICE]\n"
1066                 " -a\tStart swapping on all swap devices\n"
1067                 " -p pri\tSet priority of swap device\n"
1068                 " -s\tShow summary\n");
1069         return -1;
1070 }
1071
1072 static int main_swapon(int argc, char **argv)
1073 {
1074         int ch;
1075         FILE *fp;
1076         char *lineptr;
1077         size_t s;
1078         struct blkid_struct_probe *pr;
1079         int flags = 0;
1080         int pri;
1081         struct stat st;
1082         int err;
1083
1084         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1085                 switch(ch) {
1086                 case 's':
1087                         fp = fopen("/proc/swaps", "r");
1088                         lineptr = NULL;
1089
1090                         if (!fp) {
1091                                 ERROR("failed to open /proc/swaps\n");
1092                                 return -1;
1093                         }
1094                         while (getline(&lineptr, &s, fp) > 0)
1095                                 printf(lineptr);
1096                         if (lineptr)
1097                                 free(lineptr);
1098                         fclose(fp);
1099                         return 0;
1100                 case 'a':
1101                         cache_load(0);
1102                         list_for_each_entry(pr, &devices, list) {
1103                                 if (strcmp(pr->id->name, "swap"))
1104                                         continue;
1105                                 if (swapon(pr->dev, 0))
1106                                         ERROR("failed to swapon %s\n", pr->dev);
1107                         }
1108                         return 0;
1109                 case 'p':
1110                         pri = atoi(optarg);
1111                         if (pri >= 0)
1112                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1113                         break;
1114                 default:
1115                         return swapon_usage();
1116                 }
1117
1118         }
1119
1120         if (optind != (argc - 1))
1121                 return swapon_usage();
1122
1123         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1124                 ERROR("%s is not a block device or file\n", argv[optind]);
1125                 return -1;
1126         }
1127         err = swapon(argv[optind], flags);
1128         if (err) {
1129                 ERROR("failed to swapon %s (%d)\n", argv[optind], err);
1130                 return err;
1131         }
1132
1133         return 0;
1134 }
1135
1136 static int main_swapoff(int argc, char **argv)
1137 {
1138         if (argc != 2) {
1139                 ERROR("Usage: swapoff [-a] [DEVICE]\n\n"
1140                         "\tStop swapping on DEVICE\n"
1141                         " -a\tStop swapping on all swap devices\n");
1142                 return -1;
1143         }
1144
1145         if (!strcmp(argv[1], "-a")) {
1146                 FILE *fp = fopen("/proc/swaps", "r");
1147                 char line[256];
1148
1149                 if (!fp) {
1150                         ERROR("failed to open /proc/swaps\n");
1151                         return -1;
1152                 }
1153                 fgets(line, sizeof(line), fp);
1154                 while (fgets(line, sizeof(line), fp)) {
1155                         char *end = strchr(line, ' ');
1156                         int err;
1157
1158                         if (!end)
1159                                 continue;
1160                         *end = '\0';
1161                         err = swapoff(line);
1162                         if (err)
1163                                 ERROR("failed to swapoff %s (%d)\n", line, err);
1164                 }
1165                 fclose(fp);
1166         } else {
1167                 struct stat s;
1168                 int err;
1169
1170                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1171                         ERROR("%s is not a block device or file\n", argv[1]);
1172                         return -1;
1173                 }
1174                 err = swapoff(argv[1]);
1175                 if (err) {
1176                         ERROR("fsiled to swapoff %s (%d)\n", argv[1], err);
1177                         return err;
1178                 }
1179         }
1180
1181         return 0;
1182 }
1183
1184 int main(int argc, char **argv)
1185 {
1186         char *base = basename(*argv);
1187
1188         umask(0);
1189
1190         if (!strcmp(base, "swapon"))
1191                 return main_swapon(argc, argv);
1192
1193         if (!strcmp(base, "swapoff"))
1194                 return main_swapoff(argc, argv);
1195
1196         if ((argc > 1) && !strcmp(base, "block")) {
1197                 if (!strcmp(argv[1], "info"))
1198                         return main_info(argc, argv);
1199
1200                 if (!strcmp(argv[1], "detect"))
1201                         return main_detect(argc, argv);
1202
1203                 if (!strcmp(argv[1], "hotplug"))
1204                         return main_hotplug(argc, argv);
1205
1206                 if (!strcmp(argv[1], "extroot"))
1207                         return main_extroot(argc, argv);
1208
1209                 if (!strcmp(argv[1], "mount"))
1210                         return main_mount(argc, argv);
1211
1212                 if (!strcmp(argv[1], "umount"))
1213                         return main_umount(argc, argv);
1214         }
1215
1216         fprintf(stderr, "Usage: block <info|mount|umount|detect>\n");
1217
1218         return -1;
1219 }