ofp-parse: Do not exit() upon a parse error.
[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->table_id = 0xff;
1129     fm->command = command;
1130     fm->idle_timeout = OFP_FLOW_PERMANENT;
1131     fm->hard_timeout = OFP_FLOW_PERMANENT;
1132     fm->buffer_id = UINT32_MAX;
1133     fm->out_port = OFPP_ANY;
1134     fm->flags = 0;
1135     if (fields & F_ACTIONS) {
1136         act_str = strstr(string, "action");
1137         if (!act_str) {
1138             return xstrdup("must specify an action");
1139         }
1140         *act_str = '\0';
1141
1142         act_str = strchr(act_str + 1, '=');
1143         if (!act_str) {
1144             return xstrdup("must specify an action");
1145         }
1146
1147         act_str++;
1148     }
1149     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1150          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1151         const struct protocol *p;
1152         char *error = NULL;
1153
1154         if (parse_protocol(name, &p)) {
1155             match_set_dl_type(&fm->match, htons(p->dl_type));
1156             if (p->nw_proto) {
1157                 match_set_nw_proto(&fm->match, p->nw_proto);
1158             }
1159         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
1160             fm->flags |= OFPFF_SEND_FLOW_REM;
1161         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
1162             fm->flags |= OFPFF_CHECK_OVERLAP;
1163         } else if (fields & F_FLAGS && !strcmp(name, "reset_counts")) {
1164             fm->flags |= OFPFF12_RESET_COUNTS;
1165         } else if (fields & F_FLAGS && !strcmp(name, "no_packet_counts")) {
1166             fm->flags |= OFPFF13_NO_PKT_COUNTS;
1167         } else if (fields & F_FLAGS && !strcmp(name, "no_byte_counts")) {
1168             fm->flags |= OFPFF13_NO_BYT_COUNTS;
1169         } else {
1170             char *value;
1171
1172             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1173             if (!value) {
1174                 return xasprintf("field %s missing value", name);
1175             }
1176
1177             if (!strcmp(name, "table")) {
1178                 error = str_to_u8(value, "table", &fm->table_id);
1179             } else if (!strcmp(name, "out_port")) {
1180                 if (!ofputil_port_from_string(value, &fm->out_port)) {
1181                     error = xasprintf("%s is not a valid OpenFlow port",
1182                                       value);
1183                 }
1184             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
1185                 uint16_t priority;
1186
1187                 error = str_to_u16(value, name, &priority);
1188                 fm->priority = priority;
1189             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
1190                 error = str_to_u16(value, name, &fm->idle_timeout);
1191             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
1192                 error = str_to_u16(value, name, &fm->hard_timeout);
1193             } else if (!strcmp(name, "cookie")) {
1194                 char *mask = strchr(value, '/');
1195
1196                 if (mask) {
1197                     /* A mask means we're searching for a cookie. */
1198                     if (command == OFPFC_ADD) {
1199                         return xstrdup("flow additions cannot use "
1200                                        "a cookie mask");
1201                     }
1202                     *mask = '\0';
1203                     error = str_to_be64(value, &fm->cookie);
1204                     if (error) {
1205                         return error;
1206                     }
1207                     error = str_to_be64(mask + 1, &fm->cookie_mask);
1208                 } else {
1209                     /* No mask means that the cookie is being set. */
1210                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
1211                         && command != OFPFC_MODIFY_STRICT) {
1212                         return xstrdup("cannot set cookie");
1213                     }
1214                     error = str_to_be64(value, &fm->new_cookie);
1215                 }
1216             } else if (mf_from_name(name)) {
1217                 error = parse_field(mf_from_name(name), value, &fm->match);
1218             } else if (!strcmp(name, "duration")
1219                        || !strcmp(name, "n_packets")
1220                        || !strcmp(name, "n_bytes")
1221                        || !strcmp(name, "idle_age")
1222                        || !strcmp(name, "hard_age")) {
1223                 /* Ignore these, so that users can feed the output of
1224                  * "ovs-ofctl dump-flows" back into commands that parse
1225                  * flows. */
1226             } else {
1227                 error = xasprintf("unknown keyword %s", name);
1228             }
1229
1230             if (error) {
1231                 return error;
1232             }
1233         }
1234     }
1235     if (!fm->cookie_mask && fm->new_cookie == htonll(UINT64_MAX)
1236         && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
1237         /* On modifies without a mask, we are supposed to add a flow if
1238          * one does not exist.  If a cookie wasn't been specified, use a
1239          * default of zero. */
1240         fm->new_cookie = htonll(0);
1241     }
1242     if (fields & F_ACTIONS) {
1243         struct ofpbuf ofpacts;
1244         char *error;
1245
1246         ofpbuf_init(&ofpacts, 32);
1247         error = str_to_inst_ofpacts(act_str, &ofpacts);
1248         if (!error) {
1249             enum ofperr err;
1250
1251             err = ofpacts_check(ofpacts.data, ofpacts.size, &fm->match.flow,
1252                                 OFPP_MAX, 0);
1253             if (err) {
1254                 error = xasprintf("actions are invalid with specified match "
1255                                   "(%s)", ofperr_to_string(err));
1256             }
1257         }
1258         if (error) {
1259             ofpbuf_uninit(&ofpacts);
1260             return error;
1261         }
1262
1263         fm->ofpacts_len = ofpacts.size;
1264         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
1265     } else {
1266         fm->ofpacts_len = 0;
1267         fm->ofpacts = NULL;
1268     }
1269
1270     return NULL;
1271 }
1272
1273 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1274  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
1275  *
1276  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
1277  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
1278  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'.
1279  *
1280  * Returns NULL if successful, otherwise a malloc()'d string describing the
1281  * error.  The caller is responsible for freeing the returned string. */
1282 char * WARN_UNUSED_RESULT
1283 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_)
1284 {
1285     char *string = xstrdup(str_);
1286     char *error;
1287
1288     error = parse_ofp_str__(fm, command, string);
1289     if (error) {
1290         fm->ofpacts = NULL;
1291         fm->ofpacts_len = 0;
1292     }
1293
1294     free(string);
1295     return error;
1296 }
1297
1298 static char * WARN_UNUSED_RESULT
1299 parse_ofp_meter_mod_str__(struct ofputil_meter_mod *mm, char *string,
1300                           struct ofpbuf *bands, int command)
1301 {
1302     enum {
1303         F_METER = 1 << 0,
1304         F_FLAGS = 1 << 1,
1305         F_BANDS = 1 << 2,
1306     } fields;
1307     char *save_ptr = NULL;
1308     char *band_str = NULL;
1309     char *name;
1310
1311     switch (command) {
1312     case -1:
1313         fields = F_METER;
1314         break;
1315
1316     case OFPMC13_ADD:
1317         fields = F_METER | F_FLAGS | F_BANDS;
1318         break;
1319
1320     case OFPMC13_DELETE:
1321         fields = F_METER;
1322         break;
1323
1324     case OFPMC13_MODIFY:
1325         fields = F_METER | F_FLAGS | F_BANDS;
1326         break;
1327
1328     default:
1329         NOT_REACHED();
1330     }
1331
1332     mm->command = command;
1333     mm->meter.meter_id = 0;
1334     mm->meter.flags = 0;
1335     if (fields & F_BANDS) {
1336         band_str = strstr(string, "band");
1337         if (!band_str) {
1338             return xstrdup("must specify bands");
1339         }
1340         *band_str = '\0';
1341
1342         band_str = strchr(band_str + 1, '=');
1343         if (!band_str) {
1344             return xstrdup("must specify bands");
1345         }
1346
1347         band_str++;
1348     }
1349     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1350          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1351
1352         if (fields & F_FLAGS && !strcmp(name, "kbps")) {
1353             mm->meter.flags |= OFPMF13_KBPS;
1354         } else if (fields & F_FLAGS && !strcmp(name, "pktps")) {
1355             mm->meter.flags |= OFPMF13_PKTPS;
1356         } else if (fields & F_FLAGS && !strcmp(name, "burst")) {
1357             mm->meter.flags |= OFPMF13_BURST;
1358         } else if (fields & F_FLAGS && !strcmp(name, "stats")) {
1359             mm->meter.flags |= OFPMF13_STATS;
1360         } else {
1361             char *value;
1362
1363             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1364             if (!value) {
1365                 return xasprintf("field %s missing value", name);
1366             }
1367
1368             if (!strcmp(name, "meter")) {
1369                 if (!strcmp(value, "all")) {
1370                     mm->meter.meter_id = OFPM13_ALL;
1371                 } else if (!strcmp(value, "controller")) {
1372                     mm->meter.meter_id = OFPM13_CONTROLLER;
1373                 } else if (!strcmp(value, "slowpath")) {
1374                     mm->meter.meter_id = OFPM13_SLOWPATH;
1375                 } else {
1376                     char *error = str_to_u32(value, &mm->meter.meter_id);
1377                     if (error) {
1378                         return error;
1379                     }
1380                     if (mm->meter.meter_id > OFPM13_MAX) {
1381                         return xasprintf("invalid value for %s", name);
1382                     }
1383                 }
1384             } else {
1385                 return xasprintf("unknown keyword %s", name);
1386             }
1387         }
1388     }
1389     if (fields & F_METER && !mm->meter.meter_id) {
1390         return xstrdup("must specify 'meter'");
1391     }
1392     if (fields & F_FLAGS && !mm->meter.flags) {
1393         return xstrdup("meter must specify either 'kbps' or 'pktps'");
1394     }
1395
1396     if (fields & F_BANDS) {
1397         uint16_t n_bands = 0;
1398         struct ofputil_meter_band *band = NULL;
1399         int i;
1400
1401         for (name = strtok_r(band_str, "=, \t\r\n", &save_ptr); name;
1402              name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1403
1404             char *value;
1405
1406             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1407             if (!value) {
1408                 return xasprintf("field %s missing value", name);
1409             }
1410
1411             if (!strcmp(name, "type")) {
1412                 /* Start a new band */
1413                 band = ofpbuf_put_zeros(bands, sizeof *band);
1414                 n_bands++;
1415
1416                 if (!strcmp(value, "drop")) {
1417                     band->type = OFPMBT13_DROP;
1418                 } else if (!strcmp(value, "dscp_remark")) {
1419                     band->type = OFPMBT13_DSCP_REMARK;
1420                 } else {
1421                     return xasprintf("field %s unknown value %s", name, value);
1422                 }
1423             } else if (!band || !band->type) {
1424                 return xstrdup("band must start with the 'type' keyword");
1425             } else if (!strcmp(name, "rate")) {
1426                 char *error = str_to_u32(value, &band->rate);
1427                 if (error) {
1428                     return error;
1429                 }
1430             } else if (!strcmp(name, "burst_size")) {
1431                 char *error = str_to_u32(value, &band->burst_size);
1432                 if (error) {
1433                     return error;
1434                 }
1435             } else if (!strcmp(name, "prec_level")) {
1436                 char *error = str_to_u8(value, name, &band->prec_level);
1437                 if (error) {
1438                     return error;
1439                 }
1440             } else {
1441                 return xasprintf("unknown keyword %s", name);
1442             }
1443         }
1444         /* validate bands */
1445         if (!n_bands) {
1446             return xstrdup("meter must have bands");
1447         }
1448
1449         mm->meter.n_bands = n_bands;
1450         mm->meter.bands = ofpbuf_steal_data(bands);
1451
1452         for (i = 0; i < n_bands; ++i) {
1453             band = &mm->meter.bands[i];
1454
1455             if (!band->type) {
1456                 return xstrdup("band must have 'type'");
1457             }
1458             if (band->type == OFPMBT13_DSCP_REMARK) {
1459                 if (!band->prec_level) {
1460                     return xstrdup("'dscp_remark' band must have"
1461                                    " 'prec_level'");
1462                 }
1463             } else {
1464                 if (band->prec_level) {
1465                     return xstrdup("Only 'dscp_remark' band may have"
1466                                    " 'prec_level'");
1467                 }
1468             }
1469             if (!band->rate) {
1470                 return xstrdup("band must have 'rate'");
1471             }
1472             if (mm->meter.flags & OFPMF13_BURST) {
1473                 if (!band->burst_size) {
1474                     return xstrdup("band must have 'burst_size' "
1475                                    "when 'burst' flag is set");
1476                 }
1477             } else {
1478                 if (band->burst_size) {
1479                     return xstrdup("band may have 'burst_size' only "
1480                                    "when 'burst' flag is set");
1481                 }
1482             }
1483         }
1484     } else {
1485         mm->meter.n_bands = 0;
1486         mm->meter.bands = NULL;
1487     }
1488
1489     return NULL;
1490 }
1491
1492 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
1493  * page) into 'mm' for sending the specified meter_mod 'command' to a switch.
1494  *
1495  * Returns NULL if successful, otherwise a malloc()'d string describing the
1496  * error.  The caller is responsible for freeing the returned string. */
1497 char * WARN_UNUSED_RESULT
1498 parse_ofp_meter_mod_str(struct ofputil_meter_mod *mm, const char *str_,
1499                         int command)
1500 {
1501     struct ofpbuf bands;
1502     char *string;
1503     char *error;
1504
1505     ofpbuf_init(&bands, 64);
1506     string = xstrdup(str_);
1507
1508     error = parse_ofp_meter_mod_str__(mm, string, &bands, command);
1509
1510     free(string);
1511     ofpbuf_uninit(&bands);
1512
1513     return error;
1514 }
1515
1516 static char * WARN_UNUSED_RESULT
1517 parse_flow_monitor_request__(struct ofputil_flow_monitor_request *fmr,
1518                              const char *str_, char *string)
1519 {
1520     static uint32_t id;
1521
1522     char *save_ptr = NULL;
1523     char *name;
1524
1525     fmr->id = id++;
1526     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
1527                   | NXFMF_OWN | NXFMF_ACTIONS);
1528     fmr->out_port = OFPP_NONE;
1529     fmr->table_id = 0xff;
1530     match_init_catchall(&fmr->match);
1531
1532     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
1533          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
1534         const struct protocol *p;
1535
1536         if (!strcmp(name, "!initial")) {
1537             fmr->flags &= ~NXFMF_INITIAL;
1538         } else if (!strcmp(name, "!add")) {
1539             fmr->flags &= ~NXFMF_ADD;
1540         } else if (!strcmp(name, "!delete")) {
1541             fmr->flags &= ~NXFMF_DELETE;
1542         } else if (!strcmp(name, "!modify")) {
1543             fmr->flags &= ~NXFMF_MODIFY;
1544         } else if (!strcmp(name, "!actions")) {
1545             fmr->flags &= ~NXFMF_ACTIONS;
1546         } else if (!strcmp(name, "!own")) {
1547             fmr->flags &= ~NXFMF_OWN;
1548         } else if (parse_protocol(name, &p)) {
1549             match_set_dl_type(&fmr->match, htons(p->dl_type));
1550             if (p->nw_proto) {
1551                 match_set_nw_proto(&fmr->match, p->nw_proto);
1552             }
1553         } else {
1554             char *value;
1555
1556             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1557             if (!value) {
1558                 return xasprintf("%s: field %s missing value", str_, name);
1559             }
1560
1561             if (!strcmp(name, "table")) {
1562                 char *error = str_to_u8(value, "table", &fmr->table_id);
1563                 if (error) {
1564                     return error;
1565                 }
1566             } else if (!strcmp(name, "out_port")) {
1567                 fmr->out_port = u16_to_ofp(atoi(value));
1568             } else if (mf_from_name(name)) {
1569                 char *error;
1570
1571                 error = parse_field(mf_from_name(name), value, &fmr->match);
1572                 if (error) {
1573                     return error;
1574                 }
1575             } else {
1576                 return xasprintf("%s: unknown keyword %s", str_, name);
1577             }
1578         }
1579     }
1580     return NULL;
1581 }
1582
1583 /* Convert 'str_' (as described in the documentation for the "monitor" command
1584  * in the ovs-ofctl man page) into 'fmr'.
1585  *
1586  * Returns NULL if successful, otherwise a malloc()'d string describing the
1587  * error.  The caller is responsible for freeing the returned string. */
1588 char * WARN_UNUSED_RESULT
1589 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
1590                            const char *str_)
1591 {
1592     char *string = xstrdup(str_);
1593     char *error = parse_flow_monitor_request__(fmr, str_, string);
1594     free(string);
1595     return error;
1596 }
1597
1598 /* Parses 's' as a set of OpenFlow actions and appends the actions to
1599  * 'actions'.
1600  *
1601  * Returns NULL if successful, otherwise a malloc()'d string describing the
1602  * error.  The caller is responsible for freeing the returned string. */
1603 char * WARN_UNUSED_RESULT
1604 parse_ofpacts(const char *s_, struct ofpbuf *ofpacts)
1605 {
1606     char *s = xstrdup(s_);
1607     char *error = str_to_ofpacts(s, ofpacts);
1608     free(s);
1609
1610     return error;
1611 }
1612
1613 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1614  * (one of OFPFC_*) into 'fm'.
1615  *
1616  * Returns NULL if successful, otherwise a malloc()'d string describing the
1617  * error.  The caller is responsible for freeing the returned string. */
1618 char * WARN_UNUSED_RESULT
1619 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
1620                        uint16_t command)
1621 {
1622     char *error = parse_ofp_str(fm, command, string);
1623     if (!error) {
1624         /* Normalize a copy of the match.  This ensures that non-normalized
1625          * flows get logged but doesn't affect what gets sent to the switch, so
1626          * that the switch can do whatever it likes with the flow. */
1627         struct match match_copy = fm->match;
1628         ofputil_normalize_match(&match_copy);
1629     }
1630
1631     return error;
1632 }
1633
1634 /* Opens file 'file_name' and reads each line as a flow_mod of the specified
1635  * type (one of OFPFC_*).  Stores each flow_mod in '*fm', an array allocated
1636  * on the caller's behalf, and the number of flow_mods in '*n_fms'.
1637  *
1638  * Returns NULL if successful, otherwise a malloc()'d string describing the
1639  * error.  The caller is responsible for freeing the returned string. */
1640 char * WARN_UNUSED_RESULT
1641 parse_ofp_flow_mod_file(const char *file_name, uint16_t command,
1642                         struct ofputil_flow_mod **fms, size_t *n_fms)
1643 {
1644     size_t allocated_fms;
1645     int line_number;
1646     FILE *stream;
1647     struct ds s;
1648
1649     *fms = NULL;
1650     *n_fms = 0;
1651
1652     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1653     if (stream == NULL) {
1654         return xasprintf("%s: open failed (%s)",
1655                          file_name, ovs_strerror(errno));
1656     }
1657
1658     allocated_fms = *n_fms;
1659     ds_init(&s);
1660     line_number = 0;
1661     while (!ds_get_preprocessed_line(&s, stream, &line_number)) {
1662         char *error;
1663
1664         if (*n_fms >= allocated_fms) {
1665             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1666         }
1667         error = parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command);
1668         if (error) {
1669             size_t i;
1670
1671             for (i = 0; i < *n_fms; i++) {
1672                 free((*fms)[i].ofpacts);
1673             }
1674             free(*fms);
1675             *fms = NULL;
1676             *n_fms = 0;
1677
1678             ds_destroy(&s);
1679             if (stream != stdin) {
1680                 fclose(stream);
1681             }
1682
1683             return xasprintf("%s:%d: %s", file_name, line_number, error);
1684         }
1685         *n_fms += 1;
1686     }
1687
1688     ds_destroy(&s);
1689     if (stream != stdin) {
1690         fclose(stream);
1691     }
1692     return NULL;
1693 }
1694
1695 char * WARN_UNUSED_RESULT
1696 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1697                                  bool aggregate, const char *string)
1698 {
1699     struct ofputil_flow_mod fm;
1700     char *error;
1701
1702     error = parse_ofp_str(&fm, -1, string);
1703     if (error) {
1704         return error;
1705     }
1706
1707     fsr->aggregate = aggregate;
1708     fsr->cookie = fm.cookie;
1709     fsr->cookie_mask = fm.cookie_mask;
1710     fsr->match = fm.match;
1711     fsr->out_port = fm.out_port;
1712     fsr->table_id = fm.table_id;
1713     return NULL;
1714 }
1715
1716 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1717  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1718  * mf_field.  Fields must be specified in a natural order for satisfying
1719  * prerequisites.
1720  *
1721  * Returns NULL on success, otherwise a malloc()'d string that explains the
1722  * problem. */
1723 char *
1724 parse_ofp_exact_flow(struct flow *flow, const char *s)
1725 {
1726     char *pos, *key, *value_s;
1727     char *error = NULL;
1728     char *copy;
1729
1730     memset(flow, 0, sizeof *flow);
1731
1732     pos = copy = xstrdup(s);
1733     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
1734         const struct protocol *p;
1735         if (parse_protocol(key, &p)) {
1736             if (flow->dl_type) {
1737                 error = xasprintf("%s: Ethernet type set multiple times", s);
1738                 goto exit;
1739             }
1740             flow->dl_type = htons(p->dl_type);
1741
1742             if (p->nw_proto) {
1743                 if (flow->nw_proto) {
1744                     error = xasprintf("%s: network protocol set "
1745                                       "multiple times", s);
1746                     goto exit;
1747                 }
1748                 flow->nw_proto = p->nw_proto;
1749             }
1750         } else {
1751             const struct mf_field *mf;
1752             union mf_value value;
1753             char *field_error;
1754
1755             mf = mf_from_name(key);
1756             if (!mf) {
1757                 error = xasprintf("%s: unknown field %s", s, key);
1758                 goto exit;
1759             }
1760
1761             if (!mf_are_prereqs_ok(mf, flow)) {
1762                 error = xasprintf("%s: prerequisites not met for setting %s",
1763                                   s, key);
1764                 goto exit;
1765             }
1766
1767             if (!mf_is_zero(mf, flow)) {
1768                 error = xasprintf("%s: field %s set multiple times", s, key);
1769                 goto exit;
1770             }
1771
1772             field_error = mf_parse_value(mf, value_s, &value);
1773             if (field_error) {
1774                 error = xasprintf("%s: bad value for %s (%s)",
1775                                   s, key, field_error);
1776                 free(field_error);
1777                 goto exit;
1778             }
1779
1780             mf_set_flow_value(mf, &value, flow);
1781         }
1782     }
1783
1784     if (!flow->in_port.ofp_port) {
1785         flow->in_port.ofp_port = OFPP_NONE;
1786     }
1787
1788 exit:
1789     free(copy);
1790
1791     if (error) {
1792         memset(flow, 0, sizeof *flow);
1793     }
1794     return error;
1795 }