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