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