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