netdev-dpdk: fix mbuf leaks
[cascardo/ovs.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "ofp-parse.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdlib.h>
24 #include <netinet/in.h>
25
26 #include "byte-order.h"
27 #include "dynamic-string.h"
28 #include "learn.h"
29 #include "meta-flow.h"
30 #include "multipath.h"
31 #include "netdev.h"
32 #include "nx-match.h"
33 #include "ofp-actions.h"
34 #include "ofp-util.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "ovs-thread.h"
38 #include "packets.h"
39 #include "simap.h"
40 #include "socket-util.h"
41 #include "openvswitch/vconn.h"
42
43 /* Parses 'str' as an 8-bit unsigned integer into '*valuep'.
44  *
45  * 'name' describes the value parsed in an error message, if any.
46  *
47  * Returns NULL if successful, otherwise a malloc()'d string describing the
48  * error.  The caller is responsible for freeing the returned string. */
49 char * OVS_WARN_UNUSED_RESULT
50 str_to_u8(const char *str, const char *name, uint8_t *valuep)
51 {
52     int value;
53
54     if (!str_to_int(str, 0, &value) || value < 0 || value > 255) {
55         return xasprintf("invalid %s \"%s\"", name, str);
56     }
57     *valuep = value;
58     return NULL;
59 }
60
61 /* Parses 'str' as a 16-bit unsigned integer into '*valuep'.
62  *
63  * 'name' describes the value parsed in an error message, if any.
64  *
65  * Returns NULL if successful, otherwise a malloc()'d string describing the
66  * error.  The caller is responsible for freeing the returned string. */
67 char * OVS_WARN_UNUSED_RESULT
68 str_to_u16(const char *str, const char *name, uint16_t *valuep)
69 {
70     int value;
71
72     if (!str_to_int(str, 0, &value) || value < 0 || value > 65535) {
73         return xasprintf("invalid %s \"%s\"", name, str);
74     }
75     *valuep = value;
76     return NULL;
77 }
78
79 /* Parses 'str' as a 32-bit unsigned integer into '*valuep'.
80  *
81  * Returns NULL if successful, otherwise a malloc()'d string describing the
82  * error.  The caller is responsible for freeing the returned string. */
83 char * OVS_WARN_UNUSED_RESULT
84 str_to_u32(const char *str, uint32_t *valuep)
85 {
86     char *tail;
87     uint32_t value;
88
89     if (!str[0]) {
90         return xstrdup("missing required numeric argument");
91     }
92
93     errno = 0;
94     value = strtoul(str, &tail, 0);
95     if (errno == EINVAL || errno == ERANGE || *tail) {
96         return xasprintf("invalid numeric format %s", str);
97     }
98     *valuep = value;
99     return NULL;
100 }
101
102 /* Parses 'str' as an 64-bit unsigned integer into '*valuep'.
103  *
104  * Returns NULL if successful, otherwise a malloc()'d string describing the
105  * error.  The caller is responsible for freeing the returned string. */
106 char * OVS_WARN_UNUSED_RESULT
107 str_to_u64(const char *str, uint64_t *valuep)
108 {
109     char *tail;
110     uint64_t value;
111
112     if (!str[0]) {
113         return xstrdup("missing required numeric argument");
114     }
115
116     errno = 0;
117     value = strtoull(str, &tail, 0);
118     if (errno == EINVAL || errno == ERANGE || *tail) {
119         return xasprintf("invalid numeric format %s", str);
120     }
121     *valuep = value;
122     return NULL;
123 }
124
125 /* Parses 'str' as an 64-bit unsigned integer in network byte order into
126  * '*valuep'.
127  *
128  * Returns NULL if successful, otherwise a malloc()'d string describing the
129  * error.  The caller is responsible for freeing the returned string. */
130 char * OVS_WARN_UNUSED_RESULT
131 str_to_be64(const char *str, ovs_be64 *valuep)
132 {
133     uint64_t value = 0;
134     char *error;
135
136     error = str_to_u64(str, &value);
137     if (!error) {
138         *valuep = htonll(value);
139     }
140     return error;
141 }
142
143 /* Parses 'str' as an Ethernet address into 'mac'.
144  *
145  * Returns NULL if successful, otherwise a malloc()'d string describing the
146  * error.  The caller is responsible for freeing the returned string. */
147 char * OVS_WARN_UNUSED_RESULT
148 str_to_mac(const char *str, struct eth_addr *mac)
149 {
150     if (!ovs_scan(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(*mac))) {
151         return xasprintf("invalid mac address %s", str);
152     }
153     return NULL;
154 }
155
156 /* Parses 'str' as an IP address into '*ip'.
157  *
158  * Returns NULL if successful, otherwise a malloc()'d string describing the
159  * error.  The caller is responsible for freeing the returned string. */
160 char * OVS_WARN_UNUSED_RESULT
161 str_to_ip(const char *str, ovs_be32 *ip)
162 {
163     struct in_addr in_addr;
164
165     if (lookup_ip(str, &in_addr)) {
166         return xasprintf("%s: could not convert to IP address", str);
167     }
168     *ip = in_addr.s_addr;
169     return NULL;
170 }
171
172 /* Parses 'str' as a conntrack helper into 'alg'.
173  *
174  * Returns NULL if successful, otherwise a malloc()'d string describing the
175  * error.  The caller is responsible for freeing the returned string. */
176 char * OVS_WARN_UNUSED_RESULT
177 str_to_connhelper(const char *str, uint16_t *alg)
178 {
179     if (!strcmp(str, "ftp")) {
180         *alg = IPPORT_FTP;
181         return NULL;
182     }
183     return xasprintf("invalid conntrack helper \"%s\"", str);
184 }
185
186 struct protocol {
187     const char *name;
188     uint16_t dl_type;
189     uint8_t nw_proto;
190 };
191
192 static bool
193 parse_protocol(const char *name, const struct protocol **p_out)
194 {
195     static const struct protocol protocols[] = {
196         { "ip", ETH_TYPE_IP, 0 },
197         { "ipv4", ETH_TYPE_IP, 0 },
198         { "ip4", ETH_TYPE_IP, 0 },
199         { "arp", ETH_TYPE_ARP, 0 },
200         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
201         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
202         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
203         { "sctp", ETH_TYPE_IP, IPPROTO_SCTP },
204         { "ipv6", ETH_TYPE_IPV6, 0 },
205         { "ip6", ETH_TYPE_IPV6, 0 },
206         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
207         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
208         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
209         { "sctp6", ETH_TYPE_IPV6, IPPROTO_SCTP },
210         { "rarp", ETH_TYPE_RARP, 0},
211         { "mpls", ETH_TYPE_MPLS, 0 },
212         { "mplsm", ETH_TYPE_MPLS_MCAST, 0 },
213     };
214     const struct protocol *p;
215
216     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
217         if (!strcmp(p->name, name)) {
218             *p_out = p;
219             return true;
220         }
221     }
222     *p_out = NULL;
223     return false;
224 }
225
226 /* Parses 's' as the (possibly masked) value of field 'mf', and updates
227  * 'match' appropriately.  Restricts the set of usable protocols to ones
228  * supporting the parsed field.
229  *
230  * Returns NULL if successful, otherwise a malloc()'d string describing the
231  * error.  The caller is responsible for freeing the returned string. */
232 static char * OVS_WARN_UNUSED_RESULT
233 parse_field(const struct mf_field *mf, const char *s, struct match *match,
234             enum ofputil_protocol *usable_protocols)
235 {
236     union mf_value value, mask;
237     char *error;
238
239     if (!*s) {
240         /* If there's no string, we're just trying to match on the
241          * existence of the field, so use a no-op value. */
242         s = "0/0";
243     }
244
245     error = mf_parse(mf, s, &value, &mask);
246     if (!error) {
247         *usable_protocols &= mf_set(mf, &value, &mask, match, &error);
248     }
249     return error;
250 }
251
252 static char *
253 extract_actions(char *s)
254 {
255     s = strstr(s, "action");
256     if (s) {
257         *s = '\0';
258         s = strchr(s + 1, '=');
259         return s ? s + 1 : NULL;
260     } else {
261         return NULL;
262     }
263 }
264
265
266 static char * OVS_WARN_UNUSED_RESULT
267 parse_ofp_str__(struct ofputil_flow_mod *fm, int command, char *string,
268                 enum ofputil_protocol *usable_protocols)
269 {
270     enum {
271         F_OUT_PORT = 1 << 0,
272         F_ACTIONS = 1 << 1,
273         F_IMPORTANCE = 1 << 2,
274         F_TIMEOUT = 1 << 3,
275         F_PRIORITY = 1 << 4,
276         F_FLAGS = 1 << 5,
277     } fields;
278     char *act_str = NULL;
279     char *name, *value;
280
281     *usable_protocols = OFPUTIL_P_ANY;
282
283     if (command == -2) {
284         size_t len;
285
286         string += strspn(string, " \t\r\n");   /* Skip white space. */
287         len = strcspn(string, ", \t\r\n"); /* Get length of the first token. */
288
289         if (!strncmp(string, "add", len)) {
290             command = OFPFC_ADD;
291         } else if (!strncmp(string, "delete", len)) {
292             command = OFPFC_DELETE;
293         } else if (!strncmp(string, "delete_strict", len)) {
294             command = OFPFC_DELETE_STRICT;
295         } else if (!strncmp(string, "modify", len)) {
296             command = OFPFC_MODIFY;
297         } else if (!strncmp(string, "modify_strict", len)) {
298             command = OFPFC_MODIFY_STRICT;
299         } else {
300             len = 0;
301             command = OFPFC_ADD;
302         }
303         string += len;
304     }
305
306     switch (command) {
307     case -1:
308         fields = F_OUT_PORT;
309         break;
310
311     case OFPFC_ADD:
312         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS | F_IMPORTANCE;
313         break;
314
315     case OFPFC_DELETE:
316         fields = F_OUT_PORT;
317         break;
318
319     case OFPFC_DELETE_STRICT:
320         fields = F_OUT_PORT | F_PRIORITY;
321         break;
322
323     case OFPFC_MODIFY:
324         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
325         break;
326
327     case OFPFC_MODIFY_STRICT:
328         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
329         break;
330
331     default:
332         OVS_NOT_REACHED();
333     }
334
335     *fm = (struct ofputil_flow_mod) {
336         .match = MATCH_CATCHALL_INITIALIZER,
337         .priority = OFP_DEFAULT_PRIORITY,
338         .table_id = 0xff,
339         .command = command,
340         .buffer_id = UINT32_MAX,
341         .out_port = OFPP_ANY,
342         .out_group = OFPG_ANY,
343         .delete_reason = OFPRR_DELETE,
344     };
345     /* For modify, by default, don't update the cookie. */
346     if (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT) {
347         fm->new_cookie = OVS_BE64_MAX;
348     }
349
350     if (fields & F_ACTIONS) {
351         act_str = extract_actions(string);
352         if (!act_str) {
353             return xstrdup("must specify an action");
354         }
355     }
356
357     while (ofputil_parse_key_value(&string, &name, &value)) {
358         const struct protocol *p;
359         char *error = NULL;
360
361         if (parse_protocol(name, &p)) {
362             match_set_dl_type(&fm->match, htons(p->dl_type));
363             if (p->nw_proto) {
364                 match_set_nw_proto(&fm->match, p->nw_proto);
365             }
366         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
367             fm->flags |= OFPUTIL_FF_SEND_FLOW_REM;
368         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
369             fm->flags |= OFPUTIL_FF_CHECK_OVERLAP;
370         } else if (fields & F_FLAGS && !strcmp(name, "reset_counts")) {
371             fm->flags |= OFPUTIL_FF_RESET_COUNTS;
372             *usable_protocols &= OFPUTIL_P_OF12_UP;
373         } else if (fields & F_FLAGS && !strcmp(name, "no_packet_counts")) {
374             fm->flags |= OFPUTIL_FF_NO_PKT_COUNTS;
375             *usable_protocols &= OFPUTIL_P_OF13_UP;
376         } else if (fields & F_FLAGS && !strcmp(name, "no_byte_counts")) {
377             fm->flags |= OFPUTIL_FF_NO_BYT_COUNTS;
378             *usable_protocols &= OFPUTIL_P_OF13_UP;
379         } else if (!strcmp(name, "no_readonly_table")
380                    || !strcmp(name, "allow_hidden_fields")) {
381              /* ignore these fields. */
382         } else if (mf_from_name(name)) {
383             error = parse_field(mf_from_name(name), value, &fm->match,
384                                 usable_protocols);
385         } else {
386             if (!*value) {
387                 return xasprintf("field %s missing value", name);
388             }
389
390             if (!strcmp(name, "table")) {
391                 error = str_to_u8(value, "table", &fm->table_id);
392                 if (fm->table_id != 0xff) {
393                     *usable_protocols &= OFPUTIL_P_TID;
394                 }
395             } else if (fields & F_OUT_PORT && !strcmp(name, "out_port")) {
396                 if (!ofputil_port_from_string(value, &fm->out_port)) {
397                     error = xasprintf("%s is not a valid OpenFlow port",
398                                       value);
399                 }
400             } else if (fields & F_OUT_PORT && !strcmp(name, "out_group")) {
401                 *usable_protocols &= OFPUTIL_P_OF11_UP;
402                 if (!ofputil_group_from_string(value, &fm->out_group)) {
403                     error = xasprintf("%s is not a valid OpenFlow group",
404                                       value);
405                 }
406             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
407                 uint16_t priority = 0;
408
409                 error = str_to_u16(value, name, &priority);
410                 fm->priority = priority;
411             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
412                 error = str_to_u16(value, name, &fm->idle_timeout);
413             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
414                 error = str_to_u16(value, name, &fm->hard_timeout);
415             } else if (fields & F_IMPORTANCE && !strcmp(name, "importance")) {
416                 error = str_to_u16(value, name, &fm->importance);
417             } else if (!strcmp(name, "cookie")) {
418                 char *mask = strchr(value, '/');
419
420                 if (mask) {
421                     /* A mask means we're searching for a cookie. */
422                     if (command == OFPFC_ADD) {
423                         return xstrdup("flow additions cannot use "
424                                        "a cookie mask");
425                     }
426                     *mask = '\0';
427                     error = str_to_be64(value, &fm->cookie);
428                     if (error) {
429                         return error;
430                     }
431                     error = str_to_be64(mask + 1, &fm->cookie_mask);
432
433                     /* Matching of the cookie is only supported through NXM or
434                      * OF1.1+. */
435                     if (fm->cookie_mask != htonll(0)) {
436                         *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
437                     }
438                 } else {
439                     /* No mask means that the cookie is being set. */
440                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
441                         && command != OFPFC_MODIFY_STRICT) {
442                         return xstrdup("cannot set cookie");
443                     }
444                     error = str_to_be64(value, &fm->new_cookie);
445                     fm->modify_cookie = true;
446                 }
447             } else if (!strcmp(name, "duration")
448                        || !strcmp(name, "n_packets")
449                        || !strcmp(name, "n_bytes")
450                        || !strcmp(name, "idle_age")
451                        || !strcmp(name, "hard_age")) {
452                 /* Ignore these, so that users can feed the output of
453                  * "ovs-ofctl dump-flows" back into commands that parse
454                  * flows. */
455             } else {
456                 error = xasprintf("unknown keyword %s", name);
457             }
458         }
459
460         if (error) {
461             return error;
462         }
463     }
464     /* Check for usable protocol interdependencies between match fields. */
465     if (fm->match.flow.dl_type == htons(ETH_TYPE_IPV6)) {
466         const struct flow_wildcards *wc = &fm->match.wc;
467         /* Only NXM and OXM support matching L3 and L4 fields within IPv6.
468          *
469          * (IPv6 specific fields as well as arp_sha, arp_tha, nw_frag, and
470          *  nw_ttl are covered elsewhere so they don't need to be included in
471          *  this test too.)
472          */
473         if (wc->masks.nw_proto || wc->masks.nw_tos
474             || wc->masks.tp_src || wc->masks.tp_dst) {
475             *usable_protocols &= OFPUTIL_P_NXM_OXM_ANY;
476         }
477     }
478     if (!fm->cookie_mask && fm->new_cookie == OVS_BE64_MAX
479         && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
480         /* On modifies without a mask, we are supposed to add a flow if
481          * one does not exist.  If a cookie wasn't been specified, use a
482          * default of zero. */
483         fm->new_cookie = htonll(0);
484     }
485     if (fields & F_ACTIONS) {
486         enum ofputil_protocol action_usable_protocols;
487         struct ofpbuf ofpacts;
488         char *error;
489
490         ofpbuf_init(&ofpacts, 32);
491         error = ofpacts_parse_instructions(act_str, &ofpacts,
492                                            &action_usable_protocols);
493         *usable_protocols &= action_usable_protocols;
494         if (!error) {
495             enum ofperr err;
496
497             err = ofpacts_check(ofpacts.data, ofpacts.size, &fm->match.flow,
498                                 OFPP_MAX, fm->table_id, 255, usable_protocols);
499             if (!err && !*usable_protocols) {
500                 err = OFPERR_OFPBAC_MATCH_INCONSISTENT;
501             }
502             if (err) {
503                 error = xasprintf("actions are invalid with specified match "
504                                   "(%s)", ofperr_to_string(err));
505             }
506
507         }
508         if (error) {
509             ofpbuf_uninit(&ofpacts);
510             return error;
511         }
512
513         fm->ofpacts_len = ofpacts.size;
514         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
515     } else {
516         fm->ofpacts_len = 0;
517         fm->ofpacts = NULL;
518     }
519
520     return NULL;
521 }
522
523 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
524  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
525  * Returns the set of usable protocols in '*usable_protocols'.
526  *
527  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
528  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
529  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'.
530  *
531  * If 'command' is given as -2, 'str_' may begin with a command name ("add",
532  * "modify", "delete", "modify_strict", or "delete_strict").  A missing command
533  * name is treated as "add".
534  *
535  * Returns NULL if successful, otherwise a malloc()'d string describing the
536  * error.  The caller is responsible for freeing the returned string. */
537 char * OVS_WARN_UNUSED_RESULT
538 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
539               enum ofputil_protocol *usable_protocols)
540 {
541     char *string = xstrdup(str_);
542     char *error;
543
544     error = parse_ofp_str__(fm, command, string, usable_protocols);
545     if (error) {
546         fm->ofpacts = NULL;
547         fm->ofpacts_len = 0;
548     }
549
550     free(string);
551     return error;
552 }
553
554 static char * OVS_WARN_UNUSED_RESULT
555 parse_ofp_meter_mod_str__(struct ofputil_meter_mod *mm, char *string,
556                           struct ofpbuf *bands, int command,
557                           enum ofputil_protocol *usable_protocols)
558 {
559     enum {
560         F_METER = 1 << 0,
561         F_FLAGS = 1 << 1,
562         F_BANDS = 1 << 2,
563     } fields;
564     char *save_ptr = NULL;
565     char *band_str = NULL;
566     char *name;
567
568     /* Meters require at least OF 1.3. */
569     *usable_protocols = OFPUTIL_P_OF13_UP;
570
571     switch (command) {
572     case -1:
573         fields = F_METER;
574         break;
575
576     case OFPMC13_ADD:
577         fields = F_METER | F_FLAGS | F_BANDS;
578         break;
579
580     case OFPMC13_DELETE:
581         fields = F_METER;
582         break;
583
584     case OFPMC13_MODIFY:
585         fields = F_METER | F_FLAGS | F_BANDS;
586         break;
587
588     default:
589         OVS_NOT_REACHED();
590     }
591
592     mm->command = command;
593     mm->meter.meter_id = 0;
594     mm->meter.flags = 0;
595     if (fields & F_BANDS) {
596         band_str = strstr(string, "band");
597         if (!band_str) {
598             return xstrdup("must specify bands");
599         }
600         *band_str = '\0';
601
602         band_str = strchr(band_str + 1, '=');
603         if (!band_str) {
604             return xstrdup("must specify bands");
605         }
606
607         band_str++;
608     }
609     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
610          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
611
612         if (fields & F_FLAGS && !strcmp(name, "kbps")) {
613             mm->meter.flags |= OFPMF13_KBPS;
614         } else if (fields & F_FLAGS && !strcmp(name, "pktps")) {
615             mm->meter.flags |= OFPMF13_PKTPS;
616         } else if (fields & F_FLAGS && !strcmp(name, "burst")) {
617             mm->meter.flags |= OFPMF13_BURST;
618         } else if (fields & F_FLAGS && !strcmp(name, "stats")) {
619             mm->meter.flags |= OFPMF13_STATS;
620         } else {
621             char *value;
622
623             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
624             if (!value) {
625                 return xasprintf("field %s missing value", name);
626             }
627
628             if (!strcmp(name, "meter")) {
629                 if (!strcmp(value, "all")) {
630                     mm->meter.meter_id = OFPM13_ALL;
631                 } else if (!strcmp(value, "controller")) {
632                     mm->meter.meter_id = OFPM13_CONTROLLER;
633                 } else if (!strcmp(value, "slowpath")) {
634                     mm->meter.meter_id = OFPM13_SLOWPATH;
635                 } else {
636                     char *error = str_to_u32(value, &mm->meter.meter_id);
637                     if (error) {
638                         return error;
639                     }
640                     if (mm->meter.meter_id > OFPM13_MAX
641                         || !mm->meter.meter_id) {
642                         return xasprintf("invalid value for %s", name);
643                     }
644                 }
645             } else {
646                 return xasprintf("unknown keyword %s", name);
647             }
648         }
649     }
650     if (fields & F_METER && !mm->meter.meter_id) {
651         return xstrdup("must specify 'meter'");
652     }
653     if (fields & F_FLAGS && !mm->meter.flags) {
654         return xstrdup("meter must specify either 'kbps' or 'pktps'");
655     }
656
657     if (fields & F_BANDS) {
658         uint16_t n_bands = 0;
659         struct ofputil_meter_band *band = NULL;
660         int i;
661
662         for (name = strtok_r(band_str, "=, \t\r\n", &save_ptr); name;
663              name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
664
665             char *value;
666
667             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
668             if (!value) {
669                 return xasprintf("field %s missing value", name);
670             }
671
672             if (!strcmp(name, "type")) {
673                 /* Start a new band */
674                 band = ofpbuf_put_zeros(bands, sizeof *band);
675                 n_bands++;
676
677                 if (!strcmp(value, "drop")) {
678                     band->type = OFPMBT13_DROP;
679                 } else if (!strcmp(value, "dscp_remark")) {
680                     band->type = OFPMBT13_DSCP_REMARK;
681                 } else {
682                     return xasprintf("field %s unknown value %s", name, value);
683                 }
684             } else if (!band || !band->type) {
685                 return xstrdup("band must start with the 'type' keyword");
686             } else if (!strcmp(name, "rate")) {
687                 char *error = str_to_u32(value, &band->rate);
688                 if (error) {
689                     return error;
690                 }
691             } else if (!strcmp(name, "burst_size")) {
692                 char *error = str_to_u32(value, &band->burst_size);
693                 if (error) {
694                     return error;
695                 }
696             } else if (!strcmp(name, "prec_level")) {
697                 char *error = str_to_u8(value, name, &band->prec_level);
698                 if (error) {
699                     return error;
700                 }
701             } else {
702                 return xasprintf("unknown keyword %s", name);
703             }
704         }
705         /* validate bands */
706         if (!n_bands) {
707             return xstrdup("meter must have bands");
708         }
709
710         mm->meter.n_bands = n_bands;
711         mm->meter.bands = ofpbuf_steal_data(bands);
712
713         for (i = 0; i < n_bands; ++i) {
714             band = &mm->meter.bands[i];
715
716             if (!band->type) {
717                 return xstrdup("band must have 'type'");
718             }
719             if (band->type == OFPMBT13_DSCP_REMARK) {
720                 if (!band->prec_level) {
721                     return xstrdup("'dscp_remark' band must have"
722                                    " 'prec_level'");
723                 }
724             } else {
725                 if (band->prec_level) {
726                     return xstrdup("Only 'dscp_remark' band may have"
727                                    " 'prec_level'");
728                 }
729             }
730             if (!band->rate) {
731                 return xstrdup("band must have 'rate'");
732             }
733             if (mm->meter.flags & OFPMF13_BURST) {
734                 if (!band->burst_size) {
735                     return xstrdup("band must have 'burst_size' "
736                                    "when 'burst' flag is set");
737                 }
738             } else {
739                 if (band->burst_size) {
740                     return xstrdup("band may have 'burst_size' only "
741                                    "when 'burst' flag is set");
742                 }
743             }
744         }
745     } else {
746         mm->meter.n_bands = 0;
747         mm->meter.bands = NULL;
748     }
749
750     return NULL;
751 }
752
753 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
754  * page) into 'mm' for sending the specified meter_mod 'command' to a switch.
755  *
756  * Returns NULL if successful, otherwise a malloc()'d string describing the
757  * error.  The caller is responsible for freeing the returned string. */
758 char * OVS_WARN_UNUSED_RESULT
759 parse_ofp_meter_mod_str(struct ofputil_meter_mod *mm, const char *str_,
760                         int command, enum ofputil_protocol *usable_protocols)
761 {
762     struct ofpbuf bands;
763     char *string;
764     char *error;
765
766     ofpbuf_init(&bands, 64);
767     string = xstrdup(str_);
768
769     error = parse_ofp_meter_mod_str__(mm, string, &bands, command,
770                                       usable_protocols);
771
772     free(string);
773     ofpbuf_uninit(&bands);
774
775     return error;
776 }
777
778 static char * OVS_WARN_UNUSED_RESULT
779 parse_flow_monitor_request__(struct ofputil_flow_monitor_request *fmr,
780                              const char *str_, char *string,
781                              enum ofputil_protocol *usable_protocols)
782 {
783     static atomic_count id = ATOMIC_COUNT_INIT(0);
784     char *name, *value;
785
786     fmr->id = atomic_count_inc(&id);
787
788     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
789                   | NXFMF_OWN | NXFMF_ACTIONS);
790     fmr->out_port = OFPP_NONE;
791     fmr->table_id = 0xff;
792     match_init_catchall(&fmr->match);
793
794     while (ofputil_parse_key_value(&string, &name, &value)) {
795         const struct protocol *p;
796         char *error = NULL;
797
798         if (!strcmp(name, "!initial")) {
799             fmr->flags &= ~NXFMF_INITIAL;
800         } else if (!strcmp(name, "!add")) {
801             fmr->flags &= ~NXFMF_ADD;
802         } else if (!strcmp(name, "!delete")) {
803             fmr->flags &= ~NXFMF_DELETE;
804         } else if (!strcmp(name, "!modify")) {
805             fmr->flags &= ~NXFMF_MODIFY;
806         } else if (!strcmp(name, "!actions")) {
807             fmr->flags &= ~NXFMF_ACTIONS;
808         } else if (!strcmp(name, "!own")) {
809             fmr->flags &= ~NXFMF_OWN;
810         } else if (parse_protocol(name, &p)) {
811             match_set_dl_type(&fmr->match, htons(p->dl_type));
812             if (p->nw_proto) {
813                 match_set_nw_proto(&fmr->match, p->nw_proto);
814             }
815         } else if (mf_from_name(name)) {
816             error = parse_field(mf_from_name(name), value, &fmr->match,
817                                 usable_protocols);
818         } else {
819             if (!*value) {
820                 return xasprintf("%s: field %s missing value", str_, name);
821             }
822
823             if (!strcmp(name, "table")) {
824                 error = str_to_u8(value, "table", &fmr->table_id);
825             } else if (!strcmp(name, "out_port")) {
826                 fmr->out_port = u16_to_ofp(atoi(value));
827             } else {
828                 return xasprintf("%s: unknown keyword %s", str_, name);
829             }
830         }
831
832         if (error) {
833             return error;
834         }
835     }
836     return NULL;
837 }
838
839 /* Convert 'str_' (as described in the documentation for the "monitor" command
840  * in the ovs-ofctl man page) into 'fmr'.
841  *
842  * Returns NULL if successful, otherwise a malloc()'d string describing the
843  * error.  The caller is responsible for freeing the returned string. */
844 char * OVS_WARN_UNUSED_RESULT
845 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
846                            const char *str_,
847                            enum ofputil_protocol *usable_protocols)
848 {
849     char *string = xstrdup(str_);
850     char *error = parse_flow_monitor_request__(fmr, str_, string,
851                                                usable_protocols);
852     free(string);
853     return error;
854 }
855
856 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
857  * (one of OFPFC_*) into 'fm'.
858  *
859  * If 'command' is given as -2, 'string' may begin with a command name ("add",
860  * "modify", "delete", "modify_strict", or "delete_strict").  A missing command
861  * name is treated as "add".
862  *
863  * Returns NULL if successful, otherwise a malloc()'d string describing the
864  * error.  The caller is responsible for freeing the returned string. */
865 char * OVS_WARN_UNUSED_RESULT
866 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
867                        int command,
868                        enum ofputil_protocol *usable_protocols)
869 {
870     char *error = parse_ofp_str(fm, command, string, usable_protocols);
871
872     if (!error) {
873         /* Normalize a copy of the match.  This ensures that non-normalized
874          * flows get logged but doesn't affect what gets sent to the switch, so
875          * that the switch can do whatever it likes with the flow. */
876         struct match match_copy = fm->match;
877         ofputil_normalize_match(&match_copy);
878     }
879
880     return error;
881 }
882
883 /* Convert 'setting' (as described for the "mod-table" command
884  * in ovs-ofctl man page) into 'tm->table_vacancy->vacancy_up' and
885  * 'tm->table_vacancy->vacancy_down' threshold values.
886  * For the two threshold values, value of vacancy_up is always greater
887  * than value of vacancy_down.
888  *
889  * Returns NULL if successful, otherwise a malloc()'d string describing the
890  * error.  The caller is responsible for freeing the returned string. */
891 char * OVS_WARN_UNUSED_RESULT
892 parse_ofp_table_vacancy(struct ofputil_table_mod *tm, const char *setting)
893 {
894     char *save_ptr = NULL;
895     char *vac_up, *vac_down;
896     char *value = xstrdup(setting);
897     char *ret_msg;
898     int vacancy_up, vacancy_down;
899
900     strtok_r(value, ":", &save_ptr);
901     vac_down = strtok_r(NULL, ",", &save_ptr);
902     if (!vac_down) {
903         ret_msg = xasprintf("Vacancy down value missing");
904         goto exit;
905     }
906     if (!str_to_int(vac_down, 0, &vacancy_down) ||
907         vacancy_down < 0 || vacancy_down > 100) {
908         ret_msg = xasprintf("Invalid vacancy down value \"%s\"", vac_down);
909         goto exit;
910     }
911     vac_up = strtok_r(NULL, ",", &save_ptr);
912     if (!vac_up) {
913         ret_msg = xasprintf("Vacancy up value missing");
914         goto exit;
915     }
916     if (!str_to_int(vac_up, 0, &vacancy_up) ||
917         vacancy_up < 0 || vacancy_up > 100) {
918         ret_msg = xasprintf("Invalid vacancy up value \"%s\"", vac_up);
919         goto exit;
920     }
921     if (vacancy_down > vacancy_up) {
922         ret_msg = xasprintf("Invalid vacancy range, vacancy up should be "
923                             "greater than vacancy down (%s)",
924                             ofperr_to_string(OFPERR_OFPBPC_BAD_VALUE));
925         goto exit;
926     }
927
928     free(value);
929     tm->table_vacancy.vacancy_down = vacancy_down;
930     tm->table_vacancy.vacancy_up = vacancy_up;
931     return NULL;
932
933 exit:
934     free(value);
935     return ret_msg;
936 }
937
938 /* Convert 'table_id' and 'setting' (as described for the "mod-table" command
939  * in the ovs-ofctl man page) into 'tm' for sending a table_mod command to a
940  * switch.
941  *
942  * Stores a bitmap of the OpenFlow versions that are usable for 'tm' into
943  * '*usable_versions'.
944  *
945  * Returns NULL if successful, otherwise a malloc()'d string describing the
946  * error.  The caller is responsible for freeing the returned string. */
947 char * OVS_WARN_UNUSED_RESULT
948 parse_ofp_table_mod(struct ofputil_table_mod *tm, const char *table_id,
949                     const char *setting, uint32_t *usable_versions)
950 {
951     *usable_versions = 0;
952     if (!strcasecmp(table_id, "all")) {
953         tm->table_id = OFPTT_ALL;
954     } else {
955         char *error = str_to_u8(table_id, "table_id", &tm->table_id);
956         if (error) {
957             return error;
958         }
959     }
960
961     tm->miss = OFPUTIL_TABLE_MISS_DEFAULT;
962     tm->eviction = OFPUTIL_TABLE_EVICTION_DEFAULT;
963     tm->eviction_flags = UINT32_MAX;
964     tm->vacancy = OFPUTIL_TABLE_VACANCY_DEFAULT;
965     tm->table_vacancy.vacancy_down = 0;
966     tm->table_vacancy.vacancy_up = 0;
967     tm->table_vacancy.vacancy = 0;
968     /* Only OpenFlow 1.1 and 1.2 can configure table-miss via table_mod.
969      * Only OpenFlow 1.4+ can configure eviction and vacancy events
970      * via table_mod.
971      */
972     if (!strcmp(setting, "controller")) {
973         tm->miss = OFPUTIL_TABLE_MISS_CONTROLLER;
974         *usable_versions = (1u << OFP11_VERSION) | (1u << OFP12_VERSION);
975     } else if (!strcmp(setting, "continue")) {
976         tm->miss = OFPUTIL_TABLE_MISS_CONTINUE;
977         *usable_versions = (1u << OFP11_VERSION) | (1u << OFP12_VERSION);
978     } else if (!strcmp(setting, "drop")) {
979         tm->miss = OFPUTIL_TABLE_MISS_DROP;
980         *usable_versions = (1u << OFP11_VERSION) | (1u << OFP12_VERSION);
981     } else if (!strcmp(setting, "evict")) {
982         tm->eviction = OFPUTIL_TABLE_EVICTION_ON;
983         *usable_versions = (1 << OFP14_VERSION) | (1u << OFP15_VERSION);
984     } else if (!strcmp(setting, "noevict")) {
985         tm->eviction = OFPUTIL_TABLE_EVICTION_OFF;
986         *usable_versions = (1 << OFP14_VERSION) | (1u << OFP15_VERSION);
987     } else if (!strncmp(setting, "vacancy", strcspn(setting, ":"))) {
988         tm->vacancy = OFPUTIL_TABLE_VACANCY_ON;
989         *usable_versions = (1 << OFP14_VERSION) | (1u << OFP15_VERSION);
990         char *error = parse_ofp_table_vacancy(tm, setting);
991         if (error) {
992             return error;
993         }
994     } else if (!strcmp(setting, "novacancy")) {
995         tm->vacancy = OFPUTIL_TABLE_VACANCY_OFF;
996         *usable_versions = (1 << OFP14_VERSION) | (1u << OFP15_VERSION);
997     } else {
998         return xasprintf("invalid table_mod setting %s", setting);
999     }
1000
1001     if (tm->table_id == 0xfe
1002         && tm->miss == OFPUTIL_TABLE_MISS_CONTINUE) {
1003         return xstrdup("last table's flow miss handling can not be continue");
1004     }
1005
1006     return NULL;
1007 }
1008
1009
1010 /* Opens file 'file_name' and reads each line as a flow_mod of the specified
1011  * type (one of OFPFC_*).  Stores each flow_mod in '*fm', an array allocated
1012  * on the caller's behalf, and the number of flow_mods in '*n_fms'.
1013  *
1014  * If 'command' is given as -2, each line may start with a command name
1015  * ("add", "modify", "delete", "modify_strict", or "delete_strict").  A missing
1016  * command name is treated as "add".
1017  *
1018  * Returns NULL if successful, otherwise a malloc()'d string describing the
1019  * error.  The caller is responsible for freeing the returned string. */
1020 char * OVS_WARN_UNUSED_RESULT
1021 parse_ofp_flow_mod_file(const char *file_name, int command,
1022                         struct ofputil_flow_mod **fms, size_t *n_fms,
1023                         enum ofputil_protocol *usable_protocols)
1024 {
1025     size_t allocated_fms;
1026     int line_number;
1027     FILE *stream;
1028     struct ds s;
1029
1030     *usable_protocols = OFPUTIL_P_ANY;
1031
1032     *fms = NULL;
1033     *n_fms = 0;
1034
1035     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1036     if (stream == NULL) {
1037         return xasprintf("%s: open failed (%s)",
1038                          file_name, ovs_strerror(errno));
1039     }
1040
1041     allocated_fms = *n_fms;
1042     ds_init(&s);
1043     line_number = 0;
1044     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
1045         char *error;
1046         enum ofputil_protocol usable;
1047
1048         if (*n_fms >= allocated_fms) {
1049             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1050         }
1051         error = parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command,
1052                                        &usable);
1053         if (error) {
1054             char *err_msg;
1055             size_t i;
1056
1057             for (i = 0; i < *n_fms; i++) {
1058                 free(CONST_CAST(struct ofpact *, (*fms)[i].ofpacts));
1059             }
1060             free(*fms);
1061             *fms = NULL;
1062             *n_fms = 0;
1063
1064             ds_destroy(&s);
1065             if (stream != stdin) {
1066                 fclose(stream);
1067             }
1068
1069             err_msg = xasprintf("%s:%d: %s", file_name, line_number, error);
1070             free(error);
1071             return err_msg;
1072         }
1073         *usable_protocols &= usable; /* Each line can narrow the set. */
1074         *n_fms += 1;
1075     }
1076
1077     ds_destroy(&s);
1078     if (stream != stdin) {
1079         fclose(stream);
1080     }
1081     return NULL;
1082 }
1083
1084 char * OVS_WARN_UNUSED_RESULT
1085 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1086                                  bool aggregate, const char *string,
1087                                  enum ofputil_protocol *usable_protocols)
1088 {
1089     struct ofputil_flow_mod fm;
1090     char *error;
1091
1092     error = parse_ofp_str(&fm, -1, string, usable_protocols);
1093     if (error) {
1094         return error;
1095     }
1096
1097     /* Special table ID support not required for stats requests. */
1098     if (*usable_protocols & OFPUTIL_P_OF10_STD_TID) {
1099         *usable_protocols |= OFPUTIL_P_OF10_STD;
1100     }
1101     if (*usable_protocols & OFPUTIL_P_OF10_NXM_TID) {
1102         *usable_protocols |= OFPUTIL_P_OF10_NXM;
1103     }
1104
1105     fsr->aggregate = aggregate;
1106     fsr->cookie = fm.cookie;
1107     fsr->cookie_mask = fm.cookie_mask;
1108     fsr->match = fm.match;
1109     fsr->out_port = fm.out_port;
1110     fsr->out_group = fm.out_group;
1111     fsr->table_id = fm.table_id;
1112     return NULL;
1113 }
1114
1115 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1116  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1117  * mf_field.  Fields must be specified in a natural order for satisfying
1118  * prerequisites. If 'mask' is specified, fills the mask field for each of the
1119  * field specified in flow. If the map, 'names_portno' is specfied, converts
1120  * the in_port name into port no while setting the 'flow'.
1121  *
1122  * Returns NULL on success, otherwise a malloc()'d string that explains the
1123  * problem. */
1124 char *
1125 parse_ofp_exact_flow(struct flow *flow, struct flow *mask, const char *s,
1126                      const struct simap *portno_names)
1127 {
1128     char *pos, *key, *value_s;
1129     char *error = NULL;
1130     char *copy;
1131
1132     memset(flow, 0, sizeof *flow);
1133     if (mask) {
1134         memset(mask, 0, sizeof *mask);
1135     }
1136
1137     pos = copy = xstrdup(s);
1138     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
1139         const struct protocol *p;
1140         if (parse_protocol(key, &p)) {
1141             if (flow->dl_type) {
1142                 error = xasprintf("%s: Ethernet type set multiple times", s);
1143                 goto exit;
1144             }
1145             flow->dl_type = htons(p->dl_type);
1146             if (mask) {
1147                 mask->dl_type = OVS_BE16_MAX;
1148             }
1149
1150             if (p->nw_proto) {
1151                 if (flow->nw_proto) {
1152                     error = xasprintf("%s: network protocol set "
1153                                       "multiple times", s);
1154                     goto exit;
1155                 }
1156                 flow->nw_proto = p->nw_proto;
1157                 if (mask) {
1158                     mask->nw_proto = UINT8_MAX;
1159                 }
1160             }
1161         } else {
1162             const struct mf_field *mf;
1163             union mf_value value;
1164             char *field_error;
1165
1166             mf = mf_from_name(key);
1167             if (!mf) {
1168                 error = xasprintf("%s: unknown field %s", s, key);
1169                 goto exit;
1170             }
1171
1172             if (!mf_are_prereqs_ok(mf, flow)) {
1173                 error = xasprintf("%s: prerequisites not met for setting %s",
1174                                   s, key);
1175                 goto exit;
1176             }
1177
1178             if (mf_is_set(mf, flow)) {
1179                 error = xasprintf("%s: field %s set multiple times", s, key);
1180                 goto exit;
1181             }
1182
1183             if (!strcmp(key, "in_port")
1184                 && portno_names
1185                 && simap_contains(portno_names, value_s)) {
1186                 flow->in_port.ofp_port = u16_to_ofp(
1187                     simap_get(portno_names, value_s));
1188                 if (mask) {
1189                     mask->in_port.ofp_port = u16_to_ofp(ntohs(OVS_BE16_MAX));
1190                 }
1191             } else {
1192                 field_error = mf_parse_value(mf, value_s, &value);
1193                 if (field_error) {
1194                     error = xasprintf("%s: bad value for %s (%s)",
1195                                       s, key, field_error);
1196                     free(field_error);
1197                     goto exit;
1198                 }
1199
1200                 mf_set_flow_value(mf, &value, flow);
1201                 if (mask) {
1202                     mf_mask_field(mf, mask);
1203                 }
1204             }
1205         }
1206     }
1207
1208     if (!flow->in_port.ofp_port) {
1209         flow->in_port.ofp_port = OFPP_NONE;
1210     }
1211
1212 exit:
1213     free(copy);
1214
1215     if (error) {
1216         memset(flow, 0, sizeof *flow);
1217         if (mask) {
1218             memset(mask, 0, sizeof *mask);
1219         }
1220     }
1221     return error;
1222 }
1223
1224 static char * OVS_WARN_UNUSED_RESULT
1225 parse_bucket_str(struct ofputil_bucket *bucket, char *str_, uint8_t group_type,
1226                   enum ofputil_protocol *usable_protocols)
1227 {
1228     char *pos, *key, *value;
1229     struct ofpbuf ofpacts;
1230     struct ds actions;
1231     char *error;
1232
1233     bucket->weight = group_type == OFPGT11_SELECT ? 1 : 0;
1234     bucket->bucket_id = OFPG15_BUCKET_ALL;
1235     bucket->watch_port = OFPP_ANY;
1236     bucket->watch_group = OFPG_ANY;
1237
1238     ds_init(&actions);
1239
1240     pos = str_;
1241     error = NULL;
1242     while (ofputil_parse_key_value(&pos, &key, &value)) {
1243         if (!strcasecmp(key, "weight")) {
1244             error = str_to_u16(value, "weight", &bucket->weight);
1245         } else if (!strcasecmp(key, "watch_port")) {
1246             if (!ofputil_port_from_string(value, &bucket->watch_port)
1247                 || (ofp_to_u16(bucket->watch_port) >= ofp_to_u16(OFPP_MAX)
1248                     && bucket->watch_port != OFPP_ANY)) {
1249                 error = xasprintf("%s: invalid watch_port", value);
1250             }
1251         } else if (!strcasecmp(key, "watch_group")) {
1252             error = str_to_u32(value, &bucket->watch_group);
1253             if (!error && bucket->watch_group > OFPG_MAX) {
1254                 error = xasprintf("invalid watch_group id %"PRIu32,
1255                                   bucket->watch_group);
1256             }
1257         } else if (!strcasecmp(key, "bucket_id")) {
1258             error = str_to_u32(value, &bucket->bucket_id);
1259             if (!error && bucket->bucket_id > OFPG15_BUCKET_MAX) {
1260                 error = xasprintf("invalid bucket_id id %"PRIu32,
1261                                   bucket->bucket_id);
1262             }
1263             *usable_protocols &= OFPUTIL_P_OF15_UP;
1264         } else if (!strcasecmp(key, "action") || !strcasecmp(key, "actions")) {
1265             ds_put_format(&actions, "%s,", value);
1266         } else {
1267             ds_put_format(&actions, "%s(%s),", key, value);
1268         }
1269
1270         if (error) {
1271             ds_destroy(&actions);
1272             return error;
1273         }
1274     }
1275
1276     if (!actions.length) {
1277         return xstrdup("bucket must specify actions");
1278     }
1279     ds_chomp(&actions, ',');
1280
1281     ofpbuf_init(&ofpacts, 0);
1282     error = ofpacts_parse_actions(ds_cstr(&actions), &ofpacts,
1283                                   usable_protocols);
1284     ds_destroy(&actions);
1285     if (error) {
1286         ofpbuf_uninit(&ofpacts);
1287         return error;
1288     }
1289     bucket->ofpacts = ofpacts.data;
1290     bucket->ofpacts_len = ofpacts.size;
1291
1292     return NULL;
1293 }
1294
1295 static char * OVS_WARN_UNUSED_RESULT
1296 parse_select_group_field(char *s, struct field_array *fa,
1297                          enum ofputil_protocol *usable_protocols)
1298 {
1299     char *name, *value_str;
1300
1301     while (ofputil_parse_key_value(&s, &name, &value_str)) {
1302         const struct mf_field *mf = mf_from_name(name);
1303
1304         if (mf) {
1305             char *error;
1306             union mf_value value;
1307
1308             if (bitmap_is_set(fa->used.bm, mf->id)) {
1309                 return xasprintf("%s: duplicate field", name);
1310             }
1311
1312             if (*value_str) {
1313                 error = mf_parse_value(mf, value_str, &value);
1314                 if (error) {
1315                     return error;
1316                 }
1317
1318                 /* The mask cannot be all-zeros */
1319                 if (!mf_is_tun_metadata(mf) &&
1320                     is_all_zeros(&value, mf->n_bytes)) {
1321                     return xasprintf("%s: values are wildcards here "
1322                                      "and must not be all-zeros", s);
1323                 }
1324
1325                 /* The values parsed are masks for fields used
1326                  * by the selection method */
1327                 if (!mf_is_mask_valid(mf, &value)) {
1328                     return xasprintf("%s: invalid mask for field %s",
1329                                      value_str, mf->name);
1330                 }
1331             } else {
1332                 memset(&value, 0xff, mf->n_bytes);
1333             }
1334
1335             field_array_set(mf->id, &value, fa);
1336
1337             if (is_all_ones(&value, mf->n_bytes)) {
1338                 *usable_protocols &= mf->usable_protocols_exact;
1339             } else if (mf->usable_protocols_bitwise == mf->usable_protocols_cidr
1340                        || ip_is_cidr(value.be32)) {
1341                 *usable_protocols &= mf->usable_protocols_cidr;
1342             } else {
1343                 *usable_protocols &= mf->usable_protocols_bitwise;
1344             }
1345         } else {
1346             return xasprintf("%s: unknown field %s", s, name);
1347         }
1348     }
1349
1350     return NULL;
1351 }
1352
1353 static char * OVS_WARN_UNUSED_RESULT
1354 parse_ofp_group_mod_str__(struct ofputil_group_mod *gm, uint16_t command,
1355                           char *string,
1356                           enum ofputil_protocol *usable_protocols)
1357 {
1358     enum {
1359         F_GROUP_TYPE            = 1 << 0,
1360         F_BUCKETS               = 1 << 1,
1361         F_COMMAND_BUCKET_ID     = 1 << 2,
1362         F_COMMAND_BUCKET_ID_ALL = 1 << 3,
1363     } fields;
1364     bool had_type = false;
1365     bool had_command_bucket_id = false;
1366     struct ofputil_bucket *bucket;
1367     char *error = NULL;
1368
1369     *usable_protocols = OFPUTIL_P_OF11_UP;
1370
1371     switch (command) {
1372     case OFPGC11_ADD:
1373         fields = F_GROUP_TYPE | F_BUCKETS;
1374         break;
1375
1376     case OFPGC11_DELETE:
1377         fields = 0;
1378         break;
1379
1380     case OFPGC11_MODIFY:
1381         fields = F_GROUP_TYPE | F_BUCKETS;
1382         break;
1383
1384     case OFPGC15_INSERT_BUCKET:
1385         fields = F_BUCKETS | F_COMMAND_BUCKET_ID;
1386         *usable_protocols &= OFPUTIL_P_OF15_UP;
1387         break;
1388
1389     case OFPGC15_REMOVE_BUCKET:
1390         fields = F_COMMAND_BUCKET_ID | F_COMMAND_BUCKET_ID_ALL;
1391         *usable_protocols &= OFPUTIL_P_OF15_UP;
1392         break;
1393
1394     default:
1395         OVS_NOT_REACHED();
1396     }
1397
1398     memset(gm, 0, sizeof *gm);
1399     gm->command = command;
1400     gm->group_id = OFPG_ANY;
1401     gm->command_bucket_id = OFPG15_BUCKET_ALL;
1402     list_init(&gm->buckets);
1403     if (command == OFPGC11_DELETE && string[0] == '\0') {
1404         gm->group_id = OFPG_ALL;
1405         return NULL;
1406     }
1407
1408     *usable_protocols = OFPUTIL_P_OF11_UP;
1409
1410     /* Strip the buckets off the end of 'string', if there are any, saving a
1411      * pointer for later.  We want to parse the buckets last because the bucket
1412      * type influences bucket defaults. */
1413     char *bkt_str = strstr(string, "bucket=");
1414     if (bkt_str) {
1415         if (!(fields & F_BUCKETS)) {
1416             error = xstrdup("bucket is not needed");
1417             goto out;
1418         }
1419         *bkt_str = '\0';
1420     }
1421
1422     /* Parse everything before the buckets. */
1423     char *pos = string;
1424     char *name, *value;
1425     while (ofputil_parse_key_value(&pos, &name, &value)) {
1426         if (!strcmp(name, "command_bucket_id")) {
1427             if (!(fields & F_COMMAND_BUCKET_ID)) {
1428                 error = xstrdup("command bucket id is not needed");
1429                 goto out;
1430             }
1431             if (!strcmp(value, "all")) {
1432                 gm->command_bucket_id = OFPG15_BUCKET_ALL;
1433             } else if (!strcmp(value, "first")) {
1434                 gm->command_bucket_id = OFPG15_BUCKET_FIRST;
1435             } else if (!strcmp(value, "last")) {
1436                 gm->command_bucket_id = OFPG15_BUCKET_LAST;
1437             } else {
1438                 error = str_to_u32(value, &gm->command_bucket_id);
1439                 if (error) {
1440                     goto out;
1441                 }
1442                 if (gm->command_bucket_id > OFPG15_BUCKET_MAX
1443                     && (gm->command_bucket_id != OFPG15_BUCKET_FIRST
1444                         && gm->command_bucket_id != OFPG15_BUCKET_LAST
1445                         && gm->command_bucket_id != OFPG15_BUCKET_ALL)) {
1446                     error = xasprintf("invalid command bucket id %"PRIu32,
1447                                       gm->command_bucket_id);
1448                     goto out;
1449                 }
1450             }
1451             if (gm->command_bucket_id == OFPG15_BUCKET_ALL
1452                 && !(fields & F_COMMAND_BUCKET_ID_ALL)) {
1453                 error = xstrdup("command_bucket_id=all is not permitted");
1454                 goto out;
1455             }
1456             had_command_bucket_id = true;
1457         } else if (!strcmp(name, "group_id")) {
1458             if(!strcmp(value, "all")) {
1459                 gm->group_id = OFPG_ALL;
1460             } else {
1461                 error = str_to_u32(value, &gm->group_id);
1462                 if (error) {
1463                     goto out;
1464                 }
1465                 if (gm->group_id != OFPG_ALL && gm->group_id > OFPG_MAX) {
1466                     error = xasprintf("invalid group id %"PRIu32,
1467                                       gm->group_id);
1468                     goto out;
1469                 }
1470             }
1471         } else if (!strcmp(name, "type")){
1472             if (!(fields & F_GROUP_TYPE)) {
1473                 error = xstrdup("type is not needed");
1474                 goto out;
1475             }
1476             if (!strcmp(value, "all")) {
1477                 gm->type = OFPGT11_ALL;
1478             } else if (!strcmp(value, "select")) {
1479                 gm->type = OFPGT11_SELECT;
1480             } else if (!strcmp(value, "indirect")) {
1481                 gm->type = OFPGT11_INDIRECT;
1482             } else if (!strcmp(value, "ff") ||
1483                        !strcmp(value, "fast_failover")) {
1484                 gm->type = OFPGT11_FF;
1485             } else {
1486                 error = xasprintf("invalid group type %s", value);
1487                 goto out;
1488             }
1489             had_type = true;
1490         } else if (!strcmp(name, "selection_method")) {
1491             if (!(fields & F_GROUP_TYPE)) {
1492                 error = xstrdup("selection method is not needed");
1493                 goto out;
1494             }
1495             if (strlen(value) >= NTR_MAX_SELECTION_METHOD_LEN) {
1496                 error = xasprintf("selection method is longer than %u"
1497                                   " bytes long",
1498                                   NTR_MAX_SELECTION_METHOD_LEN - 1);
1499                 goto out;
1500             }
1501             memset(gm->props.selection_method, '\0',
1502                    NTR_MAX_SELECTION_METHOD_LEN);
1503             strcpy(gm->props.selection_method, value);
1504             *usable_protocols &= OFPUTIL_P_OF15_UP;
1505         } else if (!strcmp(name, "selection_method_param")) {
1506             if (!(fields & F_GROUP_TYPE)) {
1507                 error = xstrdup("selection method param is not needed");
1508                 goto out;
1509             }
1510             error = str_to_u64(value, &gm->props.selection_method_param);
1511             if (error) {
1512                 goto out;
1513             }
1514             *usable_protocols &= OFPUTIL_P_OF15_UP;
1515         } else if (!strcmp(name, "fields")) {
1516             if (!(fields & F_GROUP_TYPE)) {
1517                 error = xstrdup("fields are not needed");
1518                 goto out;
1519             }
1520             error = parse_select_group_field(value, &gm->props.fields,
1521                                              usable_protocols);
1522             if (error) {
1523                 goto out;
1524             }
1525             *usable_protocols &= OFPUTIL_P_OF15_UP;
1526         } else {
1527             error = xasprintf("unknown keyword %s", name);
1528             goto out;
1529         }
1530     }
1531     if (gm->group_id == OFPG_ANY) {
1532         error = xstrdup("must specify a group_id");
1533         goto out;
1534     }
1535     if (fields & F_GROUP_TYPE && !had_type) {
1536         error = xstrdup("must specify a type");
1537         goto out;
1538     }
1539
1540     if (fields & F_COMMAND_BUCKET_ID) {
1541         if (!(fields & F_COMMAND_BUCKET_ID_ALL || had_command_bucket_id)) {
1542             error = xstrdup("must specify a command bucket id");
1543             goto out;
1544         }
1545     } else if (had_command_bucket_id) {
1546         error = xstrdup("command bucket id is not needed");
1547         goto out;
1548     }
1549
1550     /* Now parse the buckets, if any. */
1551     while (bkt_str) {
1552         char *next_bkt_str;
1553
1554         bkt_str = strchr(bkt_str + 1, '=');
1555         if (!bkt_str) {
1556             error = xstrdup("must specify bucket content");
1557             goto out;
1558         }
1559         bkt_str++;
1560
1561         next_bkt_str = strstr(bkt_str, "bucket=");
1562         if (next_bkt_str) {
1563             *next_bkt_str = '\0';
1564         }
1565
1566         bucket = xzalloc(sizeof(struct ofputil_bucket));
1567         error = parse_bucket_str(bucket, bkt_str, gm->type, usable_protocols);
1568         if (error) {
1569             free(bucket);
1570             goto out;
1571         }
1572         list_push_back(&gm->buckets, &bucket->list_node);
1573
1574         if (gm->type != OFPGT11_SELECT && bucket->weight) {
1575             error = xstrdup("Only select groups can have bucket weights.");
1576             goto out;
1577         }
1578
1579         bkt_str = next_bkt_str;
1580     }
1581     if (gm->type == OFPGT11_INDIRECT && !list_is_short(&gm->buckets)) {
1582         error = xstrdup("Indirect groups can have at most one bucket.");
1583         goto out;
1584     }
1585
1586     return NULL;
1587  out:
1588     ofputil_bucket_list_destroy(&gm->buckets);
1589     return error;
1590 }
1591
1592 char * OVS_WARN_UNUSED_RESULT
1593 parse_ofp_group_mod_str(struct ofputil_group_mod *gm, uint16_t command,
1594                         const char *str_,
1595                         enum ofputil_protocol *usable_protocols)
1596 {
1597     char *string = xstrdup(str_);
1598     char *error = parse_ofp_group_mod_str__(gm, command, string,
1599                                             usable_protocols);
1600     free(string);
1601
1602     if (error) {
1603         ofputil_bucket_list_destroy(&gm->buckets);
1604     }
1605     return error;
1606 }
1607
1608 char * OVS_WARN_UNUSED_RESULT
1609 parse_ofp_group_mod_file(const char *file_name, uint16_t command,
1610                          struct ofputil_group_mod **gms, size_t *n_gms,
1611                          enum ofputil_protocol *usable_protocols)
1612 {
1613     size_t allocated_gms;
1614     int line_number;
1615     FILE *stream;
1616     struct ds s;
1617
1618     *gms = NULL;
1619     *n_gms = 0;
1620
1621     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1622     if (stream == NULL) {
1623         return xasprintf("%s: open failed (%s)",
1624                          file_name, ovs_strerror(errno));
1625     }
1626
1627     allocated_gms = *n_gms;
1628     ds_init(&s);
1629     line_number = 0;
1630     *usable_protocols = OFPUTIL_P_OF11_UP;
1631     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
1632         enum ofputil_protocol usable;
1633         char *error;
1634
1635         if (*n_gms >= allocated_gms) {
1636             struct ofputil_group_mod *new_gms;
1637             size_t i;
1638
1639             new_gms = x2nrealloc(*gms, &allocated_gms, sizeof **gms);
1640             for (i = 0; i < *n_gms; i++) {
1641                 list_moved(&new_gms[i].buckets, &(*gms)[i].buckets);
1642             }
1643             *gms = new_gms;
1644         }
1645         error = parse_ofp_group_mod_str(&(*gms)[*n_gms], command, ds_cstr(&s),
1646                                         &usable);
1647         if (error) {
1648             size_t i;
1649
1650             for (i = 0; i < *n_gms; i++) {
1651                 ofputil_bucket_list_destroy(&(*gms)[i].buckets);
1652             }
1653             free(*gms);
1654             *gms = NULL;
1655             *n_gms = 0;
1656
1657             ds_destroy(&s);
1658             if (stream != stdin) {
1659                 fclose(stream);
1660             }
1661
1662             return xasprintf("%s:%d: %s", file_name, line_number, error);
1663         }
1664         *usable_protocols &= usable;
1665         *n_gms += 1;
1666     }
1667
1668     ds_destroy(&s);
1669     if (stream != stdin) {
1670         fclose(stream);
1671     }
1672     return NULL;
1673 }
1674
1675 char * OVS_WARN_UNUSED_RESULT
1676 parse_ofp_tlv_table_mod_str(struct ofputil_tlv_table_mod *ttm,
1677                                uint16_t command, const char *s,
1678                                enum ofputil_protocol *usable_protocols)
1679 {
1680     *usable_protocols = OFPUTIL_P_NXM_OXM_ANY;
1681
1682     ttm->command = command;
1683     list_init(&ttm->mappings);
1684
1685     while (*s) {
1686         struct ofputil_tlv_map *map = xmalloc(sizeof *map);
1687         int n;
1688
1689         if (*s == ',') {
1690             s++;
1691         }
1692
1693         list_push_back(&ttm->mappings, &map->list_node);
1694
1695         if (!ovs_scan(s, "{class=%"SCNi16",type=%"SCNi8",len=%"SCNi8"}->tun_metadata%"SCNi16"%n",
1696                       &map->option_class, &map->option_type, &map->option_len,
1697                       &map->index, &n)) {
1698             ofputil_uninit_tlv_table(&ttm->mappings);
1699             return xstrdup("invalid tlv mapping");
1700         }
1701
1702         s += n;
1703     }
1704
1705     return NULL;
1706 }