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