summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRui Salvaterra <rsalvaterra@gmail.com>2020-10-19 16:51:16 +0100
committerRui Salvaterra <rsalvaterra@gmail.com>2021-03-23 09:18:33 +0000
commitedd0dc5829b4d948fb878d667e2135662d98e011 (patch)
treea867a73dee8604d723bc5d00c548ffb4da2dd42c
parent61db17edddb1f05e8107f0dbef6f7d060ce67483 (diff)
downloadfirewall3-edd0dc5829b4d948fb878d667e2135662d98e011.tar.gz
firewall3: create a common helper to find strings in files
Both fw3_has_table and fw3_has_target do the same thing. Factor out the common code into a separate function. Signed-off-by: Rui Salvaterra <rsalvaterra@gmail.com>
-rw-r--r--utils.c38
-rw-r--r--utils.h3
2 files changed, 13 insertions, 28 deletions
diff --git a/utils.c b/utils.c
index 5667bcf..17d5bf9 100644
--- a/utils.c
+++ b/utils.c
@@ -315,23 +315,19 @@ fw3_command_close(void)
pipe_pid = -1;
}
-bool
-fw3_has_table(bool ipv6, const char *table)
+static bool
+file_contains(const char *path, const char *str)
{
FILE *f;
-
char line[12];
bool seen = false;
- const char *path = ipv6
- ? "/proc/net/ip6_tables_names" : "/proc/net/ip_tables_names";
-
if (!(f = fopen(path, "r")))
return false;
while (fgets(line, sizeof(line), f))
{
- if (!strncmp(line, table, strlen(table)))
+ if (!strncmp(line, str, strlen(str)))
{
seen = true;
break;
@@ -344,31 +340,21 @@ fw3_has_table(bool ipv6, const char *table)
}
bool
-fw3_has_target(const bool ipv6, const char *target)
+fw3_has_table(const bool ipv6, const char *table)
{
- FILE *f;
+ const char *path = ipv6
+ ? "/proc/net/ip6_tables_names" : "/proc/net/ip_tables_names";
- char line[12];
- bool seen = false;
+ return file_contains(path, table);
+}
+bool
+fw3_has_target(const bool ipv6, const char *target)
+{
const char *path = ipv6
? "/proc/net/ip6_tables_targets" : "/proc/net/ip_tables_targets";
- if (!(f = fopen(path, "r")))
- return false;
-
- while (fgets(line, sizeof(line), f))
- {
- if (!strcmp(line, target))
- {
- seen = true;
- break;
- }
- }
-
- fclose(f);
-
- return seen;
+ return file_contains(path, target);
}
bool
diff --git a/utils.h b/utils.h
index 254bea4..884907d 100644
--- a/utils.h
+++ b/utils.h
@@ -55,7 +55,6 @@ void error(const char *format, ...)
void info(const char *format, ...)
__attribute__ ((format (printf, 1, 2)));
-
#define warn_section(t, r, e, fmt, ...) \
do { \
if (e) \
@@ -103,7 +102,7 @@ void fw3_command_close(void);
void fw3_pr(const char *fmt, ...)
__attribute__ ((format (printf, 1, 2)));
-bool fw3_has_table(bool ipv6, const char *table);
+bool fw3_has_table(const bool ipv6, const char *table);
bool fw3_has_target(const bool ipv6, const char *target);