Add CmakeList support for the block tool
[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 mount_extroot(char *path, char *cfg)
453 {
454         struct blkid_struct_probe *pr;
455         struct mount *m;
456         int err = -1;
457
458         if (config_load(cfg))
459                 return 2;
460
461         m = find_block(NULL, NULL, "/");
462         if (!m)
463                 return 1;
464
465         pr = find_block_info(m->uuid, m->label, NULL);
466         if (pr) {
467                 mkdir_p(path);
468                 err = mount(pr->dev, path, pr->id->name, 0, (m->options) ? (m->options) : (""));
469
470                 if (err)
471                         fprintf(stderr, "mounting %s (%s) as %s failed (%d) - %s\n",
472                                         pr->dev, pr->id->name, path, err, strerror(err));
473         }
474
475         return err;
476 }
477
478 static int main_extroot(int argc, char **argv)
479 {
480         struct blkid_struct_probe *pr;
481         char fs[32] = { 0 };
482         char fs_data[32] = { 0 };
483         int err = 1;
484         char extroot[] = "/tmp/overlay";
485
486         if (!getenv("PREINIT"))
487                 return -1;
488
489         if (argc != 2) {
490                 fprintf(stderr, "Usage: block extroot mountpoint\n");
491                 return 1;
492         }
493
494         mkblkdev();
495         cache_load(1);
496
497         find_block_mtd("rootfs", fs, sizeof(fs));
498         if (!fs[0])
499                 return 2;
500
501         pr = find_block_info(NULL, NULL, fs);
502         if (!pr || strcmp(pr->id->name, "squashfs"))
503                 return 3;
504
505         find_block_mtd("rootfs_data", fs_data, sizeof(fs_data));
506         if (fs_data[0]) {
507                 pr = find_block_info(NULL, NULL, fs_data);
508                 if (pr && !strcmp(pr->id->name, "jffs2")) {
509                         char cfg[] = "/tmp/jffs_cfg";
510
511                         mkdir_p(cfg);
512                         if (!mount(fs_data, cfg, "jffs2", MS_NOATIME, NULL)) {
513                                 err = mount_extroot(extroot, cfg);
514                                 umount2(cfg, MNT_DETACH);
515                         }
516                         if (err)
517                                 rmdir(extroot);
518                         rmdir(cfg);
519                         return err;
520                 }
521         }
522
523         err = mount_extroot(extroot, NULL);
524
525         return err;
526 }
527
528 static int main_detect(int argc, char **argv)
529 {
530         struct blkid_struct_probe *pr;
531
532         cache_load(0);
533         list_for_each_entry(pr, &devices, list)
534                 print_block_uci(pr);
535
536         return 0;
537 }
538
539 static int main_info(int argc, char **argv)
540 {
541         int i;
542         struct blkid_struct_probe *pr;
543
544         cache_load(1);
545         if (argc == 2) {
546                 list_for_each_entry(pr, &devices, list)
547                         print_block_info(pr);
548
549                 return 0;
550         };
551
552         for (i = 2; i < argc; i++) {
553                 struct stat s;
554
555                 if (stat(argv[i], &s)) {
556                         fprintf(stderr, "failed to stat %s\n", argv[i]);
557                         continue;
558                 }
559                 if (!S_ISBLK(s.st_mode)) {
560                         fprintf(stderr, "%s is not a block device\n", argv[i]);
561                         continue;
562                 }
563                 pr = find_block_info(NULL, NULL, argv[i]);
564                 if (pr)
565                         print_block_info(pr);
566         }
567
568         return 0;
569 }
570
571 static int main_swapon(int argc, char **argv)
572 {
573         if (argc != 2) {
574                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
575                 return -1;
576         }
577
578         if (!strcmp(argv[1], "-a")) {
579                 struct blkid_struct_probe *pr;
580
581                 cache_load(0);
582                 list_for_each_entry(pr, &devices, list) {
583                         if (strcmp(pr->id->name, "swap"))
584                                 continue;
585                         if (swapon(pr->dev, 0))
586                                 fprintf(stderr, "failed to swapon %s\n", pr->dev);
587                 }
588         } else {
589                 struct stat s;
590                 int err;
591
592                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
593                         fprintf(stderr, "%s is not a block device\n", argv[1]);
594                         return -1;
595                 }
596                 err = swapon(argv[1], 0);
597                 if (err) {
598                         fprintf(stderr, "failed to swapon %s (%d)\n", argv[1], err);
599                         return err;
600                 }
601         }
602
603         return 0;
604 }
605
606 static int main_swapoff(int argc, char **argv)
607 {
608         if (argc != 2) {
609                 fprintf(stderr, "Usage: swapoff [-a] [DEVICE]\n\nStop swapping on DEVICE\n\n\t-a      Stop swapping on all swap devices\n");
610                 return -1;
611         }
612
613         if (!strcmp(argv[1], "-a")) {
614                 FILE *fp = fopen("/proc/swaps", "r");
615                 char line[256];
616
617                 if (!fp) {
618                         fprintf(stderr, "failed to open /proc/swaps\n");
619                         return -1;
620                 }
621                 fgets(line, sizeof(line), fp);
622                 while (fgets(line, sizeof(line), fp)) {
623                         char *end = strchr(line, ' ');
624                         int err;
625
626                         if (!end)
627                                 continue;
628                         *end = '\0';
629                         err = swapoff(line);
630                         if (err)
631                                 fprintf(stderr, "failed to swapoff %s (%d)\n", line, err);
632                 }
633                 fclose(fp);
634         } else {
635                 struct stat s;
636                 int err;
637
638                 if (stat(argv[1], &s) || !S_ISBLK(s.st_mode)) {
639                         fprintf(stderr, "%s is not a block device\n", argv[1]);
640                         return -1;
641                 }
642                 err = swapoff(argv[1]);
643                 if (err) {
644                         fprintf(stderr, "fsiled to swapoff %s (%d)\n", argv[1], err);
645                         return err;
646                 }
647         }
648
649         return 0;
650 }
651
652 int main(int argc, char **argv)
653 {
654         char *base = basename(*argv);
655
656         if (!strcmp(base, "swapon"))
657                 return main_swapon(argc, argv);
658
659         if (!strcmp(base, "swapoff"))
660                 return main_swapoff(argc, argv);
661
662         if ((argc > 1) && !strcmp(base, "block")) {
663                 if (!strcmp(argv[1], "info"))
664                         return main_info(argc, argv);
665
666                 if (!strcmp(argv[1], "detect"))
667                         return main_detect(argc, argv);
668
669                 if (!strcmp(argv[1], "hotplug"))
670                         return main_hotplug(argc, argv);
671
672                 if (!strcmp(argv[1], "extroot"))
673                         return main_extroot(argc, argv);
674         }
675
676         fprintf(stderr, "Usage: block <info|detect>\n");
677
678         return -1;
679 }