ofp-util: Abstract table miss configuration and fix related bugs.
[cascardo/ovs.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010, 2011, 2012, 2013, 2014 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 (!ovs_scan(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))) {
151         return xasprintf("invalid mac address %s", str);
152     }
153     return NULL;
154 }
155
156 /* Parses 'str' as an IP address into '*ip'.
157  *
158  * Returns NULL if successful, otherwise a malloc()'d string describing the
159  * error.  The caller is responsible for freeing the returned string. */
160 static char * WARN_UNUSED_RESULT
161 str_to_ip(const char *str, ovs_be32 *ip)
162 {
163     struct in_addr in_addr;
164
165     if (lookup_ip(str, &in_addr)) {
166         return xasprintf("%s: could not convert to IP address", str);
167     }
168     *ip = in_addr.s_addr;
169     return NULL;
170 }
171
172 /* Parses 'arg' as the argument to an "enqueue" action, and appends such an
173  * action to 'ofpacts'.
174  *
175  * Returns NULL if successful, otherwise a malloc()'d string describing the
176  * error.  The caller is responsible for freeing the returned string. */
177 static char * WARN_UNUSED_RESULT
178 parse_enqueue(char *arg, struct ofpbuf *ofpacts)
179 {
180     char *sp = NULL;
181     char *port = strtok_r(arg, ":q,", &sp);
182     char *queue = strtok_r(NULL, "", &sp);
183     struct ofpact_enqueue *enqueue;
184
185     if (port == NULL || queue == NULL) {
186         return xstrdup("\"enqueue\" syntax is \"enqueue:PORT:QUEUE\" or "
187                        "\"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         if (!ofputil_port_from_string(arg, &output->port)) {
216             return xasprintf("%s: output to unknown port", arg);
217         }
218         output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0;
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->frame;
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     ofpact_put_DEC_TTL(b);
402     ofpbuf_put(b, &id, sizeof id);
403     ids = b->frame;
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->frame;
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 = ofpbuf_size(ofpacts);
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;
643     uint8_t ecn = 0;
644     uint8_t ttl = 0;
645     uint8_t pcp = 0;
646
647     switch (code) {
648     case OFPUTIL_ACTION_INVALID:
649         OVS_NOT_REACHED();
650
651     case OFPUTIL_OFPAT10_OUTPUT:
652     case OFPUTIL_OFPAT11_OUTPUT:
653     case OFPUTIL_OFPAT13_OUTPUT:
654         error = parse_output(arg, ofpacts);
655         break;
656
657     case OFPUTIL_OFPAT10_SET_VLAN_VID:
658     case OFPUTIL_OFPAT11_SET_VLAN_VID:
659         error = str_to_u16(arg, "VLAN VID", &vid);
660         if (error) {
661             return error;
662         }
663
664         if (vid & ~VLAN_VID_MASK) {
665             return xasprintf("%s: not a valid VLAN VID", arg);
666         }
667         vlan_vid = ofpact_put_SET_VLAN_VID(ofpacts);
668         vlan_vid->vlan_vid = vid;
669         vlan_vid->ofpact.compat = code;
670         vlan_vid->push_vlan_if_needed = code == OFPUTIL_OFPAT10_SET_VLAN_VID;
671         break;
672
673     case OFPUTIL_OFPAT10_SET_VLAN_PCP:
674     case OFPUTIL_OFPAT11_SET_VLAN_PCP:
675         error = str_to_u8(arg, "VLAN PCP", &pcp);
676         if (error) {
677             return error;
678         }
679
680         if (pcp & ~7) {
681             return xasprintf("%s: not a valid VLAN PCP", arg);
682         }
683         vlan_pcp = ofpact_put_SET_VLAN_PCP(ofpacts);
684         vlan_pcp->vlan_pcp = pcp;
685         vlan_pcp->ofpact.compat = code;
686         vlan_pcp->push_vlan_if_needed = code == OFPUTIL_OFPAT10_SET_VLAN_PCP;
687         break;
688
689     case OFPUTIL_OFPAT12_SET_FIELD:
690     case OFPUTIL_OFPAT13_SET_FIELD:
691         return set_field_parse(arg, ofpacts, usable_protocols);
692
693     case OFPUTIL_OFPAT10_STRIP_VLAN:
694     case OFPUTIL_OFPAT11_POP_VLAN:
695     case OFPUTIL_OFPAT13_POP_VLAN:
696         ofpact_put_STRIP_VLAN(ofpacts)->ofpact.compat = code;
697         break;
698
699     case OFPUTIL_OFPAT11_PUSH_VLAN:
700     case OFPUTIL_OFPAT13_PUSH_VLAN:
701         *usable_protocols &= OFPUTIL_P_OF11_UP;
702         error = str_to_u16(arg, "ethertype", &ethertype);
703         if (error) {
704             return error;
705         }
706
707         if (ethertype != ETH_TYPE_VLAN_8021Q) {
708             /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */
709             return xasprintf("%s: not a valid VLAN ethertype", arg);
710         }
711
712         ofpact_put_PUSH_VLAN(ofpacts);
713         break;
714
715     case OFPUTIL_OFPAT11_SET_QUEUE:
716     case OFPUTIL_OFPAT13_SET_QUEUE:
717         error = str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
718         break;
719
720     case OFPUTIL_OFPAT10_SET_DL_SRC:
721     case OFPUTIL_OFPAT11_SET_DL_SRC:
722         error = str_to_mac(arg, ofpact_put_SET_ETH_SRC(ofpacts)->mac);
723         break;
724
725     case OFPUTIL_OFPAT10_SET_DL_DST:
726     case OFPUTIL_OFPAT11_SET_DL_DST:
727         error = str_to_mac(arg, ofpact_put_SET_ETH_DST(ofpacts)->mac);
728         break;
729
730     case OFPUTIL_OFPAT10_SET_NW_SRC:
731     case OFPUTIL_OFPAT11_SET_NW_SRC:
732         error = str_to_ip(arg, &ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4);
733         break;
734
735     case OFPUTIL_OFPAT10_SET_NW_DST:
736     case OFPUTIL_OFPAT11_SET_NW_DST:
737         error = str_to_ip(arg, &ofpact_put_SET_IPV4_DST(ofpacts)->ipv4);
738         break;
739
740     case OFPUTIL_OFPAT10_SET_NW_TOS:
741     case OFPUTIL_OFPAT11_SET_NW_TOS:
742         error = str_to_u8(arg, "TOS", &tos);
743         if (error) {
744             return error;
745         }
746
747         if (tos & ~IP_DSCP_MASK) {
748             return xasprintf("%s: not a valid TOS", arg);
749         }
750         ofpact_put_SET_IP_DSCP(ofpacts)->dscp = tos;
751         break;
752
753     case OFPUTIL_OFPAT11_SET_NW_ECN:
754         error = str_to_u8(arg, "ECN", &ecn);
755         if (error) {
756             return error;
757         }
758
759         if (ecn & ~IP_ECN_MASK) {
760             return xasprintf("%s: not a valid ECN", arg);
761         }
762         ofpact_put_SET_IP_ECN(ofpacts)->ecn = ecn;
763         break;
764
765     case OFPUTIL_OFPAT11_SET_NW_TTL:
766     case OFPUTIL_OFPAT13_SET_NW_TTL:
767         error = str_to_u8(arg, "TTL", &ttl);
768         if (error) {
769             return error;
770         }
771
772         ofpact_put_SET_IP_TTL(ofpacts)->ttl = ttl;
773         break;
774
775     case OFPUTIL_OFPAT11_DEC_NW_TTL:
776     case OFPUTIL_OFPAT13_DEC_NW_TTL:
777         OVS_NOT_REACHED();
778
779     case OFPUTIL_OFPAT10_SET_TP_SRC:
780     case OFPUTIL_OFPAT11_SET_TP_SRC:
781         error = str_to_u16(arg, "source port",
782                            &ofpact_put_SET_L4_SRC_PORT(ofpacts)->port);
783         break;
784
785     case OFPUTIL_OFPAT10_SET_TP_DST:
786     case OFPUTIL_OFPAT11_SET_TP_DST:
787         error = str_to_u16(arg, "destination port",
788                            &ofpact_put_SET_L4_DST_PORT(ofpacts)->port);
789         break;
790
791     case OFPUTIL_OFPAT10_ENQUEUE:
792         error = parse_enqueue(arg, ofpacts);
793         break;
794
795     case OFPUTIL_NXAST_RESUBMIT:
796         error = parse_resubmit(arg, ofpacts);
797         break;
798
799     case OFPUTIL_NXAST_SET_TUNNEL:
800     case OFPUTIL_NXAST_SET_TUNNEL64:
801         tunnel = ofpact_put_SET_TUNNEL(ofpacts);
802         tunnel->ofpact.compat = code;
803         error = str_to_u64(arg, &tunnel->tun_id);
804         break;
805
806     case OFPUTIL_NXAST_WRITE_METADATA:
807         error = parse_metadata(ofpacts, arg);
808         break;
809
810     case OFPUTIL_NXAST_SET_QUEUE:
811         error = str_to_u32(arg, &ofpact_put_SET_QUEUE(ofpacts)->queue_id);
812         break;
813
814     case OFPUTIL_NXAST_POP_QUEUE:
815         ofpact_put_POP_QUEUE(ofpacts);
816         break;
817
818     case OFPUTIL_NXAST_REG_MOVE:
819         error = nxm_parse_reg_move(ofpact_put_REG_MOVE(ofpacts), arg);
820         break;
821
822     case OFPUTIL_NXAST_REG_LOAD:
823         error = nxm_parse_reg_load(ofpact_put_REG_LOAD(ofpacts), arg);
824         break;
825
826     case OFPUTIL_NXAST_NOTE:
827         error = parse_note(arg, ofpacts);
828         break;
829
830     case OFPUTIL_NXAST_MULTIPATH:
831         error = multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
832         break;
833
834     case OFPUTIL_NXAST_BUNDLE:
835         error = bundle_parse(arg, ofpacts);
836         break;
837
838     case OFPUTIL_NXAST_BUNDLE_LOAD:
839         error = bundle_parse_load(arg, ofpacts);
840         break;
841
842     case OFPUTIL_NXAST_RESUBMIT_TABLE:
843     case OFPUTIL_NXAST_OUTPUT_REG:
844     case OFPUTIL_NXAST_DEC_TTL_CNT_IDS:
845         OVS_NOT_REACHED();
846
847     case OFPUTIL_NXAST_LEARN:
848         error = learn_parse(arg, ofpacts);
849         break;
850
851     case OFPUTIL_NXAST_EXIT:
852         ofpact_put_EXIT(ofpacts);
853         break;
854
855     case OFPUTIL_NXAST_DEC_TTL:
856         error = parse_dec_ttl(ofpacts, arg);
857         break;
858
859     case OFPUTIL_NXAST_SET_MPLS_LABEL:
860     case OFPUTIL_OFPAT11_SET_MPLS_LABEL:
861         error = parse_set_mpls_label(ofpacts, arg);
862         break;
863
864     case OFPUTIL_NXAST_SET_MPLS_TC:
865     case OFPUTIL_OFPAT11_SET_MPLS_TC:
866         error = parse_set_mpls_tc(ofpacts, arg);
867         break;
868
869     case OFPUTIL_NXAST_SET_MPLS_TTL:
870     case OFPUTIL_OFPAT11_SET_MPLS_TTL:
871     case OFPUTIL_OFPAT13_SET_MPLS_TTL:
872         error = parse_set_mpls_ttl(ofpacts, arg);
873         break;
874
875     case OFPUTIL_OFPAT11_DEC_MPLS_TTL:
876     case OFPUTIL_OFPAT13_DEC_MPLS_TTL:
877     case OFPUTIL_NXAST_DEC_MPLS_TTL:
878         ofpact_put_DEC_MPLS_TTL(ofpacts);
879         break;
880
881     case OFPUTIL_NXAST_FIN_TIMEOUT:
882         error = parse_fin_timeout(ofpacts, arg);
883         break;
884
885     case OFPUTIL_NXAST_CONTROLLER:
886         error = parse_controller(ofpacts, arg);
887         break;
888
889     case OFPUTIL_OFPAT11_PUSH_MPLS:
890     case OFPUTIL_OFPAT13_PUSH_MPLS:
891     case OFPUTIL_NXAST_PUSH_MPLS:
892         error = str_to_u16(arg, "push_mpls", &ethertype);
893         if (!error) {
894             ofpact_put_PUSH_MPLS(ofpacts)->ethertype = htons(ethertype);
895         }
896         break;
897
898     case OFPUTIL_OFPAT11_POP_MPLS:
899     case OFPUTIL_OFPAT13_POP_MPLS:
900     case OFPUTIL_NXAST_POP_MPLS:
901         error = str_to_u16(arg, "pop_mpls", &ethertype);
902         if (!error) {
903             ofpact_put_POP_MPLS(ofpacts)->ethertype = htons(ethertype);
904         }
905         break;
906
907     case OFPUTIL_OFPAT11_GROUP:
908     case OFPUTIL_OFPAT13_GROUP:
909         error = str_to_u32(arg, &ofpact_put_GROUP(ofpacts)->group_id);
910         break;
911
912     /* FIXME when implement OFPAT13_* */
913     case OFPUTIL_OFPAT13_COPY_TTL_OUT:
914     case OFPUTIL_OFPAT13_COPY_TTL_IN:
915     case OFPUTIL_OFPAT13_PUSH_PBB:
916     case OFPUTIL_OFPAT13_POP_PBB:
917         OVS_NOT_REACHED();
918
919     case OFPUTIL_NXAST_STACK_PUSH:
920         error = nxm_parse_stack_action(ofpact_put_STACK_PUSH(ofpacts), arg);
921         break;
922     case OFPUTIL_NXAST_STACK_POP:
923         error = nxm_parse_stack_action(ofpact_put_STACK_POP(ofpacts), arg);
924         break;
925
926     case OFPUTIL_NXAST_SAMPLE:
927         error = parse_sample(ofpacts, arg);
928         break;
929     }
930
931     if (error) {
932         ofpbuf_set_size(ofpacts, orig_size);
933     }
934     return error;
935 }
936
937 /* Parses action 'act', with argument 'arg', and appends a parsed version to
938  * 'ofpacts'.
939  *
940  * 'n_actions' specifies the number of actions already parsed (for proper
941  * handling of "drop" actions).
942  *
943  * Returns NULL if successful, otherwise a malloc()'d string describing the
944  * error.  The caller is responsible for freeing the returned string. */
945 static char * WARN_UNUSED_RESULT
946 str_to_ofpact__(char *pos, char *act, char *arg,
947                 struct ofpbuf *ofpacts, int n_actions,
948                 enum ofputil_protocol *usable_protocols)
949 {
950     int code = ofputil_action_code_from_name(act);
951     if (code >= 0) {
952         return parse_named_action(code, arg, ofpacts, usable_protocols);
953     } else if (!strcasecmp(act, "drop")) {
954         if (n_actions) {
955             return xstrdup("Drop actions must not be preceded by other "
956                            "actions");
957         } else if (ofputil_parse_key_value(&pos, &act, &arg)) {
958             return xstrdup("Drop actions must not be followed by other "
959                            "actions");
960         }
961     } else {
962         ofp_port_t port;
963         if (ofputil_port_from_string(act, &port)) {
964             ofpact_put_OUTPUT(ofpacts)->port = port;
965         } else {
966             return xasprintf("Unknown action: %s", act);
967         }
968     }
969
970     return NULL;
971 }
972
973 /* Parses 'str' as a series of actions, and appends them to 'ofpacts'.
974  *
975  * Returns NULL if successful, otherwise a malloc()'d string describing the
976  * error.  The caller is responsible for freeing the returned string. */
977 static char * WARN_UNUSED_RESULT
978 str_to_ofpacts__(char *str, struct ofpbuf *ofpacts,
979                  enum ofputil_protocol *usable_protocols)
980 {
981     size_t orig_size = ofpbuf_size(ofpacts);
982     char *pos, *act, *arg;
983     int n_actions;
984
985     pos = str;
986     n_actions = 0;
987     while (ofputil_parse_key_value(&pos, &act, &arg)) {
988         char *error = str_to_ofpact__(pos, act, arg, ofpacts, n_actions,
989                                       usable_protocols);
990         if (error) {
991             ofpbuf_set_size(ofpacts, orig_size);
992             return error;
993         }
994         n_actions++;
995     }
996
997     ofpact_pad(ofpacts);
998     return NULL;
999 }
1000
1001
1002 /* Parses 'str' as a series of actions, and appends them to 'ofpacts'.
1003  *
1004  * Returns NULL if successful, otherwise a malloc()'d string describing the
1005  * error.  The caller is responsible for freeing the returned string. */
1006 static char * WARN_UNUSED_RESULT
1007 str_to_ofpacts(char *str, struct ofpbuf *ofpacts,
1008                enum ofputil_protocol *usable_protocols)
1009 {
1010     size_t orig_size = ofpbuf_size(ofpacts);
1011     char *error_s;
1012     enum ofperr error;
1013
1014     error_s = str_to_ofpacts__(str, ofpacts, usable_protocols);
1015     if (error_s) {
1016         return error_s;
1017     }
1018
1019     error = ofpacts_verify(ofpbuf_data(ofpacts), ofpbuf_size(ofpacts));
1020     if (error) {
1021         ofpbuf_set_size(ofpacts, orig_size);
1022         return xstrdup("Incorrect action ordering");
1023     }
1024
1025     return NULL;
1026 }
1027
1028 /* Parses 'arg' as the argument to instruction 'type', and appends such an
1029  * instruction to 'ofpacts'.
1030  *
1031  * Returns NULL if successful, otherwise a malloc()'d string describing the
1032  * error.  The caller is responsible for freeing the returned string. */
1033 static char * WARN_UNUSED_RESULT
1034 parse_named_instruction(enum ovs_instruction_type type,
1035                         char *arg, struct ofpbuf *ofpacts,
1036                         enum ofputil_protocol *usable_protocols)
1037 {
1038     char *error_s = NULL;
1039     enum ofperr error;
1040
1041     *usable_protocols &= OFPUTIL_P_OF11_UP;
1042
1043     switch (type) {
1044     case OVSINST_OFPIT11_APPLY_ACTIONS:
1045         OVS_NOT_REACHED();  /* This case is handled by str_to_inst_ofpacts() */
1046         break;
1047
1048     case OVSINST_OFPIT11_WRITE_ACTIONS: {
1049         struct ofpact_nest *on;
1050         size_t ofs;
1051
1052         ofpact_pad(ofpacts);
1053         ofs = ofpbuf_size(ofpacts);
1054         ofpact_put(ofpacts, OFPACT_WRITE_ACTIONS,
1055                    offsetof(struct ofpact_nest, actions));
1056         error_s = str_to_ofpacts__(arg, ofpacts, usable_protocols);
1057
1058         on = ofpbuf_at_assert(ofpacts, ofs, sizeof *on);
1059         on->ofpact.len = ofpbuf_size(ofpacts) - ofs;
1060
1061         if (error_s) {
1062             ofpbuf_set_size(ofpacts, ofs);
1063         }
1064         break;
1065     }
1066
1067     case OVSINST_OFPIT11_CLEAR_ACTIONS:
1068         ofpact_put_CLEAR_ACTIONS(ofpacts);
1069         break;
1070
1071     case OVSINST_OFPIT13_METER:
1072         *usable_protocols &= OFPUTIL_P_OF13_UP;
1073         error_s = str_to_u32(arg, &ofpact_put_METER(ofpacts)->meter_id);
1074         break;
1075
1076     case OVSINST_OFPIT11_WRITE_METADATA:
1077         *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
1078         error_s = parse_metadata(ofpacts, arg);
1079         break;
1080
1081     case OVSINST_OFPIT11_GOTO_TABLE: {
1082         struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
1083         char *table_s = strsep(&arg, ",");
1084         if (!table_s || !table_s[0]) {
1085             return xstrdup("instruction goto-table needs table id");
1086         }
1087         error_s = str_to_u8(table_s, "table", &ogt->table_id);
1088         break;
1089     }
1090     }
1091
1092     if (error_s) {
1093         return error_s;
1094     }
1095
1096     /* If write_metadata is specified as an action AND an instruction, ofpacts
1097        could be invalid. */
1098     error = ofpacts_verify(ofpbuf_data(ofpacts), ofpbuf_size(ofpacts));
1099     if (error) {
1100         return xstrdup("Incorrect instruction ordering");
1101     }
1102     return NULL;
1103 }
1104
1105 /* Parses 'str' as a series of instructions, and appends them to 'ofpacts'.
1106  *
1107  * Returns NULL if successful, otherwise a malloc()'d string describing the
1108  * error.  The caller is responsible for freeing the returned string. */
1109 static char * WARN_UNUSED_RESULT
1110 str_to_inst_ofpacts(char *str, struct ofpbuf *ofpacts,
1111                     enum ofputil_protocol *usable_protocols)
1112 {
1113     size_t orig_size = ofpbuf_size(ofpacts);
1114     char *pos, *inst, *arg;
1115     int type;
1116     const char *prev_inst = NULL;
1117     int prev_type = -1;
1118     int n_actions = 0;
1119
1120     pos = str;
1121     while (ofputil_parse_key_value(&pos, &inst, &arg)) {
1122         type = ovs_instruction_type_from_name(inst);
1123         if (type < 0) {
1124             char *error = str_to_ofpact__(pos, inst, arg, ofpacts, n_actions,
1125                                           usable_protocols);
1126             if (error) {
1127                 ofpbuf_set_size(ofpacts, orig_size);
1128                 return error;
1129             }
1130
1131             type = OVSINST_OFPIT11_APPLY_ACTIONS;
1132             if (prev_type == type) {
1133                 n_actions++;
1134                 continue;
1135             }
1136         } else if (type == OVSINST_OFPIT11_APPLY_ACTIONS) {
1137             ofpbuf_set_size(ofpacts, orig_size);
1138             return xasprintf("%s isn't supported. Just write actions then "
1139                              "it is interpreted as apply_actions", inst);
1140         } else {
1141             char *error = parse_named_instruction(type, arg, ofpacts,
1142                                                   usable_protocols);
1143             if (error) {
1144                 ofpbuf_set_size(ofpacts, orig_size);
1145                 return error;
1146             }
1147         }
1148
1149         if (type <= prev_type) {
1150             ofpbuf_set_size(ofpacts, orig_size);
1151             if (type == prev_type) {
1152                 return xasprintf("instruction %s may be specified only once",
1153                                  inst);
1154             } else {
1155                 return xasprintf("instruction %s must be specified before %s",
1156                                  inst, prev_inst);
1157             }
1158         }
1159
1160         prev_inst = inst;
1161         prev_type = type;
1162         n_actions++;
1163     }
1164     ofpact_pad(ofpacts);
1165
1166     return NULL;
1167 }
1168
1169 struct protocol {
1170     const char *name;
1171     uint16_t dl_type;
1172     uint8_t nw_proto;
1173 };
1174
1175 static bool
1176 parse_protocol(const char *name, const struct protocol **p_out)
1177 {
1178     static const struct protocol protocols[] = {
1179         { "ip", ETH_TYPE_IP, 0 },
1180         { "arp", ETH_TYPE_ARP, 0 },
1181         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
1182         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
1183         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
1184         { "sctp", ETH_TYPE_IP, IPPROTO_SCTP },
1185         { "ipv6", ETH_TYPE_IPV6, 0 },
1186         { "ip6", ETH_TYPE_IPV6, 0 },
1187         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
1188         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
1189         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
1190         { "sctp6", ETH_TYPE_IPV6, IPPROTO_SCTP },
1191         { "rarp", ETH_TYPE_RARP, 0},
1192         { "mpls", ETH_TYPE_MPLS, 0 },
1193         { "mplsm", ETH_TYPE_MPLS_MCAST, 0 },
1194     };
1195     const struct protocol *p;
1196
1197     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
1198         if (!strcmp(p->name, name)) {
1199             *p_out = p;
1200             return true;
1201         }
1202     }
1203     *p_out = NULL;
1204     return false;
1205 }
1206
1207 /* Parses 's' as the (possibly masked) value of field 'mf', and updates
1208  * 'match' appropriately.  Restricts the set of usable protocols to ones
1209  * supporting the parsed field.
1210  *
1211  * Returns NULL if successful, otherwise a malloc()'d string describing the
1212  * error.  The caller is responsible for freeing the returned string. */
1213 static char * WARN_UNUSED_RESULT
1214 parse_field(const struct mf_field *mf, const char *s, struct match *match,
1215             enum ofputil_protocol *usable_protocols)
1216 {
1217     union mf_value value, mask;
1218     char *error;
1219
1220     error = mf_parse(mf, s, &value, &mask);
1221     if (!error) {
1222         *usable_protocols &= mf_set(mf, &value, &mask, match);
1223     }
1224     return error;
1225 }
1226
1227 static char * WARN_UNUSED_RESULT
1228 parse_ofp_str__(struct ofputil_flow_mod *fm, int command, char *string,
1229                 enum ofputil_protocol *usable_protocols)
1230 {
1231     enum {
1232         F_OUT_PORT = 1 << 0,
1233         F_ACTIONS = 1 << 1,
1234         F_TIMEOUT = 1 << 3,
1235         F_PRIORITY = 1 << 4,
1236         F_FLAGS = 1 << 5,
1237     } fields;
1238     char *save_ptr = NULL;
1239     char *act_str = NULL;
1240     char *name;
1241
1242     *usable_protocols = OFPUTIL_P_ANY;
1243
1244     switch (command) {
1245     case -1:
1246         fields = F_OUT_PORT;
1247         break;
1248
1249     case OFPFC_ADD:
1250         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1251         break;
1252
1253     case OFPFC_DELETE:
1254         fields = F_OUT_PORT;
1255         break;
1256
1257     case OFPFC_DELETE_STRICT:
1258         fields = F_OUT_PORT | F_PRIORITY;
1259         break;
1260
1261     case OFPFC_MODIFY:
1262         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1263         break;
1264
1265     case OFPFC_MODIFY_STRICT:
1266         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
1267         break;
1268
1269     default:
1270         OVS_NOT_REACHED();
1271     }
1272
1273     match_init_catchall(&fm->match);
1274     fm->priority = OFP_DEFAULT_PRIORITY;
1275     fm->cookie = htonll(0);
1276     fm->cookie_mask = htonll(0);
1277     if (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT) {
1278         /* For modify, by default, don't update the cookie. */
1279         fm->new_cookie = OVS_BE64_MAX;
1280     } else{
1281         fm->new_cookie = htonll(0);
1282     }
1283     fm->modify_cookie = false;
1284     fm->table_id = 0xff;
1285     fm->command = command;
1286     fm->idle_timeout = OFP_FLOW_PERMANENT;
1287     fm->hard_timeout = OFP_FLOW_PERMANENT;
1288     fm->buffer_id = UINT32_MAX;
1289     fm->out_port = OFPP_ANY;
1290     fm->flags = 0;
1291     fm->out_group = OFPG11_ANY;
1292     fm->delete_reason = OFPRR_DELETE;
1293     if (fields & F_ACTIONS) {
1294         act_str = strstr(string, "action");
1295         if (!act_str) {
1296             return xstrdup("must specify an action");
1297         }
1298         *act_str = '\0';
1299
1300         act_str = strchr(act_str + 1, '=');
1301         if (!act_str) {
1302             return xstrdup("must specify an action");
1303         }
1304
1305         act_str++;
1306     }
1307     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1308          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1309         const struct protocol *p;
1310         char *error = NULL;
1311
1312         if (parse_protocol(name, &p)) {
1313             match_set_dl_type(&fm->match, htons(p->dl_type));
1314             if (p->nw_proto) {
1315                 match_set_nw_proto(&fm->match, p->nw_proto);
1316             }
1317         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
1318             fm->flags |= OFPUTIL_FF_SEND_FLOW_REM;
1319         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
1320             fm->flags |= OFPUTIL_FF_CHECK_OVERLAP;
1321         } else if (fields & F_FLAGS && !strcmp(name, "reset_counts")) {
1322             fm->flags |= OFPUTIL_FF_RESET_COUNTS;
1323             *usable_protocols &= OFPUTIL_P_OF12_UP;
1324         } else if (fields & F_FLAGS && !strcmp(name, "no_packet_counts")) {
1325             fm->flags |= OFPUTIL_FF_NO_PKT_COUNTS;
1326             *usable_protocols &= OFPUTIL_P_OF13_UP;
1327         } else if (fields & F_FLAGS && !strcmp(name, "no_byte_counts")) {
1328             fm->flags |= OFPUTIL_FF_NO_BYT_COUNTS;
1329             *usable_protocols &= OFPUTIL_P_OF13_UP;
1330         } else if (!strcmp(name, "no_readonly_table")
1331                    || !strcmp(name, "allow_hidden_fields")) {
1332              /* ignore these fields. */
1333         } else {
1334             char *value;
1335
1336             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1337             if (!value) {
1338                 return xasprintf("field %s missing value", name);
1339             }
1340
1341             if (!strcmp(name, "table")) {
1342                 error = str_to_u8(value, "table", &fm->table_id);
1343                 if (fm->table_id != 0xff) {
1344                     *usable_protocols &= OFPUTIL_P_TID;
1345                 }
1346             } else if (!strcmp(name, "out_port")) {
1347                 if (!ofputil_port_from_string(value, &fm->out_port)) {
1348                     error = xasprintf("%s is not a valid OpenFlow port",
1349                                       value);
1350                 }
1351             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
1352                 uint16_t priority = 0;
1353
1354                 error = str_to_u16(value, name, &priority);
1355                 fm->priority = priority;
1356             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
1357                 error = str_to_u16(value, name, &fm->idle_timeout);
1358             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
1359                 error = str_to_u16(value, name, &fm->hard_timeout);
1360             } else if (!strcmp(name, "cookie")) {
1361                 char *mask = strchr(value, '/');
1362
1363                 if (mask) {
1364                     /* A mask means we're searching for a cookie. */
1365                     if (command == OFPFC_ADD) {
1366                         return xstrdup("flow additions cannot use "
1367                                        "a cookie mask");
1368                     }
1369                     *mask = '\0';
1370                     error = str_to_be64(value, &fm->cookie);
1371                     if (error) {
1372                         return error;
1373                     }
1374                     error = str_to_be64(mask + 1, &fm->cookie_mask);
1375
1376                     /* Matching of the cookie is only supported through NXM or
1377                      * OF1.1+. */
1378                     if (fm->cookie_mask != htonll(0)) {
1379                         *usable_protocols &= OFPUTIL_P_NXM_OF11_UP;
1380                     }
1381                 } else {
1382                     /* No mask means that the cookie is being set. */
1383                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
1384                         && command != OFPFC_MODIFY_STRICT) {
1385                         return xstrdup("cannot set cookie");
1386                     }
1387                     error = str_to_be64(value, &fm->new_cookie);
1388                     fm->modify_cookie = true;
1389                 }
1390             } else if (mf_from_name(name)) {
1391                 error = parse_field(mf_from_name(name), value, &fm->match,
1392                                     usable_protocols);
1393             } else if (!strcmp(name, "duration")
1394                        || !strcmp(name, "n_packets")
1395                        || !strcmp(name, "n_bytes")
1396                        || !strcmp(name, "idle_age")
1397                        || !strcmp(name, "hard_age")) {
1398                 /* Ignore these, so that users can feed the output of
1399                  * "ovs-ofctl dump-flows" back into commands that parse
1400                  * flows. */
1401             } else {
1402                 error = xasprintf("unknown keyword %s", name);
1403             }
1404
1405             if (error) {
1406                 return error;
1407             }
1408         }
1409     }
1410     /* Check for usable protocol interdependencies between match fields. */
1411     if (fm->match.flow.dl_type == htons(ETH_TYPE_IPV6)) {
1412         const struct flow_wildcards *wc = &fm->match.wc;
1413         /* Only NXM and OXM support matching L3 and L4 fields within IPv6.
1414          *
1415          * (IPv6 specific fields as well as arp_sha, arp_tha, nw_frag, and
1416          *  nw_ttl are covered elsewhere so they don't need to be included in
1417          *  this test too.)
1418          */
1419         if (wc->masks.nw_proto || wc->masks.nw_tos
1420             || wc->masks.tp_src || wc->masks.tp_dst) {
1421             *usable_protocols &= OFPUTIL_P_NXM_OXM_ANY;
1422         }
1423     }
1424     if (!fm->cookie_mask && fm->new_cookie == OVS_BE64_MAX
1425         && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
1426         /* On modifies without a mask, we are supposed to add a flow if
1427          * one does not exist.  If a cookie wasn't been specified, use a
1428          * default of zero. */
1429         fm->new_cookie = htonll(0);
1430     }
1431     if (fields & F_ACTIONS) {
1432         struct ofpbuf ofpacts;
1433         char *error;
1434
1435         ofpbuf_init(&ofpacts, 32);
1436         error = str_to_inst_ofpacts(act_str, &ofpacts, usable_protocols);
1437         if (!error) {
1438             enum ofperr err;
1439
1440             err = ofpacts_check(ofpbuf_data(&ofpacts), ofpbuf_size(&ofpacts), &fm->match.flow,
1441                                 OFPP_MAX, fm->table_id, 255, usable_protocols);
1442             if (!err && !usable_protocols) {
1443                 err = OFPERR_OFPBAC_MATCH_INCONSISTENT;
1444             }
1445             if (err) {
1446                 error = xasprintf("actions are invalid with specified match "
1447                                   "(%s)", ofperr_to_string(err));
1448             }
1449
1450         }
1451         if (error) {
1452             ofpbuf_uninit(&ofpacts);
1453             return error;
1454         }
1455
1456         fm->ofpacts_len = ofpbuf_size(&ofpacts);
1457         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
1458     } else {
1459         fm->ofpacts_len = 0;
1460         fm->ofpacts = NULL;
1461     }
1462
1463     return NULL;
1464 }
1465
1466 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1467  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
1468  * Returns the set of usable protocols in '*usable_protocols'.
1469  *
1470  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
1471  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
1472  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'.
1473  *
1474  * Returns NULL if successful, otherwise a malloc()'d string describing the
1475  * error.  The caller is responsible for freeing the returned string. */
1476 char * WARN_UNUSED_RESULT
1477 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
1478               enum ofputil_protocol *usable_protocols)
1479 {
1480     char *string = xstrdup(str_);
1481     char *error;
1482
1483     error = parse_ofp_str__(fm, command, string, usable_protocols);
1484     if (error) {
1485         fm->ofpacts = NULL;
1486         fm->ofpacts_len = 0;
1487     }
1488
1489     free(string);
1490     return error;
1491 }
1492
1493 static char * WARN_UNUSED_RESULT
1494 parse_ofp_meter_mod_str__(struct ofputil_meter_mod *mm, char *string,
1495                           struct ofpbuf *bands, int command,
1496                           enum ofputil_protocol *usable_protocols)
1497 {
1498     enum {
1499         F_METER = 1 << 0,
1500         F_FLAGS = 1 << 1,
1501         F_BANDS = 1 << 2,
1502     } fields;
1503     char *save_ptr = NULL;
1504     char *band_str = NULL;
1505     char *name;
1506
1507     /* Meters require at least OF 1.3. */
1508     *usable_protocols = OFPUTIL_P_OF13_UP;
1509
1510     switch (command) {
1511     case -1:
1512         fields = F_METER;
1513         break;
1514
1515     case OFPMC13_ADD:
1516         fields = F_METER | F_FLAGS | F_BANDS;
1517         break;
1518
1519     case OFPMC13_DELETE:
1520         fields = F_METER;
1521         break;
1522
1523     case OFPMC13_MODIFY:
1524         fields = F_METER | F_FLAGS | F_BANDS;
1525         break;
1526
1527     default:
1528         OVS_NOT_REACHED();
1529     }
1530
1531     mm->command = command;
1532     mm->meter.meter_id = 0;
1533     mm->meter.flags = 0;
1534     if (fields & F_BANDS) {
1535         band_str = strstr(string, "band");
1536         if (!band_str) {
1537             return xstrdup("must specify bands");
1538         }
1539         *band_str = '\0';
1540
1541         band_str = strchr(band_str + 1, '=');
1542         if (!band_str) {
1543             return xstrdup("must specify bands");
1544         }
1545
1546         band_str++;
1547     }
1548     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1549          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1550
1551         if (fields & F_FLAGS && !strcmp(name, "kbps")) {
1552             mm->meter.flags |= OFPMF13_KBPS;
1553         } else if (fields & F_FLAGS && !strcmp(name, "pktps")) {
1554             mm->meter.flags |= OFPMF13_PKTPS;
1555         } else if (fields & F_FLAGS && !strcmp(name, "burst")) {
1556             mm->meter.flags |= OFPMF13_BURST;
1557         } else if (fields & F_FLAGS && !strcmp(name, "stats")) {
1558             mm->meter.flags |= OFPMF13_STATS;
1559         } else {
1560             char *value;
1561
1562             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1563             if (!value) {
1564                 return xasprintf("field %s missing value", name);
1565             }
1566
1567             if (!strcmp(name, "meter")) {
1568                 if (!strcmp(value, "all")) {
1569                     mm->meter.meter_id = OFPM13_ALL;
1570                 } else if (!strcmp(value, "controller")) {
1571                     mm->meter.meter_id = OFPM13_CONTROLLER;
1572                 } else if (!strcmp(value, "slowpath")) {
1573                     mm->meter.meter_id = OFPM13_SLOWPATH;
1574                 } else {
1575                     char *error = str_to_u32(value, &mm->meter.meter_id);
1576                     if (error) {
1577                         return error;
1578                     }
1579                     if (mm->meter.meter_id > OFPM13_MAX) {
1580                         return xasprintf("invalid value for %s", name);
1581                     }
1582                 }
1583             } else {
1584                 return xasprintf("unknown keyword %s", name);
1585             }
1586         }
1587     }
1588     if (fields & F_METER && !mm->meter.meter_id) {
1589         return xstrdup("must specify 'meter'");
1590     }
1591     if (fields & F_FLAGS && !mm->meter.flags) {
1592         return xstrdup("meter must specify either 'kbps' or 'pktps'");
1593     }
1594
1595     if (fields & F_BANDS) {
1596         uint16_t n_bands = 0;
1597         struct ofputil_meter_band *band = NULL;
1598         int i;
1599
1600         for (name = strtok_r(band_str, "=, \t\r\n", &save_ptr); name;
1601              name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1602
1603             char *value;
1604
1605             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1606             if (!value) {
1607                 return xasprintf("field %s missing value", name);
1608             }
1609
1610             if (!strcmp(name, "type")) {
1611                 /* Start a new band */
1612                 band = ofpbuf_put_zeros(bands, sizeof *band);
1613                 n_bands++;
1614
1615                 if (!strcmp(value, "drop")) {
1616                     band->type = OFPMBT13_DROP;
1617                 } else if (!strcmp(value, "dscp_remark")) {
1618                     band->type = OFPMBT13_DSCP_REMARK;
1619                 } else {
1620                     return xasprintf("field %s unknown value %s", name, value);
1621                 }
1622             } else if (!band || !band->type) {
1623                 return xstrdup("band must start with the 'type' keyword");
1624             } else if (!strcmp(name, "rate")) {
1625                 char *error = str_to_u32(value, &band->rate);
1626                 if (error) {
1627                     return error;
1628                 }
1629             } else if (!strcmp(name, "burst_size")) {
1630                 char *error = str_to_u32(value, &band->burst_size);
1631                 if (error) {
1632                     return error;
1633                 }
1634             } else if (!strcmp(name, "prec_level")) {
1635                 char *error = str_to_u8(value, name, &band->prec_level);
1636                 if (error) {
1637                     return error;
1638                 }
1639             } else {
1640                 return xasprintf("unknown keyword %s", name);
1641             }
1642         }
1643         /* validate bands */
1644         if (!n_bands) {
1645             return xstrdup("meter must have bands");
1646         }
1647
1648         mm->meter.n_bands = n_bands;
1649         mm->meter.bands = ofpbuf_steal_data(bands);
1650
1651         for (i = 0; i < n_bands; ++i) {
1652             band = &mm->meter.bands[i];
1653
1654             if (!band->type) {
1655                 return xstrdup("band must have 'type'");
1656             }
1657             if (band->type == OFPMBT13_DSCP_REMARK) {
1658                 if (!band->prec_level) {
1659                     return xstrdup("'dscp_remark' band must have"
1660                                    " 'prec_level'");
1661                 }
1662             } else {
1663                 if (band->prec_level) {
1664                     return xstrdup("Only 'dscp_remark' band may have"
1665                                    " 'prec_level'");
1666                 }
1667             }
1668             if (!band->rate) {
1669                 return xstrdup("band must have 'rate'");
1670             }
1671             if (mm->meter.flags & OFPMF13_BURST) {
1672                 if (!band->burst_size) {
1673                     return xstrdup("band must have 'burst_size' "
1674                                    "when 'burst' flag is set");
1675                 }
1676             } else {
1677                 if (band->burst_size) {
1678                     return xstrdup("band may have 'burst_size' only "
1679                                    "when 'burst' flag is set");
1680                 }
1681             }
1682         }
1683     } else {
1684         mm->meter.n_bands = 0;
1685         mm->meter.bands = NULL;
1686     }
1687
1688     return NULL;
1689 }
1690
1691 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1692  * page) into 'mm' for sending the specified meter_mod 'command' to a switch.
1693  *
1694  * Returns NULL if successful, otherwise a malloc()'d string describing the
1695  * error.  The caller is responsible for freeing the returned string. */
1696 char * WARN_UNUSED_RESULT
1697 parse_ofp_meter_mod_str(struct ofputil_meter_mod *mm, const char *str_,
1698                         int command, enum ofputil_protocol *usable_protocols)
1699 {
1700     struct ofpbuf bands;
1701     char *string;
1702     char *error;
1703
1704     ofpbuf_init(&bands, 64);
1705     string = xstrdup(str_);
1706
1707     error = parse_ofp_meter_mod_str__(mm, string, &bands, command,
1708                                       usable_protocols);
1709
1710     free(string);
1711     ofpbuf_uninit(&bands);
1712
1713     return error;
1714 }
1715
1716 static char * WARN_UNUSED_RESULT
1717 parse_flow_monitor_request__(struct ofputil_flow_monitor_request *fmr,
1718                              const char *str_, char *string,
1719                              enum ofputil_protocol *usable_protocols)
1720 {
1721     static atomic_uint32_t id = ATOMIC_VAR_INIT(0);
1722     char *save_ptr = NULL;
1723     char *name;
1724
1725     atomic_add(&id, 1, &fmr->id);
1726
1727     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
1728                   | NXFMF_OWN | NXFMF_ACTIONS);
1729     fmr->out_port = OFPP_NONE;
1730     fmr->table_id = 0xff;
1731     match_init_catchall(&fmr->match);
1732
1733     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1734          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1735         const struct protocol *p;
1736
1737         if (!strcmp(name, "!initial")) {
1738             fmr->flags &= ~NXFMF_INITIAL;
1739         } else if (!strcmp(name, "!add")) {
1740             fmr->flags &= ~NXFMF_ADD;
1741         } else if (!strcmp(name, "!delete")) {
1742             fmr->flags &= ~NXFMF_DELETE;
1743         } else if (!strcmp(name, "!modify")) {
1744             fmr->flags &= ~NXFMF_MODIFY;
1745         } else if (!strcmp(name, "!actions")) {
1746             fmr->flags &= ~NXFMF_ACTIONS;
1747         } else if (!strcmp(name, "!own")) {
1748             fmr->flags &= ~NXFMF_OWN;
1749         } else if (parse_protocol(name, &p)) {
1750             match_set_dl_type(&fmr->match, htons(p->dl_type));
1751             if (p->nw_proto) {
1752                 match_set_nw_proto(&fmr->match, p->nw_proto);
1753             }
1754         } else {
1755             char *value;
1756
1757             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1758             if (!value) {
1759                 return xasprintf("%s: field %s missing value", str_, name);
1760             }
1761
1762             if (!strcmp(name, "table")) {
1763                 char *error = str_to_u8(value, "table", &fmr->table_id);
1764                 if (error) {
1765                     return error;
1766                 }
1767             } else if (!strcmp(name, "out_port")) {
1768                 fmr->out_port = u16_to_ofp(atoi(value));
1769             } else if (mf_from_name(name)) {
1770                 char *error;
1771
1772                 error = parse_field(mf_from_name(name), value, &fmr->match,
1773                                     usable_protocols);
1774                 if (error) {
1775                     return error;
1776                 }
1777             } else {
1778                 return xasprintf("%s: unknown keyword %s", str_, name);
1779             }
1780         }
1781     }
1782     return NULL;
1783 }
1784
1785 /* Convert 'str_' (as described in the documentation for the "monitor" command
1786  * in the ovs-ofctl man page) into 'fmr'.
1787  *
1788  * Returns NULL if successful, otherwise a malloc()'d string describing the
1789  * error.  The caller is responsible for freeing the returned string. */
1790 char * WARN_UNUSED_RESULT
1791 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
1792                            const char *str_,
1793                            enum ofputil_protocol *usable_protocols)
1794 {
1795     char *string = xstrdup(str_);
1796     char *error = parse_flow_monitor_request__(fmr, str_, string,
1797                                                usable_protocols);
1798     free(string);
1799     return error;
1800 }
1801
1802 /* Parses 's' as a set of OpenFlow actions and appends the actions to
1803  * 'actions'.
1804  *
1805  * Returns NULL if successful, otherwise a malloc()'d string describing the
1806  * error.  The caller is responsible for freeing the returned string. */
1807 char * WARN_UNUSED_RESULT
1808 parse_ofpacts(const char *s_, struct ofpbuf *ofpacts,
1809               enum ofputil_protocol *usable_protocols)
1810 {
1811     char *s = xstrdup(s_);
1812     char *error;
1813
1814     *usable_protocols = OFPUTIL_P_ANY;
1815
1816     error = str_to_ofpacts(s, ofpacts, usable_protocols);
1817     free(s);
1818
1819     return error;
1820 }
1821
1822 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1823  * (one of OFPFC_*) into 'fm'.
1824  *
1825  * Returns NULL if successful, otherwise a malloc()'d string describing the
1826  * error.  The caller is responsible for freeing the returned string. */
1827 char * WARN_UNUSED_RESULT
1828 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
1829                        uint16_t command,
1830                        enum ofputil_protocol *usable_protocols)
1831 {
1832     char *error = parse_ofp_str(fm, command, string, usable_protocols);
1833     if (!error) {
1834         /* Normalize a copy of the match.  This ensures that non-normalized
1835          * flows get logged but doesn't affect what gets sent to the switch, so
1836          * that the switch can do whatever it likes with the flow. */
1837         struct match match_copy = fm->match;
1838         ofputil_normalize_match(&match_copy);
1839     }
1840
1841     return error;
1842 }
1843
1844 /* Convert 'table_id' and 'flow_miss_handling' (as described for the
1845  * "mod-table" command in the ovs-ofctl man page) into 'tm' for sending the
1846  * specified table_mod 'command' to a switch.
1847  *
1848  * Returns NULL if successful, otherwise a malloc()'d string describing the
1849  * error.  The caller is responsible for freeing the returned string. */
1850 char * WARN_UNUSED_RESULT
1851 parse_ofp_table_mod(struct ofputil_table_mod *tm, const char *table_id,
1852                     const char *flow_miss_handling,
1853                     enum ofputil_protocol *usable_protocols)
1854 {
1855     /* Table mod requires at least OF 1.1. */
1856     *usable_protocols = OFPUTIL_P_OF11_UP;
1857
1858     if (!strcasecmp(table_id, "all")) {
1859         tm->table_id = OFPTT_ALL;
1860     } else {
1861         char *error = str_to_u8(table_id, "table_id", &tm->table_id);
1862         if (error) {
1863             return error;
1864         }
1865     }
1866
1867     if (strcmp(flow_miss_handling, "controller") == 0) {
1868         tm->miss_config = OFPUTIL_TABLE_MISS_CONTROLLER;
1869     } else if (strcmp(flow_miss_handling, "continue") == 0) {
1870         tm->miss_config = OFPUTIL_TABLE_MISS_CONTINUE;
1871     } else if (strcmp(flow_miss_handling, "drop") == 0) {
1872         tm->miss_config = OFPUTIL_TABLE_MISS_DROP;
1873     } else {
1874         return xasprintf("invalid flow_miss_handling %s", flow_miss_handling);
1875     }
1876
1877     if (tm->table_id == 0xfe
1878         && tm->miss_config == OFPUTIL_TABLE_MISS_CONTINUE) {
1879         return xstrdup("last table's flow miss handling can not be continue");
1880     }
1881
1882     return NULL;
1883 }
1884
1885
1886 /* Opens file 'file_name' and reads each line as a flow_mod of the specified
1887  * type (one of OFPFC_*).  Stores each flow_mod in '*fm', an array allocated
1888  * on the caller's behalf, and the number of flow_mods in '*n_fms'.
1889  *
1890  * Returns NULL if successful, otherwise a malloc()'d string describing the
1891  * error.  The caller is responsible for freeing the returned string. */
1892 char * WARN_UNUSED_RESULT
1893 parse_ofp_flow_mod_file(const char *file_name, uint16_t command,
1894                         struct ofputil_flow_mod **fms, size_t *n_fms,
1895                         enum ofputil_protocol *usable_protocols)
1896 {
1897     size_t allocated_fms;
1898     int line_number;
1899     FILE *stream;
1900     struct ds s;
1901
1902     *usable_protocols = OFPUTIL_P_ANY;
1903
1904     *fms = NULL;
1905     *n_fms = 0;
1906
1907     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1908     if (stream == NULL) {
1909         return xasprintf("%s: open failed (%s)",
1910                          file_name, ovs_strerror(errno));
1911     }
1912
1913     allocated_fms = *n_fms;
1914     ds_init(&s);
1915     line_number = 0;
1916     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
1917         char *error;
1918         enum ofputil_protocol usable;
1919
1920         if (*n_fms >= allocated_fms) {
1921             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1922         }
1923         error = parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command,
1924                                        &usable);
1925         if (error) {
1926             size_t i;
1927
1928             for (i = 0; i < *n_fms; i++) {
1929                 free(CONST_CAST(struct ofpact *, (*fms)[i].ofpacts));
1930             }
1931             free(*fms);
1932             *fms = NULL;
1933             *n_fms = 0;
1934
1935             ds_destroy(&s);
1936             if (stream != stdin) {
1937                 fclose(stream);
1938             }
1939
1940             return xasprintf("%s:%d: %s", file_name, line_number, error);
1941         }
1942         *usable_protocols &= usable; /* Each line can narrow the set. */
1943         *n_fms += 1;
1944     }
1945
1946     ds_destroy(&s);
1947     if (stream != stdin) {
1948         fclose(stream);
1949     }
1950     return NULL;
1951 }
1952
1953 char * WARN_UNUSED_RESULT
1954 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1955                                  bool aggregate, const char *string,
1956                                  enum ofputil_protocol *usable_protocols)
1957 {
1958     struct ofputil_flow_mod fm;
1959     char *error;
1960
1961     error = parse_ofp_str(&fm, -1, string, usable_protocols);
1962     if (error) {
1963         return error;
1964     }
1965
1966     /* Special table ID support not required for stats requests. */
1967     if (*usable_protocols & OFPUTIL_P_OF10_STD_TID) {
1968         *usable_protocols |= OFPUTIL_P_OF10_STD;
1969     }
1970     if (*usable_protocols & OFPUTIL_P_OF10_NXM_TID) {
1971         *usable_protocols |= OFPUTIL_P_OF10_NXM;
1972     }
1973
1974     fsr->aggregate = aggregate;
1975     fsr->cookie = fm.cookie;
1976     fsr->cookie_mask = fm.cookie_mask;
1977     fsr->match = fm.match;
1978     fsr->out_port = fm.out_port;
1979     fsr->out_group = fm.out_group;
1980     fsr->table_id = fm.table_id;
1981     return NULL;
1982 }
1983
1984 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1985  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1986  * mf_field.  Fields must be specified in a natural order for satisfying
1987  * prerequisites. If 'mask' is specified, fills the mask field for each of the
1988  * field specified in flow. If the map, 'names_portno' is specfied, converts
1989  * the in_port name into port no while setting the 'flow'.
1990  *
1991  * Returns NULL on success, otherwise a malloc()'d string that explains the
1992  * problem. */
1993 char *
1994 parse_ofp_exact_flow(struct flow *flow, struct flow *mask, const char *s,
1995                      const struct simap *portno_names)
1996 {
1997     char *pos, *key, *value_s;
1998     char *error = NULL;
1999     char *copy;
2000
2001     memset(flow, 0, sizeof *flow);
2002     if (mask) {
2003         memset(mask, 0, sizeof *mask);
2004     }
2005
2006     pos = copy = xstrdup(s);
2007     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
2008         const struct protocol *p;
2009         if (parse_protocol(key, &p)) {
2010             if (flow->dl_type) {
2011                 error = xasprintf("%s: Ethernet type set multiple times", s);
2012                 goto exit;
2013             }
2014             flow->dl_type = htons(p->dl_type);
2015             if (mask) {
2016                 mask->dl_type = OVS_BE16_MAX;
2017             }
2018
2019             if (p->nw_proto) {
2020                 if (flow->nw_proto) {
2021                     error = xasprintf("%s: network protocol set "
2022                                       "multiple times", s);
2023                     goto exit;
2024                 }
2025                 flow->nw_proto = p->nw_proto;
2026                 if (mask) {
2027                     mask->nw_proto = UINT8_MAX;
2028                 }
2029             }
2030         } else {
2031             const struct mf_field *mf;
2032             union mf_value value;
2033             char *field_error;
2034
2035             mf = mf_from_name(key);
2036             if (!mf) {
2037                 error = xasprintf("%s: unknown field %s", s, key);
2038                 goto exit;
2039             }
2040
2041             if (!mf_are_prereqs_ok(mf, flow)) {
2042                 error = xasprintf("%s: prerequisites not met for setting %s",
2043                                   s, key);
2044                 goto exit;
2045             }
2046
2047             if (!mf_is_zero(mf, flow)) {
2048                 error = xasprintf("%s: field %s set multiple times", s, key);
2049                 goto exit;
2050             }
2051
2052             if (!strcmp(key, "in_port")
2053                 && portno_names
2054                 && simap_contains(portno_names, value_s)) {
2055                 flow->in_port.ofp_port = u16_to_ofp(
2056                     simap_get(portno_names, value_s));
2057                 if (mask) {
2058                     mask->in_port.ofp_port = u16_to_ofp(ntohs(OVS_BE16_MAX));
2059                 }
2060             } else {
2061                 field_error = mf_parse_value(mf, value_s, &value);
2062                 if (field_error) {
2063                     error = xasprintf("%s: bad value for %s (%s)",
2064                                       s, key, field_error);
2065                     free(field_error);
2066                     goto exit;
2067                 }
2068
2069                 mf_set_flow_value(mf, &value, flow);
2070                 if (mask) {
2071                     mf_mask_field(mf, mask);
2072                 }
2073             }
2074         }
2075     }
2076
2077     if (!flow->in_port.ofp_port) {
2078         flow->in_port.ofp_port = OFPP_NONE;
2079     }
2080
2081 exit:
2082     free(copy);
2083
2084     if (error) {
2085         memset(flow, 0, sizeof *flow);
2086         if (mask) {
2087             memset(mask, 0, sizeof *mask);
2088         }
2089     }
2090     return error;
2091 }
2092
2093 static char * WARN_UNUSED_RESULT
2094 parse_bucket_str(struct ofputil_bucket *bucket, char *str_,
2095                   enum ofputil_protocol *usable_protocols)
2096 {
2097     struct ofpbuf ofpacts;
2098     char *pos, *act, *arg;
2099     int n_actions;
2100
2101     bucket->weight = 1;
2102     bucket->watch_port = OFPP_ANY;
2103     bucket->watch_group = OFPG11_ANY;
2104
2105     pos = str_;
2106     n_actions = 0;
2107     ofpbuf_init(&ofpacts, 64);
2108     while (ofputil_parse_key_value(&pos, &act, &arg)) {
2109         char *error = NULL;
2110
2111         if (!strcasecmp(act, "weight")) {
2112             error = str_to_u16(arg, "weight", &bucket->weight);
2113         } else if (!strcasecmp(act, "watch_port")) {
2114             if (!ofputil_port_from_string(arg, &bucket->watch_port)
2115                 || (ofp_to_u16(bucket->watch_port) >= ofp_to_u16(OFPP_MAX)
2116                     && bucket->watch_port != OFPP_ANY)) {
2117                 error = xasprintf("%s: invalid watch_port", arg);
2118             }
2119         } else if (!strcasecmp(act, "watch_group")) {
2120             error = str_to_u32(arg, &bucket->watch_group);
2121             if (!error && bucket->watch_group > OFPG_MAX) {
2122                 error = xasprintf("invalid watch_group id %"PRIu32,
2123                                   bucket->watch_group);
2124             }
2125         } else if (!strcasecmp(act, "actions")) {
2126             if (ofputil_parse_key_value(&arg, &act, &arg)) {
2127                 error = str_to_ofpact__(pos, act, arg, &ofpacts, n_actions,
2128                                         usable_protocols);
2129                 n_actions++;
2130             }
2131         } else {
2132             error = str_to_ofpact__(pos, act, arg, &ofpacts, n_actions,
2133                                     usable_protocols);
2134             n_actions++;
2135         }
2136
2137         if (error) {
2138             ofpbuf_uninit(&ofpacts);
2139             return error;
2140         }
2141     }
2142
2143     ofpact_pad(&ofpacts);
2144     bucket->ofpacts = ofpbuf_data(&ofpacts);
2145     bucket->ofpacts_len = ofpbuf_size(&ofpacts);
2146
2147     return NULL;
2148 }
2149
2150 static char * WARN_UNUSED_RESULT
2151 parse_ofp_group_mod_str__(struct ofputil_group_mod *gm, uint16_t command,
2152                           char *string,
2153                           enum ofputil_protocol *usable_protocols)
2154 {
2155     enum {
2156         F_GROUP_TYPE  = 1 << 0,
2157         F_BUCKETS     = 1 << 1,
2158     } fields;
2159     char *save_ptr = NULL;
2160     bool had_type = false;
2161     char *name;
2162     struct ofputil_bucket *bucket;
2163     char *error = NULL;
2164
2165     *usable_protocols = OFPUTIL_P_OF11_UP;
2166
2167     switch (command) {
2168     case OFPGC11_ADD:
2169         fields = F_GROUP_TYPE | F_BUCKETS;
2170         break;
2171
2172     case OFPGC11_DELETE:
2173         fields = 0;
2174         break;
2175
2176     case OFPGC11_MODIFY:
2177         fields = F_GROUP_TYPE | F_BUCKETS;
2178         break;
2179
2180     default:
2181         OVS_NOT_REACHED();
2182     }
2183
2184     memset(gm, 0, sizeof *gm);
2185     gm->command = command;
2186     gm->group_id = OFPG_ANY;
2187     list_init(&gm->buckets);
2188     if (command == OFPGC11_DELETE && string[0] == '\0') {
2189         gm->group_id = OFPG_ALL;
2190         return NULL;
2191     }
2192
2193     *usable_protocols = OFPUTIL_P_OF11_UP;
2194
2195     if (fields & F_BUCKETS) {
2196         char *bkt_str = strstr(string, "bucket");
2197
2198         if (bkt_str) {
2199             *bkt_str = '\0';
2200         }
2201
2202         while (bkt_str) {
2203             char *next_bkt_str;
2204
2205             bkt_str = strchr(bkt_str + 1, '=');
2206             if (!bkt_str) {
2207                 error = xstrdup("must specify bucket content");
2208                 goto out;
2209             }
2210             bkt_str++;
2211
2212             next_bkt_str = strstr(bkt_str, "bucket");
2213             if (next_bkt_str) {
2214                 *next_bkt_str = '\0';
2215             }
2216
2217             bucket = xzalloc(sizeof(struct ofputil_bucket));
2218             error = parse_bucket_str(bucket, bkt_str, usable_protocols);
2219             if (error) {
2220                 free(bucket);
2221                 goto out;
2222             }
2223             list_push_back(&gm->buckets, &bucket->list_node);
2224
2225             bkt_str = next_bkt_str;
2226         }
2227     }
2228
2229     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
2230          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
2231         char *value;
2232
2233         value = strtok_r(NULL, ", \t\r\n", &save_ptr);
2234         if (!value) {
2235             error = xasprintf("field %s missing value", name);
2236             goto out;
2237         }
2238
2239         if (!strcmp(name, "group_id")) {
2240             if(!strcmp(value, "all")) {
2241                 gm->group_id = OFPG_ALL;
2242             } else {
2243                 char *error = str_to_u32(value, &gm->group_id);
2244                 if (error) {
2245                     goto out;
2246                 }
2247                 if (gm->group_id != OFPG_ALL && gm->group_id > OFPG_MAX) {
2248                     error = xasprintf("invalid group id %"PRIu32,
2249                                       gm->group_id);
2250                     goto out;
2251                 }
2252             }
2253         } else if (!strcmp(name, "type")){
2254             if (!(fields & F_GROUP_TYPE)) {
2255                 error = xstrdup("type is not needed");
2256                 goto out;
2257             }
2258             if (!strcmp(value, "all")) {
2259                 gm->type = OFPGT11_ALL;
2260             } else if (!strcmp(value, "select")) {
2261                 gm->type = OFPGT11_SELECT;
2262             } else if (!strcmp(value, "indirect")) {
2263                 gm->type = OFPGT11_INDIRECT;
2264             } else if (!strcmp(value, "ff") ||
2265                        !strcmp(value, "fast_failover")) {
2266                 gm->type = OFPGT11_FF;
2267             } else {
2268                 error = xasprintf("invalid group type %s", value);
2269                 goto out;
2270             }
2271             had_type = true;
2272         } else if (!strcmp(name, "bucket")) {
2273             error = xstrdup("bucket is not needed");
2274             goto out;
2275         } else {
2276             error = xasprintf("unknown keyword %s", name);
2277             goto out;
2278         }
2279     }
2280     if (gm->group_id == OFPG_ANY) {
2281         error = xstrdup("must specify a group_id");
2282         goto out;
2283     }
2284     if (fields & F_GROUP_TYPE && !had_type) {
2285         error = xstrdup("must specify a type");
2286         goto out;
2287     }
2288
2289     /* Validate buckets. */
2290     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
2291         if (bucket->weight != 1 && gm->type != OFPGT11_SELECT) {
2292             error = xstrdup("Only select groups can have bucket weights.");
2293             goto out;
2294         }
2295     }
2296     if (gm->type == OFPGT11_INDIRECT && !list_is_short(&gm->buckets)) {
2297         error = xstrdup("Indirect groups can have at most one bucket.");
2298         goto out;
2299     }
2300
2301     return NULL;
2302  out:
2303     ofputil_bucket_list_destroy(&gm->buckets);
2304     return error;
2305 }
2306
2307 char * WARN_UNUSED_RESULT
2308 parse_ofp_group_mod_str(struct ofputil_group_mod *gm, uint16_t command,
2309                         const char *str_,
2310                         enum ofputil_protocol *usable_protocols)
2311 {
2312     char *string = xstrdup(str_);
2313     char *error = parse_ofp_group_mod_str__(gm, command, string,
2314                                             usable_protocols);
2315     free(string);
2316
2317     if (error) {
2318         ofputil_bucket_list_destroy(&gm->buckets);
2319     }
2320     return error;
2321 }
2322
2323 char * WARN_UNUSED_RESULT
2324 parse_ofp_group_mod_file(const char *file_name, uint16_t command,
2325                          struct ofputil_group_mod **gms, size_t *n_gms,
2326                          enum ofputil_protocol *usable_protocols)
2327 {
2328     size_t allocated_gms;
2329     int line_number;
2330     FILE *stream;
2331     struct ds s;
2332
2333     *gms = NULL;
2334     *n_gms = 0;
2335
2336     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
2337     if (stream == NULL) {
2338         return xasprintf("%s: open failed (%s)",
2339                          file_name, ovs_strerror(errno));
2340     }
2341
2342     allocated_gms = *n_gms;
2343     ds_init(&s);
2344     line_number = 0;
2345     *usable_protocols = OFPUTIL_P_OF11_UP;
2346     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
2347         enum ofputil_protocol usable;
2348         char *error;
2349
2350         if (*n_gms >= allocated_gms) {
2351             size_t i;
2352
2353             *gms = x2nrealloc(*gms, &allocated_gms, sizeof **gms);
2354             for (i = 0; i < *n_gms; i++) {
2355                 list_moved(&(*gms)[i].buckets);
2356             }
2357         }
2358         error = parse_ofp_group_mod_str(&(*gms)[*n_gms], command, ds_cstr(&s),
2359                                         &usable);
2360         if (error) {
2361             size_t i;
2362
2363             for (i = 0; i < *n_gms; i++) {
2364                 ofputil_bucket_list_destroy(&(*gms)[i].buckets);
2365             }
2366             free(*gms);
2367             *gms = NULL;
2368             *n_gms = 0;
2369
2370             ds_destroy(&s);
2371             if (stream != stdin) {
2372                 fclose(stream);
2373             }
2374
2375             return xasprintf("%s:%d: %s", file_name, line_number, error);
2376         }
2377         *usable_protocols &= usable;
2378         *n_gms += 1;
2379     }
2380
2381     ds_destroy(&s);
2382     if (stream != stdin) {
2383         fclose(stream);
2384     }
2385     return NULL;
2386 }