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