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