Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.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 * 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         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 /* Converts 'datum', of the specified 'type', to JSON format, and returns the
1272  * JSON.  The caller is responsible for freeing the returned JSON.
1273  *
1274  * 'type' constraints on datum->n are ignored.
1275  *
1276  * Refer to RFC 7047 for the format of the JSON that this function produces. */
1277 struct json *
1278 ovsdb_datum_to_json(const struct ovsdb_datum *datum,
1279                     const struct ovsdb_type *type)
1280 {
1281     if (ovsdb_type_is_map(type)) {
1282         struct json **elems;
1283         size_t i;
1284
1285         elems = xmalloc(datum->n * sizeof *elems);
1286         for (i = 0; i < datum->n; i++) {
1287             elems[i] = json_array_create_2(
1288                 ovsdb_atom_to_json(&datum->keys[i], type->key.type),
1289                 ovsdb_atom_to_json(&datum->values[i], type->value.type));
1290         }
1291
1292         return wrap_json("map", json_array_create(elems, datum->n));
1293     } else if (datum->n == 1) {
1294         return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
1295     } else {
1296         struct json **elems;
1297         size_t i;
1298
1299         elems = xmalloc(datum->n * sizeof *elems);
1300         for (i = 0; i < datum->n; i++) {
1301             elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
1302         }
1303
1304         return wrap_json("set", json_array_create(elems, datum->n));
1305     }
1306 }
1307
1308 static const char *
1309 skip_spaces(const char *p)
1310 {
1311     while (isspace((unsigned char) *p)) {
1312         p++;
1313     }
1314     return p;
1315 }
1316
1317 static char *
1318 parse_atom_token(const char **s, const struct ovsdb_base_type *base,
1319                  union ovsdb_atom *atom, struct ovsdb_symbol_table *symtab)
1320 {
1321     char *token, *error;
1322
1323     error = ovsdb_token_parse(s, &token);
1324     if (!error) {
1325         error = ovsdb_atom_from_string(atom, base, token, symtab);
1326         free(token);
1327     }
1328     return error;
1329 }
1330
1331 static char *
1332 parse_key_value(const char **s, const struct ovsdb_type *type,
1333                 union ovsdb_atom *key, union ovsdb_atom *value,
1334                 struct ovsdb_symbol_table *symtab)
1335 {
1336     const char *start = *s;
1337     char *error;
1338
1339     error = parse_atom_token(s, &type->key, key, symtab);
1340     if (!error && type->value.type != OVSDB_TYPE_VOID) {
1341         *s = skip_spaces(*s);
1342         if (**s == '=') {
1343             (*s)++;
1344             *s = skip_spaces(*s);
1345             error = parse_atom_token(s, &type->value, value, symtab);
1346         } else {
1347             error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
1348                               start, **s);
1349         }
1350         if (error) {
1351             ovsdb_atom_destroy(key, type->key.type);
1352         }
1353     }
1354     return error;
1355 }
1356
1357 static void
1358 free_key_value(const struct ovsdb_type *type,
1359                union ovsdb_atom *key, union ovsdb_atom *value)
1360 {
1361     ovsdb_atom_destroy(key, type->key.type);
1362     if (type->value.type != OVSDB_TYPE_VOID) {
1363         ovsdb_atom_destroy(value, type->value.type);
1364     }
1365 }
1366
1367 /* Initializes 'datum' as a datum of the given 'type', parsing its contents
1368  * from 's'.  The format of 's' is a series of space or comma separated atoms
1369  * or, for a map, '='-delimited pairs of atoms.  Each atom must in a format
1370  * acceptable to ovsdb_atom_from_string().  Optionally, a set may be enclosed
1371  * in "[]" or a map in "{}"; for an empty set or map these punctuators are
1372  * required.
1373  *
1374  * Optionally, a symbol table may be supplied as 'symtab'.  It is passed to
1375  * ovsdb_atom_to_string(). */
1376 char *
1377 ovsdb_datum_from_string(struct ovsdb_datum *datum,
1378                         const struct ovsdb_type *type, const char *s,
1379                         struct ovsdb_symbol_table *symtab)
1380 {
1381     bool is_map = ovsdb_type_is_map(type);
1382     struct ovsdb_error *dberror;
1383     const char *p;
1384     int end_delim;
1385     char *error;
1386
1387     ovsdb_datum_init_empty(datum);
1388
1389     /* Swallow a leading delimiter if there is one. */
1390     p = skip_spaces(s);
1391     if (*p == (is_map ? '{' : '[')) {
1392         end_delim = is_map ? '}' : ']';
1393         p = skip_spaces(p + 1);
1394     } else if (!*p) {
1395         if (is_map) {
1396             return xstrdup("use \"{}\" to specify the empty map");
1397         } else {
1398             return xstrdup("use \"[]\" to specify the empty set");
1399         }
1400     } else {
1401         end_delim = 0;
1402     }
1403
1404     while (*p && *p != end_delim) {
1405         union ovsdb_atom key, value;
1406
1407         if (ovsdb_token_is_delim(*p)) {
1408             char *type_str = ovsdb_type_to_english(type);
1409             error = xasprintf("%s: unexpected \"%c\" parsing %s",
1410                               s, *p, type_str);
1411             free(type_str);
1412             goto error;
1413         }
1414
1415         /* Add to datum. */
1416         error = parse_key_value(&p, type, &key, &value, symtab);
1417         if (error) {
1418             goto error;
1419         }
1420         ovsdb_datum_add_unsafe(datum, &key, &value, type);
1421         free_key_value(type, &key, &value);
1422
1423         /* Skip optional white space and comma. */
1424         p = skip_spaces(p);
1425         if (*p == ',') {
1426             p = skip_spaces(p + 1);
1427         }
1428     }
1429
1430     if (*p != end_delim) {
1431         error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
1432         goto error;
1433     }
1434     if (end_delim) {
1435         p = skip_spaces(p + 1);
1436         if (*p) {
1437             error = xasprintf("%s: trailing garbage after \"%c\"",
1438                               s, end_delim);
1439             goto error;
1440         }
1441     }
1442
1443     if (datum->n < type->n_min) {
1444         error = xasprintf("%s: %u %s specified but the minimum number is %u",
1445                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1446                           type->n_min);
1447         goto error;
1448     } else if (datum->n > type->n_max) {
1449         error = xasprintf("%s: %u %s specified but the maximum number is %u",
1450                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1451             type->n_max);
1452         goto error;
1453     }
1454
1455     dberror = ovsdb_datum_sort(datum, type->key.type);
1456     if (dberror) {
1457         ovsdb_error_destroy(dberror);
1458         if (ovsdb_type_is_map(type)) {
1459             error = xasprintf("%s: map contains duplicate key", s);
1460         } else {
1461             error = xasprintf("%s: set contains duplicate value", s);
1462         }
1463         goto error;
1464     }
1465
1466     return NULL;
1467
1468 error:
1469     ovsdb_datum_destroy(datum, type);
1470     ovsdb_datum_init_empty(datum);
1471     return error;
1472 }
1473
1474 /* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
1475  * to ovsdb_datum_from_string(). */
1476 void
1477 ovsdb_datum_to_string(const struct ovsdb_datum *datum,
1478                       const struct ovsdb_type *type, struct ds *out)
1479 {
1480     bool is_map = ovsdb_type_is_map(type);
1481     size_t i;
1482
1483     if (type->n_max > 1 || !datum->n) {
1484         ds_put_char(out, is_map ? '{' : '[');
1485     }
1486     for (i = 0; i < datum->n; i++) {
1487         if (i > 0) {
1488             ds_put_cstr(out, ", ");
1489         }
1490
1491         ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
1492         if (is_map) {
1493             ds_put_char(out, '=');
1494             ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
1495         }
1496     }
1497     if (type->n_max > 1 || !datum->n) {
1498         ds_put_char(out, is_map ? '}' : ']');
1499     }
1500 }
1501
1502 /* Appends to 'out' the 'datum' (with the given 'type') in a bare string format
1503  * that cannot be parsed uniformly back into a datum but is easier for shell
1504  * scripts, etc., to deal with. */
1505 void
1506 ovsdb_datum_to_bare(const struct ovsdb_datum *datum,
1507                     const struct ovsdb_type *type, struct ds *out)
1508 {
1509     bool is_map = ovsdb_type_is_map(type);
1510     size_t i;
1511
1512     for (i = 0; i < datum->n; i++) {
1513         if (i > 0) {
1514             ds_put_cstr(out, " ");
1515         }
1516
1517         ovsdb_atom_to_bare(&datum->keys[i], type->key.type, out);
1518         if (is_map) {
1519             ds_put_char(out, '=');
1520             ovsdb_atom_to_bare(&datum->values[i], type->value.type, out);
1521         }
1522     }
1523 }
1524
1525 /* Initializes 'datum' as a string-to-string map whose contents are taken from
1526  * 'smap'.  Destroys 'smap'. */
1527 void
1528 ovsdb_datum_from_smap(struct ovsdb_datum *datum, struct smap *smap)
1529 {
1530     struct smap_node *node, *next;
1531     size_t i;
1532
1533     datum->n = smap_count(smap);
1534     datum->keys = xmalloc(datum->n * sizeof *datum->keys);
1535     datum->values = xmalloc(datum->n * sizeof *datum->values);
1536
1537     i = 0;
1538     SMAP_FOR_EACH_SAFE (node, next, smap) {
1539         smap_steal(smap, node,
1540                    &datum->keys[i].string, &datum->values[i].string);
1541         i++;
1542     }
1543     ovs_assert(i == datum->n);
1544
1545     smap_destroy(smap);
1546     ovsdb_datum_sort_unique(datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
1547 }
1548
1549 static uint32_t
1550 hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
1551            unsigned int n, uint32_t basis)
1552 {
1553     if (type != OVSDB_TYPE_VOID) {
1554         unsigned int i;
1555
1556         for (i = 0; i < n; i++) {
1557             basis = ovsdb_atom_hash(&atoms[i], type, basis);
1558         }
1559     }
1560     return basis;
1561 }
1562
1563 uint32_t
1564 ovsdb_datum_hash(const struct ovsdb_datum *datum,
1565                  const struct ovsdb_type *type, uint32_t basis)
1566 {
1567     basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
1568     basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
1569     basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
1570     return basis;
1571 }
1572
1573 static int
1574 atom_arrays_compare_3way(const union ovsdb_atom *a,
1575                          const union ovsdb_atom *b,
1576                          enum ovsdb_atomic_type type,
1577                          size_t n)
1578 {
1579     unsigned int i;
1580
1581     for (i = 0; i < n; i++) {
1582         int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
1583         if (cmp) {
1584             return cmp;
1585         }
1586     }
1587
1588     return 0;
1589 }
1590
1591 bool
1592 ovsdb_datum_equals(const struct ovsdb_datum *a,
1593                    const struct ovsdb_datum *b,
1594                    const struct ovsdb_type *type)
1595 {
1596     return !ovsdb_datum_compare_3way(a, b, type);
1597 }
1598
1599 int
1600 ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
1601                          const struct ovsdb_datum *b,
1602                          const struct ovsdb_type *type)
1603 {
1604     int cmp;
1605
1606     if (a->n != b->n) {
1607         return a->n < b->n ? -1 : 1;
1608     }
1609
1610     cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
1611     if (cmp) {
1612         return cmp;
1613     }
1614
1615     return (type->value.type == OVSDB_TYPE_VOID ? 0
1616             : atom_arrays_compare_3way(a->values, b->values, type->value.type,
1617                                        a->n));
1618 }
1619
1620 /* If 'key' is one of the keys in 'datum', returns its index within 'datum',
1621  * otherwise UINT_MAX.  'key.type' must be the type of the atoms stored in the
1622  * 'keys' array in 'datum'.
1623  */
1624 unsigned int
1625 ovsdb_datum_find_key(const struct ovsdb_datum *datum,
1626                      const union ovsdb_atom *key,
1627                      enum ovsdb_atomic_type key_type)
1628 {
1629     unsigned int low = 0;
1630     unsigned int high = datum->n;
1631     while (low < high) {
1632         unsigned int idx = (low + high) / 2;
1633         int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
1634         if (cmp < 0) {
1635             high = idx;
1636         } else if (cmp > 0) {
1637             low = idx + 1;
1638         } else {
1639             return idx;
1640         }
1641     }
1642     return UINT_MAX;
1643 }
1644
1645 /* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
1646  * index within 'datum', otherwise UINT_MAX.  'key.type' must be the type of
1647  * the atoms stored in the 'keys' array in 'datum'.  'value_type' may be the
1648  * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
1649  */
1650 unsigned int
1651 ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
1652                            const union ovsdb_atom *key,
1653                            enum ovsdb_atomic_type key_type,
1654                            const union ovsdb_atom *value,
1655                            enum ovsdb_atomic_type value_type)
1656 {
1657     unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
1658     if (idx != UINT_MAX
1659         && value_type != OVSDB_TYPE_VOID
1660         && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
1661         idx = UINT_MAX;
1662     }
1663     return idx;
1664 }
1665
1666 /* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
1667  * UINT_MAX.  'type' must be the type of 'a' and 'b', except that
1668  * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
1669  * values. */
1670 static unsigned int
1671 ovsdb_datum_find(const struct ovsdb_datum *a, int i,
1672                  const struct ovsdb_datum *b,
1673                  const struct ovsdb_type *type)
1674 {
1675     return ovsdb_datum_find_key_value(b,
1676                                       &a->keys[i], type->key.type,
1677                                       a->values ? &a->values[i] : NULL,
1678                                       type->value.type);
1679 }
1680
1681 /* Returns true if every element in 'a' is also in 'b', false otherwise. */
1682 bool
1683 ovsdb_datum_includes_all(const struct ovsdb_datum *a,
1684                          const struct ovsdb_datum *b,
1685                          const struct ovsdb_type *type)
1686 {
1687     size_t i;
1688
1689     if (a->n > b->n) {
1690         return false;
1691     }
1692     for (i = 0; i < a->n; i++) {
1693         if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
1694             return false;
1695         }
1696     }
1697     return true;
1698 }
1699
1700 /* Returns true if no element in 'a' is also in 'b', false otherwise. */
1701 bool
1702 ovsdb_datum_excludes_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     for (i = 0; i < a->n; i++) {
1709         if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
1710             return false;
1711         }
1712     }
1713     return true;
1714 }
1715
1716 static void
1717 ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
1718                        unsigned int capacity)
1719 {
1720     a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
1721     if (type->value.type != OVSDB_TYPE_VOID) {
1722         a->values = xrealloc(a->values, capacity * sizeof *a->values);
1723     }
1724 }
1725
1726 /* Removes the element with index 'idx' from 'datum', which has type 'type'.
1727  * If 'idx' is not the last element in 'datum', then the removed element is
1728  * replaced by the (former) last element.
1729  *
1730  * This function does not maintain ovsdb_datum invariants.  Use
1731  * ovsdb_datum_sort() to check and restore these invariants. */
1732 void
1733 ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
1734                           const struct ovsdb_type *type)
1735 {
1736     ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
1737     datum->keys[idx] = datum->keys[datum->n - 1];
1738     if (type->value.type != OVSDB_TYPE_VOID) {
1739         ovsdb_atom_destroy(&datum->values[idx], type->value.type);
1740         datum->values[idx] = datum->values[datum->n - 1];
1741     }
1742     datum->n--;
1743 }
1744
1745 /* Adds the element with the given 'key' and 'value' to 'datum', which must
1746  * have the specified 'type'.
1747  *
1748  * This function always allocates memory, so it is not an efficient way to add
1749  * a number of elements to a datum.
1750  *
1751  * This function does not maintain ovsdb_datum invariants.  Use
1752  * ovsdb_datum_sort() to check and restore these invariants.  (But a datum with
1753  * 0 or 1 elements cannot violate the invariants anyhow.) */
1754 void
1755 ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
1756                        const union ovsdb_atom *key,
1757                        const union ovsdb_atom *value,
1758                        const struct ovsdb_type *type)
1759 {
1760     size_t idx = datum->n++;
1761     datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
1762     ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
1763     if (type->value.type != OVSDB_TYPE_VOID) {
1764         datum->values = xrealloc(datum->values,
1765                                  datum->n * sizeof *datum->values);
1766         ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
1767     }
1768 }
1769
1770 void
1771 ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
1772                   const struct ovsdb_type *type, bool replace)
1773 {
1774     unsigned int n;
1775     size_t bi;
1776
1777     n = a->n;
1778     for (bi = 0; bi < b->n; bi++) {
1779         unsigned int ai;
1780
1781         ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
1782         if (ai == UINT_MAX) {
1783             if (n == a->n) {
1784                 ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
1785             }
1786             ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
1787             if (type->value.type != OVSDB_TYPE_VOID) {
1788                 ovsdb_atom_clone(&a->values[n], &b->values[bi],
1789                                  type->value.type);
1790             }
1791             n++;
1792         } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
1793             ovsdb_atom_destroy(&a->values[ai], type->value.type);
1794             ovsdb_atom_clone(&a->values[ai], &b->values[bi],
1795                              type->value.type);
1796         }
1797     }
1798     if (n != a->n) {
1799         struct ovsdb_error *error;
1800         a->n = n;
1801         error = ovsdb_datum_sort(a, type->key.type);
1802         ovs_assert(!error);
1803     }
1804 }
1805
1806 void
1807 ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
1808                      const struct ovsdb_datum *b,
1809                      const struct ovsdb_type *b_type)
1810 {
1811     bool changed = false;
1812     size_t i;
1813
1814     ovs_assert(a_type->key.type == b_type->key.type);
1815     ovs_assert(a_type->value.type == b_type->value.type
1816                || b_type->value.type == OVSDB_TYPE_VOID);
1817
1818     /* XXX The big-O of this could easily be improved. */
1819     for (i = 0; i < a->n; ) {
1820         unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
1821         if (idx != UINT_MAX) {
1822             changed = true;
1823             ovsdb_datum_remove_unsafe(a, i, a_type);
1824         } else {
1825             i++;
1826         }
1827     }
1828     if (changed) {
1829         ovsdb_datum_sort_assert(a, a_type->key.type);
1830     }
1831 }
1832 \f
1833 struct ovsdb_symbol_table *
1834 ovsdb_symbol_table_create(void)
1835 {
1836     struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
1837     shash_init(&symtab->sh);
1838     return symtab;
1839 }
1840
1841 void
1842 ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
1843 {
1844     if (symtab) {
1845         shash_destroy_free_data(&symtab->sh);
1846         free(symtab);
1847     }
1848 }
1849
1850 struct ovsdb_symbol *
1851 ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
1852                        const char *name)
1853 {
1854     return shash_find_data(&symtab->sh, name);
1855 }
1856
1857 struct ovsdb_symbol *
1858 ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
1859                        const struct uuid *uuid, bool created)
1860 {
1861     struct ovsdb_symbol *symbol;
1862
1863     ovs_assert(!ovsdb_symbol_table_get(symtab, name));
1864     symbol = xmalloc(sizeof *symbol);
1865     symbol->uuid = *uuid;
1866     symbol->created = created;
1867     symbol->strong_ref = false;
1868     symbol->weak_ref = false;
1869     shash_add(&symtab->sh, name, symbol);
1870     return symbol;
1871 }
1872
1873 struct ovsdb_symbol *
1874 ovsdb_symbol_table_insert(struct ovsdb_symbol_table *symtab,
1875                           const char *name)
1876 {
1877     struct ovsdb_symbol *symbol;
1878
1879     symbol = ovsdb_symbol_table_get(symtab, name);
1880     if (!symbol) {
1881         struct uuid uuid;
1882
1883         uuid_generate(&uuid);
1884         symbol = ovsdb_symbol_table_put(symtab, name, &uuid, false);
1885     }
1886     return symbol;
1887 }
1888 \f
1889 /* Extracts a token from the beginning of 's' and returns a pointer just after
1890  * the token.  Stores the token itself into '*outp', which the caller is
1891  * responsible for freeing (with free()).
1892  *
1893  * If 's[0]' is a delimiter, the returned token is the empty string.
1894  *
1895  * A token extends from 's' to the first delimiter, as defined by
1896  * ovsdb_token_is_delim(), or until the end of the string.  A delimiter can be
1897  * escaped with a backslash, in which case the backslash does not appear in the
1898  * output.  Double quotes also cause delimiters to be ignored, but the double
1899  * quotes are retained in the output.  (Backslashes inside double quotes are
1900  * not removed, either.)
1901  */
1902 char *
1903 ovsdb_token_parse(const char **s, char **outp)
1904 {
1905     const char *p;
1906     struct ds out;
1907     bool in_quotes;
1908     char *error;
1909
1910     ds_init(&out);
1911     in_quotes = false;
1912     for (p = *s; *p != '\0'; ) {
1913         int c = *p++;
1914         if (c == '\\') {
1915             if (in_quotes) {
1916                 ds_put_char(&out, '\\');
1917             }
1918             if (!*p) {
1919                 error = xasprintf("%s: backslash at end of argument", *s);
1920                 goto error;
1921             }
1922             ds_put_char(&out, *p++);
1923         } else if (!in_quotes && ovsdb_token_is_delim(c)) {
1924             p--;
1925             break;
1926         } else {
1927             ds_put_char(&out, c);
1928             if (c == '"') {
1929                 in_quotes = !in_quotes;
1930             }
1931         }
1932     }
1933     if (in_quotes) {
1934         error = xasprintf("%s: quoted string extends past end of argument",
1935                           *s);
1936         goto error;
1937     }
1938     *outp = ds_cstr(&out);
1939     *s = p;
1940     return NULL;
1941
1942 error:
1943     ds_destroy(&out);
1944     *outp = NULL;
1945     return error;
1946 }
1947
1948 /* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
1949 bool
1950 ovsdb_token_is_delim(unsigned char c)
1951 {
1952     return strchr(":=, []{}!<>", c) != NULL;
1953 }