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