71548f5bfcb5a942135bed92f412ced50f83c057
[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 char*
40 find_mount(char *mp)
41 {
42 FILE *fp = fopen("/proc/mounts", "r");
43 static char line[256];
44 char *point = NULL;
45
46 if(!fp)
47 return NULL;
48
49 while (fgets(line, sizeof(line), fp)) {
50 char *s, *t = strstr(line, " ");
51
52 if (!t) {
53 fclose(fp);
54 return NULL;
55 }
56 t++;
57 s = strstr(t, " ");
58 if (!s) {
59 fclose(fp);
60 return NULL;
61 }
62 *s = '\0';
63
64 if (!strcmp(t, mp)) {
65 fclose(fp);
66 return t;
67 }
68 }
69
70 fclose(fp);
71
72 return point;
73 }
74
75 char*
76 find_mount_point(char *block, char *fs)
77 {
78 FILE *fp = fopen("/proc/mounts", "r");
79 static char line[256];
80 int len = strlen(block);
81 char *point = NULL;
82
83 if(!fp)
84 return NULL;
85
86 while (fgets(line, sizeof(line), fp)) {
87 if (!strncmp(line, block, len)) {
88 char *p = &line[len + 1];
89 char *t = strstr(p, " ");
90
91 if (!t) {
92 fclose(fp);
93 return NULL;
94 }
95
96 *t = '\0';
97 t++;
98
99 if (fs && strncmp(t, fs, strlen(fs))) {
100 fclose(fp);
101 fprintf(stderr, "block is mounted with wrong fs\n");
102 return NULL;
103 }
104 point = p;
105
106 break;
107 }
108 }
109
110 fclose(fp);
111
112 return point;
113 }
114
115 int
116 find_filesystem(char *fs)
117 {
118 FILE *fp = fopen("/proc/filesystems", "r");
119 static char line[256];
120 int ret = -1;
121
122 if (!fp) {
123 fprintf(stderr, "opening /proc/filesystems failed: %s\n", strerror(errno));
124 goto out;
125 }
126
127 while (ret && fgets(line, sizeof(line), fp))
128 if (strstr(line, fs))
129 ret = 0;
130
131 fclose(fp);
132
133 out:
134 return ret;
135 }