fstools: support for ext4fs overlay
[project/fstools.git] / libfstools / find.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 <errno.h>
15 #include <stdio.h>
16 #include <string.h>
17
18 #include "libfstools.h"
19
20 int
21 find_overlay_mount(char *overlay)
22 {
23 FILE *fp = fopen("/proc/mounts", "r");
24 static char line[256];
25 int ret = -1;
26
27 if(!fp)
28 return ret;
29
30 while (ret && fgets(line, sizeof(line), fp))
31 if (!strncmp(line, overlay, strlen(overlay)))
32 ret = 0;
33
34 fclose(fp);
35
36 return ret;
37 }
38
39 /*
40 * Find path of a device mounted to the given point.
41 */
42 char*
43 find_mount(char *mp)
44 {
45 FILE *fp = fopen("/proc/mounts", "r");
46 static char line[256];
47 char *point = NULL;
48
49 if(!fp)
50 return NULL;
51
52 while (fgets(line, sizeof(line), fp)) {
53 char *s, *t = strstr(line, " ");
54
55 if (!t) {
56 fclose(fp);
57 return NULL;
58 }
59 *t = '\0';
60 t++;
61 s = strstr(t, " ");
62 if (!s) {
63 fclose(fp);
64 return NULL;
65 }
66 *s = '\0';
67
68 if (!strcmp(t, mp)) {
69 fclose(fp);
70 return line;
71 }
72 }
73
74 fclose(fp);
75
76 return point;
77 }
78
79 char*
80 find_mount_point(char *block, int mtd_only)
81 {
82 FILE *fp = fopen("/proc/mounts", "r");
83 static char line[256];
84 int len = strlen(block);
85 char *point = NULL;
86
87 if(!fp)
88 return NULL;
89
90 while (fgets(line, sizeof(line), fp)) {
91 if (!strncmp(line, block, len)) {
92 char *p = &line[len + 1];
93 char *t = strstr(p, " ");
94
95 if (!t) {
96 fclose(fp);
97 return NULL;
98 }
99
100 *t = '\0';
101 t++;
102
103 if (mtd_only &&
104 strncmp(t, "jffs2", 5) &&
105 strncmp(t, "ubifs", 5) &&
106 strncmp(t, "ext4", 4)) {
107 fclose(fp);
108 ULOG_ERR("block is mounted with wrong fs\n");
109 return NULL;
110 }
111 point = p;
112
113 break;
114 }
115 }
116
117 fclose(fp);
118
119 return point;
120 }
121
122 int
123 find_filesystem(char *fs)
124 {
125 FILE *fp = fopen("/proc/filesystems", "r");
126 static char line[256];
127 int ret = -1;
128
129 if (!fp) {
130 ULOG_ERR("opening /proc/filesystems failed: %s\n", strerror(errno));
131 goto out;
132 }
133
134 while (ret && fgets(line, sizeof(line), fp))
135 if (strstr(line, fs))
136 ret = 0;
137
138 fclose(fp);
139
140 out:
141 return ret;
142 }