d456dd586ff741fdd556b6a11d7eec6a50e8cf2b
[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         _cache_load("/dev/mmcblk*");
258 }
259
260 static int print_block_info(struct blkid_struct_probe *pr)
261 {
262         printf("%s:", pr->dev);
263         if (pr->uuid[0])
264                 printf(" UUID=\"%s\"", pr->uuid);
265
266         if (pr->label[0])
267                 printf(" LABEL=\"%s\"", pr->label);
268
269         if (pr->name[0])
270                 printf(" NAME=\"%s\"", pr->name);
271
272         if (pr->version[0])
273                 printf(" VERSION=\"%s\"", pr->version);
274
275         printf(" TYPE=\"%s\"\n", pr->id->name);
276
277         return 0;
278 }
279
280 static int print_block_uci(struct blkid_struct_probe *pr)
281 {
282         if (!pr->uuid[0])
283                 return 0;
284
285         if (!strcmp(pr->id->name, "swap")) {
286                 printf("config 'swap'\n");
287         } else {
288                 printf("config 'mount'\n");
289                 printf("\toption\ttarget\t'/mnt/%s'\n", basename(pr->dev));
290         }
291         printf("\toption\tuuid\t'%s'\n", pr->uuid);
292         printf("\toption\tenabled\t'0'\n\n");
293
294         return 0;
295 }
296
297 static struct blkid_struct_probe* find_block_info(char *uuid, char *label, char *path)
298 {
299         struct blkid_struct_probe *pr = NULL;
300
301         if (uuid)
302                 list_for_each_entry(pr, &devices, list)
303                         if (!strcmp(pr->uuid, uuid))
304                                 return pr;
305
306         if (label)
307                 list_for_each_entry(pr, &devices, list)
308                         if (strcmp(pr->label, label))
309                                 return pr;
310
311         if (path)
312                 list_for_each_entry(pr, &devices, list)
313                         if (!strcmp(pr->dev, path))
314                                 return pr;
315
316         return NULL;
317 }
318
319 static char* find_mount_point(char *block)
320 {
321         FILE *fp = fopen("/proc/mounts", "r");
322         static char line[256];
323         int len = strlen(block);
324         char *point = NULL;
325
326         if(!fp)
327                 return NULL;
328
329         while (fgets(line, sizeof(line), fp)) {
330                 if (!strncmp(line, block, len)) {
331                         char *p = &line[len + 1];
332                         char *t = strstr(p, " ");
333
334                         if (!t)
335                                 return NULL;
336                         *t = '\0';
337                         point = p;
338                         break;
339                 }
340         }
341
342         fclose(fp);
343
344         return point;
345 }
346
347 static void mkdir_p(char *dir)
348 {
349         char *l = strrchr(dir, '/');
350
351         if (l) {
352                 *l = '\0';
353                 mkdir_p(dir);
354                 *l = '/';
355                 mkdir(dir, 0755);
356         }
357 }
358
359 static int main_hotplug(int argc, char **argv)
360 {
361         struct mount *m;
362         char path[256];
363         char *action, *device, *mount_point;
364         struct blkid_struct_probe *pr;
365
366         action = getenv("ACTION");
367         device = getenv("DEVNAME");
368
369         if (!action || !device)
370                 return -1;
371         snprintf(path, sizeof(path), "/dev/%s", device);
372
373         if (!strcmp(action, "remove")) {
374                 int err = 0;
375                 mount_point = find_mount_point(path);
376                 if (mount_point)
377                         err = umount2(mount_point, MNT_DETACH);
378
379                 if (err)
380                         fprintf(stderr, "unmount of %s failed (%d) - %s\n",
381                                         mount_point, err, strerror(err));
382
383                 return 0;
384         } else if (strcmp(action, "add")) {
385                 fprintf(stderr, "Unkown action %s\n", action);
386
387                 return -1;
388         }
389
390         if (config_load(NULL))
391                 return -1;
392         cache_load(0);
393
394         pr = find_block_info(NULL, NULL, path);
395         if (!pr && pr->uuid) {
396                 fprintf(stderr, "failed to read blockinfo for %s\n", path);
397                 return -1;
398         }
399
400         m = find_swap(pr->uuid);
401         if (m) {
402                 if (!strcmp(action, "add"))
403                         swapon(path, m->prio);
404                 else
405                         swapoff(path);
406         } else {
407                 m = find_block(pr->uuid, pr->label, NULL);
408                 if (m && strcmp(m->target, "/")) {
409                         int err = 0;
410
411                         mkdir_p(m->target);
412                         err = mount(path, m->target, pr->id->name, 0, (m->options) ? (m->options) : (""));
413                         if (err)
414                                 fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
415                                                 path, pr->id->name, m->target, err, strerror(err));
416                 }
417         }
418
419         return 0;
420 }
421
422 static int find_block_mtd(char *name, char *part, int plen)
423 {
424         FILE *fp = fopen("/proc/mtd", "r");
425         static char line[256];
426         char *index = NULL;
427
428         if(!fp)
429                 return -1;
430
431         while (!index && fgets(line, sizeof(line), fp)) {
432                 if (strstr(line, name)) {
433                         char *eol = strstr(line, ":");
434
435                         if (!eol)
436                                 continue;
437
438                         *eol = '\0';
439                         index = &line[3];
440                 }
441         }
442
443         fclose(fp);
444
445         if (!index)
446                 return -1;
447
448         snprintf(part, plen, "/dev/mtdblock%s", index);
449
450         return 0;
451 }
452
453 static int check_extroot(char *path)
454 {
455         struct blkid_struct_probe *pr = NULL;
456         char fs[32];
457
458         if (find_block_mtd("rootfs", fs, sizeof(fs)))
459                 return -1;
460
461         list_for_each_entry(pr, &devices, list) {
462                 if (!strcmp(pr->dev, fs)) {
463                         struct stat s;
464                         FILE *fp = NULL;
465                         char tag[32];
466                         char uuid[32] = { 0 };
467
468                         snprintf(tag, sizeof(tag), "%s/etc/.extroot-uuid", path);
469                         if (stat(tag, &s)) {
470                                 fp = fopen(tag, "w+");
471                                 if (!fp) {
472                                         fprintf(stderr, "extroot: failed to write uuid tag file\n");
473                                         /* return 0 to continue boot regardless of error */
474                                         return 0;
475                                 }
476                                 fputs(pr->uuid, fp);
477                                 fclose(fp);
478                                 return 0;
479                         }
480
481                         fp = fopen(tag, "r");
482                         if (!fp) {
483                                 fprintf(stderr, "extroot: failed to open uuid tag file\n");
484                                 return -1;
485                         }
486
487                         fgets(uuid, sizeof(uuid), fp);
488                         fclose(fp);
489                         if (!strcmp(uuid, pr->uuid))
490                                 return 0;
491                         fprintf(stderr, "extroot: uuid tag does not match rom uuid\n");
492                 }
493         }
494         return -1;
495 }
496
497 static int mount_extroot(char *path, char *cfg)
498 {
499         struct blkid_struct_probe *pr;
500         struct mount *m;
501         int err = -1;
502
503         if (config_load(cfg))
504                 return 2;
505
506         m = find_block(NULL, NULL, "/");
507         if (!m)
508                 return 1;
509
510         pr = find_block_info(m->uuid, m->label, NULL);
511         if (pr) {
512                 mkdir_p(path);
513                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
514
515                 if (err) {
516                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
517                                         pr->dev, pr->id->name, path, err, strerror(err));
518                 } else {
519                         err = check_extroot(path);
520                         if (err)
521                                 umount(path);
522                 }
523         }
524
525         return err;
526 }
527
528 static int main_extroot(int argc, char **argv)
529 {
530         struct blkid_struct_probe *pr;
531         char fs[32] = { 0 };
532         char fs_data[32] = { 0 };
533         int err = 1;
534         char extroot[] = "/tmp/overlay";
535
536         if (!getenv("PREINIT"))
537                 return -1;
538
539         if (argc != 2) {
540                 fprintf(stderr, "Usage: block extroot mountpoint\n");
541                 return 1;
542         }
543
544         mkblkdev();
545         cache_load(1);
546
547         find_block_mtd("rootfs", fs, sizeof(fs));
548         if (!fs[0])
549                 return 2;
550
551         pr = find_block_info(NULL, NULL, fs);
552         if (!pr || strcmp(pr->id->name, "squashfs"))
553                 return 3;
554
555         find_block_mtd("rootfs_data", fs_data, sizeof(fs_data));
556         if (fs_data[0]) {
557                 pr = find_block_info(NULL, NULL, fs_data);
558                 if (pr && !strcmp(pr->id->name, "jffs2")) {
559                         char cfg[] = "/tmp/jffs_cfg";
560
561                         mkdir_p(cfg);
562                         if (!mount(fs_data, cfg, "jffs2", MS_NOATIME, NULL)) {
563                                 err = mount_extroot(extroot, cfg);
564                                 umount2(cfg, MNT_DETACH);
565                         }
566                         if (err)
567                                 rmdir(extroot);
568                         rmdir(cfg);
569                         return err;
570                 }
571         }
572
573         err = mount_extroot(extroot, NULL);
574
575         return err;
576 }
577
578 static int main_detect(int argc, char **argv)
579 {
580         struct blkid_struct_probe *pr;
581
582         cache_load(0);
583         list_for_each_entry(pr, &devices, list)
584                 print_block_uci(pr);
585
586         return 0;
587 }
588
589 static int main_info(int argc, char **argv)
590 {
591         int i;
592         struct blkid_struct_probe *pr;
593
594         cache_load(1);
595         if (argc == 2) {
596                 list_for_each_entry(pr, &devices, list)
597                         print_block_info(pr);
598
599                 return 0;
600         };
601
602         for (i = 2; i < argc; i++) {
603                 struct stat s;
604
605                 if (stat(argv[i], &s)) {
606                         fprintf(stderr, "failed to stat %s\n", argv[i]);
607                         continue;
608                 }
609                 if (!S_ISBLK(s.st_mode)) {
610                         fprintf(stderr, "%s is not a block device\n", argv[i]);
611                         continue;
612                 }
613                 pr = find_block_info(NULL, NULL, argv[i]);
614                 if (pr)
615                         print_block_info(pr);
616         }
617
618         return 0;
619 }
620
621 static int main_swapon(int argc, char **argv)
622 {
623         if (argc != 2) {
624                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
625                 return -1;
626         }
627
628         if (!strcmp(argv[1], "-a")) {
629                 struct blkid_struct_probe *pr;
630
631                 cache_load(0);
632                 list_for_each_entry(pr, &devices, list) {
633                         if (strcmp(pr->id->name, "swap"))
634                                 continue;
635                         if (swapon(pr->dev, 0))
636                                 fprintf(stderr, "failed to swapon %s\n", pr->dev);
637                 }
638         } else {
639                 struct stat s;
640                 int err;
641
642                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
643                         fprintf(stderr, "%s is not a block device\n", argv[1]);
644                         return -1;
645                 }
646                 err = swapon(argv[1], 0);
647                 if (err) {
648                         fprintf(stderr, "failed to swapon %s (%d)\n", argv[1], err);
649                         return err;
650                 }
651         }
652
653         return 0;
654 }
655
656 static int main_swapoff(int argc, char **argv)
657 {
658         if (argc != 2) {
659                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
660                 return -1;
661         }
662
663         if (!strcmp(argv[1], "-a")) {
664                 FILE *fp = fopen("/proc/swaps", "r");
665                 char line[256];
666
667                 if (!fp) {
668                         fprintf(stderr, "failed to open /proc/swaps\n");
669                         return -1;
670                 }
671                 fgets(line, sizeof(line), fp);
672                 while (fgets(line, sizeof(line), fp)) {
673                         char *end = strchr(line, ' ');
674                         int err;
675
676                         if (!end)
677                                 continue;
678                         *end = '\0';
679                         err = swapoff(line);
680                         if (err)
681                                 fprintf(stderr, "failed to swapoff %s (%d)\n", line, err);
682                 }
683                 fclose(fp);
684         } else {
685                 struct stat s;
686                 int err;
687
688                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
689                         fprintf(stderr, "%s is not a block device\n", argv[1]);
690                         return -1;
691                 }
692                 err = swapoff(argv[1]);
693                 if (err) {
694                         fprintf(stderr, "fsiled to swapoff %s (%d)\n", argv[1], err);
695                         return err;
696                 }
697         }
698
699         return 0;
700 }
701
702 int main(int argc, char **argv)
703 {
704         char *base = basename(*argv);
705
706         if (!strcmp(base, "swapon"))
707                 return main_swapon(argc, argv);
708
709         if (!strcmp(base, "swapoff"))
710                 return main_swapoff(argc, argv);
711
712         if ((argc > 1) && !strcmp(base, "block")) {
713                 if (!strcmp(argv[1], "info"))
714                         return main_info(argc, argv);
715
716                 if (!strcmp(argv[1], "detect"))
717                         return main_detect(argc, argv);
718
719                 if (!strcmp(argv[1], "hotplug"))
720                         return main_hotplug(argc, argv);
721
722                 if (!strcmp(argv[1], "extroot"))
723                         return main_extroot(argc, argv);
724         }
725
726         fprintf(stderr, "Usage: block <info|detect>\n");
727
728         return -1;
729 }