1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
/*
Tomato Firmware
Copyright (C) 2006-2009 Jonathan Zarate
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <bcmnvram.h>
#include "shutils.h"
#include "shared.h"
int f_exists(const char *path) // note: anything but a directory
{
struct stat st;
return (stat(path, &st) == 0) && (!S_ISDIR(st.st_mode));
}
unsigned long f_size(const char *path) // 4GB-1 -1 = error
{
struct stat st;
if (stat(path, &st) == 0) return st.st_size;
return (unsigned long)-1;
}
int f_read(const char *path, void *buffer, int max)
{
int f;
int n;
if ((f = open(path, O_RDONLY)) < 0) return -1;
n = read(f, buffer, max);
close(f);
return n;
}
int f_write(const char *path, const void *buffer, int len, unsigned flags, unsigned cmode)
{
static const char nl = '\n';
int f;
int r = -1;
mode_t m;
m = umask(0);
if (cmode == 0) cmode = 0666;
if ((f = open(path, (flags & FW_APPEND) ? (O_WRONLY|O_CREAT|O_APPEND) : (O_WRONLY|O_CREAT|O_TRUNC), cmode)) >= 0) {
if ((buffer == NULL) || ((r = write(f, buffer, len)) == len)) {
if (flags & FW_NEWLINE) {
if (write(f, &nl, 1) == 1) ++r;
}
}
close(f);
}
umask(m);
return r;
}
int f_read_string(const char *path, char *buffer, int max)
{
if (max <= 0) return -1;
int n = f_read(path, buffer, max - 1);
buffer[(n > 0) ? n : 0] = 0;
return n;
}
int f_write_string(const char *path, const char *buffer, unsigned flags, unsigned cmode)
{
return f_write(path, buffer, strlen(buffer), flags, cmode);
}
static int _f_read_alloc(const char *path, char **buffer, int max, int z)
{
unsigned long n;
*buffer = NULL;
if (max >= 0) {
if ((n = f_size(path)) != (unsigned long)-1) {
if (n < max) max = n;
if ((!z) && (max == 0)) return 0;
if ((*buffer = malloc(max + z)) != NULL) {
if ((max = f_read(path, *buffer, max)) >= 0) {
if (z) *(*buffer + max) = 0;
return max;
}
free(buffer);
}
}
}
return -1;
}
int f_read_alloc(const char *path, char **buffer, int max)
{
return _f_read_alloc(path, buffer, max, 0);
}
int f_read_alloc_string(const char *path, char **buffer, int max)
{
return _f_read_alloc(path, buffer, max, 1);
}
static int _f_wait_exists(const char *name, int max, int invert)
{
while (max-- > 0) {
if (f_exists(name) ^ invert) return 1;
sleep(1);
}
return 0;
}
int f_wait_exists(const char *name, int max)
{
return _f_wait_exists(name, max, 0);
}
int f_wait_notexists(const char *name, int max)
{
return _f_wait_exists(name, max, 1);
}
|