ofp-parse: Ignore "idle_age" and "hard_age" when parsing a flow string.
[cascardo/ovs.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     ovs_be32 ip;
388     uint8_t pcp;
389     uint8_t tos;
390
391     switch (code) {
392     case OFPUTIL_ACTION_INVALID:
393         NOT_REACHED();
394
395     case OFPUTIL_OFPAT10_OUTPUT:
396     case OFPUTIL_OFPAT11_OUTPUT:
397         parse_output(arg, ofpacts);
398         break;
399
400     case OFPUTIL_OFPAT10_SET_VLAN_VID:
401     case OFPUTIL_OFPAT11_SET_VLAN_VID:
402         vid = str_to_u32(arg);
403         if (vid & ~VLAN_VID_MASK) {
404             ovs_fatal(0, "%s: not a valid VLAN VID", arg);
405         }
406         ofpact_put_SET_VLAN_VID(ofpacts)->vlan_vid = vid;
407         break;
408
409     case OFPUTIL_OFPAT10_SET_VLAN_PCP:
410     case OFPUTIL_OFPAT11_SET_VLAN_PCP:
411         pcp = str_to_u32(arg);
412         if (pcp & ~7) {
413             ovs_fatal(0, "%s: not a valid VLAN PCP", arg);
414         }
415         ofpact_put_SET_VLAN_PCP(ofpacts)->vlan_pcp = pcp;
416         break;
417
418     case OFPUTIL_OFPAT12_SET_FIELD:
419         set_field_parse(arg, ofpacts);
420         break;
421
422     case OFPUTIL_OFPAT10_STRIP_VLAN:
423     case OFPUTIL_OFPAT11_POP_VLAN:
424         ofpact_put_STRIP_VLAN(ofpacts);
425         break;
426
427     case OFPUTIL_OFPAT10_SET_DL_SRC:
428     case OFPUTIL_OFPAT11_SET_DL_SRC:
429         str_to_mac(arg, ofpact_put_SET_ETH_SRC(ofpacts)->mac);
430         break;
431
432     case OFPUTIL_OFPAT10_SET_DL_DST:
433     case OFPUTIL_OFPAT11_SET_DL_DST:
434         str_to_mac(arg, ofpact_put_SET_ETH_DST(ofpacts)->mac);
435         break;
436
437     case OFPUTIL_OFPAT10_SET_NW_SRC:
438     case OFPUTIL_OFPAT11_SET_NW_SRC:
439         str_to_ip(arg, &ip);
440         ofpact_put_SET_IPV4_SRC(ofpacts)->ipv4 = ip;
441         break;
442
443     case OFPUTIL_OFPAT10_SET_NW_DST:
444     case OFPUTIL_OFPAT11_SET_NW_DST:
445         str_to_ip(arg, &ip);
446         ofpact_put_SET_IPV4_DST(ofpacts)->ipv4 = ip;
447         break;
448
449     case OFPUTIL_OFPAT10_SET_NW_TOS:
450     case OFPUTIL_OFPAT11_SET_NW_TOS:
451         tos = str_to_u32(arg);
452         if (tos & ~IP_DSCP_MASK) {
453             ovs_fatal(0, "%s: not a valid TOS", arg);
454         }
455         ofpact_put_SET_IPV4_DSCP(ofpacts)->dscp = tos;
456         break;
457
458     case OFPUTIL_OFPAT11_DEC_NW_TTL:
459         NOT_REACHED();
460
461     case OFPUTIL_OFPAT10_SET_TP_SRC:
462     case OFPUTIL_OFPAT11_SET_TP_SRC:
463         ofpact_put_SET_L4_SRC_PORT(ofpacts)->port = str_to_u32(arg);
464         break;
465
466     case OFPUTIL_OFPAT10_SET_TP_DST:
467     case OFPUTIL_OFPAT11_SET_TP_DST:
468         ofpact_put_SET_L4_DST_PORT(ofpacts)->port = str_to_u32(arg);
469         break;
470
471     case OFPUTIL_OFPAT10_ENQUEUE:
472         parse_enqueue(arg, ofpacts);
473         break;
474
475     case OFPUTIL_NXAST_RESUBMIT:
476         parse_resubmit(arg, ofpacts);
477         break;
478
479     case OFPUTIL_NXAST_SET_TUNNEL:
480     case OFPUTIL_NXAST_SET_TUNNEL64:
481         tunnel = ofpact_put_SET_TUNNEL(ofpacts);
482         tunnel->ofpact.compat = code;
483         tunnel->tun_id = str_to_u64(arg);
484         break;
485
486     case OFPUTIL_NXAST_WRITE_METADATA:
487         parse_metadata(ofpacts, arg);
488         break;
489
490     case OFPUTIL_NXAST_SET_QUEUE:
491         ofpact_put_SET_QUEUE(ofpacts)->queue_id = str_to_u32(arg);
492         break;
493
494     case OFPUTIL_NXAST_POP_QUEUE:
495         ofpact_put_POP_QUEUE(ofpacts);
496         break;
497
498     case OFPUTIL_NXAST_REG_MOVE:
499         nxm_parse_reg_move(ofpact_put_REG_MOVE(ofpacts), arg);
500         break;
501
502     case OFPUTIL_NXAST_REG_LOAD:
503         nxm_parse_reg_load(ofpact_put_REG_LOAD(ofpacts), arg);
504         break;
505
506     case OFPUTIL_NXAST_NOTE:
507         parse_note(arg, ofpacts);
508         break;
509
510     case OFPUTIL_NXAST_MULTIPATH:
511         multipath_parse(ofpact_put_MULTIPATH(ofpacts), arg);
512         break;
513
514     case OFPUTIL_NXAST_AUTOPATH__DEPRECATED:
515         autopath_parse(ofpact_put_AUTOPATH(ofpacts), arg);
516         break;
517
518     case OFPUTIL_NXAST_BUNDLE:
519         bundle_parse(arg, ofpacts);
520         break;
521
522     case OFPUTIL_NXAST_BUNDLE_LOAD:
523         bundle_parse_load(arg, ofpacts);
524         break;
525
526     case OFPUTIL_NXAST_RESUBMIT_TABLE:
527     case OFPUTIL_NXAST_OUTPUT_REG:
528     case OFPUTIL_NXAST_DEC_TTL_CNT_IDS:
529         NOT_REACHED();
530
531     case OFPUTIL_NXAST_LEARN:
532         learn_parse(arg, flow, ofpacts);
533         break;
534
535     case OFPUTIL_NXAST_EXIT:
536         ofpact_put_EXIT(ofpacts);
537         break;
538
539     case OFPUTIL_NXAST_DEC_TTL:
540         parse_dec_ttl(ofpacts, arg);
541         break;
542
543     case OFPUTIL_NXAST_FIN_TIMEOUT:
544         parse_fin_timeout(ofpacts, arg);
545         break;
546
547     case OFPUTIL_NXAST_CONTROLLER:
548         parse_controller(ofpacts, arg);
549         break;
550     }
551 }
552
553 static bool
554 str_to_ofpact__(const struct flow *flow, char *pos, char *act, char *arg,
555                 struct ofpbuf *ofpacts, int n_actions)
556 {
557     int code = ofputil_action_code_from_name(act);
558     if (code >= 0) {
559         parse_named_action(code, flow, arg, ofpacts);
560     } else if (!strcasecmp(act, "drop")) {
561         if (n_actions) {
562             ovs_fatal(0, "Drop actions must not be preceded by other "
563                       "actions");
564         } else if (ofputil_parse_key_value(&pos, &act, &arg)) {
565             ovs_fatal(0, "Drop actions must not be followed by other "
566                       "actions");
567         }
568         return false;
569     } else {
570         uint16_t port;
571         if (ofputil_port_from_string(act, &port)) {
572             ofpact_put_OUTPUT(ofpacts)->port = port;
573         } else {
574             ovs_fatal(0, "Unknown action: %s", act);
575         }
576     }
577
578     return true;
579 }
580
581 static void
582 str_to_ofpacts(const struct flow *flow, char *str, struct ofpbuf *ofpacts)
583 {
584     char *pos, *act, *arg;
585     enum ofperr error;
586     int n_actions;
587
588     pos = str;
589     n_actions = 0;
590     while (ofputil_parse_key_value(&pos, &act, &arg)) {
591         if (!str_to_ofpact__(flow, pos, act, arg, ofpacts, n_actions)) {
592             break;
593         }
594         n_actions++;
595     }
596
597     error = ofpacts_verify(ofpacts->data, ofpacts->size);
598     if (error) {
599         ovs_fatal(0, "Incorrect action ordering");
600     }
601
602     ofpact_pad(ofpacts);
603 }
604
605 static void
606 parse_named_instruction(enum ovs_instruction_type type,
607                         char *arg, struct ofpbuf *ofpacts)
608 {
609     enum ofperr error;
610
611     switch (type) {
612     case OVSINST_OFPIT11_APPLY_ACTIONS:
613         NOT_REACHED();  /* This case is handled by str_to_inst_ofpacts() */
614         break;
615
616     case OVSINST_OFPIT11_WRITE_ACTIONS:
617         /* TODO:XXX */
618         ovs_fatal(0, "instruction write-actions is not supported yet");
619         break;
620
621     case OVSINST_OFPIT11_CLEAR_ACTIONS:
622         ofpact_put_CLEAR_ACTIONS(ofpacts);
623         break;
624
625     case OVSINST_OFPIT11_WRITE_METADATA:
626         parse_metadata(ofpacts, arg);
627         break;
628
629     case OVSINST_OFPIT11_GOTO_TABLE: {
630         struct ofpact_goto_table *ogt = ofpact_put_GOTO_TABLE(ofpacts);
631         char *table_s = strsep(&arg, ",");
632         if (!table_s || !table_s[0]) {
633             ovs_fatal(0, "instruction goto-table needs table id");
634         }
635         ogt->table_id = str_to_table_id(table_s);
636         break;
637     }
638     }
639
640     /* If write_metadata is specified as an action AND an instruction, ofpacts
641        could be invalid. */
642     error = ofpacts_verify(ofpacts->data, ofpacts->size);
643     if (error) {
644         ovs_fatal(0, "Incorrect instruction ordering");
645     }
646 }
647
648 static void
649 str_to_inst_ofpacts(const struct flow *flow, char *str, struct ofpbuf *ofpacts)
650 {
651     char *pos, *inst, *arg;
652     int type;
653     const char *prev_inst = NULL;
654     int prev_type = -1;
655     int n_actions = 0;
656
657     pos = str;
658     while (ofputil_parse_key_value(&pos, &inst, &arg)) {
659         type = ofpact_instruction_type_from_name(inst);
660         if (type < 0) {
661             if (!str_to_ofpact__(flow, pos, inst, arg, ofpacts, n_actions)) {
662                 break;
663             }
664
665             type = OVSINST_OFPIT11_APPLY_ACTIONS;
666             if (prev_type == type) {
667                 n_actions++;
668                 continue;
669             }
670         } else if (type == OVSINST_OFPIT11_APPLY_ACTIONS) {
671             ovs_fatal(0, "%s isn't supported. Just write actions then "
672                       "it is interpreted as apply_actions", inst);
673         } else {
674             parse_named_instruction(type, arg, ofpacts);
675         }
676
677         if (type == prev_type) {
678             ovs_fatal(0, "instruction can be specified at most once: %s",
679                       inst);
680         }
681         if (type <= prev_type) {
682             ovs_fatal(0, "Instruction %s must be specified before %s",
683                       inst, prev_inst);
684         }
685
686         prev_inst = inst;
687         prev_type = type;
688         n_actions++;
689     }
690     ofpact_pad(ofpacts);
691 }
692
693 struct protocol {
694     const char *name;
695     uint16_t dl_type;
696     uint8_t nw_proto;
697 };
698
699 static bool
700 parse_protocol(const char *name, const struct protocol **p_out)
701 {
702     static const struct protocol protocols[] = {
703         { "ip", ETH_TYPE_IP, 0 },
704         { "arp", ETH_TYPE_ARP, 0 },
705         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
706         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
707         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
708         { "ipv6", ETH_TYPE_IPV6, 0 },
709         { "ip6", ETH_TYPE_IPV6, 0 },
710         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
711         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
712         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
713         { "rarp", ETH_TYPE_RARP, 0},
714 };
715     const struct protocol *p;
716
717     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
718         if (!strcmp(p->name, name)) {
719             *p_out = p;
720             return true;
721         }
722     }
723     *p_out = NULL;
724     return false;
725 }
726
727 static void
728 ofp_fatal(const char *flow, bool verbose, const char *format, ...)
729 {
730     va_list args;
731
732     if (verbose) {
733         fprintf(stderr, "%s:\n", flow);
734     }
735
736     va_start(args, format);
737     ovs_fatal_valist(0, format, args);
738 }
739
740 static void
741 parse_field(const struct mf_field *mf, const char *s, struct match *match)
742 {
743     union mf_value value, mask;
744     char *error;
745
746     error = mf_parse(mf, s, &value, &mask);
747     if (error) {
748         ovs_fatal(0, "%s", error);
749     }
750
751     mf_set(mf, &value, &mask, match);
752 }
753
754 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
755  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
756  * If 'actions' is specified, an action must be in 'string' and may be expanded
757  * or reallocated.
758  *
759  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
760  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
761  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'. */
762 void
763 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
764               bool verbose)
765 {
766     enum {
767         F_OUT_PORT = 1 << 0,
768         F_ACTIONS = 1 << 1,
769         F_TIMEOUT = 1 << 3,
770         F_PRIORITY = 1 << 4,
771         F_FLAGS = 1 << 5,
772     } fields;
773     char *string = xstrdup(str_);
774     char *save_ptr = NULL;
775     char *act_str = NULL;
776     char *name;
777
778     switch (command) {
779     case -1:
780         fields = F_OUT_PORT;
781         break;
782
783     case OFPFC_ADD:
784         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
785         break;
786
787     case OFPFC_DELETE:
788         fields = F_OUT_PORT;
789         break;
790
791     case OFPFC_DELETE_STRICT:
792         fields = F_OUT_PORT | F_PRIORITY;
793         break;
794
795     case OFPFC_MODIFY:
796         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
797         break;
798
799     case OFPFC_MODIFY_STRICT:
800         fields = F_ACTIONS | F_TIMEOUT | F_PRIORITY | F_FLAGS;
801         break;
802
803     default:
804         NOT_REACHED();
805     }
806
807     match_init_catchall(&fm->match);
808     fm->priority = OFP_DEFAULT_PRIORITY;
809     fm->cookie = htonll(0);
810     fm->cookie_mask = htonll(0);
811     if (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT) {
812         /* For modify, by default, don't update the cookie. */
813         fm->new_cookie = htonll(UINT64_MAX);
814     } else{
815         fm->new_cookie = htonll(0);
816     }
817     fm->table_id = 0xff;
818     fm->command = command;
819     fm->idle_timeout = OFP_FLOW_PERMANENT;
820     fm->hard_timeout = OFP_FLOW_PERMANENT;
821     fm->buffer_id = UINT32_MAX;
822     fm->out_port = OFPP_NONE;
823     fm->flags = 0;
824     if (fields & F_ACTIONS) {
825         act_str = strstr(string, "action");
826         if (!act_str) {
827             ofp_fatal(str_, verbose, "must specify an action");
828         }
829         *act_str = '\0';
830
831         act_str = strchr(act_str + 1, '=');
832         if (!act_str) {
833             ofp_fatal(str_, verbose, "must specify an action");
834         }
835
836         act_str++;
837     }
838     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
839          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
840         const struct protocol *p;
841
842         if (parse_protocol(name, &p)) {
843             match_set_dl_type(&fm->match, htons(p->dl_type));
844             if (p->nw_proto) {
845                 match_set_nw_proto(&fm->match, p->nw_proto);
846             }
847         } else if (fields & F_FLAGS && !strcmp(name, "send_flow_rem")) {
848             fm->flags |= OFPFF_SEND_FLOW_REM;
849         } else if (fields & F_FLAGS && !strcmp(name, "check_overlap")) {
850             fm->flags |= OFPFF_CHECK_OVERLAP;
851         } else {
852             char *value;
853
854             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
855             if (!value) {
856                 ofp_fatal(str_, verbose, "field %s missing value", name);
857             }
858
859             if (!strcmp(name, "table")) {
860                 fm->table_id = str_to_table_id(value);
861             } else if (!strcmp(name, "out_port")) {
862                 if (!ofputil_port_from_string(name, &fm->out_port)) {
863                     ofp_fatal(str_, verbose, "%s is not a valid OpenFlow port",
864                               name);
865                 }
866             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
867                 fm->priority = str_to_u16(value, name);
868             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
869                 fm->idle_timeout = str_to_u16(value, name);
870             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
871                 fm->hard_timeout = str_to_u16(value, name);
872             } else if (!strcmp(name, "cookie")) {
873                 char *mask = strchr(value, '/');
874
875                 if (mask) {
876                     /* A mask means we're searching for a cookie. */
877                     if (command == OFPFC_ADD) {
878                         ofp_fatal(str_, verbose, "flow additions cannot use "
879                                   "a cookie mask");
880                     }
881                     *mask = '\0';
882                     fm->cookie = htonll(str_to_u64(value));
883                     fm->cookie_mask = htonll(str_to_u64(mask+1));
884                 } else {
885                     /* No mask means that the cookie is being set. */
886                     if (command != OFPFC_ADD && command != OFPFC_MODIFY
887                             && command != OFPFC_MODIFY_STRICT) {
888                         ofp_fatal(str_, verbose, "cannot set cookie");
889                     }
890                     fm->new_cookie = htonll(str_to_u64(value));
891                 }
892             } else if (mf_from_name(name)) {
893                 parse_field(mf_from_name(name), value, &fm->match);
894             } else if (!strcmp(name, "duration")
895                        || !strcmp(name, "n_packets")
896                        || !strcmp(name, "n_bytes")
897                        || !strcmp(name, "idle_age")
898                        || !strcmp(name, "hard_age")) {
899                 /* Ignore these, so that users can feed the output of
900                  * "ovs-ofctl dump-flows" back into commands that parse
901                  * flows. */
902             } else {
903                 ofp_fatal(str_, verbose, "unknown keyword %s", name);
904             }
905         }
906     }
907     if (!fm->cookie_mask && fm->new_cookie == htonll(UINT64_MAX)
908             && (command == OFPFC_MODIFY || command == OFPFC_MODIFY_STRICT)) {
909         /* On modifies without a mask, we are supposed to add a flow if
910          * one does not exist.  If a cookie wasn't been specified, use a
911          * default of zero. */
912         fm->new_cookie = htonll(0);
913     }
914     if (fields & F_ACTIONS) {
915         struct ofpbuf ofpacts;
916
917         ofpbuf_init(&ofpacts, 32);
918         str_to_inst_ofpacts(&fm->match.flow, act_str, &ofpacts);
919         fm->ofpacts_len = ofpacts.size;
920         fm->ofpacts = ofpbuf_steal_data(&ofpacts);
921     } else {
922         fm->ofpacts_len = 0;
923         fm->ofpacts = NULL;
924     }
925
926     free(string);
927 }
928
929 /* Convert 'str_' (as described in the documentation for the "monitor" command
930  * in the ovs-ofctl man page) into 'fmr'. */
931 void
932 parse_flow_monitor_request(struct ofputil_flow_monitor_request *fmr,
933                            const char *str_)
934 {
935     static uint32_t id;
936
937     char *string = xstrdup(str_);
938     char *save_ptr = NULL;
939     char *name;
940
941     fmr->id = id++;
942     fmr->flags = (NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY
943                   | NXFMF_OWN | NXFMF_ACTIONS);
944     fmr->out_port = OFPP_NONE;
945     fmr->table_id = 0xff;
946     match_init_catchall(&fmr->match);
947
948     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
949          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
950         const struct protocol *p;
951
952         if (!strcmp(name, "!initial")) {
953             fmr->flags &= ~NXFMF_INITIAL;
954         } else if (!strcmp(name, "!add")) {
955             fmr->flags &= ~NXFMF_ADD;
956         } else if (!strcmp(name, "!delete")) {
957             fmr->flags &= ~NXFMF_DELETE;
958         } else if (!strcmp(name, "!modify")) {
959             fmr->flags &= ~NXFMF_MODIFY;
960         } else if (!strcmp(name, "!actions")) {
961             fmr->flags &= ~NXFMF_ACTIONS;
962         } else if (!strcmp(name, "!own")) {
963             fmr->flags &= ~NXFMF_OWN;
964         } else if (parse_protocol(name, &p)) {
965             match_set_dl_type(&fmr->match, htons(p->dl_type));
966             if (p->nw_proto) {
967                 match_set_nw_proto(&fmr->match, p->nw_proto);
968             }
969         } else {
970             char *value;
971
972             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
973             if (!value) {
974                 ovs_fatal(0, "%s: field %s missing value", str_, name);
975             }
976
977             if (!strcmp(name, "table")) {
978                 fmr->table_id = str_to_table_id(value);
979             } else if (!strcmp(name, "out_port")) {
980                 fmr->out_port = atoi(value);
981             } else if (mf_from_name(name)) {
982                 parse_field(mf_from_name(name), value, &fmr->match);
983             } else {
984                 ovs_fatal(0, "%s: unknown keyword %s", str_, name);
985             }
986         }
987     }
988     free(string);
989 }
990
991 /* Parses 's' as a set of OpenFlow actions and appends the actions to
992  * 'actions'.
993  *
994  * Prints an error on stderr and aborts the program if 's' syntax is
995  * invalid. */
996 void
997 parse_ofpacts(const char *s_, struct ofpbuf *ofpacts)
998 {
999     char *s = xstrdup(s_);
1000     str_to_ofpacts(NULL, s, ofpacts);
1001     free(s);
1002 }
1003
1004 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1005  * (one of OFPFC_*) into 'fm'. */
1006 void
1007 parse_ofp_flow_mod_str(struct ofputil_flow_mod *fm, const char *string,
1008                        uint16_t command, bool verbose)
1009 {
1010     struct match match_copy;
1011
1012     parse_ofp_str(fm, command, string, verbose);
1013
1014     /* Normalize a copy of the match.  This ensures that non-normalized flows
1015      * get logged but doesn't affect what gets sent to the switch, so that the
1016      * switch can do whatever it likes with the flow. */
1017     match_copy = fm->match;
1018     ofputil_normalize_match(&match_copy);
1019 }
1020
1021 void
1022 parse_ofp_flow_mod_file(const char *file_name, uint16_t command,
1023                         struct ofputil_flow_mod **fms, size_t *n_fms)
1024 {
1025     size_t allocated_fms;
1026     FILE *stream;
1027     struct ds s;
1028
1029     stream = !strcmp(file_name, "-") ? stdin : fopen(file_name, "r");
1030     if (stream == NULL) {
1031         ovs_fatal(errno, "%s: open", file_name);
1032     }
1033
1034     allocated_fms = *n_fms;
1035     ds_init(&s);
1036     while (!ds_get_preprocessed_line(&s, stream)) {
1037         if (*n_fms >= allocated_fms) {
1038             *fms = x2nrealloc(*fms, &allocated_fms, sizeof **fms);
1039         }
1040         parse_ofp_flow_mod_str(&(*fms)[*n_fms], ds_cstr(&s), command, false);
1041         *n_fms += 1;
1042     }
1043     ds_destroy(&s);
1044
1045     if (stream != stdin) {
1046         fclose(stream);
1047     }
1048 }
1049
1050 void
1051 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1052                                  bool aggregate, const char *string)
1053 {
1054     struct ofputil_flow_mod fm;
1055
1056     parse_ofp_str(&fm, -1, string, false);
1057     fsr->aggregate = aggregate;
1058     fsr->cookie = fm.cookie;
1059     fsr->cookie_mask = fm.cookie_mask;
1060     fsr->match = fm.match;
1061     fsr->out_port = fm.out_port;
1062     fsr->table_id = fm.table_id;
1063 }
1064
1065 /* Parses a specification of a flow from 's' into 'flow'.  's' must take the
1066  * form FIELD=VALUE[,FIELD=VALUE]... where each FIELD is the name of a
1067  * mf_field.  Fields must be specified in a natural order for satisfying
1068  * prerequisites.
1069  *
1070  * Returns NULL on success, otherwise a malloc()'d string that explains the
1071  * problem. */
1072 char *
1073 parse_ofp_exact_flow(struct flow *flow, const char *s)
1074 {
1075     char *pos, *key, *value_s;
1076     char *error = NULL;
1077     char *copy;
1078
1079     memset(flow, 0, sizeof *flow);
1080
1081     pos = copy = xstrdup(s);
1082     while (ofputil_parse_key_value(&pos, &key, &value_s)) {
1083         const struct protocol *p;
1084         if (parse_protocol(key, &p)) {
1085             if (flow->dl_type) {
1086                 error = xasprintf("%s: Ethernet type set multiple times", s);
1087                 goto exit;
1088             }
1089             flow->dl_type = htons(p->dl_type);
1090
1091             if (p->nw_proto) {
1092                 if (flow->nw_proto) {
1093                     error = xasprintf("%s: network protocol set "
1094                                       "multiple times", s);
1095                     goto exit;
1096                 }
1097                 flow->nw_proto = p->nw_proto;
1098             }
1099         } else {
1100             const struct mf_field *mf;
1101             union mf_value value;
1102             char *field_error;
1103
1104             mf = mf_from_name(key);
1105             if (!mf) {
1106                 error = xasprintf("%s: unknown field %s", s, key);
1107                 goto exit;
1108             }
1109
1110             if (!mf_are_prereqs_ok(mf, flow)) {
1111                 error = xasprintf("%s: prerequisites not met for setting %s",
1112                                   s, key);
1113                 goto exit;
1114             }
1115
1116             if (!mf_is_zero(mf, flow)) {
1117                 error = xasprintf("%s: field %s set multiple times", s, key);
1118                 goto exit;
1119             }
1120
1121             field_error = mf_parse_value(mf, value_s, &value);
1122             if (field_error) {
1123                 error = xasprintf("%s: bad value for %s (%s)",
1124                                   s, key, field_error);
1125                 free(field_error);
1126                 goto exit;
1127             }
1128
1129             mf_set_flow_value(mf, &value, flow);
1130         }
1131     }
1132
1133 exit:
1134     free(copy);
1135
1136     if (error) {
1137         memset(flow, 0, sizeof *flow);
1138     }
1139     return error;
1140 }