libfstools: move mount points when switching to JFFS2
[project/fstools.git] / libfstools / overlay.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/stat.h>
15 #include <sys/types.h>
16 #include <sys/mount.h>
17
18 #include <asm/byteorder.h>
19
20 #include <errno.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <unistd.h>
24 #include <stdlib.h>
25 #include <glob.h>
26 #include <errno.h>
27 #include <dirent.h>
28 #include <fcntl.h>
29
30 #include "libfstools.h"
31 #include "volume.h"
32
33 #define SWITCH_JFFS2 "/tmp/.switch_jffs2"
34
35 static bool keep_sysupgrade;
36
37 static int
38 handle_rmdir(const char *dir)
39 {
40         struct dirent *dt;
41         struct stat st;
42         DIR *d;
43         int fd;
44
45         d = opendir(dir);
46         if (!d)
47                 return -1;
48
49         fd = dirfd(d);
50
51         while ((dt = readdir(d)) != NULL) {
52                 if (fstatat(fd, dt->d_name, &st, AT_SYMLINK_NOFOLLOW) || S_ISDIR(st.st_mode))
53                         continue;
54
55                 if (keep_sysupgrade && !strcmp(dt->d_name, "sysupgrade.tgz"))
56                         continue;
57
58                 unlinkat(fd, dt->d_name, 0);
59         }
60
61         closedir(d);
62         rmdir(dir);
63
64         return 0;
65 }
66
67 void
68 foreachdir(const char *dir, int (*cb)(const char*))
69 {
70         static char *globdir = NULL;
71         static size_t globdirlen = 0;
72         struct stat s = { 0 };
73         size_t dirlen = strlen(dir);
74         glob_t gl;
75         int j;
76
77         if (dirlen + sizeof("/*") > globdirlen) {
78                 /* Alloc extra 256 B to avoid too many reallocs */
79                 size_t len = dirlen + sizeof("/*") + 256;
80                 char *tmp;
81
82                 tmp = realloc(globdir, len);
83                 if (!tmp)
84                         return;
85                 globdir = tmp;
86                 globdirlen = len;
87         }
88
89         sprintf(globdir, "%s/*", dir);
90
91         /* Include GLOB_MARK as callbacks expect a trailing slash */
92         if (!glob(globdir, GLOB_NOESCAPE | GLOB_MARK | GLOB_ONLYDIR, NULL, &gl))
93                 for (j = 0; j < gl.gl_pathc; j++) {
94                         char *dir = gl.gl_pathv[j];
95                         int len = strlen(gl.gl_pathv[j]);
96                         int err;
97
98                         /* Quick way of skipping files */
99                         if (dir[len - 1] != '/')
100                                 continue;
101
102                         /* lstat needs path without a trailing slash */
103                         if (len > 1)
104                                 dir[len - 1] = '\0';
105                         err = lstat(gl.gl_pathv[j], &s);
106                         if (len > 1)
107                                 dir[len - 1] = '/';
108
109                         if (!err && !S_ISLNK(s.st_mode))
110                                 foreachdir(gl.gl_pathv[j], cb);
111         }
112         cb(dir);
113 }
114
115 static void foreach_mount(int (*cb)(const char *, const char *))
116 {
117         FILE *fp = fopen("/proc/mounts", "r");
118         static char line[256];
119
120         if (!fp)
121                 return;
122
123         while (fgets(line, sizeof(line), fp)) {
124                 char device[32], mount_point[32];
125
126                 if (sscanf(line, "%31s %31s %*s %*s %*u %*u", device, mount_point) == 2)
127                         cb(device, mount_point);
128         }
129
130         fclose(fp);
131 }
132
133 void
134 overlay_delete(const char *dir, bool _keep_sysupgrade)
135 {
136         keep_sysupgrade = _keep_sysupgrade;
137         foreachdir(dir, handle_rmdir);
138 }
139
140 static int
141 overlay_mount(struct volume *v, char *fs)
142 {
143         if (mkdir("/tmp/overlay", 0755)) {
144                 ULOG_ERR("failed to mkdir /tmp/overlay: %m\n");
145                 return -1;
146         }
147
148         if (mount(v->blk, "/tmp/overlay", fs, MS_NOATIME, NULL)) {
149                 ULOG_ERR("failed to mount -t %s %s /tmp/overlay: %m\n", fs, v->blk);
150                 return -1;
151         }
152
153         return 0;
154 }
155
156 /**
157  * move_mount - move mount point to the new root
158  */
159 static int move_mount(const char *device, const char *mount_point)
160 {
161         static const char *prefix = "/tmp/root/";
162
163         if (strncmp(mount_point, prefix, strlen(prefix)))
164                 return 0;
165
166         return mount_move(prefix, "/", mount_point + strlen(prefix));
167 }
168
169 static int
170 switch2jffs(struct volume *v)
171 {
172         struct stat s;
173         int ret;
174
175         if (!stat(SWITCH_JFFS2, &s)) {
176                 ULOG_ERR("jffs2 switch already running\n");
177                 return -1;
178         }
179
180         creat("/tmp/.switch_jffs2", 0600);
181         ret = mount(v->blk, "/rom/overlay", "jffs2", MS_NOATIME, NULL);
182         unlink("/tmp/.switch_jffs2");
183         if (ret) {
184                 ULOG_ERR("failed - mount -t jffs2 %s /rom/overlay: %m\n", v->blk);
185                 return -1;
186         }
187
188         if (mount("none", "/", NULL, MS_NOATIME | MS_REMOUNT, 0)) {
189                 ULOG_ERR("failed - mount -o remount,ro none: %m\n");
190                 return -1;
191         }
192
193         if (system("cp -a /tmp/root/* /rom/overlay")) {
194                 ULOG_ERR("failed - cp -a /tmp/root/* /rom/overlay: %m\n");
195                 return -1;
196         }
197
198         if (pivot("/rom", "/mnt")) {
199                 ULOG_ERR("failed - pivot /rom /mnt: %m\n");
200                 return -1;
201         }
202
203         if (mount_move("/mnt", "/tmp/root", "")) {
204                 ULOG_ERR("failed - mount -o move /mnt /tmp/root %m\n");
205                 return -1;
206         }
207
208         ret = fopivot("/overlay", "/rom");
209
210         /*
211          * Besides copying overlay data from "tmpfs" to "jffs2" we should also
212          * move mount points that user could create during JFFS2 formatting.
213          * This has to happen after fopivot call because:
214          * 1) It's trivial to find mount points to move then (/tmp/root/...).
215          * 2) We can't do that earlier using /rom/overlay/upper/ as overlay(fs)
216          *    doesn't support mounts. Mounting to upper dir don't make overlay
217          *    /propagate/ files to the target dir.
218          */
219         foreach_mount(move_mount);
220
221         return ret;
222 }
223
224 int
225 handle_whiteout(const char *dir)
226 {
227         struct stat s;
228         char link[256];
229         ssize_t sz;
230         struct dirent **namelist;
231         int n;
232
233         n = scandir(dir, &namelist, NULL, NULL);
234
235         if (n < 1)
236                 return -1;
237
238         while (n--) {
239                 char file[256];
240
241                 snprintf(file, sizeof(file), "%s%s", dir, namelist[n]->d_name);
242                 if (!lstat(file, &s) && S_ISLNK(s.st_mode)) {
243                         sz = readlink(file, link, sizeof(link) - 1);
244                         if (sz > 0) {
245                                 char *orig;
246
247                                 link[sz] = '\0';
248                                 orig = strstr(&file[1], "/");
249                                 if (orig && !strcmp(link, "(overlay-whiteout)"))
250                                         unlink(orig);
251                         }
252                 }
253                 free(namelist[n]);
254         }
255         free(namelist);
256
257         return 0;
258 }
259
260 static char *overlay_fs_name(int type)
261 {
262         switch (type) {
263                 case FS_EXT4:
264                         return "ext4";
265                 case FS_F2FS:
266                         return "f2fs";
267                 case FS_UBIFS:
268                         return "ubifs";
269                 case FS_JFFS2:
270                 default:
271                         return "jffs2";
272         }
273 }
274
275 int
276 jffs2_switch(struct volume *v)
277 {
278         char *mp, *fs_name;
279         int type;
280
281         if (find_overlay_mount("overlayfs:/tmp/root"))
282                 return -1;
283
284         if (find_filesystem("overlay")) {
285                 ULOG_ERR("overlayfs not supported by kernel\n");
286                 return -1;
287         }
288
289         volume_init(v);
290         mp = find_mount_point(v->blk, 0);
291         if (mp) {
292                 ULOG_ERR("rootfs_data:%s is already mounted as %s\n", v->blk, mp);
293                 return -1;
294         }
295
296         type = volume_identify(v);
297         fs_name = overlay_fs_name(type);
298
299         switch (type) {
300         case FS_NONE:
301                 ULOG_ERR("no jffs2 marker found\n");
302                 /* fall through */
303
304         case FS_DEADCODE:
305                 if (switch2jffs(v))
306                         return -1;
307
308                 ULOG_INFO("performing overlay whiteout\n");
309                 umount2("/tmp/root", MNT_DETACH);
310                 foreachdir("/overlay/", handle_whiteout);
311
312                 /* try hard to be in sync */
313                 ULOG_INFO("syncronizing overlay\n");
314                 if (system("cp -a /tmp/root/upper/* / 2>/dev/null"))
315                         ULOG_ERR("failed to sync jffs2 overlay\n");
316                 break;
317
318         case FS_EXT4:
319         case FS_F2FS:
320         case FS_UBIFS:
321                 if (overlay_mount(v, fs_name))
322                         return -1;
323                 if (mount_move("/tmp", "", "/overlay") || fopivot("/overlay", "/rom")) {
324                         ULOG_ERR("switching to %s failed\n", fs_name);
325                         return -1;
326                 }
327                 break;
328         }
329
330         sync();
331         fs_state_set("/overlay", FS_STATE_READY);
332         return 0;
333 }
334
335 static int overlay_mount_fs(struct volume *v)
336 {
337         char *fstype = overlay_fs_name(volume_identify(v));
338
339         if (mkdir("/tmp/overlay", 0755)) {
340                 ULOG_ERR("failed to mkdir /tmp/overlay: %m\n");
341                 return -1;
342         }
343
344         if (mount(v->blk, "/tmp/overlay", fstype, MS_NOATIME, NULL)) {
345                 ULOG_ERR("failed to mount -t %s %s /tmp/overlay: %m\n",
346                          fstype, v->blk);
347                 return -1;
348         }
349
350         return 0;
351 }
352
353 enum fs_state fs_state_get(const char *dir)
354 {
355         char *path;
356         char valstr[16];
357         uint32_t val;
358         ssize_t len;
359
360         path = alloca(strlen(dir) + 1 + sizeof("/.fs_state"));
361         sprintf(path, "%s/.fs_state", dir);
362         len = readlink(path, valstr, sizeof(valstr) - 1);
363         if (len < 0)
364                 return FS_STATE_UNKNOWN;
365
366         valstr[len] = 0;
367         val = atoi(valstr);
368
369         if (val > __FS_STATE_LAST)
370                 return FS_STATE_UNKNOWN;
371
372         return val;
373 }
374
375
376 int fs_state_set(const char *dir, enum fs_state state)
377 {
378         char valstr[16];
379         char *path;
380
381         if (fs_state_get(dir) == state)
382                 return 0;
383
384         path = alloca(strlen(dir) + 1 + sizeof("/.fs_state"));
385         sprintf(path, "%s/.fs_state", dir);
386         unlink(path);
387         snprintf(valstr, sizeof(valstr), "%d", state);
388
389         return symlink(valstr, path);
390 }
391
392
393 int mount_overlay(struct volume *v)
394 {
395         char *mp, *fs_name;
396
397         if (!v)
398                 return -1;
399
400         mp = find_mount_point(v->blk, 0);
401         if (mp) {
402                 ULOG_ERR("rootfs_data:%s is already mounted as %s\n", v->blk, mp);
403                 return -1;
404         }
405
406         overlay_mount_fs(v);
407
408         extroot_prefix = "/tmp/overlay";
409         if (!mount_extroot()) {
410                 ULOG_INFO("switched to extroot\n");
411                 return 0;
412         }
413
414         switch(fs_state_get("/tmp/overlay")) {
415         case FS_STATE_UNKNOWN:
416                 fs_state_set("/tmp/overlay", FS_STATE_PENDING);
417                 if (fs_state_get("/tmp/overlay") != FS_STATE_PENDING) {
418                         ULOG_ERR("unable to set filesystem state\n");
419                         break;
420                 }
421         case FS_STATE_PENDING:
422                 ULOG_INFO("overlay filesystem has not been fully initialized yet\n");
423                 overlay_delete("/tmp/overlay", true);
424                 break;
425         case FS_STATE_READY:
426                 break;
427         }
428
429         fs_name = overlay_fs_name(volume_identify(v));
430         ULOG_INFO("switching to %s overlay\n", fs_name);
431         if (mount_move("/tmp", "", "/overlay") || fopivot("/overlay", "/rom")) {
432                 ULOG_ERR("switching to %s failed - fallback to ramoverlay\n", fs_name);
433                 return ramoverlay();
434         }
435
436         return -1;
437 }