User-Space MPLS actions and matches
[sliver-openvswitch.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010, 2011, 2012 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 "autopath.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "dynamic-string.h"
29 #include "learn.h"
30 #include "meta-flow.h"
31 #include "multipath.h"
32 #include "netdev.h"
33 #include "nx-match.h"
34 #include "ofp-actions.h"
35 #include "ofp-util.h"
36 #include "ofpbuf.h"
37 #include "openflow/openflow.h"
38 #include "packets.h"
39 #include "socket-util.h"
40 #include "vconn.h"
41 #include "vlog.h"
42
43 VLOG_DEFINE_THIS_MODULE(ofp_parse);
44
45 static void ofp_fatal(const char *flow, bool verbose, const char *format, ...)
46     NO_RETURN;
47
48 static uint8_t
49 str_to_table_id(const char *str)
50 {
51     int table_id;
52
53     if (!str_to_int(str, 10, &table_id) || table_id < 0 || table_id > 255) {
54         ovs_fatal(0, "invalid table \"%s\"", str);
55     }
56     return table_id;
57 }
58
59 static uint16_t
60 str_to_u16(const char *str, const char *name)
61 {
62     int value;
63
64     if (!str_to_int(str, 0, &value) || value < 0 || value > 65535) {
65         ovs_fatal(0, "invalid %s \"%s\"", name, str);
66     }
67     return value;
68 }
69
70 static uint32_t
71 str_to_u32(const char *str)
72 {
73     char *tail;
74     uint32_t value;
75
76     if (!str[0]) {
77         ovs_fatal(0, "missing required numeric argument");
78     }
79
80     errno = 0;
81     value = strtoul(str, &tail, 0);
82     if (errno == EINVAL || errno == ERANGE || *tail) {
83         ovs_fatal(0, "invalid numeric format %s", str);
84     }
85     return value;
86 }
87
88 static uint64_t
89 str_to_u64(const char *str)
90 {
91     char *tail;
92     uint64_t value;
93
94     if (!str[0]) {
95         ovs_fatal(0, "missing required numeric argument");
96     }
97
98     errno = 0;
99     value = strtoull(str, &tail, 0);
100     if (errno == EINVAL || errno == ERANGE || *tail) {
101         ovs_fatal(0, "invalid numeric format %s", str);
102     }
103     return value;
104 }
105
106 static void
107 str_to_mac(const char *str, uint8_t mac[6])
108 {
109     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
110         != ETH_ADDR_SCAN_COUNT) {
111         ovs_fatal(0, "invalid mac address %s", str);
112     }
113 }
114
115 static void
116 str_to_ip(const char *str, ovs_be32 *ip)
117 {
118     struct in_addr in_addr;
119
120     if (lookup_ip(str, &in_addr)) {
121         ovs_fatal(0, "%s: could not convert to IP address", str);
122     }
123     *ip = in_addr.s_addr;
124 }
125
126 static void
127 parse_enqueue(char *arg, struct ofpbuf *ofpacts)
128 {
129     char *sp = NULL;
130     char *port = strtok_r(arg, ":q", &sp);
131     char *queue = strtok_r(NULL, "", &sp);
132     struct ofpact_enqueue *enqueue;
133
134     if (port == NULL || queue == NULL) {
135         ovs_fatal(0, "\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
136     }
137
138     enqueue = ofpact_put_ENQUEUE(ofpacts);
139     enqueue->port = str_to_u32(port);
140     enqueue->queue = str_to_u32(queue);
141 }
142
143 static void
144 parse_output(char *arg, struct ofpbuf *ofpacts)
145 {
146     if (strchr(arg, '[')) {
147         struct ofpact_output_reg *output_reg;
148
149         output_reg = ofpact_put_OUTPUT_REG(ofpacts);
150         mf_parse_subfield(&output_reg->src, arg);
151         output_reg->max_len = UINT16_MAX;
152     } else {
153         struct ofpact_output *output;
154
155         output = ofpact_put_OUTPUT(ofpacts);
156         output->port = str_to_u32(arg);
157         output->max_len = output->port == OFPP_CONTROLLER ? UINT16_MAX : 0;
158     }
159 }
160
161 static void
162 parse_resubmit(char *arg, struct ofpbuf *ofpacts)
163 {
164     struct ofpact_resubmit *resubmit;
165     char *in_port_s, *table_s;
166
167     resubmit = ofpact_put_RESUBMIT(ofpacts);
168
169     in_port_s = strsep(&arg, ",");
170     if (in_port_s && in_port_s[0]) {
171         if (!ofputil_port_from_string(in_port_s, &resubmit->in_port)) {
172             ovs_fatal(0, "%s: resubmit to unknown port", in_port_s);
173         }
174     } else {
175         resubmit->in_port = OFPP_IN_PORT;
176     }
177
178     table_s = strsep(&arg, ",");
179     resubmit->table_id = table_s && table_s[0] ? str_to_u32(table_s) : 255;
180
181     if (resubmit->in_port == OFPP_IN_PORT && resubmit->table_id == 255) {
182         ovs_fatal(0, "at least one \"in_port\" or \"table\" must be specified "
183                   " on resubmit");
184     }
185 }
186
187 static void
188 parse_note(const char *arg, struct ofpbuf *ofpacts)
189 {
190     struct ofpact_note *note;
191
192     note = ofpact_put_NOTE(ofpacts);
193     while (*arg != '\0') {
194         uint8_t byte;
195         bool ok;
196
197         if (*arg == '.') {
198             arg++;
199         }
200         if (*arg == '\0') {
201             break;
202         }
203
204         byte = hexits_value(arg, 2, &ok);
205         if (!ok) {
206             ovs_fatal(0, "bad hex digit in `note' argument");
207         }
208         ofpbuf_put(ofpacts, &byte, 1);
209
210         note = ofpacts->l2;
211         note->length++;
212
213         arg += 2;
214     }
215     ofpact_update_len(ofpacts, &note->ofpact);
216 }
217
218 static void
219 parse_fin_timeout(struct ofpbuf *b, char *arg)
220 {
221     struct ofpact_fin_timeout *oft = ofpact_put_FIN_TIMEOUT(b);
222     char *key, *value;
223
224     while (ofputil_parse_key_value(&arg, &key, &value)) {
225         if (!strcmp(key, "idle_timeout")) {
226             oft->fin_idle_timeout = str_to_u16(value, key);
227         } else if (!strcmp(key, "hard_timeout")) {
228             oft->fin_hard_timeout = str_to_u16(value, key);
229         } else {
230             ovs_fatal(0, "invalid key '%s' in 'fin_timeout' argument", key);
231         }
232     }
233 }
234
235 static void
236 parse_controller(struct ofpbuf *b, char *arg)
237 {
238     enum ofp_packet_in_reason reason = OFPR_ACTION;
239     uint16_t controller_id = 0;
240     uint16_t max_len = UINT16_MAX;
241
242     if (!arg[0]) {
243         /* Use defaults. */
244     } else if (strspn(arg, "0123456789") == strlen(arg)) {
245         max_len = str_to_u16(arg, "max_len");
246     } else {
247         char *name, *value;
248
249         while (ofputil_parse_key_value(&arg, &name, &value)) {
250             if (!strcmp(name, "reason")) {
251                 if (!ofputil_packet_in_reason_from_string(value, &reason)) {
252                     ovs_fatal(0, "unknown reason \"%s\"", value);
253                 }
254             } else if (!strcmp(name, "max_len")) {
255                 max_len = str_to_u16(value, "max_len");
256             } else if (!strcmp(name, "id")) {
257                 controller_id = str_to_u16(value, "id");
258             } else {
259                 ovs_fatal(0, "unknown key \"%s\" parsing controller action",
260                           name);
261             }
262         }
263     }
264
265     if (reason == OFPR_ACTION && controller_id == 0) {
266         struct ofpact_output *output;
267
268         output = ofpact_put_OUTPUT(b);
269         output->port = OFPP_CONTROLLER;
270         output->max_len = max_len;
271     } else {
272         struct ofpact_controller *controller;
273
274         controller = ofpact_put_CONTROLLER(b);
275         controller->max_len = max_len;
276         controller->reason = reason;
277         controller->controller_id = controller_id;
278     }
279 }
280
281 static void
282 parse_noargs_dec_ttl(struct ofpbuf *b)
283 {
284     struct ofpact_cnt_ids *ids;
285     uint16_t id = 0;
286
287     ids = ofpact_put_DEC_TTL(b);
288     ofpbuf_put(b, &id, sizeof id);
289     ids = b->l2;
290     ids->n_controllers++;
291     ofpact_update_len(b, &ids->ofpact);
292 }
293
294 static void
295 parse_dec_ttl(struct ofpbuf *b, char *arg)
296 {
297     if (*arg == '\0') {
298         parse_noargs_dec_ttl(b);
299     } else {
300         struct ofpact_cnt_ids *ids;
301         char *cntr;
302
303         ids = ofpact_put_DEC_TTL(b);
304         ids->ofpact.compat = OFPUTIL_NXAST_DEC_TTL_CNT_IDS;
305         for (cntr = strtok_r(arg, ", ", &arg); cntr != NULL;
306              cntr = strtok_r(NULL, ", ", &arg)) {
307             uint16_t id = atoi(cntr);
308
309             ofpbuf_put(b, &id, sizeof id);
310             ids = b->l2;
311             ids->n_controllers++;
312         }
313         if (!ids->n_controllers) {
314             ovs_fatal(0, "dec_ttl_cnt_ids: expected at least one controller "
315                       "id.");
316         }
317         ofpact_update_len(b, &ids->ofpact);
318     }
319 }
320
321 static void
322 set_field_parse(const char *arg, struct ofpbuf *ofpacts)
323 {
324     char *orig = xstrdup(arg);
325     struct ofpact_reg_load *load = ofpact_put_REG_LOAD(ofpacts);
326     char *value;
327     char *delim;
328     char *key;
329     const struct mf_field *mf;
330     const char *error;
331     union mf_value mf_value;
332
333     value = orig;
334     delim = strstr(orig, "->");
335     if (!delim) {
336         ovs_fatal(0, "%s: missing `->'", orig);
337     }
338     if (strlen(delim) <= strlen("->")) {
339         ovs_fatal(0, "%s: missing field name following `->'", orig);
340     }
341
342     key = delim + strlen("->");
343     mf = mf_from_name(key);
344     if (!mf) {
345         ovs_fatal(0, "%s is not valid oxm field name", key);
346     }
347     if (!mf->writable) {
348         ovs_fatal(0, "%s is not allowed to set", key);
349     }
350
351     delim[0] = '\0';
352     error = mf_parse_value(mf, value, &mf_value);
353     if (error) {
354         ovs_fatal(0, "%s", error);
355     }
356     if (!mf_is_value_valid(mf, &mf_value)) {
357         ovs_fatal(0, "%s is not valid valid for field %s", value, key);
358     }
359     ofpact_set_field_init(load, mf, &mf_value);
360     free(orig);
361 }
362
363 static void
364 parse_metadata(struct ofpbuf *b, char *arg)
365 {
366     struct ofpact_metadata *om;
367     char *mask = strchr(arg, '/');
368
369     om = ofpact_put_WRITE_METADATA(b);
370
371     if (mask) {
372         *mask = '\0';
373         om->mask = htonll(str_to_u64(mask + 1));
374     } else {
375         om->mask = htonll(UINT64_MAX);
376     }
377
378     om->metadata = htonll(str_to_u64(arg));
379 }
380
381 static void
382 parse_named_action(enum ofputil_action_code code, const struct flow *flow,
383                    char *arg, struct ofpbuf *ofpacts)
384 {
385     struct ofpact_tunnel *tunnel;
386     uint16_t vid;
387     uint16_t ethertype;
388     ovs_be32 ip;
389     uint8_t pcp;
390     uint8_t tos;
391
392     switch (code) {
393     case OFPUTIL_ACTION_INVALID:
394         NOT_REACHED();
395
396     case OFPUTIL_OFPAT10_OUTPUT:
397     case OFPUTIL_OFPAT11_OUTPUT:
398         parse_output(arg, ofpacts);
399         break;
400
401     case OFPUTIL_OFPAT10_SET_VLAN_VID:
402     case OFPUTIL_OFPAT11_SET_VLAN_VID:
403         vid = str_to_u32(arg);
404         if (vid & ~VLAN_VID_MASK) {
405             ovs_fatal(0, "%s: not a valid VLAN VID", arg);
406         }
407         ofpact_put_SET_VLAN_VID(ofpacts)->vlan_vid = vid;
408         break;
409
410     case OFPUTIL_OFPAT10_SET_VLAN_PCP:
411     case OFPUTIL_OFPAT11_SET_VLAN_PCP:
412         pcp = str_to_u32(arg);
413         if (pcp & ~7) {
414             ovs_fatal(0, "%s: not a valid VLAN PCP", arg);
415         }
416         ofpact_put_SET_VLAN_PCP(ofpacts)->vlan_pcp = pcp;
417         break;
418
419     case OFPUTIL_OFPAT12_SET_FIELD:
420         set_field_parse(arg, ofpacts);
421         break;
422
423     case OFPUTIL_OFPAT10_STRIP_VLAN:
424     case OFPUTIL_OFPAT11_POP_VLAN:
425         ofpact_put_STRIP_VLAN(ofpacts);
426         break;
427
428     case OFPUTIL_OFPAT11_PUSH_VLAN:
429         ethertype = str_to_u16(arg, "ethertype");
430         if (ethertype != ETH_TYPE_VLAN_8021Q) {
431             /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */
432             ovs_fatal(0, "%s: not a valid VLAN ethertype", arg);
433         }
434         ofpact_put_PUSH_VLAN(ofpacts);
435         break;
436
437     case OFPUTIL_OFPAT11_SET_QUEUE:
438         ofpact_put_SET_QUEUE(ofpacts)->queue_id = str_to_u32(arg);
439         break;
440
441
442     case OFPUTIL_OFPAT10_SET_DL_SRC:
443     case OFPUTIL_OFPAT11_SET_DL_SRC:
444         str_to_mac(arg, ofpact_put_SET_ETH_SRC(ofpacts)->mac);
445         break;
446
447     case OFPUTIL_OFPAT10_SET_DL_DST:
448     case OFPUTIL_OFPAT11_SET_DL_DST:
449         str_to_mac(arg, ofpact_put_SET_ETH_DST(ofpacts)->mac);
450         break;
451
452     case OFPUTIL_OFPAT10_SET_NW_SRC:
453     case OFPUTIL_OFPAT11_SET_NW_SRC:
454         str_to_ip(arg, &ip);
455         ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4 = ip;
456         break;
457
458     case OFPUTIL_OFPAT10_SET_NW_DST:
459     case OFPUTIL_OFPAT11_SET_NW_DST:
460         str_to_ip(arg, &ip);
461         ofpact_put_SET_IPV4_DST(ofpacts)->ipv4 = ip;
462         break;
463
464     case OFPUTIL_OFPAT10_SET_NW_TOS:
465     case OFPUTIL_OFPAT11_SET_NW_TOS:
466         tos = str_to_u32(arg);
467         if (tos & ~IP_DSCP_MASK) {
468             ovs_fatal(0, "%s: not a valid TOS", arg);
469         }
470         ofpact_put_SET_IPV4_DSCP(ofpacts)->dscp = tos;
471         break;
472
473     case OFPUTIL_OFPAT11_DEC_NW_TTL:
474         NOT_REACHED();
475
476     case OFPUTIL_OFPAT10_SET_TP_SRC:
477     case OFPUTIL_OFPAT11_SET_TP_SRC:
478         ofpact_put_SET_L4_SRC_PORT(ofpacts)->port = str_to_u32(arg);
479         break;
480
481     case OFPUTIL_OFPAT10_SET_TP_DST:
482     case OFPUTIL_OFPAT11_SET_TP_DST:
483         ofpact_put_SET_L4_DST_PORT(ofpacts)->port = str_to_u32(arg);
484         break;
485
486     case OFPUTIL_OFPAT10_ENQUEUE:
487         parse_enqueue(arg, ofpacts);
488         break;
489
490     case OFPUTIL_NXAST_RESUBMIT:
491         parse_resubmit(arg, ofpacts);
492         break;
493
494     case OFPUTIL_NXAST_SET_TUNNEL:
495     case OFPUTIL_NXAST_SET_TUNNEL64:
496         tunnel = ofpact_put_SET_TUNNEL(ofpacts);
497         tunnel->ofpact.compat = code;
498         tunnel->tun_id = str_to_u64(arg);
499         break;
500
501     case OFPUTIL_NXAST_WRITE_METADATA:
502         parse_metadata(ofpacts, arg);
503         break;
504
505     case OFPUTIL_NXAST_SET_QUEUE:
506         ofpact_put_SET_QUEUE(ofpacts)->queue_id = str_to_u32(arg);
507         break;
508
509     case OFPUTIL_NXAST_POP_QUEUE:
510         ofpact_put_POP_QUEUE(ofpacts);
511         break;
512
513     case OFPUTIL_NXAST_REG_MOVE:
514         nxm_parse_reg_move(ofpact_put_REG_MOVE(ofpacts), arg);
515         break;
516
517     case OFPUTIL_NXAST_REG_LOAD:
518         nxm_parse_reg_load(ofpact_put_REG_LOAD(ofpacts), arg);
519         break;
520
521     case OFPUTIL_NXAST_NOTE:
522         parse_note(arg, ofpacts);
523         break;
524
525     case OFPUTIL_NXAST_MULTIPATH:
526         multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
527         break;
528
529     case OFPUTIL_NXAST_AUTOPATH__DEPRECATED:
530         autopath_parse(ofpact_put_AUTOPATH(ofpacts), arg);
531         break;
532
533     case OFPUTIL_NXAST_BUNDLE:
534         bundle_parse(arg, ofpacts);
535         break;
536
537     case OFPUTIL_NXAST_BUNDLE_LOAD:
538         bundle_parse_load(arg, ofpacts);
539         break;
540
541     case OFPUTIL_NXAST_RESUBMIT_TABLE:
542     case OFPUTIL_NXAST_OUTPUT_REG:
543     case OFPUTIL_NXAST_DEC_TTL_CNT_IDS:
544         NOT_REACHED();
545
546     case OFPUTIL_NXAST_LEARN:
547         learn_parse(arg, flow, ofpacts);
548         break;
549
550     case OFPUTIL_NXAST_EXIT:
551         ofpact_put_EXIT(ofpacts);
552         break;
553
554     case OFPUTIL_NXAST_DEC_TTL:
555         parse_dec_ttl(ofpacts, arg);
556         break;
557
558     case OFPUTIL_NXAST_FIN_TIMEOUT:
559         parse_fin_timeout(ofpacts, arg);
560         break;
561
562     case OFPUTIL_NXAST_CONTROLLER:
563         parse_controller(ofpacts, arg);
564         break;
565
566     case OFPUTIL_OFPAT11_PUSH_MPLS:
567     case OFPUTIL_NXAST_PUSH_MPLS:
568         ofpact_put_PUSH_MPLS(ofpacts)->ethertype =
569             htons(str_to_u16(arg, "push_mpls"));
570         break;
571
572     case OFPUTIL_OFPAT11_POP_MPLS:
573     case OFPUTIL_NXAST_POP_MPLS:
574         ofpact_put_POP_MPLS(ofpacts)->ethertype =
575             htons(str_to_u16(arg, "pop_mpls"));
576         break;
577     }
578 }
579
580 static bool
581 str_to_ofpact__(const struct flow *flow, char *pos, char *act, char *arg,
582                 struct ofpbuf *ofpacts, int n_actions)
583 {
584     int code = ofputil_action_code_from_name(act);
585     if (code >= 0) {
586         parse_named_action(code, flow, arg, ofpacts);
587     } else if (!strcasecmp(act, "drop")) {
588         if (n_actions) {
589             ovs_fatal(0, "Drop actions must not be preceded by other "
590                       "actions");
591         } else if (ofputil_parse_key_value(&pos, &act, &arg)) {
592             ovs_fatal(0, "Drop actions must not be followed by other "
593                       "actions");
594         }
595         return false;
596     } else {
597         uint16_t port;
598         if (ofputil_port_from_string(act, &port)) {
599             ofpact_put_OUTPUT(ofpacts)->port = port;
600         } else {
601             ovs_fatal(0, "Unknown action: %s", act);
602         }
603     }
604
605     return true;
606 }
607
608 static void
609 str_to_ofpacts(const struct flow *flow, char *str, struct ofpbuf *ofpacts)
610 {
611     char *pos, *act, *arg;
612     enum ofperr error;
613     int n_actions;
614
615     pos = str;
616     n_actions = 0;
617     while (ofputil_parse_key_value(&pos, &act, &arg)) {
618         if (!str_to_ofpact__(flow, pos, act, arg, ofpacts, n_actions)) {
619             break;
620         }
621         n_actions++;
622     }
623
624     error = ofpacts_verify(ofpacts->data, ofpacts->size);
625     if (error) {
626         ovs_fatal(0, "Incorrect action ordering");
627     }
628
629     ofpact_pad(ofpacts);
630 }
631
632 static void
633 parse_named_instruction(enum ovs_instruction_type type,
634                         char *arg, struct ofpbuf *ofpacts)
635 {
636     enum ofperr error;
637
638     switch (type) {
639     case OVSINST_OFPIT11_APPLY_ACTIONS:
640         NOT_REACHED();  /* This case is handled by str_to_inst_ofpacts() */
641         break;
642
643     case OVSINST_OFPIT11_WRITE_ACTIONS:
644         /* XXX */
645         ovs_fatal(0, "instruction write-actions is not supported yet");
646         break;
647
648     case OVSINST_OFPIT11_CLEAR_ACTIONS:
649         ofpact_put_CLEAR_ACTIONS(ofpacts);
650         break;
651
652     case OVSINST_OFPIT11_WRITE_METADATA:
653         parse_metadata(ofpacts, arg);
654         break;
655
656     case OVSINST_OFPIT11_GOTO_TABLE: {
657         struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
658         char *table_s = strsep(&arg, ",");
659         if (!table_s || !table_s[0]) {
660             ovs_fatal(0, "instruction goto-table needs table id");
661         }
662         ogt->table_id = str_to_table_id(table_s);
663         break;
664     }
665     }
666
667     /* If write_metadata is specified as an action AND an instruction, ofpacts
668        could be invalid. */
669     error = ofpacts_verify(ofpacts->data, ofpacts->size);
670     if (error) {
671         ovs_fatal(0, "Incorrect instruction ordering");
672     }
673 }
674
675 static void
676 str_to_inst_ofpacts(const struct flow *flow, char *str, struct ofpbuf *ofpacts)
677 {
678     char *pos, *inst, *arg;
679     int type;
680     const char *prev_inst = NULL;
681     int prev_type = -1;
682     int n_actions = 0;
683
684     pos = str;
685     while (ofputil_parse_key_value(&pos, &inst, &arg)) {
686         type = ofpact_instruction_type_from_name(inst);
687         if (type < 0) {
688             if (!str_to_ofpact__(flow, pos, inst, arg, ofpacts, n_actions)) {
689                 break;
690             }
691
692             type = OVSINST_OFPIT11_APPLY_ACTIONS;
693             if (prev_type == type) {
694                 n_actions++;
695                 continue;
696             }
697         } else if (type == OVSINST_OFPIT11_APPLY_ACTIONS) {
698             ovs_fatal(0, "%s isn't supported. Just write actions then "
699                       "it is interpreted as apply_actions", inst);
700         } else {
701             parse_named_instruction(type, arg, ofpacts);
702         }
703
704         if (type == prev_type) {
705             ovs_fatal(0, "instruction can be specified at most once: %s",
706                       inst);
707         }
708         if (type <= prev_type) {
709             ovs_fatal(0, "Instruction %s must be specified before %s",
710                       inst, prev_inst);
711         }
712
713         prev_inst = inst;
714         prev_type = type;
715         n_actions++;
716     }
717     ofpact_pad(ofpacts);
718 }
719
720 struct protocol {
721     const char *name;
722     uint16_t dl_type;
723     uint8_t nw_proto;
724 };
725
726 static bool
727 parse_protocol(const char *name, const struct protocol **p_out)
728 {
729     static const struct protocol protocols[] = {
730         { "ip", ETH_TYPE_IP, 0 },
731         { "arp", ETH_TYPE_ARP, 0 },
732         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
733         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
734         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
735         { "ipv6", ETH_TYPE_IPV6, 0 },
736         { "ip6", ETH_TYPE_IPV6, 0 },
737         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
738         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
739         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
740         { "rarp", ETH_TYPE_RARP, 0},
741         { "mpls", ETH_TYPE_MPLS, 0 },
742         { "mplsm", ETH_TYPE_MPLS_MCAST, 0 },
743     };
744     const struct protocol *p;
745
746     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
747         if (!strcmp(p->name, name)) {
748             *p_out = p;
749             return true;
750         }
751     }
752     *p_out = NULL;
753     return false;
754 }
755
756 static void
757 ofp_fatal(const char *flow, bool verbose, const char *format, ...)
758 {
759     va_list args;
760
761     if (verbose) {
762         fprintf(stderr, "%s:\n", flow);
763     }
764
765     va_start(args, format);
766     ovs_fatal_valist(0, format, args);
767 }
768
769 static void
770 parse_field(const struct mf_field *mf, const char *s, struct match *match)
771 {
772     union mf_value value, mask;
773     char *error;
774
775     error = mf_parse(mf, s, &value, &mask);
776     if (error) {
777         ovs_fatal(0, "%s", error);
778     }
779
780     mf_set(mf, &value, &mask, match);
781 }
782
783 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
784  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
785  * If 'actions' is specified, an action must be in 'string' and may be expanded
786  * or reallocated.
787  *
788  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
789  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
790  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'. */
791 void
792 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
793               bool verbose)
794 {
795     enum {
796         F_OUT_PORT = 1 << 0,
797         F_ACTIONS = 1 << 1,
798         F_TIMEOUT = 1 << 3,
799         F_PRIORITY = 1 << 4,
800         F_FLAGS = 1 << 5,
801     } fields;
802     char *string = xstrdup(str_);
803     char *save_ptr = NULL;
804     char *act_str = NULL;
805     char *name;
806
807     switch (command) {
808     case -1:
809         fields = F_OUT_PORT;
810         break;
811
812     case OFPFC_ADD:
813         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
814         break;
815
816     case OFPFC_DELETE:
817         fields = F_OUT_PORT;
818         break;
819
820     case OFPFC_DELETE_STRICT:
821         fields = F_OUT_PORT | F_PRIORITY;
822         break;
823
824     case OFPFC_MODIFY:
825         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
826         break;
827
828     case OFPFC_MODIFY_STRICT:
829         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
830         break;
831
832     default:
833         NOT_REACHED();
834     }
835
836     match_init_catchall(&fm->match);
837     fm->priority = OFP_DEFAULT_PRIORITY;
838     fm->cookie = htonll(0);
839     fm->cookie_mask = htonll(0);
840     if (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT) {
841         /* For modify, by default, don't update the cookie. */
842         fm->new_cookie = htonll(UINT64_MAX);
843     } else{
844         fm->new_cookie = htonll(0);
845     }
846     fm->table_id = 0xff;
847     fm->command = command;
848     fm->idle_timeout = OFP_FLOW_PERMANENT;
849     fm->hard_timeout = OFP_FLOW_PERMANENT;
850     fm->buffer_id = UINT32_MAX;
851     fm->out_port = OFPP_ANY;
852     fm->flags = 0;
853     if (fields & F_ACTIONS) {
854         act_str = strstr(string, "action");
855         if (!act_str) {
856             ofp_fatal(str_, verbose, "must specify an action");
857         }
858         *act_str = '\0';
859
860         act_str = strchr(act_str + 1, '=');
861         if (!act_str) {
862             ofp_fatal(str_, verbose, "must specify an action");
863         }
864
865         act_str++;
866     }
867     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
868          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
869         const struct protocol *p;
870
871         if (parse_protocol(name, &p)) {
872             match_set_dl_type(&fm->match, htons(p->dl_type));
873             if (p->nw_proto) {
874                 match_set_nw_proto(&fm->match, p->nw_proto);
875             }
876         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
877             fm->flags |= OFPFF_SEND_FLOW_REM;
878         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
879             fm->flags |= OFPFF_CHECK_OVERLAP;
880         } else if (fields & F_FLAGS && !strcmp(name, "reset_counts")) {
881             fm->flags |= OFPFF12_RESET_COUNTS;
882         } else if (fields & F_FLAGS && !strcmp(name, "no_packet_counts")) {
883             fm->flags |= OFPFF13_NO_PKT_COUNTS;
884         } else if (fields & F_FLAGS && !strcmp(name, "no_byte_counts")) {
885             fm->flags |= OFPFF13_NO_BYT_COUNTS;
886         } else {
887             char *value;
888
889             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
890             if (!value) {
891                 ofp_fatal(str_, verbose, "field %s missing value", name);
892             }
893
894             if (!strcmp(name, "table")) {
895                 fm->table_id = str_to_table_id(value);
896             } else if (!strcmp(name, "out_port")) {
897                 if (!ofputil_port_from_string(name, &fm->out_port)) {
898                     ofp_fatal(str_, verbose, "%s is not a valid OpenFlow port",
899                               name);
900                 }
901             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
902                 fm->priority = str_to_u16(value, name);
903             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
904                 fm->idle_timeout = str_to_u16(value, name);
905             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
906                 fm->hard_timeout = str_to_u16(value, name);
907             } else if (!strcmp(name, "cookie")) {
908                 char *mask = strchr(value, '/');
909
910                 if (mask) {
911                     /* A mask means we're searching for a cookie. */
912                     if (command == OFPFC_ADD) {
913                         ofp_fatal(str_, verbose, "flow additions cannot use "
914                                   "a cookie mask");
915                     }
916                     *mask = '\0';
917                     fm->cookie = htonll(str_to_u64(value));
918                     fm->cookie_mask = htonll(str_to_u64(mask+1));
919                 } else {
920                     /* No mask means that the cookie is being set. */
921                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
922                             && command != OFPFC_MODIFY_STRICT) {
923                         ofp_fatal(str_, verbose, "cannot set cookie");
924                     }
925                     fm->new_cookie = htonll(str_to_u64(value));
926                 }
927             } else if (mf_from_name(name)) {
928                 parse_field(mf_from_name(name), value, &fm->match);
929             } else if (!strcmp(name, "duration")
930                        || !strcmp(name, "n_packets")
931                        || !strcmp(name, "n_bytes")
932                        || !strcmp(name, "idle_age")
933                        || !strcmp(name, "hard_age")) {
934                 /* Ignore these, so that users can feed the output of
935                  * "ovs-ofctl dump-flows" back into commands that parse
936                  * flows. */
937             } else {
938                 ofp_fatal(str_, verbose, "unknown keyword %s", name);
939             }
940         }
941     }
942     if (!fm->cookie_mask && fm->new_cookie == htonll(UINT64_MAX)
943             && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
944         /* On modifies without a mask, we are supposed to add a flow if
945          * one does not exist.  If a cookie wasn't been specified, use a
946          * default of zero. */
947         fm->new_cookie = htonll(0);
948     }
949     if (fields & F_ACTIONS) {
950         struct ofpbuf ofpacts;
951
952         ofpbuf_init(&ofpacts, 32);
953         str_to_inst_ofpacts(&fm->match.flow, act_str, &ofpacts);
954         fm->ofpacts_len = ofpacts.size;
955         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
956     } else {
957         fm->ofpacts_len = 0;
958         fm->ofpacts = NULL;
959     }
960
961     free(string);
962 }
963
964 /* Convert 'str_' (as described in the documentation for the "monitor" command
965  * in the ovs-ofctl man page) into 'fmr'. */
966 void
967 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
968                            const char *str_)
969 {
970     static uint32_t id;
971
972     char *string = xstrdup(str_);
973     char *save_ptr = NULL;
974     char *name;
975
976     fmr->id = id++;
977     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
978                   | NXFMF_OWN | NXFMF_ACTIONS);
979     fmr->out_port = OFPP_NONE;
980     fmr->table_id = 0xff;
981     match_init_catchall(&fmr->match);
982
983     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
984          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
985         const struct protocol *p;
986
987         if (!strcmp(name, "!initial")) {
988             fmr->flags &= ~NXFMF_INITIAL;
989         } else if (!strcmp(name, "!add")) {
990             fmr->flags &= ~NXFMF_ADD;
991         } else if (!strcmp(name, "!delete")) {
992             fmr->flags &= ~NXFMF_DELETE;
993         } else if (!strcmp(name, "!modify")) {
994             fmr->flags &= ~NXFMF_MODIFY;
995         } else if (!strcmp(name, "!actions")) {
996             fmr->flags &= ~NXFMF_ACTIONS;
997         } else if (!strcmp(name, "!own")) {
998             fmr->flags &= ~NXFMF_OWN;
999         } else if (parse_protocol(name, &p)) {
1000             match_set_dl_type(&fmr->match, htons(p->dl_type));
1001             if (p->nw_proto) {
1002                 match_set_nw_proto(&fmr->match, p->nw_proto);
1003             }
1004         } else {
1005             char *value;
1006
1007             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
1008             if (!value) {
1009                 ovs_fatal(0, "%s: field %s missing value", str_, name);
1010             }
1011
1012             if (!strcmp(name, "table")) {
1013                 fmr->table_id = str_to_table_id(value);
1014             } else if (!strcmp(name, "out_port")) {
1015                 fmr->out_port = atoi(value);
1016             } else if (mf_from_name(name)) {
1017                 parse_field(mf_from_name(name), value, &fmr->match);
1018             } else {
1019                 ovs_fatal(0, "%s: unknown keyword %s", str_, name);
1020             }
1021         }
1022     }
1023     free(string);
1024 }
1025
1026 /* Parses 's' as a set of OpenFlow actions and appends the actions to
1027  * 'actions'.
1028  *
1029  * Prints an error on stderr and aborts the program if 's' syntax is
1030  * invalid. */
1031 void
1032 parse_ofpacts(const char *s_, struct ofpbuf *ofpacts)
1033 {
1034     char *s = xstrdup(s_);
1035     str_to_ofpacts(NULL, s, ofpacts);
1036     free(s);
1037 }
1038
1039 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1040  * (one of OFPFC_*) into 'fm'. */
1041 void
1042 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
1043                        uint16_t command, bool verbose)
1044 {
1045     struct match match_copy;
1046
1047     parse_ofp_str(fm, command, string, verbose);
1048
1049     /* Normalize a copy of the match.  This ensures that non-normalized flows
1050      * get logged but doesn't affect what gets sent to the switch, so that the
1051      * switch can do whatever it likes with the flow. */
1052     match_copy = fm->match;
1053     ofputil_normalize_match(&match_copy);
1054 }
1055
1056 void
1057 parse_ofp_flow_mod_file(const char *file_name, uint16_t command,
1058                         struct ofputil_flow_mod **fms, size_t *n_fms)
1059 {
1060     size_t allocated_fms;
1061     FILE *stream;
1062     struct ds s;
1063
1064     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1065     if (stream == NULL) {
1066         ovs_fatal(errno, "%s: open", file_name);
1067     }
1068
1069     allocated_fms = *n_fms;
1070     ds_init(&s);
1071     while (!ds_get_preprocessed_line(&s, stream)) {
1072         if (*n_fms >= allocated_fms) {
1073             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1074         }
1075         parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command, false);
1076         *n_fms += 1;
1077     }
1078     ds_destroy(&s);
1079
1080     if (stream != stdin) {
1081         fclose(stream);
1082     }
1083 }
1084
1085 void
1086 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1087                                  bool aggregate, const char *string)
1088 {
1089     struct ofputil_flow_mod fm;
1090
1091     parse_ofp_str(&fm, -1, string, false);
1092     fsr->aggregate = aggregate;
1093     fsr->cookie = fm.cookie;
1094     fsr->cookie_mask = fm.cookie_mask;
1095     fsr->match = fm.match;
1096     fsr->out_port = fm.out_port;
1097     fsr->table_id = fm.table_id;
1098 }
1099
1100 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1101  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1102  * mf_field.  Fields must be specified in a natural order for satisfying
1103  * prerequisites.
1104  *
1105  * Returns NULL on success, otherwise a malloc()'d string that explains the
1106  * problem. */
1107 char *
1108 parse_ofp_exact_flow(struct flow *flow, const char *s)
1109 {
1110     char *pos, *key, *value_s;
1111     char *error = NULL;
1112     char *copy;
1113
1114     memset(flow, 0, sizeof *flow);
1115
1116     pos = copy = xstrdup(s);
1117     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
1118         const struct protocol *p;
1119         if (parse_protocol(key, &p)) {
1120             if (flow->dl_type) {
1121                 error = xasprintf("%s: Ethernet type set multiple times", s);
1122                 goto exit;
1123             }
1124             flow->dl_type = htons(p->dl_type);
1125
1126             if (p->nw_proto) {
1127                 if (flow->nw_proto) {
1128                     error = xasprintf("%s: network protocol set "
1129                                       "multiple times", s);
1130                     goto exit;
1131                 }
1132                 flow->nw_proto = p->nw_proto;
1133             }
1134         } else {
1135             const struct mf_field *mf;
1136             union mf_value value;
1137             char *field_error;
1138
1139             mf = mf_from_name(key);
1140             if (!mf) {
1141                 error = xasprintf("%s: unknown field %s", s, key);
1142                 goto exit;
1143             }
1144
1145             if (!mf_are_prereqs_ok(mf, flow)) {
1146                 error = xasprintf("%s: prerequisites not met for setting %s",
1147                                   s, key);
1148                 goto exit;
1149             }
1150
1151             if (!mf_is_zero(mf, flow)) {
1152                 error = xasprintf("%s: field %s set multiple times", s, key);
1153                 goto exit;
1154             }
1155
1156             field_error = mf_parse_value(mf, value_s, &value);
1157             if (field_error) {
1158                 error = xasprintf("%s: bad value for %s (%s)",
1159                                   s, key, field_error);
1160                 free(field_error);
1161                 goto exit;
1162             }
1163
1164             mf_set_flow_value(mf, &value, flow);
1165         }
1166     }
1167
1168     if (!flow->in_port) {
1169         flow->in_port = OFPP_NONE;
1170     }
1171
1172 exit:
1173     free(copy);
1174
1175     if (error) {
1176         memset(flow, 0, sizeof *flow);
1177     }
1178     return error;
1179 }