fd8d21efd24f862acf2e4068f640b65822628a08
[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 #include <stdio.h>
16 #include <unistd.h>
17 #include <syslog.h>
18 #include <libgen.h>
19 #include <glob.h>
20
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <sys/swap.h>
24 #include <sys/mount.h>
25
26 #include <uci.h>
27 #include <uci_blob.h>
28
29 #include <libubox/list.h>
30 #include <libubox/vlist.h>
31 #include <libubox/blobmsg_json.h>
32 #include <libubox/avl-cmp.h>
33
34 #include "libblkid-tiny/libblkid-tiny.h"
35
36 enum {
37         TYPE_MOUNT,
38         TYPE_SWAP,
39 };
40
41 struct mount {
42         struct vlist_node node;
43         int type;
44
45         char *target;
46         char *path;
47         char *options;
48         char *uuid;
49         char *label;
50         int disabled_fsck;
51         unsigned int prio;
52 };
53
54 static struct vlist_tree mounts;
55 static struct blob_buf b;
56 static LIST_HEAD(devices);
57
58 enum {
59         MOUNT_UUID,
60         MOUNT_LABEL,
61         MOUNT_ENABLE,
62         MOUNT_TARGET,
63         MOUNT_OPTIONS,
64         __MOUNT_MAX
65 };
66
67 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
68         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
69         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
70         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
71         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
72         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
73 };
74
75 static const struct uci_blob_param_list mount_attr_list = {
76         .n_params = __MOUNT_MAX,
77         .params = mount_policy,
78 };
79
80 enum {
81         SWAP_ENABLE,
82         SWAP_UUID,
83         SWAP_PRIO,
84         __SWAP_MAX
85 };
86
87 static const struct blobmsg_policy swap_policy[__SWAP_MAX] = {
88         [SWAP_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
89         [SWAP_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
90         [SWAP_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
91 };
92
93 static const struct uci_blob_param_list swap_attr_list = {
94         .n_params = __SWAP_MAX,
95         .params = swap_policy,
96 };
97
98 static char *blobmsg_get_strdup(struct blob_attr *attr)
99 {
100         if (!attr)
101                 return NULL;
102
103         return strdup(blobmsg_get_string(attr));
104 }
105
106 static int mount_add(struct uci_section *s)
107 {
108         struct blob_attr *tb[__MOUNT_MAX] = { 0 };
109         struct mount *m;
110
111         blob_buf_init(&b, 0);
112         uci_to_blob(&b, s, &mount_attr_list);
113         blobmsg_parse(mount_policy, __MOUNT_MAX, tb, blob_data(b.head), blob_len(b.head));
114
115         if (!tb[MOUNT_LABEL] && !tb[MOUNT_UUID])
116                 return -1;
117
118         if (!tb[MOUNT_TARGET])
119                 return -1;
120
121         m = malloc(sizeof(struct mount));
122         m->type = TYPE_MOUNT;
123         m->uuid = blobmsg_get_strdup(tb[MOUNT_UUID]);
124         m->label = blobmsg_get_strdup(tb[MOUNT_LABEL]);
125         m->target = blobmsg_get_strdup(tb[MOUNT_TARGET]);
126         m->options = blobmsg_get_strdup(tb[MOUNT_OPTIONS]);
127
128         if ((!tb[MOUNT_ENABLE]) || blobmsg_get_u32(tb[MOUNT_ENABLE]))
129                 vlist_add(&mounts, &m->node, m->target);
130
131         return 0;
132 }
133
134 static int swap_add(struct uci_section *s)
135 {
136         struct blob_attr *tb[__SWAP_MAX] = { 0 };
137         struct mount *m;
138
139         blob_buf_init(&b, 0);
140         uci_to_blob(&b, s, &swap_attr_list);
141         blobmsg_parse(swap_policy, __SWAP_MAX, tb, blob_data(b.head), blob_len(b.head));
142
143         if (!tb[SWAP_UUID])
144                 return -1;
145
146         m = malloc(sizeof(struct mount));
147         memset(m, 0, sizeof(struct mount));
148         m->type = TYPE_SWAP;
149         m->uuid = blobmsg_get_strdup(tb[SWAP_UUID]);
150         if (tb[SWAP_PRIO])
151                 m->prio = blobmsg_get_u32(tb[SWAP_PRIO]);
152         if (m->prio)
153                 m->prio = ((m->prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK) | SWAP_FLAG_PREFER;
154
155         if ((!tb[SWAP_ENABLE]) || blobmsg_get_u32(tb[SWAP_ENABLE]))
156                 vlist_add(&mounts, &m->node, m->uuid);
157
158         return 0;
159 }
160
161 static struct mount* find_swap(const char *uuid)
162 {
163         struct mount *m;
164
165         if (!uuid)
166                 return NULL;
167
168         vlist_for_each_element(&mounts, m, node)
169                 if ((m->type == TYPE_SWAP) && m->uuid && !strcmp(m->uuid, uuid))
170                         return m;
171
172         return NULL;
173 }
174
175 static struct mount* find_block(const char *uuid, const char *label, const char *target)
176 {
177         struct mount *m;
178
179         vlist_for_each_element(&mounts, m, node) {
180                 if ((m->type == TYPE_MOUNT) && m->uuid && uuid && !strcmp(m->uuid, uuid))
181                         return m;
182                 if ((m->type == TYPE_MOUNT) && m->label && label && !strcmp(m->label, label))
183                         return m;
184                 if ((m->type == TYPE_MOUNT) && target && !strcmp(m->target, target))
185                         return m;
186         }
187
188         return NULL;
189 }
190
191 static void mounts_update(struct vlist_tree *tree, struct vlist_node *node_new,
192                           struct vlist_node *node_old)
193 {
194 }
195
196 static int config_load(char *cfg)
197 {
198         struct uci_context *ctx;
199         struct uci_package *pkg;
200         struct uci_element *e;
201
202         vlist_init(&mounts, avl_strcmp, mounts_update);
203
204         ctx = uci_alloc_context();
205         if (cfg) {
206                 char path[32];
207                 snprintf(path, 32, "%s/etc/config", cfg);
208                 uci_set_confdir(ctx, path);
209         }
210
211         if (uci_load(ctx, "fstab", &pkg))
212                 return -1;
213
214         vlist_update(&mounts);
215         uci_foreach_element(&pkg->sections, e) {
216                 struct uci_section *s = uci_to_section(e);
217
218                 if (!strcmp(s->type, "mount"))
219                         mount_add(s);
220                 if (!strcmp(s->type, "swap"))
221                         swap_add(s);
222         }
223         vlist_flush(&mounts);
224
225         return 0;
226 }
227
228 static int _cache_load(const char *path)
229 {
230         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
231         int j;
232         glob_t gl;
233
234         if (glob(path, gl_flags, NULL, &gl) < 0)
235                 return -1;
236
237         for (j = 0; j < gl.gl_pathc; j++) {
238                 struct blkid_struct_probe *pr = malloc(sizeof(struct blkid_struct_probe));
239                 memset(pr, 0, sizeof(struct blkid_struct_probe));
240                 probe_block(gl.gl_pathv[j], pr);
241                 if (pr->err)
242                         free(pr);
243                 else
244                         list_add_tail(&pr->list, &devices);
245         }
246
247         globfree(&gl);
248
249         return 0;
250 }
251
252 static void cache_load(int mtd)
253 {
254         if (mtd)
255                 _cache_load("/dev/mtdblock*");
256         _cache_load("/dev/sd*");
257 }
258
259 static int print_block_info(struct blkid_struct_probe *pr)
260 {
261         printf("%s:", pr->dev);
262         if (pr->uuid[0])
263                 printf(" UUID=\"%s\"", pr->uuid);
264
265         if (pr->label[0])
266                 printf(" LABEL=\"%s\"", pr->label);
267
268         if (pr->name[0])
269                 printf(" NAME=\"%s\"", pr->name);
270
271         if (pr->version[0])
272                 printf(" VERSION=\"%s\"", pr->version);
273
274         printf(" TYPE=\"%s\"\n", pr->id->name);
275
276         return 0;
277 }
278
279 static int print_block_uci(struct blkid_struct_probe *pr)
280 {
281         if (!pr->uuid[0])
282                 return 0;
283
284         if (!strcmp(pr->id->name, "swap")) {
285                 printf("config 'swap'\n");
286         } else {
287                 printf("config 'mount'\n");
288                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
289         }
290         printf("\toption\tuuid\t'%s'\n", pr->uuid);
291         printf("\toption\tenabled\t'0'\n\n");
292
293         return 0;
294 }
295
296 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
297 {
298         struct blkid_struct_probe *pr = NULL;
299
300         if (uuid)
301                 list_for_each_entry(pr, &devices, list)
302                         if (!strcmp(pr->uuid, uuid))
303                                 return pr;
304
305         if (label)
306                 list_for_each_entry(pr, &devices, list)
307                         if (strcmp(pr->label, label))
308                                 return pr;
309
310         if (path)
311                 list_for_each_entry(pr, &devices, list)
312                         if (!strcmp(pr->dev, path))
313                                 return pr;
314
315         return NULL;
316 }
317
318 static char* find_mount_point(char *block)
319 {
320         FILE *fp = fopen("/proc/mounts", "r");
321         static char line[256];
322         int len = strlen(block);
323         char *point = NULL;
324
325         if(!fp)
326                 return NULL;
327
328         while (fgets(line, sizeof(line), fp)) {
329                 if (!strncmp(line, block, len)) {
330                         char *p = &line[len + 1];
331                         char *t = strstr(p, " ");
332
333                         if (!t)
334                                 return NULL;
335                         *t = '\0';
336                         point = p;
337                         break;
338                 }
339         }
340
341         fclose(fp);
342
343         return point;
344 }
345
346 static void mkdir_p(char *dir)
347 {
348         char *l = strrchr(dir, '/');
349
350         if (l) {
351                 *l = '\0';
352                 mkdir_p(dir);
353                 *l = '/';
354                 mkdir(dir, 0755);
355         }
356 }
357
358 static int main_hotplug(int argc, char **argv)
359 {
360         struct mount *m;
361         char path[256];
362         char *action, *device, *mount_point;
363         struct blkid_struct_probe *pr;
364
365         action = getenv("ACTION");
366         device = getenv("DEVNAME");
367
368         if (!action || !device)
369                 return -1;
370         snprintf(path, sizeof(path), "/dev/%s", device);
371
372         if (!strcmp(action, "remove")) {
373                 int err = 0;
374                 mount_point = find_mount_point(path);
375                 if (mount_point)
376                         err = umount2(mount_point, MNT_DETACH);
377
378                 if (err)
379                         fprintf(stderr, "unmount of %s failed (%d) - %s\n",
380                                         mount_point, err, strerror(err));
381
382                 return 0;
383         } else if (strcmp(action, "add")) {
384                 fprintf(stderr, "Unkown action %s\n", action);
385
386                 return -1;
387         }
388
389         if (config_load(NULL))
390                 return -1;
391         cache_load(0);
392
393         pr = find_block_info(NULL, NULL, path);
394         if (!pr && pr->uuid) {
395                 fprintf(stderr, "failed to read blockinfo for %s\n", path);
396                 return -1;
397         }
398
399         m = find_swap(pr->uuid);
400         if (m) {
401                 if (!strcmp(action, "add"))
402                         swapon(path, m->prio);
403                 else
404                         swapoff(path);
405         } else {
406                 m = find_block(pr->uuid, pr->label, NULL);
407                 if (m && strcmp(m->target, "/")) {
408                         int err = 0;
409
410                         mkdir_p(m->target);
411                         err = mount(path, m->target, pr->id->name, 0, (m->options) ? (m->options) : (""));
412                         if (err)
413                                 fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
414                                                 path, pr->id->name, m->target, err, strerror(err));
415                 }
416         }
417
418         return 0;
419 }
420
421 static int find_block_mtd(char *name, char *part, int plen)
422 {
423         FILE *fp = fopen("/proc/mtd", "r");
424         static char line[256];
425         char *index = NULL;
426
427         if(!fp)
428                 return -1;
429
430         while (!index && fgets(line, sizeof(line), fp)) {
431                 if (strstr(line, name)) {
432                         char *eol = strstr(line, ":");
433
434                         if (!eol)
435                                 continue;
436
437                         *eol = '\0';
438                         index = &line[3];
439                 }
440         }
441
442         fclose(fp);
443
444         if (!index)
445                 return -1;
446
447         snprintf(part, plen, "/dev/mtdblock%s", index);
448
449         return 0;
450 }
451
452 static int check_extroot(char *path)
453 {
454         struct blkid_struct_probe *pr = NULL;
455         char fs[32];
456
457         if (find_block_mtd("rootfs", fs, sizeof(fs)))
458                 return -1;
459
460         list_for_each_entry(pr, &devices, list) {
461                 if (!strcmp(pr->dev, fs)) {
462                         struct stat s;
463                         FILE *fp = NULL;
464                         char tag[32];
465                         char uuid[32] = { 0 };
466
467                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
468                         if (stat(tag, &s)) {
469                                 fp = fopen(tag, "w+");
470                                 if (!fp) {
471                                         fprintf(stderr, "extroot: failed to write uuid tag file\n");
472                                         /* return 0 to continue boot regardless of error */
473                                         return 0;
474                                 }
475                                 fputs(pr->uuid, fp);
476                                 fclose(fp);
477                                 return 0;
478                         }
479
480                         fp = fopen(tag, "r");
481                         if (!fp) {
482                                 fprintf(stderr, "extroot: failed to open uuid tag file\n");
483                                 return -1;
484                         }
485
486                         fgets(uuid, sizeof(uuid), fp);
487                         fclose(fp);
488                         if (!strcmp(uuid, pr->uuid))
489                                 return 0;
490                         fprintf(stderr, "extroot: uuid tag does not match rom uuid\n");
491                 }
492         }
493         return -1;
494 }
495
496 static int mount_extroot(char *path, char *cfg)
497 {
498         struct blkid_struct_probe *pr;
499         struct mount *m;
500         int err = -1;
501
502         if (config_load(cfg))
503                 return 2;
504
505         m = find_block(NULL, NULL, "/");
506         if (!m)
507                 return 1;
508
509         pr = find_block_info(m->uuid, m->label, NULL);
510         if (pr) {
511                 mkdir_p(path);
512                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
513
514                 if (err) {
515                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
516                                         pr->dev, pr->id->name, path, err, strerror(err));
517                 } else {
518                         err = check_extroot(path);
519                         if (err)
520                                 umount(path);
521                 }
522         }
523
524         return err;
525 }
526
527 static int main_extroot(int argc, char **argv)
528 {
529         struct blkid_struct_probe *pr;
530         char fs[32] = { 0 };
531         char fs_data[32] = { 0 };
532         int err = 1;
533         char extroot[] = "/tmp/overlay";
534
535         if (!getenv("PREINIT"))
536                 return -1;
537
538         if (argc != 2) {
539                 fprintf(stderr, "Usage: block extroot mountpoint\n");
540                 return 1;
541         }
542
543         mkblkdev();
544         cache_load(1);
545
546         find_block_mtd("rootfs", fs, sizeof(fs));
547         if (!fs[0])
548                 return 2;
549
550         pr = find_block_info(NULL, NULL, fs);
551         if (!pr || strcmp(pr->id->name, "squashfs"))
552                 return 3;
553
554         find_block_mtd("rootfs_data", fs_data, sizeof(fs_data));
555         if (fs_data[0]) {
556                 pr = find_block_info(NULL, NULL, fs_data);
557                 if (pr && !strcmp(pr->id->name, "jffs2")) {
558                         char cfg[] = "/tmp/jffs_cfg";
559
560                         mkdir_p(cfg);
561                         if (!mount(fs_data, cfg, "jffs2", MS_NOATIME, NULL)) {
562                                 err = mount_extroot(extroot, cfg);
563                                 umount2(cfg, MNT_DETACH);
564                         }
565                         if (err)
566                                 rmdir(extroot);
567                         rmdir(cfg);
568                         return err;
569                 }
570         }
571
572         err = mount_extroot(extroot, NULL);
573
574         return err;
575 }
576
577 static int main_detect(int argc, char **argv)
578 {
579         struct blkid_struct_probe *pr;
580
581         cache_load(0);
582         list_for_each_entry(pr, &devices, list)
583                 print_block_uci(pr);
584
585         return 0;
586 }
587
588 static int main_info(int argc, char **argv)
589 {
590         int i;
591         struct blkid_struct_probe *pr;
592
593         cache_load(1);
594         if (argc == 2) {
595                 list_for_each_entry(pr, &devices, list)
596                         print_block_info(pr);
597
598                 return 0;
599         };
600
601         for (i = 2; i < argc; i++) {
602                 struct stat s;
603
604                 if (stat(argv[i], &s)) {
605                         fprintf(stderr, "failed to stat %s\n", argv[i]);
606                         continue;
607                 }
608                 if (!S_ISBLK(s.st_mode)) {
609                         fprintf(stderr, "%s is not a block device\n", argv[i]);
610                         continue;
611                 }
612                 pr = find_block_info(NULL, NULL, argv[i]);
613                 if (pr)
614                         print_block_info(pr);
615         }
616
617         return 0;
618 }
619
620 static int main_swapon(int argc, char **argv)
621 {
622         if (argc != 2) {
623                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
624                 return -1;
625         }
626
627         if (!strcmp(argv[1], "-a")) {
628                 struct blkid_struct_probe *pr;
629
630                 cache_load(0);
631                 list_for_each_entry(pr, &devices, list) {
632                         if (strcmp(pr->id->name, "swap"))
633                                 continue;
634                         if (swapon(pr->dev, 0))
635                                 fprintf(stderr, "failed to swapon %s\n", pr->dev);
636                 }
637         } else {
638                 struct stat s;
639                 int err;
640
641                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
642                         fprintf(stderr, "%s is not a block device\n", argv[1]);
643                         return -1;
644                 }
645                 err = swapon(argv[1], 0);
646                 if (err) {
647                         fprintf(stderr, "failed to swapon %s (%d)\n", argv[1], err);
648                         return err;
649                 }
650         }
651
652         return 0;
653 }
654
655 static int main_swapoff(int argc, char **argv)
656 {
657         if (argc != 2) {
658                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
659                 return -1;
660         }
661
662         if (!strcmp(argv[1], "-a")) {
663                 FILE *fp = fopen("/proc/swaps", "r");
664                 char line[256];
665
666                 if (!fp) {
667                         fprintf(stderr, "failed to open /proc/swaps\n");
668                         return -1;
669                 }
670                 fgets(line, sizeof(line), fp);
671                 while (fgets(line, sizeof(line), fp)) {
672                         char *end = strchr(line, ' ');
673                         int err;
674
675                         if (!end)
676                                 continue;
677                         *end = '\0';
678                         err = swapoff(line);
679                         if (err)
680                                 fprintf(stderr, "failed to swapoff %s (%d)\n", line, err);
681                 }
682                 fclose(fp);
683         } else {
684                 struct stat s;
685                 int err;
686
687                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
688                         fprintf(stderr, "%s is not a block device\n", argv[1]);
689                         return -1;
690                 }
691                 err = swapoff(argv[1]);
692                 if (err) {
693                         fprintf(stderr, "fsiled to swapoff %s (%d)\n", argv[1], err);
694                         return err;
695                 }
696         }
697
698         return 0;
699 }
700
701 int main(int argc, char **argv)
702 {
703         char *base = basename(*argv);
704
705         if (!strcmp(base, "swapon"))
706                 return main_swapon(argc, argv);
707
708         if (!strcmp(base, "swapoff"))
709                 return main_swapoff(argc, argv);
710
711         if ((argc > 1) && !strcmp(base, "block")) {
712                 if (!strcmp(argv[1], "info"))
713                         return main_info(argc, argv);
714
715                 if (!strcmp(argv[1], "detect"))
716                         return main_detect(argc, argv);
717
718                 if (!strcmp(argv[1], "hotplug"))
719                         return main_hotplug(argc, argv);
720
721                 if (!strcmp(argv[1], "extroot"))
722                         return main_extroot(argc, argv);
723         }
724
725         fprintf(stderr, "Usage: block <info|detect>\n");
726
727         return -1;
728 }