ovsdb: Remove write-only variable from parse_body() in log.c.
[cascardo/ovs.git] / ovsdb / log.c
1 /* Copyright (c) 2009, 2010 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 "log.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.h"
30 #include "ovsdb-error.h"
31 #include "sha1.h"
32 #include "transaction.h"
33 #include "util.h"
34
35 #define THIS_MODULE VLM_ovsdb_log
36 #include "vlog.h"
37
38 enum ovsdb_log_mode {
39     OVSDB_LOG_READ,
40     OVSDB_LOG_WRITE
41 };
42
43 struct ovsdb_log {
44     off_t offset;
45     char *name;
46     struct lockfile *lockfile;
47     FILE *stream;
48     struct ovsdb_error *read_error;
49     struct ovsdb_error *write_error;
50     enum ovsdb_log_mode mode;
51 };
52
53 struct ovsdb_error *
54 ovsdb_log_open(const char *name, int flags, struct ovsdb_log **filep)
55 {
56     struct lockfile *lockfile;
57     struct ovsdb_error *error;
58     struct ovsdb_log *file;
59     struct stat s;
60     FILE *stream;
61     int accmode;
62     int fd;
63
64     *filep = NULL;
65
66     accmode = flags & O_ACCMODE;
67     if (accmode == O_RDWR || accmode == O_WRONLY) {
68         int retval = lockfile_lock(name, 0, &lockfile);
69         if (retval) {
70             error = ovsdb_io_error(retval, "%s: failed to lock lockfile",
71                                    name);
72             goto error;
73         }
74     } else {
75         lockfile = NULL;
76     }
77
78     fd = open(name, flags, 0666);
79     if (fd < 0) {
80         const char *op = flags & O_CREAT && flags & O_EXCL ? "create" : "open";
81         error = ovsdb_io_error(errno, "%s: %s failed", op, name);
82         goto error_unlock;
83     }
84
85     if (!fstat(fd, &s) && s.st_size == 0) {
86         /* It's (probably) a new file so fsync() its parent directory to ensure
87          * that its directory entry is committed to disk. */
88         char *dir = dir_name(name);
89         int dirfd = open(dir, O_RDONLY);
90         if (dirfd >= 0) {
91             if (fsync(dirfd) && errno != EINVAL) {
92                 VLOG_ERR("%s: fsync failed (%s)", dir, strerror(errno));
93             }
94             close(dirfd);
95         } else {
96             VLOG_ERR("%s: open failed (%s)", dir, strerror(errno));
97         }
98         free(dir);
99     }
100
101     stream = fdopen(fd, (accmode == O_RDONLY ? "rb"
102                          : accmode == O_WRONLY ? "wb"
103                          : "w+b"));
104     if (!stream) {
105         error = ovsdb_io_error(errno, "%s: fdopen failed", name);
106         goto error_close;
107     }
108
109     file = xmalloc(sizeof *file);
110     file->name = xstrdup(name);
111     file->lockfile = lockfile;
112     file->stream = stream;
113     file->offset = 0;
114     file->read_error = NULL;
115     file->write_error = NULL;
116     file->mode = OVSDB_LOG_READ;
117     *filep = file;
118     return NULL;
119
120 error_close:
121     close(fd);
122 error_unlock:
123     lockfile_unlock(lockfile);
124 error:
125     return error;
126 }
127
128 void
129 ovsdb_log_close(struct ovsdb_log *file)
130 {
131     if (file) {
132         free(file->name);
133         fclose(file->stream);
134         lockfile_unlock(file->lockfile);
135         ovsdb_error_destroy(file->read_error);
136         ovsdb_error_destroy(file->write_error);
137         free(file);
138     }
139 }
140
141 static const char magic[] = "OVSDB JSON ";
142
143 static bool
144 parse_header(char *header, unsigned long int *length,
145              uint8_t sha1[SHA1_DIGEST_SIZE])
146 {
147     char *p;
148
149     /* 'header' must consist of a magic string... */
150     if (strncmp(header, magic, strlen(magic))) {
151         return false;
152     }
153
154     /* ...followed by a length in bytes... */
155     *length = strtoul(header + strlen(magic), &p, 10);
156     if (!*length || *length == ULONG_MAX || *p != ' ') {
157         return false;
158     }
159     p++;
160
161     /* ...followed by a SHA-1 hash... */
162     if (!sha1_from_hex(sha1, p)) {
163         return false;
164     }
165     p += SHA1_HEX_DIGEST_LEN;
166
167     /* ...and ended by a new-line. */
168     if (*p != '\n') {
169         return false;
170     }
171
172     return true;
173 }
174
175 struct ovsdb_log_read_cbdata {
176     char input[4096];
177     struct ovsdb_log *file;
178     int error;
179     unsigned long length;
180 };
181
182 static struct ovsdb_error *
183 parse_body(struct ovsdb_log *file, off_t offset, unsigned long int length,
184            uint8_t sha1[SHA1_DIGEST_SIZE], struct json **jsonp)
185 {
186     struct json_parser *parser;
187     struct sha1_ctx ctx;
188
189     sha1_init(&ctx);
190     parser = json_parser_create(JSPF_TRAILER);
191
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_log_read(struct ovsdb_log *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_LOG_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_log_write(struct ovsdb_log *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_LOG_READ) {
300         file->mode = OVSDB_LOG_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         ignore(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_log_commit(struct ovsdb_log *file)
355 {
356     if (fsync(fileno(file->stream))) {
357         return ovsdb_io_error(errno, "%s: fsync failed", file->name);
358     }
359     return 0;
360 }
361