Initial implementation of OVSDB.
[sliver-openvswitch.git] / ovsdb / file.c
1 /* Copyright (c) 2009 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "file.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "json.h"
28 #include "lockfile.h"
29 #include "ovsdb-error.h"
30 #include "sha1.h"
31 #include "util.h"
32
33 #define THIS_MODULE VLM_ovsdb_file
34 #include "vlog.h"
35
36 enum ovsdb_file_mode {
37     OVSDB_FILE_READ,
38     OVSDB_FILE_WRITE
39 };
40
41 struct ovsdb_file {
42     off_t offset;
43     char *name;
44     struct lockfile *lockfile;
45     FILE *stream;
46     struct ovsdb_error *read_error;
47     struct ovsdb_error *write_error;
48     enum ovsdb_file_mode mode;
49 };
50
51 struct ovsdb_error *
52 ovsdb_file_open(const char *name, int flags, struct ovsdb_file **filep)
53 {
54     struct lockfile *lockfile;
55     struct ovsdb_error *error;
56     struct ovsdb_file *file;
57     struct stat s;
58     FILE *stream;
59     int accmode;
60     int fd;
61
62     *filep = NULL;
63
64     accmode = flags & O_ACCMODE;
65     if (accmode == O_RDWR || accmode == O_WRONLY) {
66         int retval = lockfile_lock(name, 0, &lockfile);
67         if (retval) {
68             error = ovsdb_io_error(retval, "%s: failed to lock lockfile",
69                                    name);
70             goto error;
71         }
72     } else {
73         lockfile = NULL;
74     }
75
76     fd = open(name, flags, 0666);
77     if (fd < 0) {
78         const char *op = flags & O_CREAT && flags & O_EXCL ? "create" : "open";
79         error = ovsdb_io_error(errno, "%s: %s failed", op, name);
80         goto error_unlock;
81     }
82
83     if (!fstat(fd, &s) && s.st_size == 0) {
84         /* It's (probably) a new file so fsync() its parent directory to ensure
85          * that its directory entry is committed to disk. */
86         char *dir = dir_name(name);
87         int dirfd = open(dir, O_RDONLY);
88         if (dirfd >= 0) {
89             if (fsync(dirfd) && errno != EINVAL) {
90                 VLOG_ERR("%s: fsync failed (%s)", dir, strerror(errno));
91             }
92             close(dirfd);
93         } else {
94             VLOG_ERR("%s: open failed (%s)", dir, strerror(errno));
95         }
96         free(dir);
97     }
98
99     stream = fdopen(fd, (accmode == O_RDONLY ? "rb"
100                          : accmode == O_WRONLY ? "wb"
101                          : "w+b"));
102     if (!stream) {
103         error = ovsdb_io_error(errno, "%s: fdopen failed", name);
104         goto error_close;
105     }
106
107     file = xmalloc(sizeof *file);
108     file->name = xstrdup(name);
109     file->lockfile = lockfile;
110     file->stream = stream;
111     file->offset = 0;
112     file->read_error = NULL;
113     file->write_error = NULL;
114     file->mode = OVSDB_FILE_READ;
115     *filep = file;
116     return NULL;
117
118 error_close:
119     close(fd);
120 error_unlock:
121     lockfile_unlock(lockfile);
122 error:
123     return error;
124 }
125
126 void
127 ovsdb_file_close(struct ovsdb_file *file)
128 {
129     if (file) {
130         free(file->name);
131         fclose(file->stream);
132         lockfile_unlock(file->lockfile);
133         ovsdb_error_destroy(file->read_error);
134         ovsdb_error_destroy(file->write_error);
135         free(file);
136     }
137 }
138
139 static const char magic[] = "OVSDB JSON ";
140
141 static bool
142 parse_header(char *header, unsigned long int *length,
143              uint8_t sha1[SHA1_DIGEST_SIZE])
144 {
145     char *p;
146
147     /* 'header' must consist of a magic string... */
148     if (strncmp(header, magic, strlen(magic))) {
149         return false;
150     }
151
152     /* ...followed by a length in bytes... */
153     *length = strtoul(header + strlen(magic), &p, 10);
154     if (!*length || *length == ULONG_MAX || *p != ' ') {
155         return false;
156     }
157     p++;
158
159     /* ...followed by a SHA-1 hash... */
160     if (!sha1_from_hex(sha1, p)) {
161         return false;
162     }
163     p += SHA1_HEX_DIGEST_LEN;
164
165     /* ...and ended by a new-line. */
166     if (*p != '\n') {
167         return false;
168     }
169
170     return true;
171 }
172
173 struct ovsdb_file_read_cbdata {
174     char input[4096];
175     struct ovsdb_file *file;
176     int error;
177     unsigned long length;
178 };
179
180 static struct ovsdb_error *
181 parse_body(struct ovsdb_file *file, off_t offset, unsigned long int length,
182            uint8_t sha1[SHA1_DIGEST_SIZE], struct json **jsonp)
183 {
184     unsigned long int bytes_left;
185     struct json_parser *parser;
186     struct sha1_ctx ctx;
187
188     sha1_init(&ctx);
189     parser = json_parser_create(JSPF_TRAILER);
190
191     bytes_left = length;
192     while (length > 0) {
193         char input[BUFSIZ];
194         int chunk;
195
196         chunk = MIN(length, sizeof input);
197         if (fread(input, 1, chunk, file->stream) != chunk) {
198             json_parser_abort(parser);
199             return ovsdb_io_error(ferror(file->stream) ? errno : EOF,
200                                   "%s: error reading %lu bytes "
201                                   "starting at offset %lld", file->name,
202                                   length, (long long int) offset);
203         }
204         sha1_update(&ctx, input, chunk);
205         json_parser_feed(parser, input, chunk);
206         length -= chunk;
207     }
208
209     sha1_final(&ctx, sha1);
210     *jsonp = json_parser_finish(parser);
211     return NULL;
212 }
213
214 struct ovsdb_error *
215 ovsdb_file_read(struct ovsdb_file *file, struct json **jsonp)
216 {
217     uint8_t expected_sha1[SHA1_DIGEST_SIZE];
218     uint8_t actual_sha1[SHA1_DIGEST_SIZE];
219     struct ovsdb_error *error;
220     off_t data_offset;
221     unsigned long data_length;
222     struct json *json;
223     char header[128];
224
225     *jsonp = json = NULL;
226
227     if (file->read_error) {
228         return ovsdb_error_clone(file->read_error);
229     } else if (file->mode == OVSDB_FILE_WRITE) {
230         return OVSDB_BUG("reading file in write mode");
231     }
232
233     if (!fgets(header, sizeof header, file->stream)) {
234         if (feof(file->stream)) {
235             error = NULL;
236         } else {
237             error = ovsdb_io_error(errno, "%s: read failed", file->name);
238         }
239         goto error;
240     }
241
242     if (!parse_header(header, &data_length, expected_sha1)) {
243         error = ovsdb_syntax_error(NULL, NULL, "%s: parse error at offset "
244                                    "%lld in header line \"%.*s\"",
245                                    file->name, (long long int) file->offset,
246                                    (int) strcspn(header, "\n"), header);
247         goto error;
248     }
249
250     data_offset = file->offset + strlen(header);
251     error = parse_body(file, data_offset, data_length, actual_sha1, &json);
252     if (error) {
253         goto error;
254     }
255
256     if (memcmp(expected_sha1, actual_sha1, SHA1_DIGEST_SIZE)) {
257         error = ovsdb_syntax_error(NULL, NULL, "%s: %lu bytes starting at "
258                                    "offset %lld have SHA-1 hash "SHA1_FMT" "
259                                    "but should have hash "SHA1_FMT,
260                                    file->name, data_length,
261                                    (long long int) data_offset,
262                                    SHA1_ARGS(actual_sha1),
263                                    SHA1_ARGS(expected_sha1));
264         goto error;
265     }
266
267     if (json->type == JSON_STRING) {
268         error = ovsdb_syntax_error(NULL, NULL, "%s: %lu bytes starting at "
269                                    "offset %lld are not valid JSON (%s)",
270                                    file->name, data_length,
271                                    (long long int) data_offset,
272                                    json->u.string);
273         goto error;
274     }
275
276     file->offset = data_offset + data_length;
277     *jsonp = json;
278     return 0;
279
280 error:
281     file->read_error = ovsdb_error_clone(error);
282     json_destroy(json);
283     return error;
284 }
285
286 struct ovsdb_error *
287 ovsdb_file_write(struct ovsdb_file *file, struct json *json)
288 {
289     uint8_t sha1[SHA1_DIGEST_SIZE];
290     struct ovsdb_error *error;
291     char *json_string;
292     char header[128];
293     size_t length;
294
295     json_string = NULL;
296
297     if (file->write_error) {
298         return ovsdb_error_clone(file->write_error);
299     } else if (file->mode == OVSDB_FILE_READ) {
300         file->mode = OVSDB_FILE_WRITE;
301         if (fseeko(file->stream, file->offset, SEEK_SET)) {
302             error = ovsdb_io_error(errno, "%s: cannot seek to offset %lld",
303                                    file->name, (long long int) file->offset);
304             goto error;
305         }
306         if (ftruncate(fileno(file->stream), file->offset)) {
307             error = ovsdb_io_error(errno, "%s: cannot truncate to length %lld",
308                                    file->name, (long long int) file->offset);
309             goto error;
310         }
311     }
312
313     if (json->type != JSON_OBJECT && json->type != JSON_ARRAY) {
314         error = OVSDB_BUG("bad JSON type");
315         goto error;
316     }
317
318     /* Compose content.  Add a new-line (replacing the null terminator) to make
319      * the file easier to read, even though it has no semantic value.  */
320     json_string = json_to_string(json, 0);
321     length = strlen(json_string) + 1;
322     json_string[length - 1] = '\n';
323
324     /* Compose header. */
325     sha1_bytes(json_string, length, sha1);
326     snprintf(header, sizeof header, "%s%zu "SHA1_FMT"\n",
327              magic, length, SHA1_ARGS(sha1));
328
329     /* Write. */
330     if (fwrite(header, strlen(header), 1, file->stream) != 1
331         || fwrite(json_string, length, 1, file->stream) != 1
332         || fflush(file->stream))
333     {
334         error = ovsdb_io_error(errno, "%s: write failed", file->name);
335
336         /* Remove any partially written data, ignoring errors since there is
337          * nothing further we can do. */
338         ftruncate(fileno(file->stream), file->offset);
339
340         goto error;
341     }
342
343     file->offset += strlen(header) + length;
344     free(json_string);
345     return 0;
346
347 error:
348     file->write_error = ovsdb_error_clone(error);
349     free(json_string);
350     return error;
351 }
352
353 struct ovsdb_error *
354 ovsdb_file_commit(struct ovsdb_file *file)
355 {
356     if (fsync(fileno(file->stream))) {
357         return ovsdb_io_error(errno, "%s: fsync failed", file->name);
358     }
359     return 0;
360 }