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