vswitch: Implement bundle 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 "netdev.h"
30 #include "multipath.h"
31 #include "nx-match.h"
32 #include "ofp-util.h"
33 #include "ofpbuf.h"
34 #include "openflow/openflow.h"
35 #include "packets.h"
36 #include "socket-util.h"
37 #include "vconn.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(ofp_parse);
41
42 static uint32_t
43 str_to_u32(const char *str)
44 {
45     char *tail;
46     uint32_t value;
47
48     if (!str[0]) {
49         ovs_fatal(0, "missing required numeric argument");
50     }
51
52     errno = 0;
53     value = strtoul(str, &tail, 0);
54     if (errno == EINVAL || errno == ERANGE || *tail) {
55         ovs_fatal(0, "invalid numeric format %s", str);
56     }
57     return value;
58 }
59
60 static uint64_t
61 str_to_u64(const char *str)
62 {
63     char *tail;
64     uint64_t value;
65
66     if (!str[0]) {
67         ovs_fatal(0, "missing required numeric argument");
68     }
69
70     errno = 0;
71     value = strtoull(str, &tail, 0);
72     if (errno == EINVAL || errno == ERANGE || *tail) {
73         ovs_fatal(0, "invalid numeric format %s", str);
74     }
75     return value;
76 }
77
78 static void
79 str_to_mac(const char *str, uint8_t mac[6])
80 {
81     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
82         != ETH_ADDR_SCAN_COUNT) {
83         ovs_fatal(0, "invalid mac address %s", str);
84     }
85 }
86
87 static void
88 str_to_eth_dst(const char *str,
89                uint8_t mac[ETH_ADDR_LEN], uint8_t mask[ETH_ADDR_LEN])
90 {
91     if (sscanf(str, ETH_ADDR_SCAN_FMT"/"ETH_ADDR_SCAN_FMT,
92                ETH_ADDR_SCAN_ARGS(mac), ETH_ADDR_SCAN_ARGS(mask))
93         == ETH_ADDR_SCAN_COUNT * 2) {
94         if (!flow_wildcards_is_dl_dst_mask_valid(mask)) {
95             ovs_fatal(0, "%s: invalid Ethernet destination mask (only "
96                       "00:00:00:00:00:00, 01:00:00:00:00:00, "
97                       "fe:ff:ff:ff:ff:ff, and ff:ff:ff:ff:ff:ff are allowed)",
98                       str);
99         }
100     } else if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
101                == ETH_ADDR_SCAN_COUNT) {
102         memset(mask, 0xff, ETH_ADDR_LEN);
103     } else {
104         ovs_fatal(0, "invalid mac address %s", str);
105     }
106 }
107
108 static void
109 str_to_ip(const char *str_, ovs_be32 *ip, ovs_be32 *maskp)
110 {
111     char *str = xstrdup(str_);
112     char *save_ptr = NULL;
113     const char *name, *netmask;
114     struct in_addr in_addr;
115     ovs_be32 mask;
116     int retval;
117
118     name = strtok_r(str, "/", &save_ptr);
119     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
120     if (retval) {
121         ovs_fatal(0, "%s: could not convert to IP address", str);
122     }
123     *ip = in_addr.s_addr;
124
125     netmask = strtok_r(NULL, "/", &save_ptr);
126     if (netmask) {
127         uint8_t o[4];
128         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
129                    &o[0], &o[1], &o[2], &o[3]) == 4) {
130             mask = htonl((o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3]);
131         } else {
132             int prefix = atoi(netmask);
133             if (prefix <= 0 || prefix > 32) {
134                 ovs_fatal(0, "%s: network prefix bits not between 1 and 32",
135                           str);
136             } else if (prefix == 32) {
137                 mask = htonl(UINT32_MAX);
138             } else {
139                 mask = htonl(((1u << prefix) - 1) << (32 - prefix));
140             }
141         }
142     } else {
143         mask = htonl(UINT32_MAX);
144     }
145     *ip &= mask;
146
147     if (maskp) {
148         *maskp = mask;
149     } else {
150         if (mask != htonl(UINT32_MAX)) {
151             ovs_fatal(0, "%s: netmask not allowed here", str_);
152         }
153     }
154
155     free(str);
156 }
157
158 static void
159 str_to_tun_id(const char *str, ovs_be64 *tun_idp, ovs_be64 *maskp)
160 {
161     uint64_t tun_id, mask;
162     char *tail;
163
164     errno = 0;
165     tun_id = strtoull(str, &tail, 0);
166     if (errno || (*tail != '\0' && *tail != '/')) {
167         goto error;
168     }
169
170     if (*tail == '/') {
171         mask = strtoull(tail + 1, &tail, 0);
172         if (errno || *tail != '\0') {
173             goto error;
174         }
175     } else {
176         mask = UINT64_MAX;
177     }
178
179     *tun_idp = htonll(tun_id);
180     *maskp = htonll(mask);
181     return;
182
183 error:
184     ovs_fatal(0, "%s: bad syntax for tunnel id", str);
185 }
186
187 static void
188 str_to_vlan_tci(const char *str, ovs_be16 *vlan_tcip, ovs_be16 *maskp)
189 {
190     uint16_t vlan_tci, mask;
191     char *tail;
192
193     errno = 0;
194     vlan_tci = strtol(str, &tail, 0);
195     if (errno || (*tail != '\0' && *tail != '/')) {
196         goto error;
197     }
198
199     if (*tail == '/') {
200         mask = strtol(tail + 1, &tail, 0);
201         if (errno || *tail != '\0') {
202             goto error;
203         }
204     } else {
205         mask = UINT16_MAX;
206     }
207
208     *vlan_tcip = htons(vlan_tci);
209     *maskp = htons(mask);
210     return;
211
212 error:
213     ovs_fatal(0, "%s: bad syntax for vlan_tci", str);
214 }
215
216 static void
217 str_to_ipv6(const char *str_, struct in6_addr *addrp, struct in6_addr *maskp)
218 {
219     char *str = xstrdup(str_);
220     char *save_ptr = NULL;
221     const char *name, *netmask;
222     struct in6_addr addr, mask;
223     int retval;
224
225     name = strtok_r(str, "/", &save_ptr);
226     retval = name ? lookup_ipv6(name, &addr) : EINVAL;
227     if (retval) {
228         ovs_fatal(0, "%s: could not convert to IPv6 address", str);
229     }
230
231     netmask = strtok_r(NULL, "/", &save_ptr);
232     if (netmask) {
233         int prefix = atoi(netmask);
234         if (prefix <= 0 || prefix > 128) {
235             ovs_fatal(0, "%s: network prefix bits not between 1 and 128",
236                       str);
237         } else {
238             mask = ipv6_create_mask(prefix);
239         }
240     } else {
241         mask = in6addr_exact;
242     }
243     *addrp = ipv6_addr_bitand(&addr, &mask);
244
245     if (maskp) {
246         *maskp = mask;
247     } else {
248         if (!ipv6_mask_is_exact(&mask)) {
249             ovs_fatal(0, "%s: netmask not allowed here", str_);
250         }
251     }
252
253     free(str);
254 }
255
256 static void *
257 put_action(struct ofpbuf *b, size_t size, uint16_t type)
258 {
259     struct ofp_action_header *ah = ofpbuf_put_zeros(b, size);
260     ah->type = htons(type);
261     ah->len = htons(size);
262     return ah;
263 }
264
265 static struct ofp_action_output *
266 put_output_action(struct ofpbuf *b, uint16_t port)
267 {
268     struct ofp_action_output *oao = put_action(b, sizeof *oao, OFPAT_OUTPUT);
269     oao->port = htons(port);
270     return oao;
271 }
272
273 static void
274 put_enqueue_action(struct ofpbuf *b, uint16_t port, uint32_t queue)
275 {
276     struct ofp_action_enqueue *oae = put_action(b, sizeof *oae, OFPAT_ENQUEUE);
277     oae->port = htons(port);
278     oae->queue_id = htonl(queue);
279 }
280
281 static void
282 put_dl_addr_action(struct ofpbuf *b, uint16_t type, const char *addr)
283 {
284     struct ofp_action_dl_addr *oada = put_action(b, sizeof *oada, type);
285     str_to_mac(addr, oada->dl_addr);
286 }
287
288
289 static bool
290 parse_port_name(const char *name, uint16_t *port)
291 {
292     struct pair {
293         const char *name;
294         uint16_t value;
295     };
296     static const struct pair pairs[] = {
297 #define DEF_PAIR(NAME) {#NAME, OFPP_##NAME}
298         DEF_PAIR(IN_PORT),
299         DEF_PAIR(TABLE),
300         DEF_PAIR(NORMAL),
301         DEF_PAIR(FLOOD),
302         DEF_PAIR(ALL),
303         DEF_PAIR(CONTROLLER),
304         DEF_PAIR(LOCAL),
305         DEF_PAIR(NONE),
306 #undef DEF_PAIR
307     };
308     static const int n_pairs = ARRAY_SIZE(pairs);
309     size_t i;
310
311     for (i = 0; i < n_pairs; i++) {
312         if (!strcasecmp(name, pairs[i].name)) {
313             *port = pairs[i].value;
314             return true;
315         }
316     }
317     return false;
318 }
319
320 static void
321 str_to_action(char *str, struct ofpbuf *b)
322 {
323     bool drop = false;
324     int n_actions;
325     char *pos;
326
327     pos = str;
328     n_actions = 0;
329     for (;;) {
330         char empty_string[] = "";
331         char *act, *arg;
332         size_t actlen;
333         uint16_t port;
334
335         pos += strspn(pos, ", \t\r\n");
336         if (*pos == '\0') {
337             break;
338         }
339
340         if (drop) {
341             ovs_fatal(0, "Drop actions must not be followed by other actions");
342         }
343
344         act = pos;
345         actlen = strcspn(pos, ":(, \t\r\n");
346         if (act[actlen] == ':') {
347             /* The argument can be separated by a colon. */
348             size_t arglen;
349
350             arg = act + actlen + 1;
351             arglen = strcspn(arg, ", \t\r\n");
352             pos = arg + arglen + (arg[arglen] != '\0');
353             arg[arglen] = '\0';
354         } else if (act[actlen] == '(') {
355             /* The argument can be surrounded by balanced parentheses.  The
356              * outermost set of parentheses is removed. */
357             int level = 1;
358             size_t arglen;
359
360             arg = act + actlen + 1;
361             for (arglen = 0; level > 0; arglen++) {
362                 switch (arg[arglen]) {
363                 case '\0':
364                     ovs_fatal(0, "unbalanced parentheses in argument to %s "
365                               "action", act);
366
367                 case '(':
368                     level++;
369                     break;
370
371                 case ')':
372                     level--;
373                     break;
374                 }
375             }
376             arg[arglen - 1] = '\0';
377             pos = arg + arglen;
378         } else {
379             /* There might be no argument at all. */
380             arg = empty_string;
381             pos = act + actlen + (act[actlen] != '\0');
382         }
383         act[actlen] = '\0';
384
385         if (!strcasecmp(act, "mod_vlan_vid")) {
386             struct ofp_action_vlan_vid *va;
387             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_VID);
388             va->vlan_vid = htons(str_to_u32(arg));
389         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
390             struct ofp_action_vlan_pcp *va;
391             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_PCP);
392             va->vlan_pcp = str_to_u32(arg);
393         } else if (!strcasecmp(act, "strip_vlan")) {
394             struct ofp_action_header *ah;
395             ah = put_action(b, sizeof *ah, OFPAT_STRIP_VLAN);
396             ah->type = htons(OFPAT_STRIP_VLAN);
397         } else if (!strcasecmp(act, "mod_dl_src")) {
398             put_dl_addr_action(b, OFPAT_SET_DL_SRC, arg);
399         } else if (!strcasecmp(act, "mod_dl_dst")) {
400             put_dl_addr_action(b, OFPAT_SET_DL_DST, arg);
401         } else if (!strcasecmp(act, "mod_nw_src")) {
402             struct ofp_action_nw_addr *na;
403             na = put_action(b, sizeof *na, OFPAT_SET_NW_SRC);
404             str_to_ip(arg, &na->nw_addr, NULL);
405         } else if (!strcasecmp(act, "mod_nw_dst")) {
406             struct ofp_action_nw_addr *na;
407             na = put_action(b, sizeof *na, OFPAT_SET_NW_DST);
408             str_to_ip(arg, &na->nw_addr, NULL);
409         } else if (!strcasecmp(act, "mod_tp_src")) {
410             struct ofp_action_tp_port *ta;
411             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_SRC);
412             ta->tp_port = htons(str_to_u32(arg));
413         } else if (!strcasecmp(act, "mod_tp_dst")) {
414             struct ofp_action_tp_port *ta;
415             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_DST);
416             ta->tp_port = htons(str_to_u32(arg));
417         } else if (!strcasecmp(act, "mod_nw_tos")) {
418             struct ofp_action_nw_tos *nt;
419             nt = put_action(b, sizeof *nt, OFPAT_SET_NW_TOS);
420             nt->nw_tos = str_to_u32(arg);
421         } else if (!strcasecmp(act, "resubmit")) {
422             struct nx_action_resubmit *nar;
423             nar = put_action(b, sizeof *nar, OFPAT_VENDOR);
424             nar->vendor = htonl(NX_VENDOR_ID);
425             nar->subtype = htons(NXAST_RESUBMIT);
426             nar->in_port = htons(str_to_u32(arg));
427         } else if (!strcasecmp(act, "set_tunnel")
428                    || !strcasecmp(act, "set_tunnel64")) {
429             uint64_t tun_id = str_to_u64(arg);
430             if (!strcasecmp(act, "set_tunnel64") || tun_id > UINT32_MAX) {
431                 struct nx_action_set_tunnel64 *nast64;
432                 nast64 = put_action(b, sizeof *nast64, OFPAT_VENDOR);
433                 nast64->vendor = htonl(NX_VENDOR_ID);
434                 nast64->subtype = htons(NXAST_SET_TUNNEL64);
435                 nast64->tun_id = htonll(tun_id);
436             } else {
437                 struct nx_action_set_tunnel *nast;
438                 nast = put_action(b, sizeof *nast, OFPAT_VENDOR);
439                 nast->vendor = htonl(NX_VENDOR_ID);
440                 nast->subtype = htons(NXAST_SET_TUNNEL);
441                 nast->tun_id = htonl(tun_id);
442             }
443         } else if (!strcasecmp(act, "set_queue")) {
444             struct nx_action_set_queue *nasq;
445             nasq = put_action(b, sizeof *nasq, OFPAT_VENDOR);
446             nasq->vendor = htonl(NX_VENDOR_ID);
447             nasq->subtype = htons(NXAST_SET_QUEUE);
448             nasq->queue_id = htonl(str_to_u32(arg));
449         } else if (!strcasecmp(act, "pop_queue")) {
450             struct nx_action_header *nah;
451             nah = put_action(b, sizeof *nah, OFPAT_VENDOR);
452             nah->vendor = htonl(NX_VENDOR_ID);
453             nah->subtype = htons(NXAST_POP_QUEUE);
454         } else if (!strcasecmp(act, "note")) {
455             size_t start_ofs = b->size;
456             struct nx_action_note *nan;
457             int remainder;
458             size_t len;
459
460             nan = put_action(b, sizeof *nan, OFPAT_VENDOR);
461             nan->vendor = htonl(NX_VENDOR_ID);
462             nan->subtype = htons(NXAST_NOTE);
463
464             b->size -= sizeof nan->note;
465             while (*arg != '\0') {
466                 uint8_t byte;
467                 bool ok;
468
469                 if (*arg == '.') {
470                     arg++;
471                 }
472                 if (*arg == '\0') {
473                     break;
474                 }
475
476                 byte = hexits_value(arg, 2, &ok);
477                 if (!ok) {
478                     ovs_fatal(0, "bad hex digit in `note' argument");
479                 }
480                 ofpbuf_put(b, &byte, 1);
481
482                 arg += 2;
483             }
484
485             len = b->size - start_ofs;
486             remainder = len % OFP_ACTION_ALIGN;
487             if (remainder) {
488                 ofpbuf_put_zeros(b, OFP_ACTION_ALIGN - remainder);
489             }
490             nan = (struct nx_action_note *)((char *)b->data + start_ofs);
491             nan->len = htons(b->size - start_ofs);
492         } else if (!strcasecmp(act, "move")) {
493             struct nx_action_reg_move *move;
494             move = ofpbuf_put_uninit(b, sizeof *move);
495             nxm_parse_reg_move(move, arg);
496         } else if (!strcasecmp(act, "load")) {
497             struct nx_action_reg_load *load;
498             load = ofpbuf_put_uninit(b, sizeof *load);
499             nxm_parse_reg_load(load, arg);
500         } else if (!strcasecmp(act, "multipath")) {
501             struct nx_action_multipath *nam;
502             nam = ofpbuf_put_uninit(b, sizeof *nam);
503             multipath_parse(nam, arg);
504         } else if (!strcasecmp(act, "autopath")) {
505             struct nx_action_autopath *naa;
506             naa = ofpbuf_put_uninit(b, sizeof *naa);
507             autopath_parse(naa, arg);
508         } else if (!strcasecmp(act, "bundle")) {
509             bundle_parse(b, arg);
510         } else if (!strcasecmp(act, "output")) {
511             put_output_action(b, str_to_u32(arg));
512         } else if (!strcasecmp(act, "enqueue")) {
513             char *sp = NULL;
514             char *port_s = strtok_r(arg, ":q", &sp);
515             char *queue = strtok_r(NULL, "", &sp);
516             if (port_s == NULL || queue == NULL) {
517                 ovs_fatal(0, "\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
518             }
519             put_enqueue_action(b, str_to_u32(port_s), str_to_u32(queue));
520         } else if (!strcasecmp(act, "drop")) {
521             /* A drop action in OpenFlow occurs by just not setting
522              * an action. */
523             drop = true;
524             if (n_actions) {
525                 ovs_fatal(0, "Drop actions must not be preceded by other "
526                           "actions");
527             }
528         } else if (!strcasecmp(act, "CONTROLLER")) {
529             struct ofp_action_output *oao;
530             oao = put_output_action(b, OFPP_CONTROLLER);
531
532             /* Unless a numeric argument is specified, we send the whole
533              * packet to the controller. */
534             if (arg[0] && (strspn(arg, "0123456789") == strlen(arg))) {
535                oao->max_len = htons(str_to_u32(arg));
536             } else {
537                 oao->max_len = htons(UINT16_MAX);
538             }
539         } else if (parse_port_name(act, &port)) {
540             put_output_action(b, port);
541         } else if (strspn(act, "0123456789") == strlen(act)) {
542             put_output_action(b, str_to_u32(act));
543         } else {
544             ovs_fatal(0, "Unknown action: %s", act);
545         }
546         n_actions++;
547     }
548 }
549
550 struct protocol {
551     const char *name;
552     uint16_t dl_type;
553     uint8_t nw_proto;
554 };
555
556 static bool
557 parse_protocol(const char *name, const struct protocol **p_out)
558 {
559     static const struct protocol protocols[] = {
560         { "ip", ETH_TYPE_IP, 0 },
561         { "arp", ETH_TYPE_ARP, 0 },
562         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
563         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
564         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
565         { "ipv6", ETH_TYPE_IPV6, 0 },
566         { "ip6", ETH_TYPE_IPV6, 0 },
567         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
568         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
569         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
570     };
571     const struct protocol *p;
572
573     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
574         if (!strcmp(p->name, name)) {
575             *p_out = p;
576             return true;
577         }
578     }
579     *p_out = NULL;
580     return false;
581 }
582
583 #define FIELDS                                              \
584     FIELD(F_TUN_ID,      "tun_id",      0)                  \
585     FIELD(F_IN_PORT,     "in_port",     FWW_IN_PORT)        \
586     FIELD(F_DL_VLAN,     "dl_vlan",     0)                  \
587     FIELD(F_DL_VLAN_PCP, "dl_vlan_pcp", 0)                  \
588     FIELD(F_VLAN_TCI,    "vlan_tci",    0)                  \
589     FIELD(F_DL_SRC,      "dl_src",      FWW_DL_SRC)         \
590     FIELD(F_DL_DST,      "dl_dst",      FWW_DL_DST | FWW_ETH_MCAST) \
591     FIELD(F_DL_TYPE,     "dl_type",     FWW_DL_TYPE)        \
592     FIELD(F_NW_SRC,      "nw_src",      0)                  \
593     FIELD(F_NW_DST,      "nw_dst",      0)                  \
594     FIELD(F_NW_PROTO,    "nw_proto",    FWW_NW_PROTO)       \
595     FIELD(F_NW_TOS,      "nw_tos",      FWW_NW_TOS)         \
596     FIELD(F_TP_SRC,      "tp_src",      FWW_TP_SRC)         \
597     FIELD(F_TP_DST,      "tp_dst",      FWW_TP_DST)         \
598     FIELD(F_ICMP_TYPE,   "icmp_type",   FWW_TP_SRC)         \
599     FIELD(F_ICMP_CODE,   "icmp_code",   FWW_TP_DST)         \
600     FIELD(F_ARP_SHA,     "arp_sha",     FWW_ARP_SHA)        \
601     FIELD(F_ARP_THA,     "arp_tha",     FWW_ARP_THA)        \
602     FIELD(F_IPV6_SRC,    "ipv6_src",    0)                  \
603     FIELD(F_IPV6_DST,    "ipv6_dst",    0)                  \
604     FIELD(F_ND_TARGET,   "nd_target",   FWW_ND_TARGET)      \
605     FIELD(F_ND_SLL,      "nd_sll",      FWW_ARP_SHA)        \
606     FIELD(F_ND_TLL,      "nd_tll",      FWW_ARP_THA)
607
608 enum field_index {
609 #define FIELD(ENUM, NAME, WILDCARD) ENUM,
610     FIELDS
611 #undef FIELD
612     N_FIELDS
613 };
614
615 struct field {
616     enum field_index index;
617     const char *name;
618     flow_wildcards_t wildcard;  /* FWW_* bit. */
619 };
620
621 static void
622 ofp_fatal(const char *flow, bool verbose, const char *format, ...)
623 {
624     va_list args;
625
626     if (verbose) {
627         fprintf(stderr, "%s:\n", flow);
628     }
629
630     va_start(args, format);
631     ovs_fatal_valist(0, format, args);
632 }
633
634 static bool
635 parse_field_name(const char *name, const struct field **f_out)
636 {
637     static const struct field fields[N_FIELDS] = {
638 #define FIELD(ENUM, NAME, WILDCARD) { ENUM, NAME, WILDCARD },
639         FIELDS
640 #undef FIELD
641     };
642     const struct field *f;
643
644     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
645         if (!strcmp(f->name, name)) {
646             *f_out = f;
647             return true;
648         }
649     }
650     *f_out = NULL;
651     return false;
652 }
653
654 static void
655 parse_field_value(struct cls_rule *rule, enum field_index index,
656                   const char *value)
657 {
658     uint8_t mac[ETH_ADDR_LEN], mac_mask[ETH_ADDR_LEN];
659     ovs_be64 tun_id, tun_mask;
660     ovs_be32 ip, mask;
661     ovs_be16 tci, tci_mask;
662     struct in6_addr ipv6, ipv6_mask;
663     uint16_t port_no;
664
665     switch (index) {
666     case F_TUN_ID:
667         str_to_tun_id(value, &tun_id, &tun_mask);
668         cls_rule_set_tun_id_masked(rule, tun_id, tun_mask);
669         break;
670
671     case F_IN_PORT:
672         if (!parse_port_name(value, &port_no)) {
673             port_no = atoi(value);
674         }
675         cls_rule_set_in_port(rule, port_no);
676         break;
677
678     case F_DL_VLAN:
679         cls_rule_set_dl_vlan(rule, htons(str_to_u32(value)));
680         break;
681
682     case F_DL_VLAN_PCP:
683         cls_rule_set_dl_vlan_pcp(rule, str_to_u32(value));
684         break;
685
686     case F_VLAN_TCI:
687         str_to_vlan_tci(value, &tci, &tci_mask);
688         cls_rule_set_dl_tci_masked(rule, tci, tci_mask);
689         break;
690
691     case F_DL_SRC:
692         str_to_mac(value, mac);
693         cls_rule_set_dl_src(rule, mac);
694         break;
695
696     case F_DL_DST:
697         str_to_eth_dst(value, mac, mac_mask);
698         cls_rule_set_dl_dst_masked(rule, mac, mac_mask);
699         break;
700
701     case F_DL_TYPE:
702         cls_rule_set_dl_type(rule, htons(str_to_u32(value)));
703         break;
704
705     case F_NW_SRC:
706         str_to_ip(value, &ip, &mask);
707         cls_rule_set_nw_src_masked(rule, ip, mask);
708         break;
709
710     case F_NW_DST:
711         str_to_ip(value, &ip, &mask);
712         cls_rule_set_nw_dst_masked(rule, ip, mask);
713         break;
714
715     case F_NW_PROTO:
716         cls_rule_set_nw_proto(rule, str_to_u32(value));
717         break;
718
719     case F_NW_TOS:
720         cls_rule_set_nw_tos(rule, str_to_u32(value));
721         break;
722
723     case F_TP_SRC:
724         cls_rule_set_tp_src(rule, htons(str_to_u32(value)));
725         break;
726
727     case F_TP_DST:
728         cls_rule_set_tp_dst(rule, htons(str_to_u32(value)));
729         break;
730
731     case F_ICMP_TYPE:
732         cls_rule_set_icmp_type(rule, str_to_u32(value));
733         break;
734
735     case F_ICMP_CODE:
736         cls_rule_set_icmp_code(rule, str_to_u32(value));
737         break;
738
739     case F_ARP_SHA:
740         str_to_mac(value, mac);
741         cls_rule_set_arp_sha(rule, mac);
742         break;
743
744     case F_ARP_THA:
745         str_to_mac(value, mac);
746         cls_rule_set_arp_tha(rule, mac);
747         break;
748
749     case F_IPV6_SRC:
750         str_to_ipv6(value, &ipv6, &ipv6_mask);
751         cls_rule_set_ipv6_src_masked(rule, &ipv6, &ipv6_mask);
752         break;
753
754     case F_IPV6_DST:
755         str_to_ipv6(value, &ipv6, &ipv6_mask);
756         cls_rule_set_ipv6_dst_masked(rule, &ipv6, &ipv6_mask);
757         break;
758
759     case F_ND_TARGET:
760         str_to_ipv6(value, &ipv6, NULL);
761         cls_rule_set_nd_target(rule, ipv6);
762         break;
763
764     case F_ND_SLL:
765         str_to_mac(value, mac);
766         cls_rule_set_arp_sha(rule, mac);
767         break;
768
769     case F_ND_TLL:
770         str_to_mac(value, mac);
771         cls_rule_set_arp_tha(rule, mac);
772         break;
773
774     case N_FIELDS:
775         NOT_REACHED();
776     }
777 }
778
779 static void
780 parse_reg_value(struct cls_rule *rule, int reg_idx, const char *value)
781 {
782     uint32_t reg_value, reg_mask;
783
784     if (!strcmp(value, "ANY") || !strcmp(value, "*")) {
785         cls_rule_set_reg_masked(rule, reg_idx, 0, 0);
786     } else if (sscanf(value, "%"SCNi32"/%"SCNi32,
787                       &reg_value, &reg_mask) == 2) {
788         cls_rule_set_reg_masked(rule, reg_idx, reg_value, reg_mask);
789     } else if (sscanf(value, "%"SCNi32, &reg_value)) {
790         cls_rule_set_reg(rule, reg_idx, reg_value);
791     } else {
792         ovs_fatal(0, "register fields must take the form <value> "
793                   "or <value>/<mask>");
794     }
795 }
796
797 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
798  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
799  * If 'actions' is specified, an action must be in 'string' and may be expanded
800  * or reallocated.
801  *
802  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
803  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
804  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'. */
805 void
806 parse_ofp_str(struct flow_mod *fm, int command, const char *str_, bool verbose)
807 {
808     enum {
809         F_OUT_PORT = 1 << 0,
810         F_ACTIONS = 1 << 1,
811         F_COOKIE = 1 << 2,
812         F_TIMEOUT = 1 << 3,
813         F_PRIORITY = 1 << 4
814     } fields;
815     char *string = xstrdup(str_);
816     char *save_ptr = NULL;
817     char *name;
818
819     switch (command) {
820     case -1:
821         fields = F_OUT_PORT;
822         break;
823
824     case OFPFC_ADD:
825         fields = F_ACTIONS | F_COOKIE | F_TIMEOUT | F_PRIORITY;
826         break;
827
828     case OFPFC_DELETE:
829         fields = F_OUT_PORT;
830         break;
831
832     case OFPFC_DELETE_STRICT:
833         fields = F_OUT_PORT | F_PRIORITY;
834         break;
835
836     case OFPFC_MODIFY:
837         fields = F_ACTIONS | F_COOKIE;
838         break;
839
840     case OFPFC_MODIFY_STRICT:
841         fields = F_ACTIONS | F_COOKIE | F_PRIORITY;
842         break;
843
844     default:
845         NOT_REACHED();
846     }
847
848     cls_rule_init_catchall(&fm->cr, OFP_DEFAULT_PRIORITY);
849     fm->cookie = htonll(0);
850     fm->table_id = 0xff;
851     fm->command = command;
852     fm->idle_timeout = OFP_FLOW_PERMANENT;
853     fm->hard_timeout = OFP_FLOW_PERMANENT;
854     fm->buffer_id = UINT32_MAX;
855     fm->out_port = OFPP_NONE;
856     fm->flags = 0;
857     if (fields & F_ACTIONS) {
858         struct ofpbuf actions;
859         char *act_str;
860
861         act_str = strstr(string, "action");
862         if (!act_str) {
863             ofp_fatal(str_, verbose, "must specify an action");
864         }
865         *act_str = '\0';
866
867         act_str = strchr(act_str + 1, '=');
868         if (!act_str) {
869             ofp_fatal(str_, verbose, "must specify an action");
870         }
871
872         act_str++;
873
874         ofpbuf_init(&actions, sizeof(union ofp_action));
875         str_to_action(act_str, &actions);
876         fm->actions = ofpbuf_steal_data(&actions);
877         fm->n_actions = actions.size / sizeof(union ofp_action);
878     } else {
879         fm->actions = NULL;
880         fm->n_actions = 0;
881     }
882     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
883          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
884         const struct protocol *p;
885
886         if (parse_protocol(name, &p)) {
887             cls_rule_set_dl_type(&fm->cr, htons(p->dl_type));
888             if (p->nw_proto) {
889                 cls_rule_set_nw_proto(&fm->cr, p->nw_proto);
890             }
891         } else {
892             const struct field *f;
893             char *value;
894
895             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
896             if (!value) {
897                 ofp_fatal(str_, verbose, "field %s missing value", name);
898             }
899
900             if (!strcmp(name, "table")) {
901                 fm->table_id = atoi(value);
902             } else if (!strcmp(name, "out_port")) {
903                 fm->out_port = atoi(value);
904             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
905                 fm->cr.priority = atoi(value);
906             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
907                 fm->idle_timeout = atoi(value);
908             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
909                 fm->hard_timeout = atoi(value);
910             } else if (fields & F_COOKIE && !strcmp(name, "cookie")) {
911                 fm->cookie = htonll(str_to_u64(value));
912             } else if (parse_field_name(name, &f)) {
913                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
914                     if (f->wildcard) {
915                         fm->cr.wc.wildcards |= f->wildcard;
916                         cls_rule_zero_wildcarded_fields(&fm->cr);
917                     } else if (f->index == F_NW_SRC) {
918                         cls_rule_set_nw_src_masked(&fm->cr, 0, 0);
919                     } else if (f->index == F_NW_DST) {
920                         cls_rule_set_nw_dst_masked(&fm->cr, 0, 0);
921                     } else if (f->index == F_IPV6_SRC) {
922                         cls_rule_set_ipv6_src_masked(&fm->cr,
923                                 &in6addr_any, &in6addr_any);
924                     } else if (f->index == F_IPV6_DST) {
925                         cls_rule_set_ipv6_dst_masked(&fm->cr,
926                                 &in6addr_any, &in6addr_any);
927                     } else if (f->index == F_DL_VLAN) {
928                         cls_rule_set_any_vid(&fm->cr);
929                     } else if (f->index == F_DL_VLAN_PCP) {
930                         cls_rule_set_any_pcp(&fm->cr);
931                     } else {
932                         NOT_REACHED();
933                     }
934                 } else {
935                     parse_field_value(&fm->cr, f->index, value);
936                 }
937             } else if (!strncmp(name, "reg", 3)
938                        && isdigit((unsigned char) name[3])) {
939                 unsigned int reg_idx = atoi(name + 3);
940                 if (reg_idx >= FLOW_N_REGS) {
941                     if (verbose) {
942                         fprintf(stderr, "%s:\n", str_);
943                     }
944                     ofp_fatal(str_, verbose, "only %d registers supported", FLOW_N_REGS);
945                 }
946                 parse_reg_value(&fm->cr, reg_idx, value);
947             } else if (!strcmp(name, "duration")
948                        || !strcmp(name, "n_packets")
949                        || !strcmp(name, "n_bytes")) {
950                 /* Ignore these, so that users can feed the output of
951                  * "ovs-ofctl dump-flows" back into commands that parse
952                  * flows. */
953             } else {
954                 ofp_fatal(str_, verbose, "unknown keyword %s", name);
955             }
956         }
957     }
958
959     free(string);
960 }
961
962 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
963  * (one of OFPFC_*) and appends the parsed OpenFlow message to 'packets'.
964  * '*cur_format' should initially contain the flow format currently configured
965  * on the connection; this function will add a message to change the flow
966  * format and update '*cur_format', if this is necessary to add the parsed
967  * flow. */
968 void
969 parse_ofp_flow_mod_str(struct list *packets, enum nx_flow_format *cur_format,
970                        bool *flow_mod_table_id, char *string, uint16_t command,
971                        bool verbose)
972 {
973     enum nx_flow_format min_format, next_format;
974     struct cls_rule rule_copy;
975     struct ofpbuf actions;
976     struct ofpbuf *ofm;
977     struct flow_mod fm;
978
979     ofpbuf_init(&actions, 64);
980     parse_ofp_str(&fm, command, string, verbose);
981
982     min_format = ofputil_min_flow_format(&fm.cr);
983     next_format = MAX(*cur_format, min_format);
984     if (next_format != *cur_format) {
985         struct ofpbuf *sff = ofputil_make_set_flow_format(next_format);
986         list_push_back(packets, &sff->list_node);
987         *cur_format = next_format;
988     }
989
990     /* Normalize a copy of the rule.  This ensures that non-normalized flows
991      * get logged but doesn't affect what gets sent to the switch, so that the
992      * switch can do whatever it likes with the flow. */
993     rule_copy = fm.cr;
994     ofputil_normalize_rule(&rule_copy, next_format);
995
996     if (fm.table_id != 0xff && !*flow_mod_table_id) {
997         struct ofpbuf *sff = ofputil_make_flow_mod_table_id(true);
998         list_push_back(packets, &sff->list_node);
999         *flow_mod_table_id = true;
1000     }
1001
1002     ofm = ofputil_encode_flow_mod(&fm, *cur_format, *flow_mod_table_id);
1003     list_push_back(packets, &ofm->list_node);
1004
1005     ofpbuf_uninit(&actions);
1006 }
1007
1008 /* Similar to parse_ofp_flow_mod_str(), except that the string is read from
1009  * 'stream' and the command is always OFPFC_ADD.  Returns false if end-of-file
1010  * is reached before reading a flow, otherwise true. */
1011 bool
1012 parse_ofp_flow_mod_file(struct list *packets,
1013                         enum nx_flow_format *cur, bool *flow_mod_table_id,
1014                         FILE *stream, uint16_t command)
1015 {
1016     struct ds s;
1017     bool ok;
1018
1019     ds_init(&s);
1020     ok = ds_get_preprocessed_line(&s, stream) == 0;
1021     if (ok) {
1022         parse_ofp_flow_mod_str(packets, cur, flow_mod_table_id,
1023                                ds_cstr(&s), command, true);
1024     }
1025     ds_destroy(&s);
1026
1027     return ok;
1028 }
1029
1030 void
1031 parse_ofp_flow_stats_request_str(struct flow_stats_request *fsr,
1032                                  bool aggregate, char *string)
1033 {
1034     struct flow_mod fm;
1035
1036     parse_ofp_str(&fm, -1, string, false);
1037     fsr->aggregate = aggregate;
1038     fsr->match = fm.cr;
1039     fsr->out_port = fm.out_port;
1040     fsr->table_id = fm.table_id;
1041 }