overlay: create a common function for deleting all overlay data (optionally excluding...
[project/fstools.git] / jffs2reset.c
1 /*
2 * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2.1
6 * as published by the Free Software Foundation
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13
14 #include <sys/mount.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17
18 #include <libubox/ulog.h>
19
20 #include <fcntl.h>
21 #include <dirent.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "libfstools/libfstools.h"
28 #include "libfstools/volume.h"
29
30 static int
31 ask_user(int argc, char **argv)
32 {
33 if ((argc < 2) || strcmp(argv[1], "-y")) {
34 ULOG_WARN("This will erase all settings and remove any installed packages. Are you sure? [N/y]\n");
35 if (getchar() != 'y')
36 return -1;
37 }
38 return 0;
39
40 }
41
42 static int
43 jffs2_reset(int argc, char **argv)
44 {
45 struct volume *v;
46 char *mp;
47
48 if (ask_user(argc, argv))
49 return -1;
50
51 if (find_filesystem("overlay")) {
52 ULOG_ERR("overlayfs not supported by kernel\n");
53 return -1;
54 }
55
56 v = volume_find("rootfs_data");
57 if (!v) {
58 ULOG_ERR("MTD partition 'rootfs_data' not found\n");
59 return -1;
60 }
61
62 mp = find_mount_point(v->blk, 1);
63 if (mp) {
64 ULOG_INFO("%s is mounted as %s, only erasing files\n", v->blk, mp);
65 overlay_delete(mp, false);
66 mount(mp, "/", NULL, MS_REMOUNT, 0);
67 } else {
68 ULOG_INFO("%s is not mounted, erasing it\n", v->blk);
69 volume_erase_all(v);
70 }
71
72 return 0;
73 }
74
75 static int
76 jffs2_mark(int argc, char **argv)
77 {
78 __u32 deadc0de = __cpu_to_be32(0xdeadc0de);
79 struct volume *v;
80 size_t sz;
81 int fd;
82
83 if (ask_user(argc, argv))
84 return -1;
85
86 v = volume_find("rootfs_data");
87 if (!v) {
88 ULOG_ERR("MTD partition 'rootfs_data' not found\n");
89 return -1;
90 }
91
92 fd = open(v->blk, O_WRONLY);
93 ULOG_INFO("%s - marking with deadc0de\n", v->blk);
94 if (!fd) {
95 ULOG_ERR("opening %s failed\n", v->blk);
96 return -1;
97 }
98
99 sz = write(fd, &deadc0de, sizeof(deadc0de));
100 close(fd);
101
102 if (sz != 4) {
103 ULOG_ERR("writing %s failed: %s\n", v->blk, strerror(errno));
104 return -1;
105 }
106
107 return 0;
108 }
109
110 int main(int argc, char **argv)
111 {
112 if (!strcmp(*argv, "jffs2mark"))
113 return jffs2_mark(argc, argv);
114 return jffs2_reset(argc, argv);
115 }