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