Implement new "learn" action.
[sliver-openvswitch.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010, 2011 Nicira Networks.
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 "netdev.h"
32 #include "multipath.h"
33 #include "nx-match.h"
34 #include "ofp-util.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "packets.h"
38 #include "socket-util.h"
39 #include "vconn.h"
40 #include "vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(ofp_parse);
43
44 static uint32_t
45 str_to_u32(const char *str)
46 {
47     char *tail;
48     uint32_t value;
49
50     if (!str[0]) {
51         ovs_fatal(0, "missing required numeric argument");
52     }
53
54     errno = 0;
55     value = strtoul(str, &tail, 0);
56     if (errno == EINVAL || errno == ERANGE || *tail) {
57         ovs_fatal(0, "invalid numeric format %s", str);
58     }
59     return value;
60 }
61
62 static uint64_t
63 str_to_u64(const char *str)
64 {
65     char *tail;
66     uint64_t value;
67
68     if (!str[0]) {
69         ovs_fatal(0, "missing required numeric argument");
70     }
71
72     errno = 0;
73     value = strtoull(str, &tail, 0);
74     if (errno == EINVAL || errno == ERANGE || *tail) {
75         ovs_fatal(0, "invalid numeric format %s", str);
76     }
77     return value;
78 }
79
80 static void
81 str_to_mac(const char *str, uint8_t mac[6])
82 {
83     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
84         != ETH_ADDR_SCAN_COUNT) {
85         ovs_fatal(0, "invalid mac address %s", str);
86     }
87 }
88
89 static void
90 str_to_ip(const char *str, ovs_be32 *ip)
91 {
92     struct in_addr in_addr;
93
94     if (lookup_ip(str, &in_addr)) {
95         ovs_fatal(0, "%s: could not convert to IP address", str);
96     }
97     *ip = in_addr.s_addr;
98 }
99
100 static struct ofp_action_output *
101 put_output_action(struct ofpbuf *b, uint16_t port)
102 {
103     struct ofp_action_output *oao;
104
105     oao = ofputil_put_OFPAT_OUTPUT(b);
106     oao->port = htons(port);
107     return oao;
108 }
109
110 static void
111 parse_enqueue(struct ofpbuf *b, char *arg)
112 {
113     char *sp = NULL;
114     char *port = strtok_r(arg, ":q", &sp);
115     char *queue = strtok_r(NULL, "", &sp);
116     struct ofp_action_enqueue *oae;
117
118     if (port == NULL || queue == NULL) {
119         ovs_fatal(0, "\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
120     }
121
122     oae = ofputil_put_OFPAT_ENQUEUE(b);
123     oae->port = htons(str_to_u32(port));
124     oae->queue_id = htonl(str_to_u32(queue));
125 }
126
127 static void
128 parse_output(struct ofpbuf *b, char *arg)
129 {
130     if (strchr(arg, '[')) {
131         struct nx_action_output_reg *naor;
132         int ofs, n_bits;
133         uint32_t src;
134
135         nxm_parse_field_bits(arg, &src, &ofs, &n_bits);
136
137         naor = ofputil_put_NXAST_OUTPUT_REG(b);
138         naor->ofs_nbits = nxm_encode_ofs_nbits(ofs, n_bits);
139         naor->src = htonl(src);
140         naor->max_len = htons(UINT16_MAX);
141     } else {
142         put_output_action(b, str_to_u32(arg));
143     }
144 }
145
146 static void
147 parse_resubmit(struct ofpbuf *b, char *arg)
148 {
149     struct nx_action_resubmit *nar;
150     char *in_port_s, *table_s;
151     uint16_t in_port;
152     uint8_t table;
153
154     in_port_s = strsep(&arg, ",");
155     if (in_port_s && in_port_s[0]) {
156         if (!ofputil_port_from_string(in_port_s, &in_port)) {
157             in_port = str_to_u32(in_port_s);
158         }
159     } else {
160         in_port = OFPP_IN_PORT;
161     }
162
163     table_s = strsep(&arg, ",");
164     table = table_s && table_s[0] ? str_to_u32(table_s) : 255;
165
166     if (in_port == OFPP_IN_PORT && table == 255) {
167         ovs_fatal(0, "at least one \"in_port\" or \"table\" must be specified "
168                   " on resubmit");
169     }
170
171     if (in_port != OFPP_IN_PORT && table == 255) {
172         nar = ofputil_put_NXAST_RESUBMIT(b);
173     } else {
174         nar = ofputil_put_NXAST_RESUBMIT_TABLE(b);
175         nar->table = table;
176     }
177     nar->in_port = htons(in_port);
178 }
179
180 static void
181 parse_set_tunnel(struct ofpbuf *b, const char *arg)
182 {
183     uint64_t tun_id = str_to_u64(arg);
184     if (tun_id > UINT32_MAX) {
185         ofputil_put_NXAST_SET_TUNNEL64(b)->tun_id = htonll(tun_id);
186     } else {
187         ofputil_put_NXAST_SET_TUNNEL(b)->tun_id = htonl(tun_id);
188     }
189 }
190
191 static void
192 parse_note(struct ofpbuf *b, const char *arg)
193 {
194     size_t start_ofs = b->size;
195     struct nx_action_note *nan;
196     int remainder;
197     size_t len;
198
199     nan = ofputil_put_NXAST_NOTE(b);
200
201     b->size -= sizeof nan->note;
202     while (*arg != '\0') {
203         uint8_t byte;
204         bool ok;
205
206         if (*arg == '.') {
207             arg++;
208         }
209         if (*arg == '\0') {
210             break;
211         }
212
213         byte = hexits_value(arg, 2, &ok);
214         if (!ok) {
215             ovs_fatal(0, "bad hex digit in `note' argument");
216         }
217         ofpbuf_put(b, &byte, 1);
218
219         arg += 2;
220     }
221
222     len = b->size - start_ofs;
223     remainder = len % OFP_ACTION_ALIGN;
224     if (remainder) {
225         ofpbuf_put_zeros(b, OFP_ACTION_ALIGN - remainder);
226     }
227     nan = (struct nx_action_note *)((char *)b->data + start_ofs);
228     nan->len = htons(b->size - start_ofs);
229 }
230
231 static void
232 parse_named_action(enum ofputil_action_code code, const struct flow *flow,
233                    struct ofpbuf *b, char *arg)
234 {
235     struct ofp_action_dl_addr *oada;
236     struct ofp_action_vlan_pcp *oavp;
237     struct ofp_action_vlan_vid *oavv;
238     struct ofp_action_nw_addr *oana;
239     struct ofp_action_tp_port *oata;
240
241     switch (code) {
242     case OFPUTIL_OFPAT_OUTPUT:
243         parse_output(b, arg);
244         break;
245
246     case OFPUTIL_OFPAT_SET_VLAN_VID:
247         oavv = ofputil_put_OFPAT_SET_VLAN_VID(b);
248         oavv->vlan_vid = htons(str_to_u32(arg));
249         break;
250
251     case OFPUTIL_OFPAT_SET_VLAN_PCP:
252         oavp = ofputil_put_OFPAT_SET_VLAN_PCP(b);
253         oavp->vlan_pcp = str_to_u32(arg);
254         break;
255
256     case OFPUTIL_OFPAT_STRIP_VLAN:
257         ofputil_put_OFPAT_STRIP_VLAN(b);
258         break;
259
260     case OFPUTIL_OFPAT_SET_DL_SRC:
261     case OFPUTIL_OFPAT_SET_DL_DST:
262         oada = ofputil_put_action(code, b);
263         str_to_mac(arg, oada->dl_addr);
264         break;
265
266     case OFPUTIL_OFPAT_SET_NW_SRC:
267     case OFPUTIL_OFPAT_SET_NW_DST:
268         oana = ofputil_put_action(code, b);
269         str_to_ip(arg, &oana->nw_addr);
270         break;
271
272     case OFPUTIL_OFPAT_SET_NW_TOS:
273         ofputil_put_OFPAT_SET_NW_TOS(b)->nw_tos = str_to_u32(arg);
274         break;
275
276     case OFPUTIL_OFPAT_SET_TP_SRC:
277     case OFPUTIL_OFPAT_SET_TP_DST:
278         oata = ofputil_put_action(code, b);
279         oata->tp_port = htons(str_to_u32(arg));
280         break;
281
282     case OFPUTIL_OFPAT_ENQUEUE:
283         parse_enqueue(b, arg);
284         break;
285
286     case OFPUTIL_NXAST_RESUBMIT:
287         parse_resubmit(b, arg);
288         break;
289
290     case OFPUTIL_NXAST_SET_TUNNEL:
291         parse_set_tunnel(b, arg);
292         break;
293
294     case OFPUTIL_NXAST_SET_QUEUE:
295         ofputil_put_NXAST_SET_QUEUE(b)->queue_id = htonl(str_to_u32(arg));
296         break;
297
298     case OFPUTIL_NXAST_POP_QUEUE:
299         ofputil_put_NXAST_POP_QUEUE(b);
300         break;
301
302     case OFPUTIL_NXAST_REG_MOVE:
303         nxm_parse_reg_move(ofputil_put_NXAST_REG_MOVE(b), arg);
304         break;
305
306     case OFPUTIL_NXAST_REG_LOAD:
307         nxm_parse_reg_load(ofputil_put_NXAST_REG_LOAD(b), arg);
308         break;
309
310     case OFPUTIL_NXAST_NOTE:
311         parse_note(b, arg);
312         break;
313
314     case OFPUTIL_NXAST_SET_TUNNEL64:
315         ofputil_put_NXAST_SET_TUNNEL64(b)->tun_id = htonll(str_to_u64(arg));
316         break;
317
318     case OFPUTIL_NXAST_MULTIPATH:
319         multipath_parse(ofputil_put_NXAST_MULTIPATH(b), arg);
320         break;
321
322     case OFPUTIL_NXAST_AUTOPATH:
323         autopath_parse(ofputil_put_NXAST_AUTOPATH(b), arg);
324         break;
325
326     case OFPUTIL_NXAST_BUNDLE:
327         bundle_parse(b, arg);
328         break;
329
330     case OFPUTIL_NXAST_BUNDLE_LOAD:
331         bundle_parse_load(b, arg);
332         break;
333
334     case OFPUTIL_NXAST_RESUBMIT_TABLE:
335     case OFPUTIL_NXAST_OUTPUT_REG:
336         NOT_REACHED();
337
338     case OFPUTIL_NXAST_LEARN:
339         learn_parse(b, arg, flow);
340         break;
341     }
342 }
343
344 static void
345 str_to_action(const struct flow *flow, char *str, struct ofpbuf *b)
346 {
347     char *pos, *act, *arg;
348     int n_actions;
349
350     pos = str;
351     n_actions = 0;
352     while (ofputil_parse_key_value(&pos, &act, &arg)) {
353         uint16_t port;
354         int code;
355
356         code = ofputil_action_code_from_name(act);
357         if (code >= 0) {
358             parse_named_action(code, flow, b, arg);
359         } else if (!strcasecmp(act, "drop")) {
360             /* A drop action in OpenFlow occurs by just not setting
361              * an action. */
362             if (n_actions) {
363                 ovs_fatal(0, "Drop actions must not be preceded by other "
364                           "actions");
365             } else if (ofputil_parse_key_value(&pos, &act, &arg)) {
366                 ovs_fatal(0, "Drop actions must not be followed by other "
367                           "actions");
368             }
369             break;
370         } else if (!strcasecmp(act, "CONTROLLER")) {
371             struct ofp_action_output *oao;
372             oao = put_output_action(b, OFPP_CONTROLLER);
373
374             /* Unless a numeric argument is specified, we send the whole
375              * packet to the controller. */
376             if (arg[0] && (strspn(arg, "0123456789") == strlen(arg))) {
377                oao->max_len = htons(str_to_u32(arg));
378             } else {
379                 oao->max_len = htons(UINT16_MAX);
380             }
381         } else if (ofputil_port_from_string(act, &port)) {
382             put_output_action(b, port);
383         } else {
384             ovs_fatal(0, "Unknown action: %s", act);
385         }
386         n_actions++;
387     }
388 }
389
390 struct protocol {
391     const char *name;
392     uint16_t dl_type;
393     uint8_t nw_proto;
394 };
395
396 static bool
397 parse_protocol(const char *name, const struct protocol **p_out)
398 {
399     static const struct protocol protocols[] = {
400         { "ip", ETH_TYPE_IP, 0 },
401         { "arp", ETH_TYPE_ARP, 0 },
402         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
403         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
404         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
405         { "ipv6", ETH_TYPE_IPV6, 0 },
406         { "ip6", ETH_TYPE_IPV6, 0 },
407         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
408         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
409         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
410     };
411     const struct protocol *p;
412
413     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
414         if (!strcmp(p->name, name)) {
415             *p_out = p;
416             return true;
417         }
418     }
419     *p_out = NULL;
420     return false;
421 }
422
423 static void
424 ofp_fatal(const char *flow, bool verbose, const char *format, ...)
425 {
426     va_list args;
427
428     if (verbose) {
429         fprintf(stderr, "%s:\n", flow);
430     }
431
432     va_start(args, format);
433     ovs_fatal_valist(0, format, args);
434 }
435
436 static void
437 parse_field(const struct mf_field *mf, const char *s, struct cls_rule *rule)
438 {
439     union mf_value value, mask;
440     char *error;
441
442     error = mf_parse(mf, s, &value, &mask);
443     if (error) {
444         ovs_fatal(0, "%s", error);
445     }
446
447     mf_set(mf, &value, &mask, rule);
448 }
449
450 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
451  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
452  * If 'actions' is specified, an action must be in 'string' and may be expanded
453  * or reallocated.
454  *
455  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
456  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
457  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'. */
458 void
459 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
460               bool verbose)
461 {
462     enum {
463         F_OUT_PORT = 1 << 0,
464         F_ACTIONS = 1 << 1,
465         F_COOKIE = 1 << 2,
466         F_TIMEOUT = 1 << 3,
467         F_PRIORITY = 1 << 4
468     } fields;
469     char *string = xstrdup(str_);
470     char *save_ptr = NULL;
471     char *act_str = NULL;
472     char *name;
473
474     switch (command) {
475     case -1:
476         fields = F_OUT_PORT;
477         break;
478
479     case OFPFC_ADD:
480         fields = F_ACTIONS | F_COOKIE | F_TIMEOUT | F_PRIORITY;
481         break;
482
483     case OFPFC_DELETE:
484         fields = F_OUT_PORT;
485         break;
486
487     case OFPFC_DELETE_STRICT:
488         fields = F_OUT_PORT | F_PRIORITY;
489         break;
490
491     case OFPFC_MODIFY:
492         fields = F_ACTIONS | F_COOKIE;
493         break;
494
495     case OFPFC_MODIFY_STRICT:
496         fields = F_ACTIONS | F_COOKIE | F_PRIORITY;
497         break;
498
499     default:
500         NOT_REACHED();
501     }
502
503     cls_rule_init_catchall(&fm->cr, OFP_DEFAULT_PRIORITY);
504     fm->cookie = htonll(0);
505     fm->table_id = 0xff;
506     fm->command = command;
507     fm->idle_timeout = OFP_FLOW_PERMANENT;
508     fm->hard_timeout = OFP_FLOW_PERMANENT;
509     fm->buffer_id = UINT32_MAX;
510     fm->out_port = OFPP_NONE;
511     fm->flags = 0;
512     if (fields & F_ACTIONS) {
513         act_str = strstr(string, "action");
514         if (!act_str) {
515             ofp_fatal(str_, verbose, "must specify an action");
516         }
517         *act_str = '\0';
518
519         act_str = strchr(act_str + 1, '=');
520         if (!act_str) {
521             ofp_fatal(str_, verbose, "must specify an action");
522         }
523
524         act_str++;
525     }
526     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
527          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
528         const struct protocol *p;
529
530         if (parse_protocol(name, &p)) {
531             cls_rule_set_dl_type(&fm->cr, htons(p->dl_type));
532             if (p->nw_proto) {
533                 cls_rule_set_nw_proto(&fm->cr, p->nw_proto);
534             }
535         } else {
536             char *value;
537
538             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
539             if (!value) {
540                 ofp_fatal(str_, verbose, "field %s missing value", name);
541             }
542
543             if (!strcmp(name, "table")) {
544                 fm->table_id = atoi(value);
545             } else if (!strcmp(name, "out_port")) {
546                 fm->out_port = atoi(value);
547             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
548                 fm->cr.priority = atoi(value);
549             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
550                 fm->idle_timeout = atoi(value);
551             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
552                 fm->hard_timeout = atoi(value);
553             } else if (fields & F_COOKIE && !strcmp(name, "cookie")) {
554                 fm->cookie = htonll(str_to_u64(value));
555             } else if (mf_from_name(name)) {
556                 parse_field(mf_from_name(name), value, &fm->cr);
557             } else if (!strcmp(name, "duration")
558                        || !strcmp(name, "n_packets")
559                        || !strcmp(name, "n_bytes")) {
560                 /* Ignore these, so that users can feed the output of
561                  * "ovs-ofctl dump-flows" back into commands that parse
562                  * flows. */
563             } else {
564                 ofp_fatal(str_, verbose, "unknown keyword %s", name);
565             }
566         }
567     }
568     if (fields & F_ACTIONS) {
569         struct ofpbuf actions;
570
571         ofpbuf_init(&actions, sizeof(union ofp_action));
572         str_to_action(&fm->cr.flow, act_str, &actions);
573         fm->actions = ofpbuf_steal_data(&actions);
574         fm->n_actions = actions.size / sizeof(union ofp_action);
575     } else {
576         fm->actions = NULL;
577         fm->n_actions = 0;
578     }
579
580     free(string);
581 }
582
583 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
584  * (one of OFPFC_*) and appends the parsed OpenFlow message to 'packets'.
585  * '*cur_format' should initially contain the flow format currently configured
586  * on the connection; this function will add a message to change the flow
587  * format and update '*cur_format', if this is necessary to add the parsed
588  * flow. */
589 void
590 parse_ofp_flow_mod_str(struct list *packets, enum nx_flow_format *cur_format,
591                        bool *flow_mod_table_id, char *string, uint16_t command,
592                        bool verbose)
593 {
594     enum nx_flow_format min_format, next_format;
595     struct cls_rule rule_copy;
596     struct ofpbuf actions;
597     struct ofpbuf *ofm;
598     struct ofputil_flow_mod fm;
599
600     ofpbuf_init(&actions, 64);
601     parse_ofp_str(&fm, command, string, verbose);
602
603     min_format = ofputil_min_flow_format(&fm.cr);
604     next_format = MAX(*cur_format, min_format);
605     if (next_format != *cur_format) {
606         struct ofpbuf *sff = ofputil_make_set_flow_format(next_format);
607         list_push_back(packets, &sff->list_node);
608         *cur_format = next_format;
609     }
610
611     /* Normalize a copy of the rule.  This ensures that non-normalized flows
612      * get logged but doesn't affect what gets sent to the switch, so that the
613      * switch can do whatever it likes with the flow. */
614     rule_copy = fm.cr;
615     ofputil_normalize_rule(&rule_copy, next_format);
616
617     if (fm.table_id != 0xff && !*flow_mod_table_id) {
618         struct ofpbuf *sff = ofputil_make_flow_mod_table_id(true);
619         list_push_back(packets, &sff->list_node);
620         *flow_mod_table_id = true;
621     }
622
623     ofm = ofputil_encode_flow_mod(&fm, *cur_format, *flow_mod_table_id);
624     list_push_back(packets, &ofm->list_node);
625
626     ofpbuf_uninit(&actions);
627 }
628
629 /* Similar to parse_ofp_flow_mod_str(), except that the string is read from
630  * 'stream' and the command is always OFPFC_ADD.  Returns false if end-of-file
631  * is reached before reading a flow, otherwise true. */
632 bool
633 parse_ofp_flow_mod_file(struct list *packets,
634                         enum nx_flow_format *cur, bool *flow_mod_table_id,
635                         FILE *stream, uint16_t command)
636 {
637     struct ds s;
638     bool ok;
639
640     ds_init(&s);
641     ok = ds_get_preprocessed_line(&s, stream) == 0;
642     if (ok) {
643         parse_ofp_flow_mod_str(packets, cur, flow_mod_table_id,
644                                ds_cstr(&s), command, true);
645     }
646     ds_destroy(&s);
647
648     return ok;
649 }
650
651 void
652 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
653                                  bool aggregate, char *string)
654 {
655     struct ofputil_flow_mod fm;
656
657     parse_ofp_str(&fm, -1, string, false);
658     fsr->aggregate = aggregate;
659     fsr->match = fm.cr;
660     fsr->out_port = fm.out_port;
661     fsr->table_id = fm.table_id;
662 }