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