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