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