Add OF11 SET MPLS LABEL and SET MPLS TC actions.
[sliver-openvswitch.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "ofp-parse.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdlib.h>
24
25 #include "bundle.h"
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 "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 static char * 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 static char * 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 static char * 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 static char * 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 static char * 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 static char * WARN_UNUSED_RESULT
148 str_to_mac(const char *str, uint8_t mac[6])
149 {
150     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
151         != ETH_ADDR_SCAN_COUNT) {
152         return xasprintf("invalid mac address %s", str);
153     }
154     return NULL;
155 }
156
157 /* Parses 'str' as an IP address into '*ip'.
158  *
159  * Returns NULL if successful, otherwise a malloc()'d string describing the
160  * error.  The caller is responsible for freeing the returned string. */
161 static char * WARN_UNUSED_RESULT
162 str_to_ip(const char *str, ovs_be32 *ip)
163 {
164     struct in_addr in_addr;
165
166     if (lookup_ip(str, &in_addr)) {
167         return xasprintf("%s: could not convert to IP address", str);
168     }
169     *ip = in_addr.s_addr;
170     return NULL;
171 }
172
173 /* Parses 'arg' as the argument to an "enqueue" action, and appends such an
174  * action to 'ofpacts'.
175  *
176  * Returns NULL if successful, otherwise a malloc()'d string describing the
177  * error.  The caller is responsible for freeing the returned string. */
178 static char * WARN_UNUSED_RESULT
179 parse_enqueue(char *arg, struct ofpbuf *ofpacts)
180 {
181     char *sp = NULL;
182     char *port = strtok_r(arg, ":q", &sp);
183     char *queue = strtok_r(NULL, "", &sp);
184     struct ofpact_enqueue *enqueue;
185
186     if (port == NULL || queue == NULL) {
187         return xstrdup("\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
188     }
189
190     enqueue = ofpact_put_ENQUEUE(ofpacts);
191     if (!ofputil_port_from_string(port, &enqueue->port)) {
192         return xasprintf("%s: enqueue to unknown port", port);
193     }
194     return str_to_u32(queue, &enqueue->queue);
195 }
196
197 /* Parses 'arg' as the argument to an "output" action, and appends such an
198  * action to 'ofpacts'.
199  *
200  * Returns NULL if successful, otherwise a malloc()'d string describing the
201  * error.  The caller is responsible for freeing the returned string. */
202 static char * WARN_UNUSED_RESULT
203 parse_output(const char *arg, struct ofpbuf *ofpacts)
204 {
205     if (strchr(arg, '[')) {
206         struct ofpact_output_reg *output_reg;
207
208         output_reg = ofpact_put_OUTPUT_REG(ofpacts);
209         output_reg->max_len = UINT16_MAX;
210         return mf_parse_subfield(&output_reg->src, arg);
211     } else {
212         struct ofpact_output *output;
213
214         output = ofpact_put_OUTPUT(ofpacts);
215         output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0;
216         if (!ofputil_port_from_string(arg, &output->port)) {
217             return xasprintf("%s: output to unknown port", arg);
218         }
219         return NULL;
220     }
221 }
222
223 /* Parses 'arg' as the argument to an "resubmit" action, and appends such an
224  * action to 'ofpacts'.
225  *
226  * Returns NULL if successful, otherwise a malloc()'d string describing the
227  * error.  The caller is responsible for freeing the returned string. */
228 static char * WARN_UNUSED_RESULT
229 parse_resubmit(char *arg, struct ofpbuf *ofpacts)
230 {
231     struct ofpact_resubmit *resubmit;
232     char *in_port_s, *table_s;
233
234     resubmit = ofpact_put_RESUBMIT(ofpacts);
235
236     in_port_s = strsep(&arg, ",");
237     if (in_port_s && in_port_s[0]) {
238         if (!ofputil_port_from_string(in_port_s, &resubmit->in_port)) {
239             return xasprintf("%s: resubmit to unknown port", in_port_s);
240         }
241     } else {
242         resubmit->in_port = OFPP_IN_PORT;
243     }
244
245     table_s = strsep(&arg, ",");
246     if (table_s && table_s[0]) {
247         uint32_t table_id = 0;
248         char *error;
249
250         error = str_to_u32(table_s, &table_id);
251         if (error) {
252             return error;
253         }
254         resubmit->table_id = table_id;
255     } else {
256         resubmit->table_id = 255;
257     }
258
259     if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) {
260         return xstrdup("at least one \"in_port\" or \"table\" must be "
261                        "specified  on resubmit");
262     }
263     return NULL;
264 }
265
266 /* Parses 'arg' as the argument to a "note" action, and appends such an action
267  * to 'ofpacts'.
268  *
269  * Returns NULL if successful, otherwise a malloc()'d string describing the
270  * error.  The caller is responsible for freeing the returned string. */
271 static char * WARN_UNUSED_RESULT
272 parse_note(const char *arg, struct ofpbuf *ofpacts)
273 {
274     struct ofpact_note *note;
275
276     note = ofpact_put_NOTE(ofpacts);
277     while (*arg != '\0') {
278         uint8_t byte;
279         bool ok;
280
281         if (*arg == '.') {
282             arg++;
283         }
284         if (*arg == '\0') {
285             break;
286         }
287
288         byte = hexits_value(arg, 2, &ok);
289         if (!ok) {
290             return xstrdup("bad hex digit in `note' argument");
291         }
292         ofpbuf_put(ofpacts, &byte, 1);
293
294         note = ofpacts->l2;
295         note->length++;
296
297         arg += 2;
298     }
299     ofpact_update_len(ofpacts, &note->ofpact);
300     return NULL;
301 }
302
303 /* Parses 'arg' as the argument to a "fin_timeout" action, and appends such an
304  * action to 'ofpacts'.
305  *
306  * Returns NULL if successful, otherwise a malloc()'d string describing the
307  * error.  The caller is responsible for freeing the returned string. */
308 static char * WARN_UNUSED_RESULT
309 parse_fin_timeout(struct ofpbuf *b, char *arg)
310 {
311     struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(b);
312     char *key, *value;
313
314     while (ofputil_parse_key_value(&arg, &key, &value)) {
315         char *error;
316
317         if (!strcmp(key, "idle_timeout")) {
318             error =  str_to_u16(value, key, &oft->fin_idle_timeout);
319         } else if (!strcmp(key, "hard_timeout")) {
320             error = str_to_u16(value, key, &oft->fin_hard_timeout);
321         } else {
322             error = xasprintf("invalid key '%s' in 'fin_timeout' argument",
323                               key);
324         }
325
326         if (error) {
327             return error;
328         }
329     }
330     return NULL;
331 }
332
333 /* Parses 'arg' as the argument to a "controller" action, and appends such an
334  * action to 'ofpacts'.
335  *
336  * Returns NULL if successful, otherwise a malloc()'d string describing the
337  * error.  The caller is responsible for freeing the returned string. */
338 static char * WARN_UNUSED_RESULT
339 parse_controller(struct ofpbuf *b, char *arg)
340 {
341     enum ofp_packet_in_reason reason = OFPR_ACTION;
342     uint16_t controller_id = 0;
343     uint16_t max_len = UINT16_MAX;
344
345     if (!arg[0]) {
346         /* Use defaults. */
347     } else if (strspn(arg, "0123456789") == strlen(arg)) {
348         char *error = str_to_u16(arg, "max_len", &max_len);
349         if (error) {
350             return error;
351         }
352     } else {
353         char *name, *value;
354
355         while (ofputil_parse_key_value(&arg, &name, &value)) {
356             if (!strcmp(name, "reason")) {
357                 if (!ofputil_packet_in_reason_from_string(value, &reason)) {
358                     return xasprintf("unknown reason \"%s\"", value);
359                 }
360             } else if (!strcmp(name, "max_len")) {
361                 char *error = str_to_u16(value, "max_len", &max_len);
362                 if (error) {
363                     return error;
364                 }
365             } else if (!strcmp(name, "id")) {
366                 char *error = str_to_u16(value, "id", &controller_id);
367                 if (error) {
368                     return error;
369                 }
370             } else {
371                 return xasprintf("unknown key \"%s\" parsing controller "
372                                  "action", name);
373             }
374         }
375     }
376
377     if (reason == OFPR_ACTION && controller_id == 0) {
378         struct ofpact_output *output;
379
380         output = ofpact_put_OUTPUT(b);
381         output->port = OFPP_CONTROLLER;
382         output->max_len = max_len;
383     } else {
384         struct ofpact_controller *controller;
385
386         controller = ofpact_put_CONTROLLER(b);
387         controller->max_len = max_len;
388         controller->reason = reason;
389         controller->controller_id = controller_id;
390     }
391
392     return NULL;
393 }
394
395 static void
396 parse_noargs_dec_ttl(struct ofpbuf *b)
397 {
398     struct ofpact_cnt_ids *ids;
399     uint16_t id = 0;
400
401     ids = ofpact_put_DEC_TTL(b);
402     ofpbuf_put(b, &id, sizeof id);
403     ids = b->l2;
404     ids->n_controllers++;
405     ofpact_update_len(b, &ids->ofpact);
406 }
407
408 /* Parses 'arg' as the argument to a "dec_ttl" action, and appends such an
409  * action to 'ofpacts'.
410  *
411  * Returns NULL if successful, otherwise a malloc()'d string describing the
412  * error.  The caller is responsible for freeing the returned string. */
413 static char * WARN_UNUSED_RESULT
414 parse_dec_ttl(struct ofpbuf *b, char *arg)
415 {
416     if (*arg == '\0') {
417         parse_noargs_dec_ttl(b);
418     } else {
419         struct ofpact_cnt_ids *ids;
420         char *cntr;
421
422         ids = ofpact_put_DEC_TTL(b);
423         ids->ofpact.compat = OFPUTIL_NXAST_DEC_TTL_CNT_IDS;
424         for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL;
425              cntr = strtok_r(NULL, ", ", &arg)) {
426             uint16_t id = atoi(cntr);
427
428             ofpbuf_put(b, &id, sizeof id);
429             ids = b->l2;
430             ids->n_controllers++;
431         }
432         if (!ids->n_controllers) {
433             return xstrdup("dec_ttl_cnt_ids: expected at least one controller "
434                            "id.");
435         }
436         ofpact_update_len(b, &ids->ofpact);
437     }
438     return NULL;
439 }
440
441 /* Parses 'arg' as the argument to a "set_mpls_label" action, and appends such
442  * an action to 'b'.
443  *
444  * Returns NULL if successful, otherwise a malloc()'d string describing the
445  * error.  The caller is responsible for freeing the returned string. */
446 static char * WARN_UNUSED_RESULT
447 parse_set_mpls_label(struct ofpbuf *b, const char *arg)
448 {
449     struct ofpact_mpls_label *mpls_label = ofpact_put_SET_MPLS_LABEL(b);
450
451     if (*arg == '\0') {
452         return xstrdup("parse_set_mpls_label: expected label.");
453     }
454
455     mpls_label->label = htonl(atoi(arg));
456     return NULL;
457 }
458
459 /* Parses 'arg' as the argument to a "set_mpls_tc" action, and appends such an
460  * action to 'b'.
461  *
462  * Returns NULL if successful, otherwise a malloc()'d string describing the
463  * error.  The caller is responsible for freeing the returned string. */
464 static char * WARN_UNUSED_RESULT
465 parse_set_mpls_tc(struct ofpbuf *b, const char *arg)
466 {
467     struct ofpact_mpls_tc *mpls_tc = ofpact_put_SET_MPLS_TC(b);
468
469     if (*arg == '\0') {
470         return xstrdup("parse_set_mpls_tc: expected tc.");
471     }
472
473     mpls_tc->tc = atoi(arg);
474     return NULL;
475 }
476
477 /* Parses 'arg' as the argument to a "set_mpls_ttl" action, and appends such an
478  * action to 'ofpacts'.
479  *
480  * Returns NULL if successful, otherwise a malloc()'d string describing the
481  * error.  The caller is responsible for freeing the returned string. */
482 static char * WARN_UNUSED_RESULT
483 parse_set_mpls_ttl(struct ofpbuf *b, const char *arg)
484 {
485     struct ofpact_mpls_ttl *mpls_ttl = ofpact_put_SET_MPLS_TTL(b);
486
487     if (*arg == '\0') {
488         return xstrdup("parse_set_mpls_ttl: expected ttl.");
489     }
490
491     mpls_ttl->ttl = atoi(arg);
492     return NULL;
493 }
494
495 /* Parses a "set_field" action with argument 'arg', appending the parsed
496  * action to 'ofpacts'.
497  *
498  * Returns NULL if successful, otherwise a malloc()'d string describing the
499  * error.  The caller is responsible for freeing the returned string. */
500 static char * WARN_UNUSED_RESULT
501 set_field_parse__(char *arg, struct ofpbuf *ofpacts,
502                   enum ofputil_protocol *usable_protocols)
503 {
504     struct ofpact_set_field *sf = ofpact_put_SET_FIELD(ofpacts);
505     char *value;
506     char *delim;
507     char *key;
508     const struct mf_field *mf;
509     char *error;
510
511     value = arg;
512     delim = strstr(arg, "->");
513     if (!delim) {
514         return xasprintf("%s: missing `->'", arg);
515     }
516     if (strlen(delim) <= strlen("->")) {
517         return xasprintf("%s: missing field name following `->'", arg);
518     }
519
520     key = delim + strlen("->");
521     mf = mf_from_name(key);
522     if (!mf) {
523         return xasprintf("%s is not a valid OXM field name", key);
524     }
525     if (!mf->writable) {
526         return xasprintf("%s is read-only", key);
527     }
528     sf->field = mf;
529     delim[0] = '\0';
530     error = mf_parse_value(mf, value, &sf->value);
531     if (error) {
532         return error;
533     }
534
535     if (!mf_is_value_valid(mf, &sf->value)) {
536         return xasprintf("%s is not a valid value for field %s", value, key);
537     }
538
539     *usable_protocols &= mf->usable_protocols;
540     return NULL;
541 }
542
543 /* Parses 'arg' as the argument to a "set_field" action, and appends such an
544  * action to 'ofpacts'.
545  *
546  * Returns NULL if successful, otherwise a malloc()'d string describing the
547  * error.  The caller is responsible for freeing the returned string. */
548 static char * WARN_UNUSED_RESULT
549 set_field_parse(const char *arg, struct ofpbuf *ofpacts,
550                 enum ofputil_protocol *usable_protocols)
551 {
552     char *copy = xstrdup(arg);
553     char *error = set_field_parse__(copy, ofpacts, usable_protocols);
554     free(copy);
555     return error;
556 }
557
558 /* Parses 'arg' as the argument to a "write_metadata" instruction, and appends
559  * such an action to 'ofpacts'.
560  *
561  * Returns NULL if successful, otherwise a malloc()'d string describing the
562  * error.  The caller is responsible for freeing the returned string. */
563 static char * WARN_UNUSED_RESULT
564 parse_metadata(struct ofpbuf *b, char *arg)
565 {
566     struct ofpact_metadata *om;
567     char *mask = strchr(arg, '/');
568
569     om = ofpact_put_WRITE_METADATA(b);
570
571     if (mask) {
572         char *error;
573
574         *mask = '\0';
575         error = str_to_be64(mask + 1, &om->mask);
576         if (error) {
577             return error;
578         }
579     } else {
580         om->mask = OVS_BE64_MAX;
581     }
582
583     return str_to_be64(arg, &om->metadata);
584 }
585
586 /* Parses 'arg' as the argument to a "sample" action, and appends such an
587  * action to 'ofpacts'.
588  *
589  * Returns NULL if successful, otherwise a malloc()'d string describing the
590  * error.  The caller is responsible for freeing the returned string. */
591 static char * WARN_UNUSED_RESULT
592 parse_sample(struct ofpbuf *b, char *arg)
593 {
594     struct ofpact_sample *os = ofpact_put_SAMPLE(b);
595     char *key, *value;
596
597     while (ofputil_parse_key_value(&arg, &key, &value)) {
598         char *error = NULL;
599
600         if (!strcmp(key, "probability")) {
601             error = str_to_u16(value, "probability", &os->probability);
602             if (!error && os->probability == 0) {
603                 error = xasprintf("invalid probability value \"%s\"", value);
604             }
605         } else if (!strcmp(key, "collector_set_id")) {
606             error = str_to_u32(value, &os->collector_set_id);
607         } else if (!strcmp(key, "obs_domain_id")) {
608             error = str_to_u32(value, &os->obs_domain_id);
609         } else if (!strcmp(key, "obs_point_id")) {
610             error = str_to_u32(value, &os->obs_point_id);
611         } else {
612             error = xasprintf("invalid key \"%s\" in \"sample\" argument",
613                               key);
614         }
615         if (error) {
616             return error;
617         }
618     }
619     if (os->probability == 0) {
620         return xstrdup("non-zero \"probability\" must be specified on sample");
621     }
622     return NULL;
623 }
624
625 /* Parses 'arg' as the argument to action 'code', and appends such an action to
626  * 'ofpacts'.
627  *
628  * Returns NULL if successful, otherwise a malloc()'d string describing the
629  * error.  The caller is responsible for freeing the returned string. */
630 static char * WARN_UNUSED_RESULT
631 parse_named_action(enum ofputil_action_code code,
632                    char *arg, struct ofpbuf *ofpacts,
633                    enum ofputil_protocol *usable_protocols)
634 {
635     size_t orig_size = ofpacts->size;
636     struct ofpact_tunnel *tunnel;
637     struct ofpact_vlan_vid *vlan_vid;
638     struct ofpact_vlan_pcp *vlan_pcp;
639     char *error = NULL;
640     uint16_t ethertype = 0;
641     uint16_t vid = 0;
642     uint8_t tos = 0, ecn, ttl;
643     uint8_t pcp = 0;
644
645     switch (code) {
646     case OFPUTIL_ACTION_INVALID:
647         NOT_REACHED();
648
649     case OFPUTIL_OFPAT10_OUTPUT:
650     case OFPUTIL_OFPAT11_OUTPUT:
651         error = parse_output(arg, ofpacts);
652         break;
653
654     case OFPUTIL_OFPAT10_SET_VLAN_VID:
655     case OFPUTIL_OFPAT11_SET_VLAN_VID:
656         error = str_to_u16(arg, "VLAN VID", &vid);
657         if (error) {
658             return error;
659         }
660
661         if (vid & ~VLAN_VID_MASK) {
662             return xasprintf("%s: not a valid VLAN VID", arg);
663         }
664         vlan_vid = ofpact_put_SET_VLAN_VID(ofpacts);
665         vlan_vid->vlan_vid = vid;
666         vlan_vid->ofpact.compat = code;
667         vlan_vid->push_vlan_if_needed = code == OFPUTIL_OFPAT10_SET_VLAN_VID;
668         break;
669
670     case OFPUTIL_OFPAT10_SET_VLAN_PCP:
671     case OFPUTIL_OFPAT11_SET_VLAN_PCP:
672         error = str_to_u8(arg, "VLAN PCP", &pcp);
673         if (error) {
674             return error;
675         }
676
677         if (pcp & ~7) {
678             return xasprintf("%s: not a valid VLAN PCP", arg);
679         }
680         vlan_pcp = ofpact_put_SET_VLAN_PCP(ofpacts);
681         vlan_pcp->vlan_pcp = pcp;
682         vlan_pcp->ofpact.compat = code;
683         vlan_pcp->push_vlan_if_needed = code == OFPUTIL_OFPAT10_SET_VLAN_PCP;
684         break;
685
686     case OFPUTIL_OFPAT12_SET_FIELD:
687         return set_field_parse(arg, ofpacts, usable_protocols);
688
689     case OFPUTIL_OFPAT10_STRIP_VLAN:
690     case OFPUTIL_OFPAT11_POP_VLAN:
691         ofpact_put_STRIP_VLAN(ofpacts)->ofpact.compat = code;
692         break;
693
694     case OFPUTIL_OFPAT11_PUSH_VLAN:
695         *usable_protocols &= OFPUTIL_P_OF11_UP;
696         error = str_to_u16(arg, "ethertype", &ethertype);
697         if (error) {
698             return error;
699         }
700
701         if (ethertype != ETH_TYPE_VLAN_8021Q) {
702             /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */
703             return xasprintf("%s: not a valid VLAN ethertype", arg);
704         }
705
706         ofpact_put_PUSH_VLAN(ofpacts);
707         break;
708
709     case OFPUTIL_OFPAT11_SET_QUEUE:
710         error = str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
711         break;
712
713     case OFPUTIL_OFPAT10_SET_DL_SRC:
714     case OFPUTIL_OFPAT11_SET_DL_SRC:
715         error = str_to_mac(arg, ofpact_put_SET_ETH_SRC(ofpacts)->mac);
716         break;
717
718     case OFPUTIL_OFPAT10_SET_DL_DST:
719     case OFPUTIL_OFPAT11_SET_DL_DST:
720         error = str_to_mac(arg, ofpact_put_SET_ETH_DST(ofpacts)->mac);
721         break;
722
723     case OFPUTIL_OFPAT10_SET_NW_SRC:
724     case OFPUTIL_OFPAT11_SET_NW_SRC:
725         error = str_to_ip(arg, &ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4);
726         break;
727
728     case OFPUTIL_OFPAT10_SET_NW_DST:
729     case OFPUTIL_OFPAT11_SET_NW_DST:
730         error = str_to_ip(arg, &ofpact_put_SET_IPV4_DST(ofpacts)->ipv4);
731         break;
732
733     case OFPUTIL_OFPAT10_SET_NW_TOS:
734     case OFPUTIL_OFPAT11_SET_NW_TOS:
735         error = str_to_u8(arg, "TOS", &tos);
736         if (error) {
737             return error;
738         }
739
740         if (tos & ~IP_DSCP_MASK) {
741             return xasprintf("%s: not a valid TOS", arg);
742         }
743         ofpact_put_SET_IP_DSCP(ofpacts)->dscp = tos;
744         break;
745
746     case OFPUTIL_OFPAT11_SET_NW_ECN:
747         error = str_to_u8(arg, "ECN", &ecn);
748         if (error) {
749             return error;
750         }
751
752         if (ecn & ~IP_ECN_MASK) {
753             return xasprintf("%s: not a valid ECN", arg);
754         }
755         ofpact_put_SET_IP_ECN(ofpacts)->ecn = ecn;
756         break;
757
758     case OFPUTIL_OFPAT11_SET_NW_TTL:
759         error = str_to_u8(arg, "TTL", &ttl);
760         if (error) {
761             return error;
762         }
763
764         ofpact_put_SET_IP_TTL(ofpacts)->ttl = ttl;
765         break;
766
767     case OFPUTIL_OFPAT11_DEC_NW_TTL:
768         NOT_REACHED();
769
770     case OFPUTIL_OFPAT10_SET_TP_SRC:
771     case OFPUTIL_OFPAT11_SET_TP_SRC:
772         error = str_to_u16(arg, "source port",
773                            &ofpact_put_SET_L4_SRC_PORT(ofpacts)->port);
774         break;
775
776     case OFPUTIL_OFPAT10_SET_TP_DST:
777     case OFPUTIL_OFPAT11_SET_TP_DST:
778         error = str_to_u16(arg, "destination port",
779                            &ofpact_put_SET_L4_DST_PORT(ofpacts)->port);
780         break;
781
782     case OFPUTIL_OFPAT10_ENQUEUE:
783         error = parse_enqueue(arg, ofpacts);
784         break;
785
786     case OFPUTIL_NXAST_RESUBMIT:
787         error = parse_resubmit(arg, ofpacts);
788         break;
789
790     case OFPUTIL_NXAST_SET_TUNNEL:
791     case OFPUTIL_NXAST_SET_TUNNEL64:
792         tunnel = ofpact_put_SET_TUNNEL(ofpacts);
793         tunnel->ofpact.compat = code;
794         error = str_to_u64(arg, &tunnel->tun_id);
795         break;
796
797     case OFPUTIL_NXAST_WRITE_METADATA:
798         error = parse_metadata(ofpacts, arg);
799         break;
800
801     case OFPUTIL_NXAST_SET_QUEUE:
802         error = str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
803         break;
804
805     case OFPUTIL_NXAST_POP_QUEUE:
806         ofpact_put_POP_QUEUE(ofpacts);
807         break;
808
809     case OFPUTIL_NXAST_REG_MOVE:
810         error = nxm_parse_reg_move(ofpact_put_REG_MOVE(ofpacts), arg);
811         break;
812
813     case OFPUTIL_NXAST_REG_LOAD:
814         error = nxm_parse_reg_load(ofpact_put_REG_LOAD(ofpacts), arg);
815         break;
816
817     case OFPUTIL_NXAST_NOTE:
818         error = parse_note(arg, ofpacts);
819         break;
820
821     case OFPUTIL_NXAST_MULTIPATH:
822         error = multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
823         break;
824
825     case OFPUTIL_NXAST_BUNDLE:
826         error = bundle_parse(arg, ofpacts);
827         break;
828
829     case OFPUTIL_NXAST_BUNDLE_LOAD:
830         error = bundle_parse_load(arg, ofpacts);
831         break;
832
833     case OFPUTIL_NXAST_RESUBMIT_TABLE:
834     case OFPUTIL_NXAST_OUTPUT_REG:
835     case OFPUTIL_NXAST_DEC_TTL_CNT_IDS:
836         NOT_REACHED();
837
838     case OFPUTIL_NXAST_LEARN:
839         error = learn_parse(arg, ofpacts);
840         break;
841
842     case OFPUTIL_NXAST_EXIT:
843         ofpact_put_EXIT(ofpacts);
844         break;
845
846     case OFPUTIL_NXAST_DEC_TTL:
847         error = parse_dec_ttl(ofpacts, arg);
848         break;
849
850     case OFPUTIL_NXAST_SET_MPLS_LABEL:
851     case OFPUTIL_OFPAT11_SET_MPLS_LABEL:
852         error = parse_set_mpls_label(ofpacts, arg);
853         break;
854
855     case OFPUTIL_NXAST_SET_MPLS_TC:
856     case OFPUTIL_OFPAT11_SET_MPLS_TC:
857         error = parse_set_mpls_tc(ofpacts, arg);
858         break;
859
860     case OFPUTIL_NXAST_SET_MPLS_TTL:
861     case OFPUTIL_OFPAT11_SET_MPLS_TTL:
862         error = parse_set_mpls_ttl(ofpacts, arg);
863         break;
864
865     case OFPUTIL_OFPAT11_DEC_MPLS_TTL:
866     case OFPUTIL_NXAST_DEC_MPLS_TTL:
867         ofpact_put_DEC_MPLS_TTL(ofpacts);
868         break;
869
870     case OFPUTIL_NXAST_FIN_TIMEOUT:
871         error = parse_fin_timeout(ofpacts, arg);
872         break;
873
874     case OFPUTIL_NXAST_CONTROLLER:
875         error = parse_controller(ofpacts, arg);
876         break;
877
878     case OFPUTIL_OFPAT11_PUSH_MPLS:
879     case OFPUTIL_NXAST_PUSH_MPLS:
880         error = str_to_u16(arg, "push_mpls", &ethertype);
881         if (!error) {
882             ofpact_put_PUSH_MPLS(ofpacts)->ethertype = htons(ethertype);
883         }
884         break;
885
886     case OFPUTIL_OFPAT11_POP_MPLS:
887     case OFPUTIL_NXAST_POP_MPLS:
888         error = str_to_u16(arg, "pop_mpls", &ethertype);
889         if (!error) {
890             ofpact_put_POP_MPLS(ofpacts)->ethertype = htons(ethertype);
891         }
892         break;
893
894     case OFPUTIL_OFPAT11_GROUP:
895         error = str_to_u32(arg, &ofpact_put_GROUP(ofpacts)->group_id);
896         break;
897
898     case OFPUTIL_NXAST_STACK_PUSH:
899         error = nxm_parse_stack_action(ofpact_put_STACK_PUSH(ofpacts), arg);
900         break;
901     case OFPUTIL_NXAST_STACK_POP:
902         error = nxm_parse_stack_action(ofpact_put_STACK_POP(ofpacts), arg);
903         break;
904
905     case OFPUTIL_NXAST_SAMPLE:
906         error = parse_sample(ofpacts, arg);
907         break;
908     }
909
910     if (error) {
911         ofpacts->size = orig_size;
912     }
913     return error;
914 }
915
916 /* Parses action 'act', with argument 'arg', and appends a parsed version to
917  * 'ofpacts'.
918  *
919  * 'n_actions' specifies the number of actions already parsed (for proper
920  * handling of "drop" actions).
921  *
922  * Returns NULL if successful, otherwise a malloc()'d string describing the
923  * error.  The caller is responsible for freeing the returned string. */
924 static char * WARN_UNUSED_RESULT
925 str_to_ofpact__(char *pos, char *act, char *arg,
926                 struct ofpbuf *ofpacts, int n_actions,
927                 enum ofputil_protocol *usable_protocols)
928 {
929     int code = ofputil_action_code_from_name(act);
930     if (code >= 0) {
931         return parse_named_action(code, arg, ofpacts, usable_protocols);
932     } else if (!strcasecmp(act, "drop")) {
933         if (n_actions) {
934             return xstrdup("Drop actions must not be preceded by other "
935                            "actions");
936         } else if (ofputil_parse_key_value(&pos, &act, &arg)) {
937             return xstrdup("Drop actions must not be followed by other "
938                            "actions");
939         }
940     } else {
941         ofp_port_t port;
942         if (ofputil_port_from_string(act, &port)) {
943             ofpact_put_OUTPUT(ofpacts)->port = port;
944         } else {
945             return xasprintf("Unknown action: %s", act);
946         }
947     }
948
949     return NULL;
950 }
951
952 /* Parses 'str' as a series of actions, and appends them to 'ofpacts'.
953  *
954  * Returns NULL if successful, otherwise a malloc()'d string describing the
955  * error.  The caller is responsible for freeing the returned string. */
956 static char * WARN_UNUSED_RESULT
957 str_to_ofpacts__(char *str, struct ofpbuf *ofpacts,
958                  enum ofputil_protocol *usable_protocols)
959 {
960     size_t orig_size = ofpacts->size;
961     char *pos, *act, *arg;
962     int n_actions;
963
964     pos = str;
965     n_actions = 0;
966     while (ofputil_parse_key_value(&pos, &act, &arg)) {
967         char *error = str_to_ofpact__(pos, act, arg, ofpacts, n_actions,
968                                       usable_protocols);
969         if (error) {
970             ofpacts->size = orig_size;
971             return error;
972         }
973         n_actions++;
974     }
975
976     ofpact_pad(ofpacts);
977     return NULL;
978 }
979
980
981 /* Parses 'str' as a series of actions, and appends them to 'ofpacts'.
982  *
983  * Returns NULL if successful, otherwise a malloc()'d string describing the
984  * error.  The caller is responsible for freeing the returned string. */
985 static char * WARN_UNUSED_RESULT
986 str_to_ofpacts(char *str, struct ofpbuf *ofpacts,
987                enum ofputil_protocol *usable_protocols)
988 {
989     size_t orig_size = ofpacts->size;
990     char *error_s;
991     enum ofperr error;
992
993     error_s = str_to_ofpacts__(str, ofpacts, usable_protocols);
994     if (error_s) {
995         return error_s;
996     }
997
998     error = ofpacts_verify(ofpacts->data, ofpacts->size);
999     if (error) {
1000         ofpacts->size = orig_size;
1001         return xstrdup("Incorrect action ordering");
1002     }
1003
1004     return NULL;
1005 }
1006
1007 /* Parses 'arg' as the argument to instruction 'type', and appends such an
1008  * instruction to 'ofpacts'.
1009  *
1010  * Returns NULL if successful, otherwise a malloc()'d string describing the
1011  * error.  The caller is responsible for freeing the returned string. */
1012 static char * WARN_UNUSED_RESULT
1013 parse_named_instruction(enum ovs_instruction_type type,
1014                         char *arg, struct ofpbuf *ofpacts,
1015                         enum ofputil_protocol *usable_protocols)
1016 {
1017     char *error_s = NULL;
1018     enum ofperr error;
1019
1020     *usable_protocols &= OFPUTIL_P_OF11_UP;
1021
1022     switch (type) {
1023     case OVSINST_OFPIT11_APPLY_ACTIONS:
1024         NOT_REACHED();  /* This case is handled by str_to_inst_ofpacts() */
1025         break;
1026
1027     case OVSINST_OFPIT11_WRITE_ACTIONS: {
1028         struct ofpact_nest *on;
1029         size_t ofs;
1030
1031         ofpact_pad(ofpacts);
1032         ofs = ofpacts->size;
1033         on = ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS,
1034                         offsetof(struct ofpact_nest, actions));
1035         error_s = str_to_ofpacts__(arg, ofpacts, usable_protocols);
1036
1037         on = ofpbuf_at_assert(ofpacts, ofs, sizeof *on);
1038         on->ofpact.len = ofpacts->size - ofs;
1039
1040         if (error_s) {
1041             ofpacts->size = ofs;
1042         }
1043         break;
1044     }
1045
1046     case OVSINST_OFPIT11_CLEAR_ACTIONS:
1047         ofpact_put_CLEAR_ACTIONS(ofpacts);
1048         break;
1049
1050     case OVSINST_OFPIT13_METER:
1051         *usable_protocols &= OFPUTIL_P_OF13_UP;
1052         error_s = str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id);
1053         break;
1054
1055     case OVSINST_OFPIT11_WRITE_METADATA:
1056         *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
1057         error_s = parse_metadata(ofpacts, arg);
1058         break;
1059
1060     case OVSINST_OFPIT11_GOTO_TABLE: {
1061         struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
1062         char *table_s = strsep(&arg, ",");
1063         if (!table_s || !table_s[0]) {
1064             return xstrdup("instruction goto-table needs table id");
1065         }
1066         error_s = str_to_u8(table_s, "table", &ogt->table_id);
1067         break;
1068     }
1069     }
1070
1071     if (error_s) {
1072         return error_s;
1073     }
1074
1075     /* If write_metadata is specified as an action AND an instruction, ofpacts
1076        could be invalid. */
1077     error = ofpacts_verify(ofpacts->data, ofpacts->size);
1078     if (error) {
1079         return xstrdup("Incorrect instruction ordering");
1080     }
1081     return NULL;
1082 }
1083
1084 /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'.
1085  *
1086  * Returns NULL if successful, otherwise a malloc()'d string describing the
1087  * error.  The caller is responsible for freeing the returned string. */
1088 static char * WARN_UNUSED_RESULT
1089 str_to_inst_ofpacts(char *str, struct ofpbuf *ofpacts,
1090                     enum ofputil_protocol *usable_protocols)
1091 {
1092     size_t orig_size = ofpacts->size;
1093     char *pos, *inst, *arg;
1094     int type;
1095     const char *prev_inst = NULL;
1096     int prev_type = -1;
1097     int n_actions = 0;
1098
1099     pos = str;
1100     while (ofputil_parse_key_value(&pos, &inst, &arg)) {
1101         type = ovs_instruction_type_from_name(inst);
1102         if (type < 0) {
1103             char *error = str_to_ofpact__(pos, inst, arg, ofpacts, n_actions,
1104                                           usable_protocols);
1105             if (error) {
1106                 ofpacts->size = orig_size;
1107                 return error;
1108             }
1109
1110             type = OVSINST_OFPIT11_APPLY_ACTIONS;
1111             if (prev_type == type) {
1112                 n_actions++;
1113                 continue;
1114             }
1115         } else if (type == OVSINST_OFPIT11_APPLY_ACTIONS) {
1116             ofpacts->size = orig_size;
1117             return xasprintf("%s isn't supported. Just write actions then "
1118                              "it is interpreted as apply_actions", inst);
1119         } else {
1120             char *error = parse_named_instruction(type, arg, ofpacts,
1121                                                   usable_protocols);
1122             if (error) {
1123                 ofpacts->size = orig_size;
1124                 return error;
1125             }
1126         }
1127
1128         if (type <= prev_type) {
1129             ofpacts->size = orig_size;
1130             if (type == prev_type) {
1131                 return xasprintf("instruction %s may be specified only once",
1132                                  inst);
1133             } else {
1134                 return xasprintf("instruction %s must be specified before %s",
1135                                  inst, prev_inst);
1136             }
1137         }
1138
1139         prev_inst = inst;
1140         prev_type = type;
1141         n_actions++;
1142     }
1143     ofpact_pad(ofpacts);
1144
1145     return NULL;
1146 }
1147
1148 struct protocol {
1149     const char *name;
1150     uint16_t dl_type;
1151     uint8_t nw_proto;
1152 };
1153
1154 static bool
1155 parse_protocol(const char *name, const struct protocol **p_out)
1156 {
1157     static const struct protocol protocols[] = {
1158         { "ip", ETH_TYPE_IP, 0 },
1159         { "arp", ETH_TYPE_ARP, 0 },
1160         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
1161         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
1162         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
1163         { "sctp", ETH_TYPE_IP, IPPROTO_SCTP },
1164         { "ipv6", ETH_TYPE_IPV6, 0 },
1165         { "ip6", ETH_TYPE_IPV6, 0 },
1166         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
1167         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
1168         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
1169         { "sctp6", ETH_TYPE_IPV6, IPPROTO_SCTP },
1170         { "rarp", ETH_TYPE_RARP, 0},
1171         { "mpls", ETH_TYPE_MPLS, 0 },
1172         { "mplsm", ETH_TYPE_MPLS_MCAST, 0 },
1173     };
1174     const struct protocol *p;
1175
1176     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
1177         if (!strcmp(p->name, name)) {
1178             *p_out = p;
1179             return true;
1180         }
1181     }
1182     *p_out = NULL;
1183     return false;
1184 }
1185
1186 /* Parses 's' as the (possibly masked) value of field 'mf', and updates
1187  * 'match' appropriately.  Restricts the set of usable protocols to ones
1188  * supporting the parsed field.
1189  *
1190  * Returns NULL if successful, otherwise a malloc()'d string describing the
1191  * error.  The caller is responsible for freeing the returned string. */
1192 static char * WARN_UNUSED_RESULT
1193 parse_field(const struct mf_field *mf, const char *s, struct match *match,
1194             enum ofputil_protocol *usable_protocols)
1195 {
1196     union mf_value value, mask;
1197     char *error;
1198
1199     error = mf_parse(mf, s, &value, &mask);
1200     if (!error) {
1201         *usable_protocols &= mf_set(mf, &value, &mask, match);
1202     }
1203     return error;
1204 }
1205
1206 static char * WARN_UNUSED_RESULT
1207 parse_ofp_str__(struct ofputil_flow_mod *fm, int command, char *string,
1208                 enum ofputil_protocol *usable_protocols,
1209                 bool enforce_consistency)
1210 {
1211     enum {
1212         F_OUT_PORT = 1 << 0,
1213         F_ACTIONS = 1 << 1,
1214         F_TIMEOUT = 1 << 3,
1215         F_PRIORITY = 1 << 4,
1216         F_FLAGS = 1 << 5,
1217     } fields;
1218     char *save_ptr = NULL;
1219     char *act_str = NULL;
1220     char *name;
1221
1222     *usable_protocols = OFPUTIL_P_ANY;
1223
1224     switch (command) {
1225     case -1:
1226         fields = F_OUT_PORT;
1227         break;
1228
1229     case OFPFC_ADD:
1230         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1231         break;
1232
1233     case OFPFC_DELETE:
1234         fields = F_OUT_PORT;
1235         break;
1236
1237     case OFPFC_DELETE_STRICT:
1238         fields = F_OUT_PORT | F_PRIORITY;
1239         break;
1240
1241     case OFPFC_MODIFY:
1242         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1243         break;
1244
1245     case OFPFC_MODIFY_STRICT:
1246         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1247         break;
1248
1249     default:
1250         NOT_REACHED();
1251     }
1252
1253     match_init_catchall(&fm->match);
1254     fm->priority = OFP_DEFAULT_PRIORITY;
1255     fm->cookie = htonll(0);
1256     fm->cookie_mask = htonll(0);
1257     if (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT) {
1258         /* For modify, by default, don't update the cookie. */
1259         fm->new_cookie = OVS_BE64_MAX;
1260     } else{
1261         fm->new_cookie = htonll(0);
1262     }
1263     fm->modify_cookie = false;
1264     fm->table_id = 0xff;
1265     fm->command = command;
1266     fm->idle_timeout = OFP_FLOW_PERMANENT;
1267     fm->hard_timeout = OFP_FLOW_PERMANENT;
1268     fm->buffer_id = UINT32_MAX;
1269     fm->out_port = OFPP_ANY;
1270     fm->flags = 0;
1271     fm->out_group = OFPG11_ANY;
1272     if (fields & F_ACTIONS) {
1273         act_str = strstr(string, "action");
1274         if (!act_str) {
1275             return xstrdup("must specify an action");
1276         }
1277         *act_str = '\0';
1278
1279         act_str = strchr(act_str + 1, '=');
1280         if (!act_str) {
1281             return xstrdup("must specify an action");
1282         }
1283
1284         act_str++;
1285     }
1286     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1287          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1288         const struct protocol *p;
1289         char *error = NULL;
1290
1291         if (parse_protocol(name, &p)) {
1292             match_set_dl_type(&fm->match, htons(p->dl_type));
1293             if (p->nw_proto) {
1294                 match_set_nw_proto(&fm->match, p->nw_proto);
1295             }
1296         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
1297             fm->flags |= OFPUTIL_FF_SEND_FLOW_REM;
1298         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
1299             fm->flags |= OFPUTIL_FF_CHECK_OVERLAP;
1300         } else if (fields & F_FLAGS && !strcmp(name, "reset_counts")) {
1301             fm->flags |= OFPUTIL_FF_RESET_COUNTS;
1302             *usable_protocols &= OFPUTIL_P_OF12_UP;
1303         } else if (fields & F_FLAGS && !strcmp(name, "no_packet_counts")) {
1304             fm->flags |= OFPUTIL_FF_NO_PKT_COUNTS;
1305             *usable_protocols &= OFPUTIL_P_OF13_UP;
1306         } else if (fields & F_FLAGS && !strcmp(name, "no_byte_counts")) {
1307             fm->flags |= OFPUTIL_FF_NO_BYT_COUNTS;
1308             *usable_protocols &= OFPUTIL_P_OF13_UP;
1309         } else {
1310             char *value;
1311
1312             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1313             if (!value) {
1314                 return xasprintf("field %s missing value", name);
1315             }
1316
1317             if (!strcmp(name, "table")) {
1318                 error = str_to_u8(value, "table", &fm->table_id);
1319                 if (fm->table_id != 0xff) {
1320                     *usable_protocols &= OFPUTIL_P_TID;
1321                 }
1322             } else if (!strcmp(name, "out_port")) {
1323                 if (!ofputil_port_from_string(value, &fm->out_port)) {
1324                     error = xasprintf("%s is not a valid OpenFlow port",
1325                                       value);
1326                 }
1327             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
1328                 uint16_t priority = 0;
1329
1330                 error = str_to_u16(value, name, &priority);
1331                 fm->priority = priority;
1332             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
1333                 error = str_to_u16(value, name, &fm->idle_timeout);
1334             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
1335                 error = str_to_u16(value, name, &fm->hard_timeout);
1336             } else if (!strcmp(name, "cookie")) {
1337                 char *mask = strchr(value, '/');
1338
1339                 if (mask) {
1340                     /* A mask means we're searching for a cookie. */
1341                     if (command == OFPFC_ADD) {
1342                         return xstrdup("flow additions cannot use "
1343                                        "a cookie mask");
1344                     }
1345                     *mask = '\0';
1346                     error = str_to_be64(value, &fm->cookie);
1347                     if (error) {
1348                         return error;
1349                     }
1350                     error = str_to_be64(mask + 1, &fm->cookie_mask);
1351
1352                     /* Matching of the cookie is only supported through NXM or
1353                      * OF1.1+. */
1354                     if (fm->cookie_mask != htonll(0)) {
1355                         *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
1356                     }
1357                 } else {
1358                     /* No mask means that the cookie is being set. */
1359                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
1360                         && command != OFPFC_MODIFY_STRICT) {
1361                         return xstrdup("cannot set cookie");
1362                     }
1363                     error = str_to_be64(value, &fm->new_cookie);
1364                     fm->modify_cookie = true;
1365                 }
1366             } else if (mf_from_name(name)) {
1367                 error = parse_field(mf_from_name(name), value, &fm->match,
1368                                     usable_protocols);
1369             } else if (!strcmp(name, "duration")
1370                        || !strcmp(name, "n_packets")
1371                        || !strcmp(name, "n_bytes")
1372                        || !strcmp(name, "idle_age")
1373                        || !strcmp(name, "hard_age")) {
1374                 /* Ignore these, so that users can feed the output of
1375                  * "ovs-ofctl dump-flows" back into commands that parse
1376                  * flows. */
1377             } else {
1378                 error = xasprintf("unknown keyword %s", name);
1379             }
1380
1381             if (error) {
1382                 return error;
1383             }
1384         }
1385     }
1386     /* Check for usable protocol interdependencies between match fields. */
1387     if (fm->match.flow.dl_type == htons(ETH_TYPE_IPV6)) {
1388         const struct flow_wildcards *wc = &fm->match.wc;
1389         /* Only NXM and OXM support matching L3 and L4 fields within IPv6.
1390          *
1391          * (IPv6 specific fields as well as arp_sha, arp_tha, nw_frag, and
1392          *  nw_ttl are covered elsewhere so they don't need to be included in
1393          *  this test too.)
1394          */
1395         if (wc->masks.nw_proto || wc->masks.nw_tos
1396             || wc->masks.tp_src || wc->masks.tp_dst) {
1397             *usable_protocols &= OFPUTIL_P_NXM_OXM_ANY;
1398         }
1399     }
1400     if (!fm->cookie_mask && fm->new_cookie == OVS_BE64_MAX
1401         && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
1402         /* On modifies without a mask, we are supposed to add a flow if
1403          * one does not exist.  If a cookie wasn't been specified, use a
1404          * default of zero. */
1405         fm->new_cookie = htonll(0);
1406     }
1407     if (fields & F_ACTIONS) {
1408         struct ofpbuf ofpacts;
1409         char *error;
1410
1411         ofpbuf_init(&ofpacts, 32);
1412         error = str_to_inst_ofpacts(act_str, &ofpacts, usable_protocols);
1413         if (!error) {
1414             enum ofperr err;
1415
1416             err = ofpacts_check(ofpacts.data, ofpacts.size, &fm->match.flow,
1417                                 true, OFPP_MAX, fm->table_id, 255);
1418             if (err) {
1419                 if (!enforce_consistency &&
1420                     err == OFPERR_OFPBAC_MATCH_INCONSISTENT) {
1421                     /* Allow inconsistent actions to be used with OF 1.0. */
1422                     *usable_protocols &= OFPUTIL_P_OF10_ANY;
1423                     /* Try again, allowing for inconsistency.
1424                      * XXX: As a side effect, logging may be duplicated. */
1425                     err = ofpacts_check(ofpacts.data, ofpacts.size,
1426                                         &fm->match.flow, false,
1427                                         OFPP_MAX, fm->table_id, 255);
1428                 }
1429                 if (err) {
1430                     error = xasprintf("actions are invalid with specified match "
1431                                       "(%s)", ofperr_to_string(err));
1432                 }
1433             }
1434         }
1435         if (error) {
1436             ofpbuf_uninit(&ofpacts);
1437             return error;
1438         }
1439
1440         fm->ofpacts_len = ofpacts.size;
1441         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
1442     } else {
1443         fm->ofpacts_len = 0;
1444         fm->ofpacts = NULL;
1445     }
1446
1447     return NULL;
1448 }
1449
1450 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1451  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
1452  * Returns the set of usable protocols in '*usable_protocols'.
1453  *
1454  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
1455  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
1456  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'.
1457  *
1458  * Returns NULL if successful, otherwise a malloc()'d string describing the
1459  * error.  The caller is responsible for freeing the returned string. */
1460 char * WARN_UNUSED_RESULT
1461 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
1462               enum ofputil_protocol *usable_protocols,
1463               bool enforce_consistency)
1464 {
1465     char *string = xstrdup(str_);
1466     char *error;
1467
1468     error = parse_ofp_str__(fm, command, string, usable_protocols,
1469                             enforce_consistency);
1470     if (error) {
1471         fm->ofpacts = NULL;
1472         fm->ofpacts_len = 0;
1473     }
1474
1475     free(string);
1476     return error;
1477 }
1478
1479 static char * WARN_UNUSED_RESULT
1480 parse_ofp_meter_mod_str__(struct ofputil_meter_mod *mm, char *string,
1481                           struct ofpbuf *bands, int command,
1482                           enum ofputil_protocol *usable_protocols)
1483 {
1484     enum {
1485         F_METER = 1 << 0,
1486         F_FLAGS = 1 << 1,
1487         F_BANDS = 1 << 2,
1488     } fields;
1489     char *save_ptr = NULL;
1490     char *band_str = NULL;
1491     char *name;
1492
1493     /* Meters require at least OF 1.3. */
1494     *usable_protocols = OFPUTIL_P_OF13_UP;
1495
1496     switch (command) {
1497     case -1:
1498         fields = F_METER;
1499         break;
1500
1501     case OFPMC13_ADD:
1502         fields = F_METER | F_FLAGS | F_BANDS;
1503         break;
1504
1505     case OFPMC13_DELETE:
1506         fields = F_METER;
1507         break;
1508
1509     case OFPMC13_MODIFY:
1510         fields = F_METER | F_FLAGS | F_BANDS;
1511         break;
1512
1513     default:
1514         NOT_REACHED();
1515     }
1516
1517     mm->command = command;
1518     mm->meter.meter_id = 0;
1519     mm->meter.flags = 0;
1520     if (fields & F_BANDS) {
1521         band_str = strstr(string, "band");
1522         if (!band_str) {
1523             return xstrdup("must specify bands");
1524         }
1525         *band_str = '\0';
1526
1527         band_str = strchr(band_str + 1, '=');
1528         if (!band_str) {
1529             return xstrdup("must specify bands");
1530         }
1531
1532         band_str++;
1533     }
1534     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1535          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1536
1537         if (fields & F_FLAGS && !strcmp(name, "kbps")) {
1538             mm->meter.flags |= OFPMF13_KBPS;
1539         } else if (fields & F_FLAGS && !strcmp(name, "pktps")) {
1540             mm->meter.flags |= OFPMF13_PKTPS;
1541         } else if (fields & F_FLAGS && !strcmp(name, "burst")) {
1542             mm->meter.flags |= OFPMF13_BURST;
1543         } else if (fields & F_FLAGS && !strcmp(name, "stats")) {
1544             mm->meter.flags |= OFPMF13_STATS;
1545         } else {
1546             char *value;
1547
1548             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1549             if (!value) {
1550                 return xasprintf("field %s missing value", name);
1551             }
1552
1553             if (!strcmp(name, "meter")) {
1554                 if (!strcmp(value, "all")) {
1555                     mm->meter.meter_id = OFPM13_ALL;
1556                 } else if (!strcmp(value, "controller")) {
1557                     mm->meter.meter_id = OFPM13_CONTROLLER;
1558                 } else if (!strcmp(value, "slowpath")) {
1559                     mm->meter.meter_id = OFPM13_SLOWPATH;
1560                 } else {
1561                     char *error = str_to_u32(value, &mm->meter.meter_id);
1562                     if (error) {
1563                         return error;
1564                     }
1565                     if (mm->meter.meter_id > OFPM13_MAX) {
1566                         return xasprintf("invalid value for %s", name);
1567                     }
1568                 }
1569             } else {
1570                 return xasprintf("unknown keyword %s", name);
1571             }
1572         }
1573     }
1574     if (fields & F_METER && !mm->meter.meter_id) {
1575         return xstrdup("must specify 'meter'");
1576     }
1577     if (fields & F_FLAGS && !mm->meter.flags) {
1578         return xstrdup("meter must specify either 'kbps' or 'pktps'");
1579     }
1580
1581     if (fields & F_BANDS) {
1582         uint16_t n_bands = 0;
1583         struct ofputil_meter_band *band = NULL;
1584         int i;
1585
1586         for (name = strtok_r(band_str, "=, \t\r\n", &save_ptr); name;
1587              name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1588
1589             char *value;
1590
1591             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1592             if (!value) {
1593                 return xasprintf("field %s missing value", name);
1594             }
1595
1596             if (!strcmp(name, "type")) {
1597                 /* Start a new band */
1598                 band = ofpbuf_put_zeros(bands, sizeof *band);
1599                 n_bands++;
1600
1601                 if (!strcmp(value, "drop")) {
1602                     band->type = OFPMBT13_DROP;
1603                 } else if (!strcmp(value, "dscp_remark")) {
1604                     band->type = OFPMBT13_DSCP_REMARK;
1605                 } else {
1606                     return xasprintf("field %s unknown value %s", name, value);
1607                 }
1608             } else if (!band || !band->type) {
1609                 return xstrdup("band must start with the 'type' keyword");
1610             } else if (!strcmp(name, "rate")) {
1611                 char *error = str_to_u32(value, &band->rate);
1612                 if (error) {
1613                     return error;
1614                 }
1615             } else if (!strcmp(name, "burst_size")) {
1616                 char *error = str_to_u32(value, &band->burst_size);
1617                 if (error) {
1618                     return error;
1619                 }
1620             } else if (!strcmp(name, "prec_level")) {
1621                 char *error = str_to_u8(value, name, &band->prec_level);
1622                 if (error) {
1623                     return error;
1624                 }
1625             } else {
1626                 return xasprintf("unknown keyword %s", name);
1627             }
1628         }
1629         /* validate bands */
1630         if (!n_bands) {
1631             return xstrdup("meter must have bands");
1632         }
1633
1634         mm->meter.n_bands = n_bands;
1635         mm->meter.bands = ofpbuf_steal_data(bands);
1636
1637         for (i = 0; i < n_bands; ++i) {
1638             band = &mm->meter.bands[i];
1639
1640             if (!band->type) {
1641                 return xstrdup("band must have 'type'");
1642             }
1643             if (band->type == OFPMBT13_DSCP_REMARK) {
1644                 if (!band->prec_level) {
1645                     return xstrdup("'dscp_remark' band must have"
1646                                    " 'prec_level'");
1647                 }
1648             } else {
1649                 if (band->prec_level) {
1650                     return xstrdup("Only 'dscp_remark' band may have"
1651                                    " 'prec_level'");
1652                 }
1653             }
1654             if (!band->rate) {
1655                 return xstrdup("band must have 'rate'");
1656             }
1657             if (mm->meter.flags & OFPMF13_BURST) {
1658                 if (!band->burst_size) {
1659                     return xstrdup("band must have 'burst_size' "
1660                                    "when 'burst' flag is set");
1661                 }
1662             } else {
1663                 if (band->burst_size) {
1664                     return xstrdup("band may have 'burst_size' only "
1665                                    "when 'burst' flag is set");
1666                 }
1667             }
1668         }
1669     } else {
1670         mm->meter.n_bands = 0;
1671         mm->meter.bands = NULL;
1672     }
1673
1674     return NULL;
1675 }
1676
1677 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1678  * page) into 'mm' for sending the specified meter_mod 'command' to a switch.
1679  *
1680  * Returns NULL if successful, otherwise a malloc()'d string describing the
1681  * error.  The caller is responsible for freeing the returned string. */
1682 char * WARN_UNUSED_RESULT
1683 parse_ofp_meter_mod_str(struct ofputil_meter_mod *mm, const char *str_,
1684                         int command, enum ofputil_protocol *usable_protocols)
1685 {
1686     struct ofpbuf bands;
1687     char *string;
1688     char *error;
1689
1690     ofpbuf_init(&bands, 64);
1691     string = xstrdup(str_);
1692
1693     error = parse_ofp_meter_mod_str__(mm, string, &bands, command,
1694                                       usable_protocols);
1695
1696     free(string);
1697     ofpbuf_uninit(&bands);
1698
1699     return error;
1700 }
1701
1702 static char * WARN_UNUSED_RESULT
1703 parse_flow_monitor_request__(struct ofputil_flow_monitor_request *fmr,
1704                              const char *str_, char *string,
1705                              enum ofputil_protocol *usable_protocols)
1706 {
1707     static atomic_uint32_t id = ATOMIC_VAR_INIT(0);
1708     char *save_ptr = NULL;
1709     char *name;
1710
1711     atomic_add(&id, 1, &fmr->id);
1712
1713     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
1714                   | NXFMF_OWN | NXFMF_ACTIONS);
1715     fmr->out_port = OFPP_NONE;
1716     fmr->table_id = 0xff;
1717     match_init_catchall(&fmr->match);
1718
1719     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1720          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1721         const struct protocol *p;
1722
1723         if (!strcmp(name, "!initial")) {
1724             fmr->flags &= ~NXFMF_INITIAL;
1725         } else if (!strcmp(name, "!add")) {
1726             fmr->flags &= ~NXFMF_ADD;
1727         } else if (!strcmp(name, "!delete")) {
1728             fmr->flags &= ~NXFMF_DELETE;
1729         } else if (!strcmp(name, "!modify")) {
1730             fmr->flags &= ~NXFMF_MODIFY;
1731         } else if (!strcmp(name, "!actions")) {
1732             fmr->flags &= ~NXFMF_ACTIONS;
1733         } else if (!strcmp(name, "!own")) {
1734             fmr->flags &= ~NXFMF_OWN;
1735         } else if (parse_protocol(name, &p)) {
1736             match_set_dl_type(&fmr->match, htons(p->dl_type));
1737             if (p->nw_proto) {
1738                 match_set_nw_proto(&fmr->match, p->nw_proto);
1739             }
1740         } else {
1741             char *value;
1742
1743             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1744             if (!value) {
1745                 return xasprintf("%s: field %s missing value", str_, name);
1746             }
1747
1748             if (!strcmp(name, "table")) {
1749                 char *error = str_to_u8(value, "table", &fmr->table_id);
1750                 if (error) {
1751                     return error;
1752                 }
1753             } else if (!strcmp(name, "out_port")) {
1754                 fmr->out_port = u16_to_ofp(atoi(value));
1755             } else if (mf_from_name(name)) {
1756                 char *error;
1757
1758                 error = parse_field(mf_from_name(name), value, &fmr->match,
1759                                     usable_protocols);
1760                 if (error) {
1761                     return error;
1762                 }
1763             } else {
1764                 return xasprintf("%s: unknown keyword %s", str_, name);
1765             }
1766         }
1767     }
1768     return NULL;
1769 }
1770
1771 /* Convert 'str_' (as described in the documentation for the "monitor" command
1772  * in the ovs-ofctl man page) into 'fmr'.
1773  *
1774  * Returns NULL if successful, otherwise a malloc()'d string describing the
1775  * error.  The caller is responsible for freeing the returned string. */
1776 char * WARN_UNUSED_RESULT
1777 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
1778                            const char *str_,
1779                            enum ofputil_protocol *usable_protocols)
1780 {
1781     char *string = xstrdup(str_);
1782     char *error = parse_flow_monitor_request__(fmr, str_, string,
1783                                                usable_protocols);
1784     free(string);
1785     return error;
1786 }
1787
1788 /* Parses 's' as a set of OpenFlow actions and appends the actions to
1789  * 'actions'.
1790  *
1791  * Returns NULL if successful, otherwise a malloc()'d string describing the
1792  * error.  The caller is responsible for freeing the returned string. */
1793 char * WARN_UNUSED_RESULT
1794 parse_ofpacts(const char *s_, struct ofpbuf *ofpacts,
1795               enum ofputil_protocol *usable_protocols)
1796 {
1797     char *s = xstrdup(s_);
1798     char *error;
1799
1800     *usable_protocols = OFPUTIL_P_ANY;
1801
1802     error = str_to_ofpacts(s, ofpacts, usable_protocols);
1803     free(s);
1804
1805     return error;
1806 }
1807
1808 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1809  * (one of OFPFC_*) into 'fm'.
1810  *
1811  * Returns NULL if successful, otherwise a malloc()'d string describing the
1812  * error.  The caller is responsible for freeing the returned string. */
1813 char * WARN_UNUSED_RESULT
1814 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
1815                        uint16_t command,
1816                        enum ofputil_protocol *usable_protocols,
1817                        bool enforce_consistency)
1818 {
1819     char *error = parse_ofp_str(fm, command, string, usable_protocols,
1820                                 enforce_consistency);
1821     if (!error) {
1822         /* Normalize a copy of the match.  This ensures that non-normalized
1823          * flows get logged but doesn't affect what gets sent to the switch, so
1824          * that the switch can do whatever it likes with the flow. */
1825         struct match match_copy = fm->match;
1826         ofputil_normalize_match(&match_copy);
1827     }
1828
1829     return error;
1830 }
1831
1832 /* Convert 'table_id' and 'flow_miss_handling' (as described for the
1833  * "mod-table" command in the ovs-ofctl man page) into 'tm' for sending the
1834  * specified table_mod 'command' to a switch.
1835  *
1836  * Returns NULL if successful, otherwise a malloc()'d string describing the
1837  * error.  The caller is responsible for freeing the returned string. */
1838 char * WARN_UNUSED_RESULT
1839 parse_ofp_table_mod(struct ofputil_table_mod *tm, const char *table_id,
1840                     const char *flow_miss_handling,
1841                     enum ofputil_protocol *usable_protocols)
1842 {
1843     /* Table mod requires at least OF 1.1. */
1844     *usable_protocols = OFPUTIL_P_OF11_UP;
1845
1846     if (!strcasecmp(table_id, "all")) {
1847         tm->table_id = 255;
1848     } else {
1849         char *error = str_to_u8(table_id, "table_id", &tm->table_id);
1850         if (error) {
1851             return error;
1852         }
1853     }
1854
1855     if (strcmp(flow_miss_handling, "controller") == 0) {
1856         tm->config = OFPTC11_TABLE_MISS_CONTROLLER;
1857     } else if (strcmp(flow_miss_handling, "continue") == 0) {
1858         tm->config = OFPTC11_TABLE_MISS_CONTINUE;
1859     } else if (strcmp(flow_miss_handling, "drop") == 0) {
1860         tm->config = OFPTC11_TABLE_MISS_DROP;
1861     } else {
1862         return xasprintf("invalid flow_miss_handling %s", flow_miss_handling);
1863     }
1864
1865     if (tm->table_id == 0xfe && tm->config == OFPTC11_TABLE_MISS_CONTINUE) {
1866         return xstrdup("last table's flow miss handling can not be continue");
1867     }
1868
1869     return NULL;
1870 }
1871
1872
1873 /* Opens file 'file_name' and reads each line as a flow_mod of the specified
1874  * type (one of OFPFC_*).  Stores each flow_mod in '*fm', an array allocated
1875  * on the caller's behalf, and the number of flow_mods in '*n_fms'.
1876  *
1877  * Returns NULL if successful, otherwise a malloc()'d string describing the
1878  * error.  The caller is responsible for freeing the returned string. */
1879 char * WARN_UNUSED_RESULT
1880 parse_ofp_flow_mod_file(const char *file_name, uint16_t command,
1881                         struct ofputil_flow_mod **fms, size_t *n_fms,
1882                         enum ofputil_protocol *usable_protocols,
1883                         bool enforce_consistency)
1884 {
1885     size_t allocated_fms;
1886     int line_number;
1887     FILE *stream;
1888     struct ds s;
1889
1890     *usable_protocols = OFPUTIL_P_ANY;
1891
1892     *fms = NULL;
1893     *n_fms = 0;
1894
1895     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1896     if (stream == NULL) {
1897         return xasprintf("%s: open failed (%s)",
1898                          file_name, ovs_strerror(errno));
1899     }
1900
1901     allocated_fms = *n_fms;
1902     ds_init(&s);
1903     line_number = 0;
1904     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
1905         char *error;
1906         enum ofputil_protocol usable;
1907
1908         if (*n_fms >= allocated_fms) {
1909             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1910         }
1911         error = parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command,
1912                                        &usable, enforce_consistency);
1913         if (error) {
1914             size_t i;
1915
1916             for (i = 0; i < *n_fms; i++) {
1917                 free((*fms)[i].ofpacts);
1918             }
1919             free(*fms);
1920             *fms = NULL;
1921             *n_fms = 0;
1922
1923             ds_destroy(&s);
1924             if (stream != stdin) {
1925                 fclose(stream);
1926             }
1927
1928             return xasprintf("%s:%d: %s", file_name, line_number, error);
1929         }
1930         *usable_protocols &= usable; /* Each line can narrow the set. */
1931         *n_fms += 1;
1932     }
1933
1934     ds_destroy(&s);
1935     if (stream != stdin) {
1936         fclose(stream);
1937     }
1938     return NULL;
1939 }
1940
1941 char * WARN_UNUSED_RESULT
1942 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1943                                  bool aggregate, const char *string,
1944                                  enum ofputil_protocol *usable_protocols,
1945                                  bool enforce_consistency)
1946 {
1947     struct ofputil_flow_mod fm;
1948     char *error;
1949
1950     error = parse_ofp_str(&fm, -1, string, usable_protocols,
1951                           enforce_consistency);
1952     if (error) {
1953         return error;
1954     }
1955
1956     /* Special table ID support not required for stats requests. */
1957     if (*usable_protocols & OFPUTIL_P_OF10_STD_TID) {
1958         *usable_protocols |= OFPUTIL_P_OF10_STD;
1959     }
1960     if (*usable_protocols & OFPUTIL_P_OF10_NXM_TID) {
1961         *usable_protocols |= OFPUTIL_P_OF10_NXM;
1962     }
1963
1964     fsr->aggregate = aggregate;
1965     fsr->cookie = fm.cookie;
1966     fsr->cookie_mask = fm.cookie_mask;
1967     fsr->match = fm.match;
1968     fsr->out_port = fm.out_port;
1969     fsr->out_group = fm.out_group;
1970     fsr->table_id = fm.table_id;
1971     return NULL;
1972 }
1973
1974 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1975  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1976  * mf_field.  Fields must be specified in a natural order for satisfying
1977  * prerequisites. If 'mask' is specified, fills the mask field for each of the
1978  * field specified in flow. If the map, 'names_portno' is specfied, converts
1979  * the in_port name into port no while setting the 'flow'.
1980  *
1981  * Returns NULL on success, otherwise a malloc()'d string that explains the
1982  * problem. */
1983 char *
1984 parse_ofp_exact_flow(struct flow *flow, struct flow *mask, const char *s,
1985                      const struct simap *portno_names)
1986 {
1987     char *pos, *key, *value_s;
1988     char *error = NULL;
1989     char *copy;
1990
1991     memset(flow, 0, sizeof *flow);
1992     if (mask) {
1993         memset(mask, 0, sizeof *mask);
1994     }
1995
1996     pos = copy = xstrdup(s);
1997     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
1998         const struct protocol *p;
1999         if (parse_protocol(key, &p)) {
2000             if (flow->dl_type) {
2001                 error = xasprintf("%s: Ethernet type set multiple times", s);
2002                 goto exit;
2003             }
2004             flow->dl_type = htons(p->dl_type);
2005             if (mask) {
2006                 mask->dl_type = OVS_BE16_MAX;
2007             }
2008
2009             if (p->nw_proto) {
2010                 if (flow->nw_proto) {
2011                     error = xasprintf("%s: network protocol set "
2012                                       "multiple times", s);
2013                     goto exit;
2014                 }
2015                 flow->nw_proto = p->nw_proto;
2016                 if (mask) {
2017                     mask->nw_proto = UINT8_MAX;
2018                 }
2019             }
2020         } else {
2021             const struct mf_field *mf;
2022             union mf_value value;
2023             char *field_error;
2024
2025             mf = mf_from_name(key);
2026             if (!mf) {
2027                 error = xasprintf("%s: unknown field %s", s, key);
2028                 goto exit;
2029             }
2030
2031             if (!mf_are_prereqs_ok(mf, flow)) {
2032                 error = xasprintf("%s: prerequisites not met for setting %s",
2033                                   s, key);
2034                 goto exit;
2035             }
2036
2037             if (!mf_is_zero(mf, flow)) {
2038                 error = xasprintf("%s: field %s set multiple times", s, key);
2039                 goto exit;
2040             }
2041
2042             if (!strcmp(key, "in_port")
2043                 && portno_names
2044                 && simap_contains(portno_names, value_s)) {
2045                 flow->in_port.ofp_port = u16_to_ofp(
2046                     simap_get(portno_names, value_s));
2047                 if (mask) {
2048                     mask->in_port.ofp_port = u16_to_ofp(ntohs(OVS_BE16_MAX));
2049                 }
2050             } else {
2051                 field_error = mf_parse_value(mf, value_s, &value);
2052                 if (field_error) {
2053                     error = xasprintf("%s: bad value for %s (%s)",
2054                                       s, key, field_error);
2055                     free(field_error);
2056                     goto exit;
2057                 }
2058
2059                 mf_set_flow_value(mf, &value, flow);
2060                 if (mask) {
2061                     mf_mask_field(mf, mask);
2062                 }
2063             }
2064         }
2065     }
2066
2067     if (!flow->in_port.ofp_port) {
2068         flow->in_port.ofp_port = OFPP_NONE;
2069     }
2070
2071 exit:
2072     free(copy);
2073
2074     if (error) {
2075         memset(flow, 0, sizeof *flow);
2076         if (mask) {
2077             memset(mask, 0, sizeof *mask);
2078         }
2079     }
2080     return error;
2081 }
2082
2083 static char * WARN_UNUSED_RESULT
2084 parse_bucket_str(struct ofputil_bucket *bucket, char *str_,
2085                   enum ofputil_protocol *usable_protocols)
2086 {
2087     struct ofpbuf ofpacts;
2088     char *pos, *act, *arg;
2089     int n_actions;
2090
2091     bucket->weight = 1;
2092     bucket->watch_port = OFPP_ANY;
2093     bucket->watch_group = OFPG11_ANY;
2094
2095     pos = str_;
2096     n_actions = 0;
2097     ofpbuf_init(&ofpacts, 64);
2098     while (ofputil_parse_key_value(&pos, &act, &arg)) {
2099         char *error = NULL;
2100
2101         if (!strcasecmp(act, "weight")) {
2102             error = str_to_u16(arg, "weight", &bucket->weight);
2103         } else if (!strcasecmp(act, "watch_port")) {
2104             if (!ofputil_port_from_string(arg, &bucket->watch_port)
2105                 || (ofp_to_u16(bucket->watch_port) >= ofp_to_u16(OFPP_MAX)
2106                     && bucket->watch_port != OFPP_ANY)) {
2107                 error = xasprintf("%s: invalid watch_port", arg);
2108             }
2109         } else if (!strcasecmp(act, "watch_group")) {
2110             error = str_to_u32(arg, &bucket->watch_group);
2111             if (!error && bucket->watch_group > OFPG_MAX) {
2112                 error = xasprintf("invalid watch_group id %"PRIu32,
2113                                   bucket->watch_group);
2114             }
2115         } else {
2116             error = str_to_ofpact__(pos, act, arg, &ofpacts, n_actions,
2117                                     usable_protocols);
2118             n_actions++;
2119         }
2120
2121         if (error) {
2122             ofpbuf_uninit(&ofpacts);
2123             return error;
2124         }
2125     }
2126
2127     ofpact_pad(&ofpacts);
2128     bucket->ofpacts = ofpacts.data;
2129     bucket->ofpacts_len = ofpacts.size;
2130
2131     return NULL;
2132 }
2133
2134 static char * WARN_UNUSED_RESULT
2135 parse_ofp_group_mod_str__(struct ofputil_group_mod *gm, uint16_t command,
2136                           char *string,
2137                           enum ofputil_protocol *usable_protocols)
2138 {
2139     enum {
2140         F_GROUP_TYPE  = 1 << 0,
2141         F_BUCKETS     = 1 << 1,
2142     } fields;
2143     char *save_ptr = NULL;
2144     bool had_type = false;
2145     char *name;
2146     struct ofputil_bucket *bucket;
2147     char *error = NULL;
2148
2149     *usable_protocols = OFPUTIL_P_OF11_UP;
2150
2151     switch (command) {
2152     case OFPGC11_ADD:
2153         fields = F_GROUP_TYPE | F_BUCKETS;
2154         break;
2155
2156     case OFPGC11_DELETE:
2157         fields = 0;
2158         break;
2159
2160     case OFPGC11_MODIFY:
2161         fields = F_GROUP_TYPE | F_BUCKETS;
2162         break;
2163
2164     default:
2165         NOT_REACHED();
2166     }
2167
2168     memset(gm, 0, sizeof *gm);
2169     gm->command = command;
2170     gm->group_id = OFPG_ANY;
2171     list_init(&gm->buckets);
2172     if (command == OFPGC11_DELETE && string[0] == '\0') {
2173         gm->group_id = OFPG_ALL;
2174         return NULL;
2175     }
2176
2177     *usable_protocols = OFPUTIL_P_OF11_UP;
2178
2179     if (fields & F_BUCKETS) {
2180         char *bkt_str = strstr(string, "bucket");
2181
2182         if (bkt_str) {
2183             *bkt_str = '\0';
2184         }
2185
2186         while (bkt_str) {
2187             char *next_bkt_str;
2188
2189             bkt_str = strchr(bkt_str + 1, '=');
2190             if (!bkt_str) {
2191                 error = xstrdup("must specify bucket content");
2192                 goto out;
2193             }
2194             bkt_str++;
2195
2196             next_bkt_str = strstr(bkt_str, "bucket");
2197             if (next_bkt_str) {
2198                 *next_bkt_str = '\0';
2199             }
2200
2201             bucket = xzalloc(sizeof(struct ofputil_bucket));
2202             error = parse_bucket_str(bucket, bkt_str, usable_protocols);
2203             if (error) {
2204                 free(bucket);
2205                 goto out;
2206             }
2207             list_push_back(&gm->buckets, &bucket->list_node);
2208
2209             bkt_str = next_bkt_str;
2210         }
2211     }
2212
2213     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
2214          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
2215         char *value;
2216
2217         value = strtok_r(NULL, ", \t\r\n", &save_ptr);
2218         if (!value) {
2219             error = xasprintf("field %s missing value", name);
2220             goto out;
2221         }
2222
2223         if (!strcmp(name, "group_id")) {
2224             if(!strcmp(value, "all")) {
2225                 gm->group_id = OFPG_ALL;
2226             } else {
2227                 char *error = str_to_u32(value, &gm->group_id);
2228                 if (error) {
2229                     goto out;
2230                 }
2231                 if (gm->group_id != OFPG_ALL && gm->group_id > OFPG_MAX) {
2232                     error = xasprintf("invalid group id %"PRIu32,
2233                                       gm->group_id);
2234                     goto out;
2235                 }
2236             }
2237         } else if (!strcmp(name, "type")){
2238             if (!(fields & F_GROUP_TYPE)) {
2239                 error = xstrdup("type is not needed");
2240                 goto out;
2241             }
2242             if (!strcmp(value, "all")) {
2243                 gm->type = OFPGT11_ALL;
2244             } else if (!strcmp(value, "select")) {
2245                 gm->type = OFPGT11_SELECT;
2246             } else if (!strcmp(value, "indirect")) {
2247                 gm->type = OFPGT11_INDIRECT;
2248             } else if (!strcmp(value, "ff") ||
2249                        !strcmp(value, "fast_failover")) {
2250                 gm->type = OFPGT11_FF;
2251             } else {
2252                 error = xasprintf("invalid group type %s", value);
2253                 goto out;
2254             }
2255             had_type = true;
2256         } else if (!strcmp(name, "bucket")) {
2257             error = xstrdup("bucket is not needed");
2258             goto out;
2259         } else {
2260             error = xasprintf("unknown keyword %s", name);
2261             goto out;
2262         }
2263     }
2264     if (gm->group_id == OFPG_ANY) {
2265         error = xstrdup("must specify a group_id");
2266         goto out;
2267     }
2268     if (fields & F_GROUP_TYPE && !had_type) {
2269         error = xstrdup("must specify a type");
2270         goto out;
2271     }
2272
2273     /* Validate buckets. */
2274     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
2275         if (bucket->weight != 1 && gm->type != OFPGT11_SELECT) {
2276             error = xstrdup("Only select groups can have bucket weights.");
2277             goto out;
2278         }
2279     }
2280     if (gm->type == OFPGT11_INDIRECT && !list_is_short(&gm->buckets)) {
2281         error = xstrdup("Indirect groups can have at most one bucket.");
2282         goto out;
2283     }
2284
2285     return NULL;
2286  out:
2287     ofputil_bucket_list_destroy(&gm->buckets);
2288     return error;
2289 }
2290
2291 char * WARN_UNUSED_RESULT
2292 parse_ofp_group_mod_str(struct ofputil_group_mod *gm, uint16_t command,
2293                         const char *str_,
2294                         enum ofputil_protocol *usable_protocols)
2295 {
2296     char *string = xstrdup(str_);
2297     char *error = parse_ofp_group_mod_str__(gm, command, string,
2298                                             usable_protocols);
2299     free(string);
2300
2301     if (error) {
2302         ofputil_bucket_list_destroy(&gm->buckets);
2303     }
2304     return error;
2305 }
2306
2307 char * WARN_UNUSED_RESULT
2308 parse_ofp_group_mod_file(const char *file_name, uint16_t command,
2309                          struct ofputil_group_mod **gms, size_t *n_gms,
2310                          enum ofputil_protocol *usable_protocols)
2311 {
2312     size_t allocated_gms;
2313     int line_number;
2314     FILE *stream;
2315     struct ds s;
2316
2317     *gms = NULL;
2318     *n_gms = 0;
2319
2320     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
2321     if (stream == NULL) {
2322         return xasprintf("%s: open failed (%s)",
2323                          file_name, ovs_strerror(errno));
2324     }
2325
2326     allocated_gms = *n_gms;
2327     ds_init(&s);
2328     line_number = 0;
2329     *usable_protocols = OFPUTIL_P_OF11_UP;
2330     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
2331         enum ofputil_protocol usable;
2332         char *error;
2333
2334         if (*n_gms >= allocated_gms) {
2335             *gms = x2nrealloc(*gms, &allocated_gms, sizeof **gms);
2336         }
2337         error = parse_ofp_group_mod_str(&(*gms)[*n_gms], command, ds_cstr(&s),
2338                                         &usable);
2339         if (error) {
2340             size_t i;
2341
2342             for (i = 0; i < *n_gms; i++) {
2343                 ofputil_bucket_list_destroy(&(*gms)[i].buckets);
2344             }
2345             free(*gms);
2346             *gms = NULL;
2347             *n_gms = 0;
2348
2349             ds_destroy(&s);
2350             if (stream != stdin) {
2351                 fclose(stream);
2352             }
2353
2354             return xasprintf("%s:%d: %s", file_name, line_number, error);
2355         }
2356         *usable_protocols &= usable;
2357         *n_gms += 1;
2358     }
2359
2360     ds_destroy(&s);
2361     if (stream != stdin) {
2362         fclose(stream);
2363     }
2364     return NULL;
2365 }