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