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