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