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