ade1971c3885be572fc137c4a90b353d73153040
[cascardo/ovs.git] / lib / ovsdb-data.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 "ovsdb-data.h"
19
20 #include <ctype.h>
21 #include <float.h>
22 #include <inttypes.h>
23 #include <limits.h>
24
25 #include "dynamic-string.h"
26 #include "hash.h"
27 #include "ovs-thread.h"
28 #include "ovsdb-error.h"
29 #include "ovsdb-parser.h"
30 #include "json.h"
31 #include "shash.h"
32 #include "smap.h"
33 #include "sort.h"
34 #include "unicode.h"
35
36 static struct json *
37 wrap_json(const char *name, struct json *wrapped)
38 {
39     return json_array_create_2(json_string_create(name), wrapped);
40 }
41
42 /* Initializes 'atom' with the default value of the given 'type'.
43  *
44  * The default value for an atom is as defined in ovsdb/SPECS:
45  *
46  *      - "integer" or "real": 0
47  *
48  *      - "boolean": false
49  *
50  *      - "string": "" (the empty string)
51  *
52  *      - "uuid": 00000000-0000-0000-0000-000000000000
53  *
54  * The caller must eventually arrange for 'atom' to be destroyed (with
55  * ovsdb_atom_destroy()). */
56 void
57 ovsdb_atom_init_default(union ovsdb_atom *atom, enum ovsdb_atomic_type type)
58 {
59     switch (type) {
60     case OVSDB_TYPE_VOID:
61         NOT_REACHED();
62
63     case OVSDB_TYPE_INTEGER:
64         atom->integer = 0;
65         break;
66
67     case OVSDB_TYPE_REAL:
68         atom->real = 0.0;
69         break;
70
71     case OVSDB_TYPE_BOOLEAN:
72         atom->boolean = false;
73         break;
74
75     case OVSDB_TYPE_STRING:
76         atom->string = xmemdup("", 1);
77         break;
78
79     case OVSDB_TYPE_UUID:
80         uuid_zero(&atom->uuid);
81         break;
82
83     case OVSDB_N_TYPES:
84     default:
85         NOT_REACHED();
86     }
87 }
88
89 /* Returns a read-only atom of the given 'type' that has the default value for
90  * 'type'.  The caller must not modify or free the returned atom.
91  *
92  * See ovsdb_atom_init_default() for an explanation of the default value of an
93  * atom. */
94 const union ovsdb_atom *
95 ovsdb_atom_default(enum ovsdb_atomic_type type)
96 {
97     static union ovsdb_atom default_atoms[OVSDB_N_TYPES];
98     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
99
100     if (ovsthread_once_start(&once)) {
101         int i;
102
103         for (i = 0; i < OVSDB_N_TYPES; i++) {
104             if (i != OVSDB_TYPE_VOID) {
105                 ovsdb_atom_init_default(&default_atoms[i], i);
106             }
107         }
108         ovsthread_once_done(&once);
109     }
110
111     ovs_assert(ovsdb_atomic_type_is_valid(type));
112     return &default_atoms[type];
113 }
114
115 /* Returns true if 'atom', which must have the given 'type', has the default
116  * value for that type.
117  *
118  * See ovsdb_atom_init_default() for an explanation of the default value of an
119  * atom. */
120 bool
121 ovsdb_atom_is_default(const union ovsdb_atom *atom,
122                       enum ovsdb_atomic_type type)
123 {
124     switch (type) {
125     case OVSDB_TYPE_VOID:
126         NOT_REACHED();
127
128     case OVSDB_TYPE_INTEGER:
129         return atom->integer == 0;
130
131     case OVSDB_TYPE_REAL:
132         return atom->real == 0.0;
133
134     case OVSDB_TYPE_BOOLEAN:
135         return atom->boolean == false;
136
137     case OVSDB_TYPE_STRING:
138         return atom->string[0] == '\0';
139
140     case OVSDB_TYPE_UUID:
141         return uuid_is_zero(&atom->uuid);
142
143     case OVSDB_N_TYPES:
144     default:
145         NOT_REACHED();
146     }
147 }
148
149 /* Initializes 'new' as a copy of 'old', with the given 'type'.
150  *
151  * The caller must eventually arrange for 'new' to be destroyed (with
152  * ovsdb_atom_destroy()). */
153 void
154 ovsdb_atom_clone(union ovsdb_atom *new, const union ovsdb_atom *old,
155                  enum ovsdb_atomic_type type)
156 {
157     switch (type) {
158     case OVSDB_TYPE_VOID:
159         NOT_REACHED();
160
161     case OVSDB_TYPE_INTEGER:
162         new->integer = old->integer;
163         break;
164
165     case OVSDB_TYPE_REAL:
166         new->real = old->real;
167         break;
168
169     case OVSDB_TYPE_BOOLEAN:
170         new->boolean = old->boolean;
171         break;
172
173     case OVSDB_TYPE_STRING:
174         new->string = xstrdup(old->string);
175         break;
176
177     case OVSDB_TYPE_UUID:
178         new->uuid = old->uuid;
179         break;
180
181     case OVSDB_N_TYPES:
182     default:
183         NOT_REACHED();
184     }
185 }
186
187 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
188 void
189 ovsdb_atom_swap(union ovsdb_atom *a, union ovsdb_atom *b)
190 {
191     union ovsdb_atom tmp = *a;
192     *a = *b;
193     *b = tmp;
194 }
195
196 /* Returns a hash value for 'atom', which has the specified 'type', folding
197  * 'basis' into the calculation. */
198 uint32_t
199 ovsdb_atom_hash(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
200                 uint32_t basis)
201 {
202     switch (type) {
203     case OVSDB_TYPE_VOID:
204         NOT_REACHED();
205
206     case OVSDB_TYPE_INTEGER:
207         return hash_int(atom->integer, basis);
208
209     case OVSDB_TYPE_REAL:
210         return hash_double(atom->real, basis);
211
212     case OVSDB_TYPE_BOOLEAN:
213         return hash_boolean(atom->boolean, basis);
214
215     case OVSDB_TYPE_STRING:
216         return hash_string(atom->string, basis);
217
218     case OVSDB_TYPE_UUID:
219         return hash_int(uuid_hash(&atom->uuid), basis);
220
221     case OVSDB_N_TYPES:
222     default:
223         NOT_REACHED();
224     }
225 }
226
227 /* Compares 'a' and 'b', which both have type 'type', and returns a
228  * strcmp()-like result. */
229 int
230 ovsdb_atom_compare_3way(const union ovsdb_atom *a,
231                         const union ovsdb_atom *b,
232                         enum ovsdb_atomic_type type)
233 {
234     switch (type) {
235     case OVSDB_TYPE_VOID:
236         NOT_REACHED();
237
238     case OVSDB_TYPE_INTEGER:
239         return a->integer < b->integer ? -1 : a->integer > b->integer;
240
241     case OVSDB_TYPE_REAL:
242         return a->real < b->real ? -1 : a->real > b->real;
243
244     case OVSDB_TYPE_BOOLEAN:
245         return a->boolean - b->boolean;
246
247     case OVSDB_TYPE_STRING:
248         return strcmp(a->string, b->string);
249
250     case OVSDB_TYPE_UUID:
251         return uuid_compare_3way(&a->uuid, &b->uuid);
252
253     case OVSDB_N_TYPES:
254     default:
255         NOT_REACHED();
256     }
257 }
258
259 static struct ovsdb_error *
260 unwrap_json(const struct json *json, const char *name,
261             enum json_type value_type, const struct json **value)
262 {
263     if (json->type != JSON_ARRAY
264         || json->u.array.n != 2
265         || json->u.array.elems[0]->type != JSON_STRING
266         || (name && strcmp(json->u.array.elems[0]->u.string, name))
267         || json->u.array.elems[1]->type != value_type)
268     {
269         *value = NULL;
270         return ovsdb_syntax_error(json, NULL, "expected [\"%s\", <%s>]", name,
271                                   json_type_to_string(value_type));
272     }
273     *value = json->u.array.elems[1];
274     return NULL;
275 }
276
277 static struct ovsdb_error *
278 parse_json_pair(const struct json *json,
279                 const struct json **elem0, const struct json **elem1)
280 {
281     if (json->type != JSON_ARRAY || json->u.array.n != 2) {
282         return ovsdb_syntax_error(json, NULL, "expected 2-element array");
283     }
284     *elem0 = json->u.array.elems[0];
285     *elem1 = json->u.array.elems[1];
286     return NULL;
287 }
288
289 static void
290 ovsdb_symbol_referenced(struct ovsdb_symbol *symbol,
291                         const struct ovsdb_base_type *base)
292 {
293     ovs_assert(base->type == OVSDB_TYPE_UUID);
294
295     if (base->u.uuid.refTableName) {
296         switch (base->u.uuid.refType) {
297         case OVSDB_REF_STRONG:
298             symbol->strong_ref = true;
299             break;
300         case OVSDB_REF_WEAK:
301             symbol->weak_ref = true;
302             break;
303         }
304     }
305 }
306
307 static struct ovsdb_error * WARN_UNUSED_RESULT
308 ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
309                       struct ovsdb_symbol_table *symtab,
310                       const struct ovsdb_base_type *base)
311 {
312     struct ovsdb_error *error0;
313     const struct json *value;
314
315     error0 = unwrap_json(json, "uuid", JSON_STRING, &value);
316     if (!error0) {
317         const char *uuid_string = json_string(value);
318         if (!uuid_from_string(uuid, uuid_string)) {
319             return ovsdb_syntax_error(json, NULL, "\"%s\" is not a valid UUID",
320                                       uuid_string);
321         }
322     } else if (symtab) {
323         struct ovsdb_error *error1;
324
325         error1 = unwrap_json(json, "named-uuid", JSON_STRING, &value);
326         if (!error1) {
327             struct ovsdb_symbol *symbol;
328
329             ovsdb_error_destroy(error0);
330             if (!ovsdb_parser_is_id(json_string(value))) {
331                 return ovsdb_syntax_error(json, NULL, "named-uuid string is "
332                                           "not a valid <id>");
333             }
334
335             symbol = ovsdb_symbol_table_insert(symtab, json_string(value));
336             *uuid = symbol->uuid;
337             ovsdb_symbol_referenced(symbol, base);
338             return NULL;
339         }
340         ovsdb_error_destroy(error1);
341     }
342
343     return error0;
344 }
345
346 static struct ovsdb_error * WARN_UNUSED_RESULT
347 ovsdb_atom_from_json__(union ovsdb_atom *atom,
348                        const struct ovsdb_base_type *base,
349                        const struct json *json,
350                        struct ovsdb_symbol_table *symtab)
351 {
352     enum ovsdb_atomic_type type = base->type;
353
354     switch (type) {
355     case OVSDB_TYPE_VOID:
356         NOT_REACHED();
357
358     case OVSDB_TYPE_INTEGER:
359         if (json->type == JSON_INTEGER) {
360             atom->integer = json->u.integer;
361             return NULL;
362         }
363         break;
364
365     case OVSDB_TYPE_REAL:
366         if (json->type == JSON_INTEGER) {
367             atom->real = json->u.integer;
368             return NULL;
369         } else if (json->type == JSON_REAL) {
370             atom->real = json->u.real;
371             return NULL;
372         }
373         break;
374
375     case OVSDB_TYPE_BOOLEAN:
376         if (json->type == JSON_TRUE) {
377             atom->boolean = true;
378             return NULL;
379         } else if (json->type == JSON_FALSE) {
380             atom->boolean = false;
381             return NULL;
382         }
383         break;
384
385     case OVSDB_TYPE_STRING:
386         if (json->type == JSON_STRING) {
387             atom->string = xstrdup(json->u.string);
388             return NULL;
389         }
390         break;
391
392     case OVSDB_TYPE_UUID:
393         return ovsdb_atom_parse_uuid(&atom->uuid, json, symtab, base);
394
395     case OVSDB_N_TYPES:
396     default:
397         NOT_REACHED();
398     }
399
400     return ovsdb_syntax_error(json, NULL, "expected %s",
401                               ovsdb_atomic_type_to_string(type));
402 }
403
404 /* Parses 'json' as an atom of the type described by 'base'.  If successful,
405  * returns NULL and initializes 'atom' with the parsed atom.  On failure,
406  * returns an error and the contents of 'atom' are indeterminate.  The caller
407  * is responsible for freeing the error or the atom that is returned.
408  *
409  * Violations of constraints expressed by 'base' are treated as errors.
410  *
411  * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
412  * ovsdb/SPECS for information about this, and for the syntax that this
413  * function accepts.  If 'base' is a reference and a symbol is parsed, then the
414  * symbol's 'strong_ref' or 'weak_ref' member is set to true, as
415  * appropriate. */
416 struct ovsdb_error *
417 ovsdb_atom_from_json(union ovsdb_atom *atom,
418                      const struct ovsdb_base_type *base,
419                      const struct json *json,
420                      struct ovsdb_symbol_table *symtab)
421 {
422     struct ovsdb_error *error;
423
424     error = ovsdb_atom_from_json__(atom, base, json, symtab);
425     if (error) {
426         return error;
427     }
428
429     error = ovsdb_atom_check_constraints(atom, base);
430     if (error) {
431         ovsdb_atom_destroy(atom, base->type);
432     }
433     return error;
434 }
435
436 /* Converts 'atom', of the specified 'type', to JSON format, and returns the
437  * JSON.  The caller is responsible for freeing the returned JSON.
438  *
439  * Refer to ovsdb/SPECS for the format of the JSON that this function
440  * produces. */
441 struct json *
442 ovsdb_atom_to_json(const union ovsdb_atom *atom, enum ovsdb_atomic_type type)
443 {
444     switch (type) {
445     case OVSDB_TYPE_VOID:
446         NOT_REACHED();
447
448     case OVSDB_TYPE_INTEGER:
449         return json_integer_create(atom->integer);
450
451     case OVSDB_TYPE_REAL:
452         return json_real_create(atom->real);
453
454     case OVSDB_TYPE_BOOLEAN:
455         return json_boolean_create(atom->boolean);
456
457     case OVSDB_TYPE_STRING:
458         return json_string_create(atom->string);
459
460     case OVSDB_TYPE_UUID:
461         return wrap_json("uuid", json_string_create_nocopy(
462                              xasprintf(UUID_FMT, UUID_ARGS(&atom->uuid))));
463
464     case OVSDB_N_TYPES:
465     default:
466         NOT_REACHED();
467     }
468 }
469
470 /* Returns strlen(json_to_string(ovsdb_atom_to_json(atom, type), 0)). */
471 size_t
472 ovsdb_atom_json_length(const union ovsdb_atom *atom,
473                        enum ovsdb_atomic_type type)
474 {
475     struct json json;
476
477     switch (type) {
478     case OVSDB_TYPE_VOID:
479         NOT_REACHED();
480
481     case OVSDB_TYPE_INTEGER:
482         json.type = JSON_INTEGER;
483         json.u.integer = atom->integer;
484         break;
485
486     case OVSDB_TYPE_REAL:
487         json.type = JSON_REAL;
488         json.u.real = atom->real;
489         break;
490
491     case OVSDB_TYPE_BOOLEAN:
492         json.type = atom->boolean ? JSON_TRUE : JSON_FALSE;
493         break;
494
495     case OVSDB_TYPE_STRING:
496         json.type = JSON_STRING;
497         json.u.string = atom->string;
498         break;
499
500     case OVSDB_TYPE_UUID:
501         return strlen("[\"uuid\",\"00000000-0000-0000-0000-000000000000\"]");
502
503     case OVSDB_N_TYPES:
504     default:
505         NOT_REACHED();
506     }
507
508     return json_serialized_length(&json);
509 }
510
511 static char *
512 ovsdb_atom_from_string__(union ovsdb_atom *atom,
513                          const struct ovsdb_base_type *base, const char *s,
514                          struct ovsdb_symbol_table *symtab)
515 {
516     enum ovsdb_atomic_type type = base->type;
517
518     switch (type) {
519     case OVSDB_TYPE_VOID:
520         NOT_REACHED();
521
522     case OVSDB_TYPE_INTEGER: {
523         long long int integer;
524         if (!str_to_llong(s, 10, &integer)) {
525             return xasprintf("\"%s\" is not a valid integer", s);
526         }
527         atom->integer = integer;
528     }
529         break;
530
531     case OVSDB_TYPE_REAL:
532         if (!str_to_double(s, &atom->real)) {
533             return xasprintf("\"%s\" is not a valid real number", s);
534         }
535         /* Our JSON input routines map negative zero to zero, so do that here
536          * too for consistency. */
537         if (atom->real == 0.0) {
538             atom->real = 0.0;
539         }
540         break;
541
542     case OVSDB_TYPE_BOOLEAN:
543         if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on")
544             || !strcmp(s, "1")) {
545             atom->boolean = true;
546         } else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "off")
547                    || !strcmp(s, "0")) {
548             atom->boolean = false;
549         } else {
550             return xasprintf("\"%s\" is not a valid boolean "
551                              "(use \"true\" or \"false\")", s);
552         }
553         break;
554
555     case OVSDB_TYPE_STRING:
556         if (*s == '\0') {
557             return xstrdup("An empty string is not valid as input; "
558                            "use \"\" to represent the empty string");
559         } else if (*s == '"') {
560             size_t s_len = strlen(s);
561
562             if (s_len < 2 || s[s_len - 1] != '"') {
563                 return xasprintf("%s: missing quote at end of "
564                                  "quoted string", s);
565             } else if (!json_string_unescape(s + 1, s_len - 2,
566                                              &atom->string)) {
567                 char *error = xasprintf("%s: %s", s, atom->string);
568                 free(atom->string);
569                 return error;
570             }
571         } else {
572             atom->string = xstrdup(s);
573         }
574         break;
575
576     case OVSDB_TYPE_UUID:
577         if (*s == '@') {
578             struct ovsdb_symbol *symbol = ovsdb_symbol_table_insert(symtab, s);
579             atom->uuid = symbol->uuid;
580             ovsdb_symbol_referenced(symbol, base);
581         } else if (!uuid_from_string(&atom->uuid, s)) {
582             return xasprintf("\"%s\" is not a valid UUID", s);
583         }
584         break;
585
586     case OVSDB_N_TYPES:
587     default:
588         NOT_REACHED();
589     }
590
591     return NULL;
592 }
593
594 /* Initializes 'atom' to a value of type 'base' parsed from 's', which takes
595  * one of the following forms:
596  *
597  *      - OVSDB_TYPE_INTEGER: A decimal integer optionally preceded by a sign.
598  *
599  *      - OVSDB_TYPE_REAL: A floating-point number in the format accepted by
600  *        strtod().
601  *
602  *      - OVSDB_TYPE_BOOLEAN: "true", "yes", "on", "1" for true, or "false",
603  *        "no", "off", or "0" for false.
604  *
605  *      - OVSDB_TYPE_STRING: A JSON string if it begins with a quote, otherwise
606  *        an arbitrary string.
607  *
608  *      - OVSDB_TYPE_UUID: A UUID in RFC 4122 format.  If 'symtab' is nonnull,
609  *        then an identifier beginning with '@' is also acceptable.  If the
610  *        named identifier is already in 'symtab', then the associated UUID is
611  *        used; otherwise, a new, random UUID is used and added to the symbol
612  *        table.  If 'base' is a reference and a symbol is parsed, then the
613  *        symbol's 'strong_ref' or 'weak_ref' member is set to true, as
614  *        appropriate.
615  *
616  * Returns a null pointer if successful, otherwise an error message describing
617  * the problem.  On failure, the contents of 'atom' are indeterminate.  The
618  * caller is responsible for freeing the atom or the error.
619  */
620 char *
621 ovsdb_atom_from_string(union ovsdb_atom *atom,
622                        const struct ovsdb_base_type *base, const char *s,
623                        struct ovsdb_symbol_table *symtab)
624 {
625     struct ovsdb_error *error;
626     char *msg;
627
628     msg = ovsdb_atom_from_string__(atom, base, s, symtab);
629     if (msg) {
630         return msg;
631     }
632
633     error = ovsdb_atom_check_constraints(atom, base);
634     if (error) {
635         ovsdb_atom_destroy(atom, base->type);
636         msg = ovsdb_error_to_string(error);
637         ovsdb_error_destroy(error);
638     }
639     return msg;
640 }
641
642 static bool
643 string_needs_quotes(const char *s)
644 {
645     const char *p = s;
646     unsigned char c;
647
648     c = *p++;
649     if (!isalpha(c) && c != '_') {
650         return true;
651     }
652
653     while ((c = *p++) != '\0') {
654         if (!isalpha(c) && c != '_' && c != '-' && c != '.') {
655             return true;
656         }
657     }
658
659     if (!strcmp(s, "true") || !strcmp(s, "false")) {
660         return true;
661     }
662
663     return false;
664 }
665
666 /* Appends 'atom' (which has the given 'type') to 'out', in a format acceptable
667  * to ovsdb_atom_from_string().  */
668 void
669 ovsdb_atom_to_string(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
670                      struct ds *out)
671 {
672     switch (type) {
673     case OVSDB_TYPE_VOID:
674         NOT_REACHED();
675
676     case OVSDB_TYPE_INTEGER:
677         ds_put_format(out, "%"PRId64, atom->integer);
678         break;
679
680     case OVSDB_TYPE_REAL:
681         ds_put_format(out, "%.*g", DBL_DIG, atom->real);
682         break;
683
684     case OVSDB_TYPE_BOOLEAN:
685         ds_put_cstr(out, atom->boolean ? "true" : "false");
686         break;
687
688     case OVSDB_TYPE_STRING:
689         if (string_needs_quotes(atom->string)) {
690             struct json json;
691
692             json.type = JSON_STRING;
693             json.u.string = atom->string;
694             json_to_ds(&json, 0, out);
695         } else {
696             ds_put_cstr(out, atom->string);
697         }
698         break;
699
700     case OVSDB_TYPE_UUID:
701         ds_put_format(out, UUID_FMT, UUID_ARGS(&atom->uuid));
702         break;
703
704     case OVSDB_N_TYPES:
705     default:
706         NOT_REACHED();
707     }
708 }
709
710 /* Appends 'atom' (which has the given 'type') to 'out', in a bare string
711  * format that cannot be parsed uniformly back into a datum but is easier for
712  * shell scripts, etc., to deal with. */
713 void
714 ovsdb_atom_to_bare(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
715                    struct ds *out)
716 {
717     if (type == OVSDB_TYPE_STRING) {
718         ds_put_cstr(out, atom->string);
719     } else {
720         ovsdb_atom_to_string(atom, type, out);
721     }
722 }
723
724 static struct ovsdb_error *
725 check_string_constraints(const char *s,
726                          const struct ovsdb_string_constraints *c)
727 {
728     size_t n_chars;
729     char *msg;
730
731     msg = utf8_validate(s, &n_chars);
732     if (msg) {
733         struct ovsdb_error *error;
734
735         error = ovsdb_error("constraint violation",
736                             "not a valid UTF-8 string: %s", msg);
737         free(msg);
738         return error;
739     }
740
741     if (n_chars < c->minLen) {
742         return ovsdb_error(
743             "constraint violation",
744             "\"%s\" length %zu is less than minimum allowed "
745             "length %u", s, n_chars, c->minLen);
746     } else if (n_chars > c->maxLen) {
747         return ovsdb_error(
748             "constraint violation",
749             "\"%s\" length %zu is greater than maximum allowed "
750             "length %u", s, n_chars, c->maxLen);
751     }
752
753     return NULL;
754 }
755
756 /* Checks whether 'atom' meets the constraints (if any) defined in 'base'.
757  * (base->type must specify 'atom''s type.)  Returns a null pointer if the
758  * constraints are met, otherwise an error that explains the violation.
759  *
760  * Checking UUID constraints is deferred to transaction commit time, so this
761  * function does nothing for UUID constraints. */
762 struct ovsdb_error *
763 ovsdb_atom_check_constraints(const union ovsdb_atom *atom,
764                              const struct ovsdb_base_type *base)
765 {
766     if (base->enum_
767         && ovsdb_datum_find_key(base->enum_, atom, base->type) == UINT_MAX) {
768         struct ovsdb_error *error;
769         struct ds actual = DS_EMPTY_INITIALIZER;
770         struct ds valid = DS_EMPTY_INITIALIZER;
771
772         ovsdb_atom_to_string(atom, base->type, &actual);
773         ovsdb_datum_to_string(base->enum_,
774                               ovsdb_base_type_get_enum_type(base->type),
775                               &valid);
776         error = ovsdb_error("constraint violation",
777                             "%s is not one of the allowed values (%s)",
778                             ds_cstr(&actual), ds_cstr(&valid));
779         ds_destroy(&actual);
780         ds_destroy(&valid);
781
782         return error;
783     }
784
785     switch (base->type) {
786     case OVSDB_TYPE_VOID:
787         NOT_REACHED();
788
789     case OVSDB_TYPE_INTEGER:
790         if (atom->integer >= base->u.integer.min
791             && atom->integer <= base->u.integer.max) {
792             return NULL;
793         } else if (base->u.integer.min != INT64_MIN) {
794             if (base->u.integer.max != INT64_MAX) {
795                 return ovsdb_error("constraint violation",
796                                    "%"PRId64" is not in the valid range "
797                                    "%"PRId64" to %"PRId64" (inclusive)",
798                                    atom->integer,
799                                    base->u.integer.min, base->u.integer.max);
800             } else {
801                 return ovsdb_error("constraint violation",
802                                    "%"PRId64" is less than minimum allowed "
803                                    "value %"PRId64,
804                                    atom->integer, base->u.integer.min);
805             }
806         } else {
807             return ovsdb_error("constraint violation",
808                                "%"PRId64" is greater than maximum allowed "
809                                "value %"PRId64,
810                                atom->integer, base->u.integer.max);
811         }
812         NOT_REACHED();
813
814     case OVSDB_TYPE_REAL:
815         if (atom->real >= base->u.real.min && atom->real <= base->u.real.max) {
816             return NULL;
817         } else if (base->u.real.min != -DBL_MAX) {
818             if (base->u.real.max != DBL_MAX) {
819                 return ovsdb_error("constraint violation",
820                                    "%.*g is not in the valid range "
821                                    "%.*g to %.*g (inclusive)",
822                                    DBL_DIG, atom->real,
823                                    DBL_DIG, base->u.real.min,
824                                    DBL_DIG, base->u.real.max);
825             } else {
826                 return ovsdb_error("constraint violation",
827                                    "%.*g is less than minimum allowed "
828                                    "value %.*g",
829                                    DBL_DIG, atom->real,
830                                    DBL_DIG, base->u.real.min);
831             }
832         } else {
833             return ovsdb_error("constraint violation",
834                                "%.*g is greater than maximum allowed "
835                                "value %.*g",
836                                DBL_DIG, atom->real,
837                                DBL_DIG, base->u.real.max);
838         }
839         NOT_REACHED();
840
841     case OVSDB_TYPE_BOOLEAN:
842         return NULL;
843
844     case OVSDB_TYPE_STRING:
845         return check_string_constraints(atom->string, &base->u.string);
846
847     case OVSDB_TYPE_UUID:
848         return NULL;
849
850     case OVSDB_N_TYPES:
851     default:
852         NOT_REACHED();
853     }
854 }
855 \f
856 static union ovsdb_atom *
857 alloc_default_atoms(enum ovsdb_atomic_type type, size_t n)
858 {
859     if (type != OVSDB_TYPE_VOID && n) {
860         union ovsdb_atom *atoms;
861         unsigned int i;
862
863         atoms = xmalloc(n * sizeof *atoms);
864         for (i = 0; i < n; i++) {
865             ovsdb_atom_init_default(&atoms[i], type);
866         }
867         return atoms;
868     } else {
869         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
870          * treated as xmalloc(1). */
871         return NULL;
872     }
873 }
874
875 /* Initializes 'datum' as an empty datum.  (An empty datum can be treated as
876  * any type.) */
877 void
878 ovsdb_datum_init_empty(struct ovsdb_datum *datum)
879 {
880     datum->n = 0;
881     datum->keys = NULL;
882     datum->values = NULL;
883 }
884
885 /* Initializes 'datum' as a datum that has the default value for 'type'.
886  *
887  * The default value for a particular type is as defined in ovsdb/SPECS:
888  *
889  *    - If n_min is 0, then the default value is the empty set (or map).
890  *
891  *    - If n_min is 1, the default value is a single value or a single
892  *      key-value pair, whose key and value are the defaults for their
893  *      atomic types.  (See ovsdb_atom_init_default() for details.)
894  *
895  *    - n_min > 1 is invalid.  See ovsdb_type_is_valid().
896  */
897 void
898 ovsdb_datum_init_default(struct ovsdb_datum *datum,
899                          const struct ovsdb_type *type)
900 {
901     datum->n = type->n_min;
902     datum->keys = alloc_default_atoms(type->key.type, datum->n);
903     datum->values = alloc_default_atoms(type->value.type, datum->n);
904 }
905
906 /* Returns a read-only datum of the given 'type' that has the default value for
907  * 'type'.  The caller must not modify or free the returned datum.
908  *
909  * See ovsdb_datum_init_default() for an explanation of the default value of a
910  * datum. */
911 const struct ovsdb_datum *
912 ovsdb_datum_default(const struct ovsdb_type *type)
913 {
914     if (type->n_min == 0) {
915         static const struct ovsdb_datum empty;
916         return &empty;
917     } else if (type->n_min == 1) {
918         static struct ovsdb_datum default_data[OVSDB_N_TYPES][OVSDB_N_TYPES];
919         struct ovsdb_datum *d;
920         int kt = type->key.type;
921         int vt = type->value.type;
922
923         ovs_assert(ovsdb_type_is_valid(type));
924
925         d = &default_data[kt][vt];
926         if (!d->n) {
927             d->n = 1;
928             d->keys = CONST_CAST(union ovsdb_atom *, ovsdb_atom_default(kt));
929             if (vt != OVSDB_TYPE_VOID) {
930                 d->values = CONST_CAST(union ovsdb_atom *,
931                                        ovsdb_atom_default(vt));
932             }
933         }
934         return d;
935     } else {
936         NOT_REACHED();
937     }
938 }
939
940 /* Returns true if 'datum', which must have the given 'type', has the default
941  * value for that type.
942  *
943  * See ovsdb_datum_init_default() for an explanation of the default value of a
944  * datum. */
945 bool
946 ovsdb_datum_is_default(const struct ovsdb_datum *datum,
947                        const struct ovsdb_type *type)
948 {
949     size_t i;
950
951     if (datum->n != type->n_min) {
952         return false;
953     }
954     for (i = 0; i < datum->n; i++) {
955         if (!ovsdb_atom_is_default(&datum->keys[i], type->key.type)) {
956             return false;
957         }
958         if (type->value.type != OVSDB_TYPE_VOID
959             && !ovsdb_atom_is_default(&datum->values[i], type->value.type)) {
960             return false;
961         }
962     }
963
964     return true;
965 }
966
967 static union ovsdb_atom *
968 clone_atoms(const union ovsdb_atom *old, enum ovsdb_atomic_type type, size_t n)
969 {
970     if (type != OVSDB_TYPE_VOID && n) {
971         union ovsdb_atom *new;
972         unsigned int i;
973
974         new = xmalloc(n * sizeof *new);
975         for (i = 0; i < n; i++) {
976             ovsdb_atom_clone(&new[i], &old[i], type);
977         }
978         return new;
979     } else {
980         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
981          * treated as xmalloc(1). */
982         return NULL;
983     }
984 }
985
986 /* Initializes 'new' as a copy of 'old', with the given 'type'.
987  *
988  * The caller must eventually arrange for 'new' to be destroyed (with
989  * ovsdb_datum_destroy()). */
990 void
991 ovsdb_datum_clone(struct ovsdb_datum *new, const struct ovsdb_datum *old,
992                   const struct ovsdb_type *type)
993 {
994     unsigned int n = old->n;
995     new->n = n;
996     new->keys = clone_atoms(old->keys, type->key.type, n);
997     new->values = clone_atoms(old->values, type->value.type, n);
998 }
999
1000 static void
1001 free_data(enum ovsdb_atomic_type type,
1002           union ovsdb_atom *atoms, size_t n_atoms)
1003 {
1004     if (ovsdb_atom_needs_destruction(type)) {
1005         unsigned int i;
1006         for (i = 0; i < n_atoms; i++) {
1007             ovsdb_atom_destroy(&atoms[i], type);
1008         }
1009     }
1010     free(atoms);
1011 }
1012
1013 /* Frees the data owned by 'datum', which must have the given 'type'.
1014  *
1015  * This does not actually call free(datum).  If necessary, the caller must be
1016  * responsible for that. */
1017 void
1018 ovsdb_datum_destroy(struct ovsdb_datum *datum, const struct ovsdb_type *type)
1019 {
1020     free_data(type->key.type, datum->keys, datum->n);
1021     free_data(type->value.type, datum->values, datum->n);
1022 }
1023
1024 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
1025 void
1026 ovsdb_datum_swap(struct ovsdb_datum *a, struct ovsdb_datum *b)
1027 {
1028     struct ovsdb_datum tmp = *a;
1029     *a = *b;
1030     *b = tmp;
1031 }
1032
1033 struct ovsdb_datum_sort_cbdata {
1034     enum ovsdb_atomic_type key_type;
1035     enum ovsdb_atomic_type value_type;
1036     struct ovsdb_datum *datum;
1037 };
1038
1039 static int
1040 ovsdb_datum_sort_compare_cb(size_t a, size_t b, void *cbdata_)
1041 {
1042     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
1043     int retval;
1044
1045     retval = ovsdb_atom_compare_3way(&cbdata->datum->keys[a],
1046                                      &cbdata->datum->keys[b],
1047                                      cbdata->key_type);
1048     if (retval || cbdata->value_type == OVSDB_TYPE_VOID) {
1049         return retval;
1050     }
1051
1052     return ovsdb_atom_compare_3way(&cbdata->datum->values[a],
1053                                    &cbdata->datum->values[b],
1054                                    cbdata->value_type);
1055 }
1056
1057 static void
1058 ovsdb_datum_sort_swap_cb(size_t a, size_t b, void *cbdata_)
1059 {
1060     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
1061
1062     ovsdb_atom_swap(&cbdata->datum->keys[a], &cbdata->datum->keys[b]);
1063     if (cbdata->datum->values) {
1064         ovsdb_atom_swap(&cbdata->datum->values[a], &cbdata->datum->values[b]);
1065     }
1066 }
1067
1068 static void
1069 ovsdb_datum_sort__(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type,
1070                    enum ovsdb_atomic_type value_type)
1071 {
1072     struct ovsdb_datum_sort_cbdata cbdata;
1073
1074     cbdata.key_type = key_type;
1075     cbdata.value_type = value_type;
1076     cbdata.datum = datum;
1077     sort(datum->n, ovsdb_datum_sort_compare_cb, ovsdb_datum_sort_swap_cb,
1078          &cbdata);
1079 }
1080
1081 /* The keys in an ovsdb_datum must be unique and in sorted order.  Most
1082  * functions that modify an ovsdb_datum maintain these invariants.  For those
1083  * that don't, this function checks and restores these invariants for 'datum',
1084  * whose keys are of type 'key_type'.
1085  *
1086  * This function returns NULL if successful, otherwise an error message.  The
1087  * caller must free the returned error when it is no longer needed.  On error,
1088  * 'datum' is sorted but not unique. */
1089 struct ovsdb_error *
1090 ovsdb_datum_sort(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type)
1091 {
1092     size_t i;
1093
1094     if (datum->n < 2) {
1095         return NULL;
1096     }
1097
1098     ovsdb_datum_sort__(datum, key_type, OVSDB_TYPE_VOID);
1099
1100     for (i = 0; i < datum->n - 1; i++) {
1101         if (ovsdb_atom_equals(&datum->keys[i], &datum->keys[i + 1],
1102                               key_type)) {
1103             if (datum->values) {
1104                 return ovsdb_error(NULL, "map contains duplicate key");
1105             } else {
1106                 return ovsdb_error(NULL, "set contains duplicate");
1107             }
1108         }
1109     }
1110     return NULL;
1111 }
1112
1113 /* This function is the same as ovsdb_datum_sort(), except that the caller
1114  * knows that 'datum' is unique.  The operation therefore "cannot fail", so
1115  * this function assert-fails if it actually does. */
1116 void
1117 ovsdb_datum_sort_assert(struct ovsdb_datum *datum,
1118                         enum ovsdb_atomic_type key_type)
1119 {
1120     struct ovsdb_error *error = ovsdb_datum_sort(datum, key_type);
1121     if (error) {
1122         NOT_REACHED();
1123     }
1124 }
1125
1126 /* This is similar to ovsdb_datum_sort(), except that it drops duplicate keys
1127  * instead of reporting an error.  In a map type, the smallest value among a
1128  * group of duplicate pairs is retained and the others are dropped.
1129  *
1130  * Returns the number of keys (or pairs) that were dropped. */
1131 size_t
1132 ovsdb_datum_sort_unique(struct ovsdb_datum *datum,
1133                         enum ovsdb_atomic_type key_type,
1134                         enum ovsdb_atomic_type value_type)
1135 {
1136     size_t src, dst;
1137
1138     if (datum->n < 2) {
1139         return 0;
1140     }
1141
1142     ovsdb_datum_sort__(datum, key_type, value_type);
1143
1144     dst = 1;
1145     for (src = 1; src < datum->n; src++) {
1146         if (ovsdb_atom_equals(&datum->keys[src], &datum->keys[dst - 1],
1147                               key_type)) {
1148             ovsdb_atom_destroy(&datum->keys[src], key_type);
1149             if (value_type != OVSDB_TYPE_VOID) {
1150                 ovsdb_atom_destroy(&datum->values[src], value_type);
1151             }
1152         } else {
1153             if (src != dst) {
1154                 datum->keys[dst] = datum->keys[src];
1155                 if (value_type != OVSDB_TYPE_VOID) {
1156                     datum->values[dst] = datum->values[src];
1157                 }
1158             }
1159             dst++;
1160         }
1161     }
1162     datum->n = dst;
1163     return datum->n - src;
1164 }
1165
1166 /* Checks that each of the atoms in 'datum' conforms to the constraints
1167  * specified by its 'type'.  Returns an error if a constraint is violated,
1168  * otherwise a null pointer.
1169  *
1170  * This function is not commonly useful because the most ordinary way to obtain
1171  * a datum is ultimately via ovsdb_atom_from_string() or
1172  * ovsdb_atom_from_json(), which check constraints themselves. */
1173 struct ovsdb_error *
1174 ovsdb_datum_check_constraints(const struct ovsdb_datum *datum,
1175                               const struct ovsdb_type *type)
1176 {
1177     struct ovsdb_error *error;
1178     unsigned int i;
1179
1180     for (i = 0; i < datum->n; i++) {
1181         error = ovsdb_atom_check_constraints(&datum->keys[i], &type->key);
1182         if (error) {
1183             return error;
1184         }
1185     }
1186
1187     if (type->value.type != OVSDB_TYPE_VOID) {
1188         for (i = 0; i < datum->n; i++) {
1189             error = ovsdb_atom_check_constraints(&datum->values[i],
1190                                                  &type->value);
1191             if (error) {
1192                 return error;
1193             }
1194         }
1195     }
1196
1197     return NULL;
1198 }
1199
1200 static struct ovsdb_error *
1201 ovsdb_datum_from_json__(struct ovsdb_datum *datum,
1202                         const struct ovsdb_type *type,
1203                         const struct json *json,
1204                         struct ovsdb_symbol_table *symtab)
1205 {
1206     struct ovsdb_error *error;
1207
1208     if (ovsdb_type_is_map(type)
1209         || (json->type == JSON_ARRAY
1210             && json->u.array.n > 0
1211             && json->u.array.elems[0]->type == JSON_STRING
1212             && !strcmp(json->u.array.elems[0]->u.string, "set"))) {
1213         bool is_map = ovsdb_type_is_map(type);
1214         const char *class = is_map ? "map" : "set";
1215         const struct json *inner;
1216         unsigned int i;
1217         size_t n;
1218
1219         error = unwrap_json(json, class, JSON_ARRAY, &inner);
1220         if (error) {
1221             return error;
1222         }
1223
1224         n = inner->u.array.n;
1225         if (n < type->n_min || n > type->n_max) {
1226             return ovsdb_syntax_error(json, NULL, "%s must have %u to "
1227                                       "%u members but %zu are present",
1228                                       class, type->n_min, type->n_max, n);
1229         }
1230
1231         datum->n = 0;
1232         datum->keys = xmalloc(n * sizeof *datum->keys);
1233         datum->values = is_map ? xmalloc(n * sizeof *datum->values) : NULL;
1234         for (i = 0; i < n; i++) {
1235             const struct json *element = inner->u.array.elems[i];
1236             const struct json *key = NULL;
1237             const struct json *value = NULL;
1238
1239             if (!is_map) {
1240                 key = element;
1241             } else {
1242                 error = parse_json_pair(element, &key, &value);
1243                 if (error) {
1244                     goto error;
1245                 }
1246             }
1247
1248             error = ovsdb_atom_from_json(&datum->keys[i], &type->key,
1249                                          key, symtab);
1250             if (error) {
1251                 goto error;
1252             }
1253
1254             if (is_map) {
1255                 error = ovsdb_atom_from_json(&datum->values[i],
1256                                              &type->value, value, symtab);
1257                 if (error) {
1258                     ovsdb_atom_destroy(&datum->keys[i], type->key.type);
1259                     goto error;
1260                 }
1261             }
1262
1263             datum->n++;
1264         }
1265         return NULL;
1266
1267     error:
1268         ovsdb_datum_destroy(datum, type);
1269         return error;
1270     } else {
1271         datum->n = 1;
1272         datum->keys = xmalloc(sizeof *datum->keys);
1273         datum->values = NULL;
1274
1275         error = ovsdb_atom_from_json(&datum->keys[0], &type->key,
1276                                      json, symtab);
1277         if (error) {
1278             free(datum->keys);
1279         }
1280         return error;
1281     }
1282 }
1283
1284 /* Parses 'json' as a datum of the type described by 'type'.  If successful,
1285  * returns NULL and initializes 'datum' with the parsed datum.  On failure,
1286  * returns an error and the contents of 'datum' are indeterminate.  The caller
1287  * is responsible for freeing the error or the datum that is returned.
1288  *
1289  * Violations of constraints expressed by 'type' are treated as errors.
1290  *
1291  * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
1292  * ovsdb/SPECS for information about this, and for the syntax that this
1293  * function accepts. */
1294 struct ovsdb_error *
1295 ovsdb_datum_from_json(struct ovsdb_datum *datum,
1296                       const struct ovsdb_type *type,
1297                       const struct json *json,
1298                       struct ovsdb_symbol_table *symtab)
1299 {
1300     struct ovsdb_error *error;
1301
1302     error = ovsdb_datum_from_json__(datum, type, json, symtab);
1303     if (error) {
1304         return error;
1305     }
1306
1307     error = ovsdb_datum_sort(datum, type->key.type);
1308     if (error) {
1309         ovsdb_datum_destroy(datum, type);
1310     }
1311     return error;
1312 }
1313
1314 /* Converts 'datum', of the specified 'type', to JSON format, and returns the
1315  * JSON.  The caller is responsible for freeing the returned JSON.
1316  *
1317  * 'type' constraints on datum->n are ignored.
1318  *
1319  * Refer to ovsdb/SPECS for the format of the JSON that this function
1320  * produces. */
1321 struct json *
1322 ovsdb_datum_to_json(const struct ovsdb_datum *datum,
1323                     const struct ovsdb_type *type)
1324 {
1325     if (ovsdb_type_is_map(type)) {
1326         struct json **elems;
1327         size_t i;
1328
1329         elems = xmalloc(datum->n * sizeof *elems);
1330         for (i = 0; i < datum->n; i++) {
1331             elems[i] = json_array_create_2(
1332                 ovsdb_atom_to_json(&datum->keys[i], type->key.type),
1333                 ovsdb_atom_to_json(&datum->values[i], type->value.type));
1334         }
1335
1336         return wrap_json("map", json_array_create(elems, datum->n));
1337     } else if (datum->n == 1) {
1338         return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
1339     } else {
1340         struct json **elems;
1341         size_t i;
1342
1343         elems = xmalloc(datum->n * sizeof *elems);
1344         for (i = 0; i < datum->n; i++) {
1345             elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
1346         }
1347
1348         return wrap_json("set", json_array_create(elems, datum->n));
1349     }
1350 }
1351
1352 /* Returns strlen(json_to_string(ovsdb_datum_to_json(datum, type), 0)). */
1353 size_t
1354 ovsdb_datum_json_length(const struct ovsdb_datum *datum,
1355                         const struct ovsdb_type *type)
1356 {
1357     if (ovsdb_type_is_map(type)) {
1358         size_t length;
1359
1360         /* ["map",[...]]. */
1361         length = 10;
1362         if (datum->n > 0) {
1363             size_t i;
1364
1365             /* Commas between pairs in the inner [...] */
1366             length += datum->n - 1;
1367
1368             /* [,] in each pair. */
1369             length += datum->n * 3;
1370
1371             /* Data. */
1372             for (i = 0; i < datum->n; i++) {
1373                 length += ovsdb_atom_json_length(&datum->keys[i],
1374                                                  type->key.type);
1375                 length += ovsdb_atom_json_length(&datum->values[i],
1376                                                  type->value.type);
1377             }
1378         }
1379         return length;
1380     } else if (datum->n == 1) {
1381         return ovsdb_atom_json_length(&datum->keys[0], type->key.type);
1382     } else {
1383         size_t length;
1384         size_t i;
1385
1386         /* ["set",[...]]. */
1387         length = 10;
1388         if (datum->n > 0) {
1389             /* Commas between elements in the inner [...]. */
1390             length += datum->n - 1;
1391
1392             /* Data. */
1393             for (i = 0; i < datum->n; i++) {
1394                 length += ovsdb_atom_json_length(&datum->keys[i],
1395                                                  type->key.type);
1396             }
1397         }
1398         return length;
1399     }
1400 }
1401
1402 static const char *
1403 skip_spaces(const char *p)
1404 {
1405     while (isspace((unsigned char) *p)) {
1406         p++;
1407     }
1408     return p;
1409 }
1410
1411 static char *
1412 parse_atom_token(const char **s, const struct ovsdb_base_type *base,
1413                  union ovsdb_atom *atom, struct ovsdb_symbol_table *symtab)
1414 {
1415     char *token, *error;
1416
1417     error = ovsdb_token_parse(s, &token);
1418     if (!error) {
1419         error = ovsdb_atom_from_string(atom, base, token, symtab);
1420         free(token);
1421     }
1422     return error;
1423 }
1424
1425 static char *
1426 parse_key_value(const char **s, const struct ovsdb_type *type,
1427                 union ovsdb_atom *key, union ovsdb_atom *value,
1428                 struct ovsdb_symbol_table *symtab)
1429 {
1430     const char *start = *s;
1431     char *error;
1432
1433     error = parse_atom_token(s, &type->key, key, symtab);
1434     if (!error && type->value.type != OVSDB_TYPE_VOID) {
1435         *s = skip_spaces(*s);
1436         if (**s == '=') {
1437             (*s)++;
1438             *s = skip_spaces(*s);
1439             error = parse_atom_token(s, &type->value, value, symtab);
1440         } else {
1441             error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
1442                               start, **s);
1443         }
1444         if (error) {
1445             ovsdb_atom_destroy(key, type->key.type);
1446         }
1447     }
1448     return error;
1449 }
1450
1451 static void
1452 free_key_value(const struct ovsdb_type *type,
1453                union ovsdb_atom *key, union ovsdb_atom *value)
1454 {
1455     ovsdb_atom_destroy(key, type->key.type);
1456     if (type->value.type != OVSDB_TYPE_VOID) {
1457         ovsdb_atom_destroy(value, type->value.type);
1458     }
1459 }
1460
1461 /* Initializes 'datum' as a datum of the given 'type', parsing its contents
1462  * from 's'.  The format of 's' is a series of space or comma separated atoms
1463  * or, for a map, '='-delimited pairs of atoms.  Each atom must in a format
1464  * acceptable to ovsdb_atom_from_string().  Optionally, a set may be enclosed
1465  * in "[]" or a map in "{}"; for an empty set or map these punctuators are
1466  * required.
1467  *
1468  * Optionally, a symbol table may be supplied as 'symtab'.  It is passed to
1469  * ovsdb_atom_to_string(). */
1470 char *
1471 ovsdb_datum_from_string(struct ovsdb_datum *datum,
1472                         const struct ovsdb_type *type, const char *s,
1473                         struct ovsdb_symbol_table *symtab)
1474 {
1475     bool is_map = ovsdb_type_is_map(type);
1476     struct ovsdb_error *dberror;
1477     const char *p;
1478     int end_delim;
1479     char *error;
1480
1481     ovsdb_datum_init_empty(datum);
1482
1483     /* Swallow a leading delimiter if there is one. */
1484     p = skip_spaces(s);
1485     if (*p == (is_map ? '{' : '[')) {
1486         end_delim = is_map ? '}' : ']';
1487         p = skip_spaces(p + 1);
1488     } else if (!*p) {
1489         if (is_map) {
1490             return xstrdup("use \"{}\" to specify the empty map");
1491         } else {
1492             return xstrdup("use \"[]\" to specify the empty set");
1493         }
1494     } else {
1495         end_delim = 0;
1496     }
1497
1498     while (*p && *p != end_delim) {
1499         union ovsdb_atom key, value;
1500
1501         if (ovsdb_token_is_delim(*p)) {
1502             char *type_str = ovsdb_type_to_english(type);
1503             error = xasprintf("%s: unexpected \"%c\" parsing %s",
1504                               s, *p, type_str);
1505             free(type_str);
1506             goto error;
1507         }
1508
1509         /* Add to datum. */
1510         error = parse_key_value(&p, type, &key, &value, symtab);
1511         if (error) {
1512             goto error;
1513         }
1514         ovsdb_datum_add_unsafe(datum, &key, &value, type);
1515         free_key_value(type, &key, &value);
1516
1517         /* Skip optional white space and comma. */
1518         p = skip_spaces(p);
1519         if (*p == ',') {
1520             p = skip_spaces(p + 1);
1521         }
1522     }
1523
1524     if (*p != end_delim) {
1525         error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
1526         goto error;
1527     }
1528     if (end_delim) {
1529         p = skip_spaces(p + 1);
1530         if (*p) {
1531             error = xasprintf("%s: trailing garbage after \"%c\"",
1532                               s, end_delim);
1533             goto error;
1534         }
1535     }
1536
1537     if (datum->n < type->n_min) {
1538         error = xasprintf("%s: %u %s specified but the minimum number is %u",
1539                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1540                           type->n_min);
1541         goto error;
1542     } else if (datum->n > type->n_max) {
1543         error = xasprintf("%s: %u %s specified but the maximum number is %u",
1544                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1545             type->n_max);
1546         goto error;
1547     }
1548
1549     dberror = ovsdb_datum_sort(datum, type->key.type);
1550     if (dberror) {
1551         ovsdb_error_destroy(dberror);
1552         if (ovsdb_type_is_map(type)) {
1553             error = xasprintf("%s: map contains duplicate key", s);
1554         } else {
1555             error = xasprintf("%s: set contains duplicate value", s);
1556         }
1557         goto error;
1558     }
1559
1560     return NULL;
1561
1562 error:
1563     ovsdb_datum_destroy(datum, type);
1564     ovsdb_datum_init_empty(datum);
1565     return error;
1566 }
1567
1568 /* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
1569  * to ovsdb_datum_from_string(). */
1570 void
1571 ovsdb_datum_to_string(const struct ovsdb_datum *datum,
1572                       const struct ovsdb_type *type, struct ds *out)
1573 {
1574     bool is_map = ovsdb_type_is_map(type);
1575     size_t i;
1576
1577     if (type->n_max > 1 || !datum->n) {
1578         ds_put_char(out, is_map ? '{' : '[');
1579     }
1580     for (i = 0; i < datum->n; i++) {
1581         if (i > 0) {
1582             ds_put_cstr(out, ", ");
1583         }
1584
1585         ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
1586         if (is_map) {
1587             ds_put_char(out, '=');
1588             ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
1589         }
1590     }
1591     if (type->n_max > 1 || !datum->n) {
1592         ds_put_char(out, is_map ? '}' : ']');
1593     }
1594 }
1595
1596 /* Appends to 'out' the 'datum' (with the given 'type') in a bare string format
1597  * that cannot be parsed uniformly back into a datum but is easier for shell
1598  * scripts, etc., to deal with. */
1599 void
1600 ovsdb_datum_to_bare(const struct ovsdb_datum *datum,
1601                     const struct ovsdb_type *type, struct ds *out)
1602 {
1603     bool is_map = ovsdb_type_is_map(type);
1604     size_t i;
1605
1606     for (i = 0; i < datum->n; i++) {
1607         if (i > 0) {
1608             ds_put_cstr(out, " ");
1609         }
1610
1611         ovsdb_atom_to_bare(&datum->keys[i], type->key.type, out);
1612         if (is_map) {
1613             ds_put_char(out, '=');
1614             ovsdb_atom_to_bare(&datum->values[i], type->value.type, out);
1615         }
1616     }
1617 }
1618
1619 /* Initializes 'datum' as a string-to-string map whose contents are taken from
1620  * 'smap'.  Destroys 'smap'. */
1621 void
1622 ovsdb_datum_from_smap(struct ovsdb_datum *datum, struct smap *smap)
1623 {
1624     struct smap_node *node, *next;
1625     size_t i;
1626
1627     datum->n = smap_count(smap);
1628     datum->keys = xmalloc(datum->n * sizeof *datum->keys);
1629     datum->values = xmalloc(datum->n * sizeof *datum->values);
1630
1631     i = 0;
1632     SMAP_FOR_EACH_SAFE (node, next, smap) {
1633         smap_steal(smap, node,
1634                    &datum->keys[i].string, &datum->values[i].string);
1635         i++;
1636     }
1637     ovs_assert(i == datum->n);
1638
1639     smap_destroy(smap);
1640     ovsdb_datum_sort_unique(datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
1641 }
1642
1643 static uint32_t
1644 hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
1645            unsigned int n, uint32_t basis)
1646 {
1647     if (type != OVSDB_TYPE_VOID) {
1648         unsigned int i;
1649
1650         for (i = 0; i < n; i++) {
1651             basis = ovsdb_atom_hash(&atoms[i], type, basis);
1652         }
1653     }
1654     return basis;
1655 }
1656
1657 uint32_t
1658 ovsdb_datum_hash(const struct ovsdb_datum *datum,
1659                  const struct ovsdb_type *type, uint32_t basis)
1660 {
1661     basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
1662     basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
1663     basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
1664     return basis;
1665 }
1666
1667 static int
1668 atom_arrays_compare_3way(const union ovsdb_atom *a,
1669                          const union ovsdb_atom *b,
1670                          enum ovsdb_atomic_type type,
1671                          size_t n)
1672 {
1673     unsigned int i;
1674
1675     for (i = 0; i < n; i++) {
1676         int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
1677         if (cmp) {
1678             return cmp;
1679         }
1680     }
1681
1682     return 0;
1683 }
1684
1685 bool
1686 ovsdb_datum_equals(const struct ovsdb_datum *a,
1687                    const struct ovsdb_datum *b,
1688                    const struct ovsdb_type *type)
1689 {
1690     return !ovsdb_datum_compare_3way(a, b, type);
1691 }
1692
1693 int
1694 ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
1695                          const struct ovsdb_datum *b,
1696                          const struct ovsdb_type *type)
1697 {
1698     int cmp;
1699
1700     if (a->n != b->n) {
1701         return a->n < b->n ? -1 : 1;
1702     }
1703
1704     cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
1705     if (cmp) {
1706         return cmp;
1707     }
1708
1709     return (type->value.type == OVSDB_TYPE_VOID ? 0
1710             : atom_arrays_compare_3way(a->values, b->values, type->value.type,
1711                                        a->n));
1712 }
1713
1714 /* If 'key' is one of the keys in 'datum', returns its index within 'datum',
1715  * otherwise UINT_MAX.  'key.type' must be the type of the atoms stored in the
1716  * 'keys' array in 'datum'.
1717  */
1718 unsigned int
1719 ovsdb_datum_find_key(const struct ovsdb_datum *datum,
1720                      const union ovsdb_atom *key,
1721                      enum ovsdb_atomic_type key_type)
1722 {
1723     unsigned int low = 0;
1724     unsigned int high = datum->n;
1725     while (low < high) {
1726         unsigned int idx = (low + high) / 2;
1727         int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
1728         if (cmp < 0) {
1729             high = idx;
1730         } else if (cmp > 0) {
1731             low = idx + 1;
1732         } else {
1733             return idx;
1734         }
1735     }
1736     return UINT_MAX;
1737 }
1738
1739 /* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
1740  * index within 'datum', otherwise UINT_MAX.  'key.type' must be the type of
1741  * the atoms stored in the 'keys' array in 'datum'.  'value_type' may be the
1742  * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
1743  */
1744 unsigned int
1745 ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
1746                            const union ovsdb_atom *key,
1747                            enum ovsdb_atomic_type key_type,
1748                            const union ovsdb_atom *value,
1749                            enum ovsdb_atomic_type value_type)
1750 {
1751     unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
1752     if (idx != UINT_MAX
1753         && value_type != OVSDB_TYPE_VOID
1754         && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
1755         idx = UINT_MAX;
1756     }
1757     return idx;
1758 }
1759
1760 /* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
1761  * UINT_MAX.  'type' must be the type of 'a' and 'b', except that
1762  * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
1763  * values. */
1764 static unsigned int
1765 ovsdb_datum_find(const struct ovsdb_datum *a, int i,
1766                  const struct ovsdb_datum *b,
1767                  const struct ovsdb_type *type)
1768 {
1769     return ovsdb_datum_find_key_value(b,
1770                                       &a->keys[i], type->key.type,
1771                                       a->values ? &a->values[i] : NULL,
1772                                       type->value.type);
1773 }
1774
1775 /* Returns true if every element in 'a' is also in 'b', false otherwise. */
1776 bool
1777 ovsdb_datum_includes_all(const struct ovsdb_datum *a,
1778                          const struct ovsdb_datum *b,
1779                          const struct ovsdb_type *type)
1780 {
1781     size_t i;
1782
1783     if (a->n > b->n) {
1784         return false;
1785     }
1786     for (i = 0; i < a->n; i++) {
1787         if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
1788             return false;
1789         }
1790     }
1791     return true;
1792 }
1793
1794 /* Returns true if no element in 'a' is also in 'b', false otherwise. */
1795 bool
1796 ovsdb_datum_excludes_all(const struct ovsdb_datum *a,
1797                          const struct ovsdb_datum *b,
1798                          const struct ovsdb_type *type)
1799 {
1800     size_t i;
1801
1802     for (i = 0; i < a->n; i++) {
1803         if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
1804             return false;
1805         }
1806     }
1807     return true;
1808 }
1809
1810 static void
1811 ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
1812                        unsigned int capacity)
1813 {
1814     a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
1815     if (type->value.type != OVSDB_TYPE_VOID) {
1816         a->values = xrealloc(a->values, capacity * sizeof *a->values);
1817     }
1818 }
1819
1820 /* Removes the element with index 'idx' from 'datum', which has type 'type'.
1821  * If 'idx' is not the last element in 'datum', then the removed element is
1822  * replaced by the (former) last element.
1823  *
1824  * This function does not maintain ovsdb_datum invariants.  Use
1825  * ovsdb_datum_sort() to check and restore these invariants. */
1826 void
1827 ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
1828                           const struct ovsdb_type *type)
1829 {
1830     ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
1831     datum->keys[idx] = datum->keys[datum->n - 1];
1832     if (type->value.type != OVSDB_TYPE_VOID) {
1833         ovsdb_atom_destroy(&datum->values[idx], type->value.type);
1834         datum->values[idx] = datum->values[datum->n - 1];
1835     }
1836     datum->n--;
1837 }
1838
1839 /* Adds the element with the given 'key' and 'value' to 'datum', which must
1840  * have the specified 'type'.
1841  *
1842  * This function always allocates memory, so it is not an efficient way to add
1843  * a number of elements to a datum.
1844  *
1845  * This function does not maintain ovsdb_datum invariants.  Use
1846  * ovsdb_datum_sort() to check and restore these invariants.  (But a datum with
1847  * 0 or 1 elements cannot violate the invariants anyhow.) */
1848 void
1849 ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
1850                        const union ovsdb_atom *key,
1851                        const union ovsdb_atom *value,
1852                        const struct ovsdb_type *type)
1853 {
1854     size_t idx = datum->n++;
1855     datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
1856     ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
1857     if (type->value.type != OVSDB_TYPE_VOID) {
1858         datum->values = xrealloc(datum->values,
1859                                  datum->n * sizeof *datum->values);
1860         ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
1861     }
1862 }
1863
1864 void
1865 ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
1866                   const struct ovsdb_type *type, bool replace)
1867 {
1868     unsigned int n;
1869     size_t bi;
1870
1871     n = a->n;
1872     for (bi = 0; bi < b->n; bi++) {
1873         unsigned int ai;
1874
1875         ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
1876         if (ai == UINT_MAX) {
1877             if (n == a->n) {
1878                 ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
1879             }
1880             ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
1881             if (type->value.type != OVSDB_TYPE_VOID) {
1882                 ovsdb_atom_clone(&a->values[n], &b->values[bi],
1883                                  type->value.type);
1884             }
1885             n++;
1886         } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
1887             ovsdb_atom_destroy(&a->values[ai], type->value.type);
1888             ovsdb_atom_clone(&a->values[ai], &b->values[bi],
1889                              type->value.type);
1890         }
1891     }
1892     if (n != a->n) {
1893         struct ovsdb_error *error;
1894         a->n = n;
1895         error = ovsdb_datum_sort(a, type->key.type);
1896         ovs_assert(!error);
1897     }
1898 }
1899
1900 void
1901 ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
1902                      const struct ovsdb_datum *b,
1903                      const struct ovsdb_type *b_type)
1904 {
1905     bool changed = false;
1906     size_t i;
1907
1908     ovs_assert(a_type->key.type == b_type->key.type);
1909     ovs_assert(a_type->value.type == b_type->value.type
1910                || b_type->value.type == OVSDB_TYPE_VOID);
1911
1912     /* XXX The big-O of this could easily be improved. */
1913     for (i = 0; i < a->n; ) {
1914         unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
1915         if (idx != UINT_MAX) {
1916             changed = true;
1917             ovsdb_datum_remove_unsafe(a, i, a_type);
1918         } else {
1919             i++;
1920         }
1921     }
1922     if (changed) {
1923         ovsdb_datum_sort_assert(a, a_type->key.type);
1924     }
1925 }
1926 \f
1927 struct ovsdb_symbol_table *
1928 ovsdb_symbol_table_create(void)
1929 {
1930     struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
1931     shash_init(&symtab->sh);
1932     return symtab;
1933 }
1934
1935 void
1936 ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
1937 {
1938     if (symtab) {
1939         shash_destroy_free_data(&symtab->sh);
1940         free(symtab);
1941     }
1942 }
1943
1944 struct ovsdb_symbol *
1945 ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
1946                        const char *name)
1947 {
1948     return shash_find_data(&symtab->sh, name);
1949 }
1950
1951 struct ovsdb_symbol *
1952 ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
1953                        const struct uuid *uuid, bool created)
1954 {
1955     struct ovsdb_symbol *symbol;
1956
1957     ovs_assert(!ovsdb_symbol_table_get(symtab, name));
1958     symbol = xmalloc(sizeof *symbol);
1959     symbol->uuid = *uuid;
1960     symbol->created = created;
1961     symbol->strong_ref = false;
1962     symbol->weak_ref = false;
1963     shash_add(&symtab->sh, name, symbol);
1964     return symbol;
1965 }
1966
1967 struct ovsdb_symbol *
1968 ovsdb_symbol_table_insert(struct ovsdb_symbol_table *symtab,
1969                           const char *name)
1970 {
1971     struct ovsdb_symbol *symbol;
1972
1973     symbol = ovsdb_symbol_table_get(symtab, name);
1974     if (!symbol) {
1975         struct uuid uuid;
1976
1977         uuid_generate(&uuid);
1978         symbol = ovsdb_symbol_table_put(symtab, name, &uuid, false);
1979     }
1980     return symbol;
1981 }
1982 \f
1983 /* Extracts a token from the beginning of 's' and returns a pointer just after
1984  * the token.  Stores the token itself into '*outp', which the caller is
1985  * responsible for freeing (with free()).
1986  *
1987  * If 's[0]' is a delimiter, the returned token is the empty string.
1988  *
1989  * A token extends from 's' to the first delimiter, as defined by
1990  * ovsdb_token_is_delim(), or until the end of the string.  A delimiter can be
1991  * escaped with a backslash, in which case the backslash does not appear in the
1992  * output.  Double quotes also cause delimiters to be ignored, but the double
1993  * quotes are retained in the output.  (Backslashes inside double quotes are
1994  * not removed, either.)
1995  */
1996 char *
1997 ovsdb_token_parse(const char **s, char **outp)
1998 {
1999     const char *p;
2000     struct ds out;
2001     bool in_quotes;
2002     char *error;
2003
2004     ds_init(&out);
2005     in_quotes = false;
2006     for (p = *s; *p != '\0'; ) {
2007         int c = *p++;
2008         if (c == '\\') {
2009             if (in_quotes) {
2010                 ds_put_char(&out, '\\');
2011             }
2012             if (!*p) {
2013                 error = xasprintf("%s: backslash at end of argument", *s);
2014                 goto error;
2015             }
2016             ds_put_char(&out, *p++);
2017         } else if (!in_quotes && ovsdb_token_is_delim(c)) {
2018             p--;
2019             break;
2020         } else {
2021             ds_put_char(&out, c);
2022             if (c == '"') {
2023                 in_quotes = !in_quotes;
2024             }
2025         }
2026     }
2027     if (in_quotes) {
2028         error = xasprintf("%s: quoted string extends past end of argument",
2029                           *s);
2030         goto error;
2031     }
2032     *outp = ds_cstr(&out);
2033     *s = p;
2034     return NULL;
2035
2036 error:
2037     ds_destroy(&out);
2038     *outp = NULL;
2039     return error;
2040 }
2041
2042 /* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
2043 bool
2044 ovsdb_token_is_delim(unsigned char c)
2045 {
2046     return strchr(":=, []{}!<>", c) != NULL;
2047 }