Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / shared / files.c
blobe15eab4b5820c44d80cf032a1f144e87de6adfff
1 /*
3 Tomato Firmware
4 Copyright (C) 2006-2009 Jonathan Zarate
6 */
8 #include <string.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <stdarg.h>
16 #include <bcmnvram.h>
17 #include "shutils.h"
18 #include "shared.h"
21 int f_exists(const char *path) // note: anything but a directory
23 struct stat st;
24 return (stat(path, &st) == 0) && (!S_ISDIR(st.st_mode));
27 unsigned long f_size(const char *path) // 4GB-1 -1 = error
29 struct stat st;
30 if (stat(path, &st) == 0) return st.st_size;
31 return (unsigned long)-1;
34 int f_read(const char *path, void *buffer, int max)
36 int f;
37 int n;
39 if ((f = open(path, O_RDONLY)) < 0) return -1;
40 n = read(f, buffer, max);
41 close(f);
42 return n;
45 int f_write(const char *path, const void *buffer, int len, unsigned flags, unsigned cmode)
47 static const char nl = '\n';
48 int f;
49 int r = -1;
50 mode_t m;
52 m = umask(0);
53 if (cmode == 0) cmode = 0666;
54 if ((f = open(path, (flags & FW_APPEND) ? (O_WRONLY|O_CREAT|O_APPEND) : (O_WRONLY|O_CREAT|O_TRUNC), cmode)) >= 0) {
55 if ((buffer == NULL) || ((r = write(f, buffer, len)) == len)) {
56 if (flags & FW_NEWLINE) {
57 if (write(f, &nl, 1) == 1) ++r;
60 close(f);
62 umask(m);
63 return r;
66 int f_read_string(const char *path, char *buffer, int max)
68 if (max <= 0) return -1;
69 int n = f_read(path, buffer, max - 1);
70 buffer[(n > 0) ? n : 0] = 0;
71 return n;
74 int f_write_string(const char *path, const char *buffer, unsigned flags, unsigned cmode)
76 return f_write(path, buffer, strlen(buffer), flags, cmode);
79 static int _f_read_alloc(const char *path, char **buffer, int max, int z)
81 unsigned long n;
83 *buffer = NULL;
84 if (max >= 0) {
85 if ((n = f_size(path)) != (unsigned long)-1) {
86 if (n < max) max = n;
87 if ((!z) && (max == 0)) return 0;
88 if ((*buffer = malloc(max + z)) != NULL) {
89 if ((max = f_read(path, *buffer, max)) >= 0) {
90 if (z) *(*buffer + max) = 0;
91 return max;
93 free(buffer);
97 return -1;
100 int f_read_alloc(const char *path, char **buffer, int max)
102 return _f_read_alloc(path, buffer, max, 0);
105 int f_read_alloc_string(const char *path, char **buffer, int max)
107 return _f_read_alloc(path, buffer, max, 1);
111 static int _f_wait_exists(const char *name, int max, int invert)
113 while (max-- > 0) {
114 if (f_exists(name) ^ invert) return 1;
115 sleep(1);
117 return 0;
120 int f_wait_exists(const char *name, int max)
122 return _f_wait_exists(name, max, 0);
125 int f_wait_notexists(const char *name, int max)
127 return _f_wait_exists(name, max, 1);