ofp-parse: Factor out duplicated code into new functions.
[sliver-openvswitch.git] / lib / ofp-parse.c
1 /*
2  * Copyright (c) 2010 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 <errno.h>
22 #include <stdlib.h>
23
24 #include "dynamic-string.h"
25 #include "netdev.h"
26 #include "ofp-util.h"
27 #include "ofpbuf.h"
28 #include "openflow/openflow.h"
29 #include "packets.h"
30 #include "socket-util.h"
31 #include "vconn.h"
32 #include "vlog.h"
33 #include "xtoxll.h"
34
35 VLOG_DEFINE_THIS_MODULE(ofp_parse)
36
37 static uint32_t
38 str_to_u32(const char *str)
39 {
40     char *tail;
41     uint32_t value;
42
43     errno = 0;
44     value = strtoul(str, &tail, 0);
45     if (errno == EINVAL || errno == ERANGE || *tail) {
46         ovs_fatal(0, "invalid numeric format %s", str);
47     }
48     return value;
49 }
50
51 static uint64_t
52 str_to_u64(const char *str)
53 {
54     char *tail;
55     uint64_t value;
56
57     errno = 0;
58     value = strtoull(str, &tail, 0);
59     if (errno == EINVAL || errno == ERANGE || *tail) {
60         ovs_fatal(0, "invalid numeric format %s", str);
61     }
62     return value;
63 }
64
65 static void
66 str_to_mac(const char *str, uint8_t mac[6])
67 {
68     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
69         != ETH_ADDR_SCAN_COUNT) {
70         ovs_fatal(0, "invalid mac address %s", str);
71     }
72 }
73
74 static uint32_t
75 str_to_ip(const char *str_, uint32_t *ip)
76 {
77     char *str = xstrdup(str_);
78     char *save_ptr = NULL;
79     const char *name, *netmask;
80     struct in_addr in_addr;
81     int n_wild, retval;
82
83     name = strtok_r(str, "/", &save_ptr);
84     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
85     if (retval) {
86         ovs_fatal(0, "%s: could not convert to IP address", str);
87     }
88     *ip = in_addr.s_addr;
89
90     netmask = strtok_r(NULL, "/", &save_ptr);
91     if (netmask) {
92         uint8_t o[4];
93         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
94                    &o[0], &o[1], &o[2], &o[3]) == 4) {
95             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
96             int i;
97
98             /* Find first 1-bit. */
99             for (i = 0; i < 32; i++) {
100                 if (nm & (1u << i)) {
101                     break;
102                 }
103             }
104             n_wild = i;
105
106             /* Verify that the rest of the bits are 1-bits. */
107             for (; i < 32; i++) {
108                 if (!(nm & (1u << i))) {
109                     ovs_fatal(0, "%s: %s is not a valid netmask",
110                               str, netmask);
111                 }
112             }
113         } else {
114             int prefix = atoi(netmask);
115             if (prefix <= 0 || prefix > 32) {
116                 ovs_fatal(0, "%s: network prefix bits not between 1 and 32",
117                           str);
118             }
119             n_wild = 32 - prefix;
120         }
121     } else {
122         n_wild = 0;
123     }
124
125     free(str);
126     return n_wild;
127 }
128
129 static void *
130 put_action(struct ofpbuf *b, size_t size, uint16_t type)
131 {
132     struct ofp_action_header *ah = ofpbuf_put_zeros(b, size);
133     ah->type = htons(type);
134     ah->len = htons(size);
135     return ah;
136 }
137
138 static struct ofp_action_output *
139 put_output_action(struct ofpbuf *b, uint16_t port)
140 {
141     struct ofp_action_output *oao = put_action(b, sizeof *oao, OFPAT_OUTPUT);
142     oao->port = htons(port);
143     return oao;
144 }
145
146 static void
147 put_enqueue_action(struct ofpbuf *b, uint16_t port, uint32_t queue)
148 {
149     struct ofp_action_enqueue *oae = put_action(b, sizeof *oae, OFPAT_ENQUEUE);
150     oae->port = htons(port);
151     oae->queue_id = htonl(queue);
152 }
153
154 static void
155 put_dl_addr_action(struct ofpbuf *b, uint16_t type, const char *addr)
156 {
157     struct ofp_action_dl_addr *oada = put_action(b, sizeof *oada, type);
158     str_to_mac(addr, oada->dl_addr);
159 }
160
161
162 static bool
163 parse_port_name(const char *name, uint16_t *port)
164 {
165     struct pair {
166         const char *name;
167         uint16_t value;
168     };
169     static const struct pair pairs[] = {
170 #define DEF_PAIR(NAME) {#NAME, OFPP_##NAME}
171         DEF_PAIR(IN_PORT),
172         DEF_PAIR(TABLE),
173         DEF_PAIR(NORMAL),
174         DEF_PAIR(FLOOD),
175         DEF_PAIR(ALL),
176         DEF_PAIR(CONTROLLER),
177         DEF_PAIR(LOCAL),
178         DEF_PAIR(NONE),
179 #undef DEF_PAIR
180     };
181     static const int n_pairs = ARRAY_SIZE(pairs);
182     size_t i;
183
184     for (i = 0; i < n_pairs; i++) {
185         if (!strcasecmp(name, pairs[i].name)) {
186             *port = pairs[i].value;
187             return true;
188         }
189     }
190     return false;
191 }
192
193 static void
194 str_to_action(char *str, struct ofpbuf *b)
195 {
196     char *act, *arg;
197     char *saveptr = NULL;
198     bool drop = false;
199     int n_actions;
200
201     for (act = strtok_r(str, ", \t\r\n", &saveptr), n_actions = 0; act;
202          act = strtok_r(NULL, ", \t\r\n", &saveptr), n_actions++)
203     {
204         uint16_t port;
205
206         if (drop) {
207             ovs_fatal(0, "Drop actions must not be followed by other actions");
208         }
209
210         /* Arguments are separated by colons */
211         arg = strchr(act, ':');
212         if (arg) {
213             *arg = '\0';
214             arg++;
215         }
216
217         if (!strcasecmp(act, "mod_vlan_vid")) {
218             struct ofp_action_vlan_vid *va;
219             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_VID);
220             va->vlan_vid = htons(str_to_u32(arg));
221         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
222             struct ofp_action_vlan_pcp *va;
223             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_PCP);
224             va->vlan_pcp = str_to_u32(arg);
225         } else if (!strcasecmp(act, "strip_vlan")) {
226             struct ofp_action_header *ah;
227             ah = put_action(b, sizeof *ah, OFPAT_STRIP_VLAN);
228             ah->type = htons(OFPAT_STRIP_VLAN);
229         } else if (!strcasecmp(act, "mod_dl_src")) {
230             put_dl_addr_action(b, OFPAT_SET_DL_SRC, arg);
231         } else if (!strcasecmp(act, "mod_dl_dst")) {
232             put_dl_addr_action(b, OFPAT_SET_DL_DST, arg);
233         } else if (!strcasecmp(act, "mod_nw_src")) {
234             struct ofp_action_nw_addr *na;
235             na = put_action(b, sizeof *na, OFPAT_SET_NW_SRC);
236             str_to_ip(arg, &na->nw_addr);
237         } else if (!strcasecmp(act, "mod_nw_dst")) {
238             struct ofp_action_nw_addr *na;
239             na = put_action(b, sizeof *na, OFPAT_SET_NW_DST);
240             str_to_ip(arg, &na->nw_addr);
241         } else if (!strcasecmp(act, "mod_tp_src")) {
242             struct ofp_action_tp_port *ta;
243             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_SRC);
244             ta->tp_port = htons(str_to_u32(arg));
245         } else if (!strcasecmp(act, "mod_tp_dst")) {
246             struct ofp_action_tp_port *ta;
247             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_DST);
248             ta->tp_port = htons(str_to_u32(arg));
249         } else if (!strcasecmp(act, "mod_nw_tos")) {
250             struct ofp_action_nw_tos *nt;
251             nt = put_action(b, sizeof *nt, OFPAT_SET_NW_TOS);
252             nt->nw_tos = str_to_u32(arg);
253         } else if (!strcasecmp(act, "resubmit")) {
254             struct nx_action_resubmit *nar;
255             nar = put_action(b, sizeof *nar, OFPAT_VENDOR);
256             nar->vendor = htonl(NX_VENDOR_ID);
257             nar->subtype = htons(NXAST_RESUBMIT);
258             nar->in_port = htons(str_to_u32(arg));
259         } else if (!strcasecmp(act, "set_tunnel")) {
260             struct nx_action_set_tunnel *nast;
261             nast = put_action(b, sizeof *nast, OFPAT_VENDOR);
262             nast->vendor = htonl(NX_VENDOR_ID);
263             nast->subtype = htons(NXAST_SET_TUNNEL);
264             nast->tun_id = htonl(str_to_u32(arg));
265         } else if (!strcasecmp(act, "drop_spoofed_arp")) {
266             struct nx_action_header *nah;
267             nah = put_action(b, sizeof *nah, OFPAT_VENDOR);
268             nah->vendor = htonl(NX_VENDOR_ID);
269             nah->subtype = htons(NXAST_DROP_SPOOFED_ARP);
270         } else if (!strcasecmp(act, "output")) {
271             put_output_action(b, str_to_u32(arg));
272         } else if (!strcasecmp(act, "enqueue")) {
273             char *sp = NULL;
274             char *port_s = strtok_r(arg, ":q", &sp);
275             char *queue = strtok_r(NULL, "", &sp);
276             if (port_s == NULL || queue == NULL) {
277                 ovs_fatal(0, "\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
278             }
279             put_enqueue_action(b, str_to_u32(port_s), str_to_u32(queue));
280         } else if (!strcasecmp(act, "drop")) {
281             /* A drop action in OpenFlow occurs by just not setting
282              * an action. */
283             drop = true;
284             if (n_actions) {
285                 ovs_fatal(0, "Drop actions must not be preceded by other "
286                           "actions");
287             }
288         } else if (!strcasecmp(act, "CONTROLLER")) {
289             struct ofp_action_output *oao;
290             oao = put_output_action(b, OFPP_CONTROLLER);
291
292             /* Unless a numeric argument is specified, we send the whole
293              * packet to the controller. */
294             if (arg && (strspn(arg, "0123456789") == strlen(arg))) {
295                oao->max_len = htons(str_to_u32(arg));
296             } else {
297                 oao->max_len = htons(UINT16_MAX);
298             }
299         } else if (parse_port_name(act, &port)) {
300             put_output_action(b, port);
301         } else if (strspn(act, "0123456789") == strlen(act)) {
302             put_output_action(b, str_to_u32(act));
303         } else {
304             ovs_fatal(0, "Unknown action: %s", act);
305         }
306     }
307 }
308
309 struct protocol {
310     const char *name;
311     uint16_t dl_type;
312     uint8_t nw_proto;
313 };
314
315 static bool
316 parse_protocol(const char *name, const struct protocol **p_out)
317 {
318     static const struct protocol protocols[] = {
319         { "ip", ETH_TYPE_IP, 0 },
320         { "arp", ETH_TYPE_ARP, 0 },
321         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
322         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
323         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
324     };
325     const struct protocol *p;
326
327     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
328         if (!strcmp(p->name, name)) {
329             *p_out = p;
330             return true;
331         }
332     }
333     *p_out = NULL;
334     return false;
335 }
336
337 struct field {
338     const char *name;
339     uint32_t wildcard;
340     enum { F_U8, F_U16, F_MAC, F_IP } type;
341     size_t offset, shift;
342 };
343
344 static bool
345 parse_field(const char *name, const struct field **f_out)
346 {
347 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
348     static const struct field fields[] = {
349         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port), 0 },
350         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan), 0 },
351         { "dl_vlan_pcp", OFPFW_DL_VLAN_PCP, F_U8, F_OFS(dl_vlan_pcp), 0 },
352         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src), 0 },
353         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst), 0 },
354         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type), 0 },
355         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
356           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
357         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
358           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
359         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto), 0 },
360         { "nw_tos", OFPFW_NW_TOS, F_U8, F_OFS(nw_tos), 0 },
361         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src), 0 },
362         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst), 0 },
363         { "icmp_type", OFPFW_ICMP_TYPE, F_U16, F_OFS(icmp_type), 0 },
364         { "icmp_code", OFPFW_ICMP_CODE, F_U16, F_OFS(icmp_code), 0 }
365     };
366     const struct field *f;
367
368     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
369         if (!strcmp(f->name, name)) {
370             *f_out = f;
371             return true;
372         }
373     }
374     *f_out = NULL;
375     return false;
376 }
377
378 /* Convert 'string' (as described in the Flow Syntax section of the
379  * ovs-ofctl man page) into 'match'.  The other arguments are optional
380  * and may be NULL if their value is not needed.  If 'actions' is
381  * specified, an action must be in 'string' and may be expanded or
382  * reallocated. */
383 void
384 parse_ofp_str(char *string, struct ofp_match *match, struct ofpbuf *actions,
385               uint8_t *table_idx, uint16_t *out_port, uint16_t *priority,
386               uint16_t *idle_timeout, uint16_t *hard_timeout,
387               uint64_t *cookie)
388 {
389     struct ofp_match normalized;
390     char *save_ptr = NULL;
391     char *name;
392     uint32_t wildcards;
393
394     if (table_idx) {
395         *table_idx = 0xff;
396     }
397     if (out_port) {
398         *out_port = OFPP_NONE;
399     }
400     if (priority) {
401         *priority = OFP_DEFAULT_PRIORITY;
402     }
403     if (idle_timeout) {
404         *idle_timeout = OFP_FLOW_PERMANENT;
405     }
406     if (hard_timeout) {
407         *hard_timeout = OFP_FLOW_PERMANENT;
408     }
409     if (cookie) {
410         *cookie = 0;
411     }
412     if (actions) {
413         char *act_str = strstr(string, "action");
414         if (!act_str) {
415             ovs_fatal(0, "must specify an action");
416         }
417         *act_str = '\0';
418
419         act_str = strchr(act_str + 1, '=');
420         if (!act_str) {
421             ovs_fatal(0, "must specify an action");
422         }
423
424         act_str++;
425
426         str_to_action(act_str, actions);
427     }
428     memset(match, 0, sizeof *match);
429     wildcards = OFPFW_ALL;
430     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
431          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
432         const struct protocol *p;
433
434         if (parse_protocol(name, &p)) {
435             wildcards &= ~OFPFW_DL_TYPE;
436             match->dl_type = htons(p->dl_type);
437             if (p->nw_proto) {
438                 wildcards &= ~OFPFW_NW_PROTO;
439                 match->nw_proto = p->nw_proto;
440             }
441         } else {
442             const struct field *f;
443             char *value;
444
445             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
446             if (!value) {
447                 ovs_fatal(0, "field %s missing value", name);
448             }
449
450             if (table_idx && !strcmp(name, "table")) {
451                 *table_idx = atoi(value);
452             } else if (out_port && !strcmp(name, "out_port")) {
453                 *out_port = atoi(value);
454             } else if (priority && !strcmp(name, "priority")) {
455                 *priority = atoi(value);
456             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
457                 *idle_timeout = atoi(value);
458             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
459                 *hard_timeout = atoi(value);
460             } else if (cookie && !strcmp(name, "cookie")) {
461                 *cookie = str_to_u64(value);
462             } else if (!strcmp(name, "tun_id_wild")) {
463                 wildcards |= NXFW_TUN_ID;
464             } else if (parse_field(name, &f)) {
465                 void *data = (char *) match + f->offset;
466                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
467                     wildcards |= f->wildcard;
468                 } else {
469                     uint16_t port_no;
470
471                     wildcards &= ~f->wildcard;
472                     if (f->wildcard == OFPFW_IN_PORT
473                         && parse_port_name(value, &port_no)) {
474                         match->in_port = htons(port_no);
475                     } else if (f->type == F_U8) {
476                         *(uint8_t *) data = str_to_u32(value);
477                     } else if (f->type == F_U16) {
478                         *(uint16_t *) data = htons(str_to_u32(value));
479                     } else if (f->type == F_MAC) {
480                         str_to_mac(value, data);
481                     } else if (f->type == F_IP) {
482                         wildcards |= str_to_ip(value, data) << f->shift;
483                     } else {
484                         NOT_REACHED();
485                     }
486                 }
487             } else {
488                 ovs_fatal(0, "unknown keyword %s", name);
489             }
490         }
491     }
492     match->wildcards = htonl(wildcards);
493
494     normalized = *match;
495     normalize_match(&normalized);
496     if (memcmp(match, &normalized, sizeof normalized)) {
497         char *old = ofp_match_to_literal_string(match);
498         char *new = ofp_match_to_literal_string(&normalized);
499         VLOG_WARN("The specified flow is not in normal form:");
500         VLOG_WARN(" as specified: %s", old);
501         VLOG_WARN("as normalized: %s", new);
502         free(old);
503         free(new);
504     }
505 }
506
507 /* Parses 'string' as a OFPT_FLOW_MOD with subtype OFPFC_ADD and returns an
508  * ofpbuf that contains it. */
509 struct ofpbuf *
510 parse_ofp_add_flow_str(char *string)
511 {
512     struct ofpbuf *buffer;
513     struct ofp_flow_mod *ofm;
514     uint16_t priority, idle_timeout, hard_timeout;
515     uint64_t cookie;
516     struct ofp_match match;
517
518     /* parse_ofp_str() will expand and reallocate the data in 'buffer', so we
519      * can't keep pointers to across the parse_ofp_str() call. */
520     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
521     parse_ofp_str(string, &match, buffer,
522                   NULL, NULL, &priority, &idle_timeout, &hard_timeout,
523                   &cookie);
524     ofm = buffer->data;
525     ofm->match = match;
526     ofm->command = htons(OFPFC_ADD);
527     ofm->cookie = htonll(cookie);
528     ofm->idle_timeout = htons(idle_timeout);
529     ofm->hard_timeout = htons(hard_timeout);
530     ofm->buffer_id = htonl(UINT32_MAX);
531     ofm->priority = htons(priority);
532     update_openflow_length(buffer);
533
534     return buffer;
535 }
536
537 /* Parses an OFPT_FLOW_MOD with subtype OFPFC_ADD from 'stream' and returns an
538  * ofpbuf that contains it.  Returns a null pointer if end-of-file is reached
539  * before reading a flow. */
540 struct ofpbuf *
541 parse_ofp_add_flow_file(FILE *stream)
542 {
543     struct ofpbuf *b = NULL;
544     struct ds s = DS_EMPTY_INITIALIZER;
545
546     while (!ds_get_line(&s, stream)) {
547         char *line = ds_cstr(&s);
548         char *comment;
549
550         /* Delete comments. */
551         comment = strchr(line, '#');
552         if (comment) {
553             *comment = '\0';
554         }
555
556         /* Drop empty lines. */
557         if (line[strspn(line, " \t\n")] == '\0') {
558             continue;
559         }
560
561         b = parse_ofp_add_flow_str(line);
562         break;
563     }
564     ds_destroy(&s);
565
566     return b;
567 }