58487a1a1935e0fe65f2c62e18e73b901feff294
[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 static int print_block_info(struct blkid_struct_probe *pr)
530 {
531         printf("%s:", pr->dev);
532         if (pr->uuid[0])
533                 printf(" UUID=\"%s\"", pr->uuid);
534
535         if (pr->label[0])
536                 printf(" LABEL=\"%s\"", pr->label);
537
538         if (pr->name[0])
539                 printf(" NAME=\"%s\"", pr->name);
540
541         if (pr->version[0])
542                 printf(" VERSION=\"%s\"", pr->version);
543
544         printf(" TYPE=\"%s\"\n", pr->id->name);
545
546         return 0;
547 }
548
549 static int print_block_uci(struct blkid_struct_probe *pr)
550 {
551         if (!strcmp(pr->id->name, "swap")) {
552                 printf("config 'swap'\n");
553         } else {
554                 printf("config 'mount'\n");
555                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
556         }
557         if (pr->uuid[0])
558                 printf("\toption\tuuid\t'%s'\n", pr->uuid);
559         else
560                 printf("\toption\tdevice\t'%s'\n", pr->dev);
561         printf("\toption\tenabled\t'0'\n\n");
562
563         return 0;
564 }
565
566 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
567 {
568         struct blkid_struct_probe *pr = NULL;
569
570         if (uuid)
571                 list_for_each_entry(pr, &devices, list)
572                         if (!strcasecmp(pr->uuid, uuid))
573                                 return pr;
574
575         if (label)
576                 list_for_each_entry(pr, &devices, list)
577                         if (!strcmp(pr->label, label))
578                                 return pr;
579
580         if (path)
581                 list_for_each_entry(pr, &devices, list)
582                         if (!strcmp(basename(pr->dev), basename(path)))
583                                 return pr;
584
585         return NULL;
586 }
587
588 static char* find_mount_point(char *block)
589 {
590         FILE *fp = fopen("/proc/mounts", "r");
591         static char line[256], *saveptr;
592         int len = strlen(block);
593         char *point = NULL;
594         struct stat s;
595
596         if(!fp)
597                 return NULL;
598
599         while (fgets(line, sizeof(line), fp)) {
600                 if (!strncmp(line, block, len)) {
601                         char *p = &line[len + 1];
602                         char *t = strstr(p, " ");
603
604                         if (!t) {
605                                 fclose(fp);
606                                 return NULL;
607                         }
608                         *t = '\0';
609                         point = p;
610                         break;
611                 }
612         }
613
614         fclose(fp);
615
616         if (point)
617                 return point;
618
619         if (stat(block, &s))
620                 return NULL;
621
622         if (!S_ISBLK(s.st_mode))
623                 return NULL;
624
625         fp = fopen("/proc/self/mountinfo", "r");
626         if(!fp)
627                 return NULL;
628
629         while (fgets(line, sizeof(line), fp)) {
630                 strtok_r(line, " \t", &saveptr);
631                 strtok_r(NULL, " \t", &saveptr);
632                 if (atoi(strtok_r(NULL, ":", &saveptr)) == major(s.st_rdev) &&
633                     atoi(strtok_r(NULL, " \t", &saveptr)) == minor(s.st_rdev)) {
634                         strtok_r(NULL, " \t", &saveptr);
635                         point = strtok_r(NULL, " \t", &saveptr);
636                         break;
637                 }
638         }
639
640         fclose(fp);
641
642         return point;
643 }
644
645 static void mkdir_p(char *dir)
646 {
647         char *l = strrchr(dir, '/');
648
649         if (l) {
650                 *l = '\0';
651                 mkdir_p(dir);
652                 *l = '/';
653                 mkdir(dir, 0755);
654         }
655 }
656
657 static void check_filesystem(struct blkid_struct_probe *pr)
658 {
659         pid_t pid;
660         struct stat statbuf;
661         const char *e2fsck = "/usr/sbin/e2fsck";
662         const char *dosfsck = "/usr/sbin/dosfsck";
663         const char *ckfs;
664
665         /* UBIFS does not need stuff like fsck */
666         if (!strncmp(pr->id->name, "ubifs", 5))
667                 return;
668
669         if (!strncmp(pr->id->name, "vfat", 4)) {
670                 ckfs = dosfsck;
671         } else if (!strncmp(pr->id->name, "ext", 3)) {
672                 ckfs = e2fsck;
673         } else {
674                 ULOG_ERR("check_filesystem: %s is not supported\n", pr->id->name);
675                 return;
676         }
677
678         if (stat(ckfs, &statbuf) < 0) {
679                 ULOG_ERR("check_filesystem: %s not found\n", ckfs);
680                 return;
681         }
682
683         pid = fork();
684         if (!pid) {
685                 execl(ckfs, ckfs, "-p", pr->dev, NULL);
686                 exit(-1);
687         } else if (pid > 0) {
688                 int status;
689
690                 waitpid(pid, &status, 0);
691                 if (WEXITSTATUS(status))
692                         ULOG_ERR("check_filesystem: %s returned %d\n", ckfs, WEXITSTATUS(status));
693         }
694 }
695
696 static void handle_swapfiles(bool on)
697 {
698         struct stat s;
699         struct mount *m;
700         struct blkid_struct_probe *pr;
701
702         vlist_for_each_element(&mounts, m, node)
703         {
704                 if (m->type != TYPE_SWAP || !m->target)
705                         continue;
706
707                 if (stat(m->target, &s) || !S_ISREG(s.st_mode))
708                         continue;
709
710                 pr = _probe_path(m->target);
711
712                 if (!pr)
713                         continue;
714
715                 if (!strcmp(pr->id->name, "swap")) {
716                         if (on)
717                                 swapon(pr->dev, m->prio);
718                         else
719                                 swapoff(pr->dev);
720                 }
721
722                 free(pr);
723         }
724 }
725
726 static int mount_device(struct blkid_struct_probe *pr, int hotplug)
727 {
728         struct mount *m;
729         char *device;
730
731         if (!pr)
732                 return -1;
733
734         device = basename(pr->dev);
735
736         if (!strcmp(pr->id->name, "swap")) {
737                 if (hotplug && !auto_swap)
738                         return -1;
739                 m = find_swap(pr->uuid, pr->label, device);
740                 if (m || anon_swap)
741                         swapon(pr->dev, (m) ? (m->prio) : (0));
742
743                 return 0;
744         }
745
746         if (hotplug && !auto_mount)
747                 return -1;
748
749         if (find_mount_point(pr->dev)) {
750                 ULOG_ERR("%s is already mounted\n", pr->dev);
751                 return -1;
752         }
753
754         m = find_block(pr->uuid, pr->label, device, NULL);
755         if (m && m->extroot)
756                 return -1;
757
758         if (m) {
759                 char *target = m->target;
760                 char _target[32];
761                 int err = 0;
762
763                 if (!target) {
764                         snprintf(_target, sizeof(_target), "/mnt/%s", device);
765                         target = _target;
766                 }
767                 mkdir_p(target);
768
769                 if (check_fs)
770                         check_filesystem(pr);
771
772                 err = mount(pr->dev, target, pr->id->name, m->flags,
773                             (m->options) ? (m->options) : (""));
774                 if (err)
775                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
776                                  pr->dev, pr->id->name, target, err, strerror(err));
777                 else
778                         handle_swapfiles(true);
779                 return err;
780         }
781
782         if (anon_mount) {
783                 char target[32];
784                 int err = 0;
785
786                 snprintf(target, sizeof(target), "/mnt/%s", device);
787                 mkdir_p(target);
788
789                 if (check_fs)
790                         check_filesystem(pr);
791
792                 err = mount(pr->dev, target, pr->id->name, 0, "");
793                 if (err)
794                         ULOG_ERR("mounting %s (%s) as %s failed (%d) - %s\n",
795                                  pr->dev, pr->id->name, target, err, strerror(err));
796                 else
797                         handle_swapfiles(true);
798                 return err;
799         }
800
801         return 0;
802 }
803
804 static int umount_device(struct blkid_struct_probe *pr)
805 {
806         struct mount *m;
807         char *device = basename(pr->dev);
808         char *mp;
809         int err;
810
811         if (!pr)
812                 return -1;
813
814         if (!strcmp(pr->id->name, "swap"))
815                 return -1;
816
817         mp = find_mount_point(pr->dev);
818         if (!mp)
819                 return -1;
820
821         m = find_block(pr->uuid, pr->label, device, NULL);
822         if (m && m->extroot)
823                 return -1;
824
825         err = umount2(mp, MNT_DETACH);
826         if (err)
827                 ULOG_ERR("unmounting %s (%s)  failed (%d) - %s\n",
828                          pr->dev, mp, err, strerror(err));
829         else
830                 ULOG_INFO("unmounted %s (%s)\n",
831                           pr->dev, mp);
832
833         return err;
834 }
835
836 static int main_hotplug(int argc, char **argv)
837 {
838         char path[32];
839         char *action, *device, *mount_point;
840
841         action = getenv("ACTION");
842         device = getenv("DEVNAME");
843
844         if (!action || !device)
845                 return -1;
846         snprintf(path, sizeof(path), "/dev/%s", device);
847
848         if (!strcmp(action, "remove")) {
849                 int err = 0;
850                 mount_point = find_mount_point(path);
851                 if (mount_point)
852                         err = umount2(mount_point, MNT_DETACH);
853
854                 if (err)
855                         ULOG_ERR("umount of %s failed (%d) - %s\n",
856                                  mount_point, err, strerror(err));
857
858                 return 0;
859         } else if (strcmp(action, "add")) {
860                 ULOG_ERR("Unkown action %s\n", action);
861
862                 return -1;
863         }
864
865         if (config_load(NULL))
866                 return -1;
867         cache_load(0);
868
869         return mount_device(find_block_info(NULL, NULL, path), 1);
870 }
871
872 static int find_block_mtd(char *name, char *part, int plen)
873 {
874         FILE *fp = fopen("/proc/mtd", "r");
875         static char line[256];
876         char *index = NULL;
877
878         if(!fp)
879                 return -1;
880
881         while (!index && fgets(line, sizeof(line), fp)) {
882                 if (strstr(line, name)) {
883                         char *eol = strstr(line, ":");
884
885                         if (!eol)
886                                 continue;
887
888                         *eol = '\0';
889                         index = &line[3];
890                 }
891         }
892
893         fclose(fp);
894
895         if (!index)
896                 return -1;
897
898         snprintf(part, plen, "/dev/mtdblock%s", index);
899
900         return 0;
901 }
902
903 #ifdef UBIFS_EXTROOT
904 static int find_ubi_vol(libubi_t libubi, char *name, int *dev_num, int *vol_id)
905 {
906         int dev = 0;
907
908         while (ubi_dev_present(libubi, dev))
909         {
910                 struct ubi_dev_info dev_info;
911                 struct ubi_vol_info vol_info;
912
913                 if (ubi_get_dev_info1(libubi, dev++, &dev_info))
914                         continue;
915                 if (ubi_get_vol_info1_nm(libubi, dev_info.dev_num, name, &vol_info))
916                         continue;
917
918                 *dev_num = dev_info.dev_num;
919                 *vol_id = vol_info.vol_id;
920
921                 return 0;
922         }
923
924         return -1;
925 }
926
927 static int find_block_ubi(libubi_t libubi, char *name, char *part, int plen)
928 {
929         int dev_num;
930         int vol_id;
931         int err = -1;
932
933         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
934         if (!err)
935                 snprintf(part, plen, "/dev/ubi%d_%d", dev_num, vol_id);
936
937         return err;
938 }
939
940 static int find_block_ubi_RO(libubi_t libubi, char *name, char *part, int plen)
941 {
942         int dev_num;
943         int vol_id;
944         int err = -1;
945
946         err = find_ubi_vol(libubi, name, &dev_num, &vol_id);
947         if (!err)
948                 snprintf(part, plen, "/dev/ubiblock%d_%d", dev_num, vol_id);
949
950         return err;
951 }
952
953 #else
954
955 static int find_root_dev(char *buf, int len)
956 {
957         DIR *d;
958         dev_t root;
959         struct stat s;
960         struct dirent *e;
961
962         if (stat("/", &s))
963                 return -1;
964
965         if (!(d = opendir("/dev")))
966                 return -1;
967
968         root = s.st_dev;
969
970         while ((e = readdir(d)) != NULL) {
971                 snprintf(buf, len, "/dev/%s", e->d_name);
972
973                 if (stat(buf, &s) || s.st_rdev != root)
974                         continue;
975
976                 closedir(d);
977                 return 0;
978         }
979
980         closedir(d);
981         return -1;
982 }
983
984 #endif
985
986 static int test_fs_support(const char *name)
987 {
988         char line[128], *p;
989         int rv = -1;
990         FILE *f;
991
992         if ((f = fopen("/proc/filesystems", "r")) != NULL) {
993                 while (fgets(line, sizeof(line), f)) {
994                         p = strtok(line, "\t\n");
995
996                         if (p && !strcmp(p, "nodev"))
997                                 p = strtok(NULL, "\t\n");
998
999                         if (p && !strcmp(p, name)) {
1000                                 rv = 0;
1001                                 break;
1002                         }
1003                 }
1004                 fclose(f);
1005         }
1006
1007         return rv;
1008 }
1009
1010 static int check_extroot(char *path)
1011 {
1012         struct blkid_struct_probe *pr = NULL;
1013         char devpath[32];
1014
1015 #ifdef UBIFS_EXTROOT
1016         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1017                 int err = -1;
1018                 libubi_t libubi;
1019
1020                 libubi = libubi_open();
1021                 err = find_block_ubi_RO(libubi, "rootfs", devpath, sizeof(devpath));
1022                 libubi_close(libubi);
1023                 if (err)
1024                         return -1;
1025         }
1026 #else
1027         if (find_block_mtd("\"rootfs\"", devpath, sizeof(devpath))) {
1028                 if (find_root_dev(devpath, sizeof(devpath))) {
1029                         ULOG_ERR("extroot: unable to determine root device\n");
1030                         return -1;
1031                 }
1032         }
1033 #endif
1034
1035         list_for_each_entry(pr, &devices, list) {
1036                 if (!strcmp(pr->dev, devpath)) {
1037                         struct stat s;
1038                         FILE *fp = NULL;
1039                         char tag[64];
1040                         char uuid[64] = { 0 };
1041
1042                         snprintf(tag, sizeof(tag), "%s/etc", path);
1043                         if (stat(tag, &s))
1044                                 mkdir_p(tag);
1045
1046                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
1047                         if (stat(tag, &s)) {
1048                                 fp = fopen(tag, "w+");
1049                                 if (!fp) {
1050                                         ULOG_ERR("extroot: failed to write UUID to %s: %d (%s)\n",
1051                                                  tag, errno, strerror(errno));
1052                                         /* return 0 to continue boot regardless of error */
1053                                         return 0;
1054                                 }
1055                                 fputs(pr->uuid, fp);
1056                                 fclose(fp);
1057                                 return 0;
1058                         }
1059
1060                         fp = fopen(tag, "r");
1061                         if (!fp) {
1062                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1063                                          tag, errno, strerror(errno));
1064                                 return -1;
1065                         }
1066
1067                         if (!fgets(uuid, sizeof(uuid), fp))
1068                                 ULOG_ERR("extroot: failed to read UUID from %s: %d (%s)\n",
1069                                          tag, errno, strerror(errno));
1070                         fclose(fp);
1071
1072                         if (*uuid || !strcasecmp(uuid, pr->uuid))
1073                                 return 0;
1074
1075                         ULOG_ERR("extroot: UUID mismatch (root: %s, %s: %s)\n",
1076                                  pr->uuid, basename(path), uuid);
1077                         return -1;
1078                 }
1079         }
1080
1081         ULOG_ERR("extroot: unable to lookup root device %s\n", devpath);
1082         return -1;
1083 }
1084
1085 /*
1086  * Read info about extroot from UCI (using prefix) and mount it.
1087  */
1088 static int mount_extroot(char *cfg)
1089 {
1090         char overlay[] = "/tmp/extroot/overlay";
1091         char mnt[] = "/tmp/extroot/mnt";
1092         char *path = mnt;
1093         struct blkid_struct_probe *pr;
1094         struct mount *m;
1095         int err = -1;
1096
1097         /* Load @cfg/etc/config/fstab */
1098         if (config_load(cfg))
1099                 return -2;
1100
1101         /* See if there is extroot-specific mount config */
1102         m = find_block(NULL, NULL, NULL, "/");
1103         if (!m)
1104                 m = find_block(NULL, NULL, NULL, "/overlay");
1105
1106         if (!m || !m->extroot)
1107         {
1108                 ULOG_INFO("extroot: not configured\n");
1109                 return -1;
1110         }
1111
1112         /* Find block device pointed by the mount config */
1113         pr = find_block_info(m->uuid, m->label, m->device);
1114
1115         if (!pr && delay_root){
1116                 ULOG_INFO("extroot: device not present, retrying in %u seconds\n", delay_root);
1117                 sleep(delay_root);
1118                 mkblkdev();
1119                 cache_load(0);
1120                 pr = find_block_info(m->uuid, m->label, m->device);
1121         }
1122         if (pr) {
1123                 if (strncmp(pr->id->name, "ext", 3) &&
1124                     strncmp(pr->id->name, "ubifs", 5)) {
1125                         ULOG_ERR("extroot: unsupported filesystem %s, try ext4\n", pr->id->name);
1126                         return -1;
1127                 }
1128
1129                 if (test_fs_support(pr->id->name)) {
1130                         ULOG_ERR("extroot: filesystem %s not supported by kernel\n", pr->id->name);
1131                         return -1;
1132                 }
1133
1134                 if (m->overlay)
1135                         path = overlay;
1136                 mkdir_p(path);
1137
1138                 if (check_fs)
1139                         check_filesystem(pr);
1140
1141                 err = mount(pr->dev, path, pr->id->name, m->flags,
1142                             (m->options) ? (m->options) : (""));
1143
1144                 if (err) {
1145                         ULOG_ERR("extroot: mounting %s (%s) on %s failed: %d (%s)\n",
1146                                  pr->dev, pr->id->name, path, err, strerror(err));
1147                 } else if (m->overlay) {
1148                         err = check_extroot(path);
1149                         if (err)
1150                                 umount(path);
1151                 }
1152         } else {
1153                 ULOG_ERR("extroot: cannot find device %s%s\n",
1154                          (m->uuid ? "with UUID " : (m->label ? "with label " : "")),
1155                          (m->uuid ? m->uuid : (m->label ? m->label : m->device)));
1156         }
1157
1158         return err;
1159 }
1160
1161 static int main_extroot(int argc, char **argv)
1162 {
1163         struct blkid_struct_probe *pr;
1164         char blkdev_path[32] = { 0 };
1165         int err = -1;
1166 #ifdef UBIFS_EXTROOT
1167         libubi_t libubi;
1168 #endif
1169
1170         if (!getenv("PREINIT"))
1171                 return -1;
1172
1173         if (argc != 2) {
1174                 ULOG_ERR("Usage: block extroot\n");
1175                 return -1;
1176         }
1177
1178         mkblkdev();
1179         cache_load(1);
1180
1181         /* enable LOG_INFO messages */
1182         ulog_threshold(LOG_INFO);
1183
1184         /*
1185          * Look for "rootfs_data". We will want to mount it and check for
1186          * extroot configuration.
1187          */
1188
1189         /* Start with looking for MTD partition */
1190         find_block_mtd("\"rootfs_data\"", blkdev_path, sizeof(blkdev_path));
1191         if (blkdev_path[0]) {
1192                 pr = find_block_info(NULL, NULL, blkdev_path);
1193                 if (pr && !strcmp(pr->id->name, "jffs2")) {
1194                         char cfg[] = "/tmp/jffs_cfg";
1195
1196                         /*
1197                          * Mount MTD part and try extroot (using
1198                          * /etc/config/fstab from that partition)
1199                          */
1200                         mkdir_p(cfg);
1201                         if (!mount(blkdev_path, cfg, "jffs2", MS_NOATIME, NULL)) {
1202                                 err = mount_extroot(cfg);
1203                                 umount2(cfg, MNT_DETACH);
1204                         }
1205                         if (err < 0)
1206                                 rmdir("/tmp/overlay");
1207                         rmdir(cfg);
1208                         return err;
1209                 }
1210         }
1211
1212 #ifdef UBIFS_EXTROOT
1213         /* ... but it also could be an UBI volume */
1214         memset(blkdev_path, 0, sizeof(blkdev_path));
1215         libubi = libubi_open();
1216         find_block_ubi(libubi, "rootfs_data", blkdev_path, sizeof(blkdev_path));
1217         libubi_close(libubi);
1218         if (blkdev_path[0]) {
1219                 char cfg[] = "/tmp/ubifs_cfg";
1220
1221                 /* Mount volume and try extroot (using fstab from that vol) */
1222                 mkdir_p(cfg);
1223                 if (!mount(blkdev_path, cfg, "ubifs", MS_NOATIME, NULL)) {
1224                         err = mount_extroot(cfg);
1225                         umount2(cfg, MNT_DETACH);
1226                 }
1227                 if (err < 0)
1228                         rmdir("/tmp/overlay");
1229                 rmdir(cfg);
1230                 return err;
1231        }
1232 #endif
1233
1234         return mount_extroot(NULL);
1235 }
1236
1237 static int main_mount(int argc, char **argv)
1238 {
1239         struct blkid_struct_probe *pr;
1240
1241         if (config_load(NULL))
1242                 return -1;
1243
1244         cache_load(1);
1245         list_for_each_entry(pr, &devices, list)
1246                 mount_device(pr, 0);
1247
1248         handle_swapfiles(true);
1249
1250         return 0;
1251 }
1252
1253 static int main_umount(int argc, char **argv)
1254 {
1255         struct blkid_struct_probe *pr;
1256
1257         if (config_load(NULL))
1258                 return -1;
1259
1260         handle_swapfiles(false);
1261
1262         cache_load(0);
1263         list_for_each_entry(pr, &devices, list)
1264                 umount_device(pr);
1265
1266         return 0;
1267 }
1268
1269 static int main_detect(int argc, char **argv)
1270 {
1271         struct blkid_struct_probe *pr;
1272
1273         cache_load(0);
1274         printf("config 'global'\n");
1275         printf("\toption\tanon_swap\t'0'\n");
1276         printf("\toption\tanon_mount\t'0'\n");
1277         printf("\toption\tauto_swap\t'1'\n");
1278         printf("\toption\tauto_mount\t'1'\n");
1279         printf("\toption\tdelay_root\t'5'\n");
1280         printf("\toption\tcheck_fs\t'0'\n\n");
1281         list_for_each_entry(pr, &devices, list)
1282                 print_block_uci(pr);
1283
1284         return 0;
1285 }
1286
1287 static int main_info(int argc, char **argv)
1288 {
1289         int i;
1290         struct blkid_struct_probe *pr;
1291
1292         cache_load(1);
1293         if (argc == 2) {
1294                 list_for_each_entry(pr, &devices, list)
1295                         print_block_info(pr);
1296
1297                 return 0;
1298         };
1299
1300         for (i = 2; i < argc; i++) {
1301                 struct stat s;
1302
1303                 if (stat(argv[i], &s)) {
1304                         ULOG_ERR("failed to stat %s\n", argv[i]);
1305                         continue;
1306                 }
1307                 if (!S_ISBLK(s.st_mode) && !(S_ISCHR(s.st_mode) && major(s.st_rdev) == 250)) {
1308                         ULOG_ERR("%s is not a block device\n", argv[i]);
1309                         continue;
1310                 }
1311                 pr = find_block_info(NULL, NULL, argv[i]);
1312                 if (pr)
1313                         print_block_info(pr);
1314         }
1315
1316         return 0;
1317 }
1318
1319 static int swapon_usage(void)
1320 {
1321         fprintf(stderr, "Usage: swapon [-s] [-a] [[-p pri] DEVICE]\n\n"
1322                 "\tStart swapping on [DEVICE]\n"
1323                 " -a\tStart swapping on all swap devices\n"
1324                 " -p pri\tSet priority of swap device\n"
1325                 " -s\tShow summary\n");
1326         return -1;
1327 }
1328
1329 static int main_swapon(int argc, char **argv)
1330 {
1331         int ch;
1332         FILE *fp;
1333         char *lineptr;
1334         size_t s;
1335         struct blkid_struct_probe *pr;
1336         int flags = 0;
1337         int pri;
1338         struct stat st;
1339         int err;
1340
1341         while ((ch = getopt(argc, argv, "ap:s")) != -1) {
1342                 switch(ch) {
1343                 case 's':
1344                         fp = fopen("/proc/swaps", "r");
1345                         lineptr = NULL;
1346
1347                         if (!fp) {
1348                                 ULOG_ERR("failed to open /proc/swaps\n");
1349                                 return -1;
1350                         }
1351                         while (getline(&lineptr, &s, fp) > 0)
1352                                 printf("%s", lineptr);
1353                         if (lineptr)
1354                                 free(lineptr);
1355                         fclose(fp);
1356                         return 0;
1357                 case 'a':
1358                         cache_load(0);
1359                         list_for_each_entry(pr, &devices, list) {
1360                                 if (strcmp(pr->id->name, "swap"))
1361                                         continue;
1362                                 if (swapon(pr->dev, 0))
1363                                         ULOG_ERR("failed to swapon %s\n", pr->dev);
1364                         }
1365                         return 0;
1366                 case 'p':
1367                         pri = atoi(optarg);
1368                         if (pri >= 0)
1369                                 flags = ((pri << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
1370                         break;
1371                 default:
1372                         return swapon_usage();
1373                 }
1374
1375         }
1376
1377         if (optind != (argc - 1))
1378                 return swapon_usage();
1379
1380         if (stat(argv[optind], &st) || (!S_ISBLK(st.st_mode) && !S_ISREG(st.st_mode))) {
1381                 ULOG_ERR("%s is not a block device or file\n", argv[optind]);
1382                 return -1;
1383         }
1384         err = swapon(argv[optind], flags);
1385         if (err) {
1386                 ULOG_ERR("failed to swapon %s (%d)\n", argv[optind], err);
1387                 return err;
1388         }
1389
1390         return 0;
1391 }
1392
1393 static int main_swapoff(int argc, char **argv)
1394 {
1395         if (argc != 2) {
1396                 ULOG_ERR("Usage: swapoff [-a] [DEVICE]\n\n"
1397                         "\tStop swapping on DEVICE\n"
1398                         " -a\tStop swapping on all swap devices\n");
1399                 return -1;
1400         }
1401
1402         if (!strcmp(argv[1], "-a")) {
1403                 FILE *fp = fopen("/proc/swaps", "r");
1404                 char line[256];
1405
1406                 if (!fp) {
1407                         ULOG_ERR("failed to open /proc/swaps\n");
1408                         return -1;
1409                 }
1410                 if (fgets(line, sizeof(line), fp))
1411                         while (fgets(line, sizeof(line), fp)) {
1412                                 char *end = strchr(line, ' ');
1413                                 int err;
1414
1415                                 if (!end)
1416                                         continue;
1417                                 *end = '\0';
1418                                 err = swapoff(line);
1419                                 if (err)
1420                                         ULOG_ERR("failed to swapoff %s (%d)\n", line, err);
1421                         }
1422                 fclose(fp);
1423         } else {
1424                 struct stat s;
1425                 int err;
1426
1427                 if (stat(argv[1], &s) || (!S_ISBLK(s.st_mode) && !S_ISREG(s.st_mode))) {
1428                         ULOG_ERR("%s is not a block device or file\n", argv[1]);
1429                         return -1;
1430                 }
1431                 err = swapoff(argv[1]);
1432                 if (err) {
1433                         ULOG_ERR("failed to swapoff %s (%d)\n", argv[1], err);
1434                         return err;
1435                 }
1436         }
1437
1438         return 0;
1439 }
1440
1441 int main(int argc, char **argv)
1442 {
1443         char *base = basename(*argv);
1444
1445         umask(0);
1446
1447         ulog_open(-1, -1, "block");
1448         ulog_threshold(LOG_NOTICE);
1449
1450         if (!strcmp(base, "swapon"))
1451                 return main_swapon(argc, argv);
1452
1453         if (!strcmp(base, "swapoff"))
1454                 return main_swapoff(argc, argv);
1455
1456         if ((argc > 1) && !strcmp(base, "block")) {
1457                 if (!strcmp(argv[1], "info"))
1458                         return main_info(argc, argv);
1459
1460                 if (!strcmp(argv[1], "detect"))
1461                         return main_detect(argc, argv);
1462
1463                 if (!strcmp(argv[1], "hotplug"))
1464                         return main_hotplug(argc, argv);
1465
1466                 if (!strcmp(argv[1], "extroot"))
1467                         return main_extroot(argc, argv);
1468
1469                 if (!strcmp(argv[1], "mount"))
1470                         return main_mount(argc, argv);
1471
1472                 if (!strcmp(argv[1], "umount"))
1473                         return main_umount(argc, argv);
1474
1475                 if (!strcmp(argv[1], "remount")) {
1476                         int ret = main_umount(argc, argv);
1477
1478                         if (!ret)
1479                                 ret = main_mount(argc, argv);
1480                         return ret;
1481                 }
1482         }
1483
1484         ULOG_ERR("Usage: block <info|mount|umount|detect>\n");
1485
1486         return -1;
1487 }