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