b29b34a79175fef698c080080ceab742faeaf9be
[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 struct ofp_action_output *
257 put_output_action(struct ofpbuf *b, uint16_t port)
258 {
259     struct ofp_action_output *oao;
260
261     oao = ofputil_put_OFPAT_OUTPUT(b);
262     oao->port = htons(port);
263     return oao;
264 }
265
266 static void
267 parse_enqueue(struct ofpbuf *b, char *arg)
268 {
269     char *sp = NULL;
270     char *port = strtok_r(arg, ":q", &sp);
271     char *queue = strtok_r(NULL, "", &sp);
272     struct ofp_action_enqueue *oae;
273
274     if (port == NULL || queue == NULL) {
275         ovs_fatal(0, "\"enqueue\" syntax is \"enqueue:PORT:QUEUE\"");
276     }
277
278     oae = ofputil_put_OFPAT_ENQUEUE(b);
279     oae->port = htons(str_to_u32(port));
280     oae->queue_id = htonl(str_to_u32(queue));
281 }
282
283 static void
284 parse_output(struct ofpbuf *b, char *arg)
285 {
286     if (strchr(arg, '[')) {
287         struct nx_action_output_reg *naor;
288         int ofs, n_bits;
289         uint32_t src;
290
291         nxm_parse_field_bits(arg, &src, &ofs, &n_bits);
292
293         naor = ofputil_put_NXAST_OUTPUT_REG(b);
294         naor->ofs_nbits = nxm_encode_ofs_nbits(ofs, n_bits);
295         naor->src = htonl(src);
296         naor->max_len = htons(UINT16_MAX);
297     } else {
298         put_output_action(b, str_to_u32(arg));
299     }
300 }
301
302 static void
303 parse_resubmit(struct ofpbuf *b, char *arg)
304 {
305     struct nx_action_resubmit *nar;
306     char *in_port_s, *table_s;
307     uint16_t in_port;
308     uint8_t table;
309
310     in_port_s = strsep(&arg, ",");
311     if (in_port_s && in_port_s[0]) {
312         if (!ofputil_port_from_string(in_port_s, &in_port)) {
313             in_port = str_to_u32(in_port_s);
314         }
315     } else {
316         in_port = OFPP_IN_PORT;
317     }
318
319     table_s = strsep(&arg, ",");
320     table = table_s && table_s[0] ? str_to_u32(table_s) : 255;
321
322     if (in_port == OFPP_IN_PORT && table == 255) {
323         ovs_fatal(0, "at least one \"in_port\" or \"table\" must be specified "
324                   " on resubmit");
325     }
326
327     if (in_port != OFPP_IN_PORT && table == 255) {
328         nar = ofputil_put_NXAST_RESUBMIT(b);
329     } else {
330         nar = ofputil_put_NXAST_RESUBMIT_TABLE(b);
331         nar->table = table;
332     }
333     nar->in_port = htons(in_port);
334 }
335
336 static void
337 parse_set_tunnel(struct ofpbuf *b, const char *arg)
338 {
339     uint64_t tun_id = str_to_u64(arg);
340     if (tun_id > UINT32_MAX) {
341         ofputil_put_NXAST_SET_TUNNEL64(b)->tun_id = htonll(tun_id);
342     } else {
343         ofputil_put_NXAST_SET_TUNNEL(b)->tun_id = htonl(tun_id);
344     }
345 }
346
347 static void
348 parse_note(struct ofpbuf *b, const char *arg)
349 {
350     size_t start_ofs = b->size;
351     struct nx_action_note *nan;
352     int remainder;
353     size_t len;
354
355     nan = ofputil_put_NXAST_NOTE(b);
356
357     b->size -= sizeof nan->note;
358     while (*arg != '\0') {
359         uint8_t byte;
360         bool ok;
361
362         if (*arg == '.') {
363             arg++;
364         }
365         if (*arg == '\0') {
366             break;
367         }
368
369         byte = hexits_value(arg, 2, &ok);
370         if (!ok) {
371             ovs_fatal(0, "bad hex digit in `note' argument");
372         }
373         ofpbuf_put(b, &byte, 1);
374
375         arg += 2;
376     }
377
378     len = b->size - start_ofs;
379     remainder = len % OFP_ACTION_ALIGN;
380     if (remainder) {
381         ofpbuf_put_zeros(b, OFP_ACTION_ALIGN - remainder);
382     }
383     nan = (struct nx_action_note *)((char *)b->data + start_ofs);
384     nan->len = htons(b->size - start_ofs);
385 }
386
387 static void
388 parse_named_action(enum ofputil_action_code code, struct ofpbuf *b, char *arg)
389 {
390     struct ofp_action_dl_addr *oada;
391     struct ofp_action_vlan_pcp *oavp;
392     struct ofp_action_vlan_vid *oavv;
393     struct ofp_action_nw_addr *oana;
394     struct ofp_action_tp_port *oata;
395
396     switch (code) {
397     case OFPUTIL_OFPAT_OUTPUT:
398         parse_output(b, arg);
399         break;
400
401     case OFPUTIL_OFPAT_SET_VLAN_VID:
402         oavv = ofputil_put_OFPAT_SET_VLAN_VID(b);
403         oavv->vlan_vid = htons(str_to_u32(arg));
404         break;
405
406     case OFPUTIL_OFPAT_SET_VLAN_PCP:
407         oavp = ofputil_put_OFPAT_SET_VLAN_PCP(b);
408         oavp->vlan_pcp = str_to_u32(arg);
409         break;
410
411     case OFPUTIL_OFPAT_STRIP_VLAN:
412         ofputil_put_OFPAT_STRIP_VLAN(b);
413         break;
414
415     case OFPUTIL_OFPAT_SET_DL_SRC:
416     case OFPUTIL_OFPAT_SET_DL_DST:
417         oada = ofputil_put_action(code, b);
418         str_to_mac(arg, oada->dl_addr);
419         break;
420
421     case OFPUTIL_OFPAT_SET_NW_SRC:
422     case OFPUTIL_OFPAT_SET_NW_DST:
423         oana = ofputil_put_action(code, b);
424         str_to_ip(arg, &oana->nw_addr, NULL);
425         break;
426
427     case OFPUTIL_OFPAT_SET_NW_TOS:
428         ofputil_put_OFPAT_SET_NW_TOS(b)->nw_tos = str_to_u32(arg);
429         break;
430
431     case OFPUTIL_OFPAT_SET_TP_SRC:
432     case OFPUTIL_OFPAT_SET_TP_DST:
433         oata = ofputil_put_action(code, b);
434         oata->tp_port = htons(str_to_u32(arg));
435         break;
436
437     case OFPUTIL_OFPAT_ENQUEUE:
438         parse_enqueue(b, arg);
439         break;
440
441     case OFPUTIL_NXAST_RESUBMIT:
442         parse_resubmit(b, arg);
443         break;
444
445     case OFPUTIL_NXAST_SET_TUNNEL:
446         parse_set_tunnel(b, arg);
447         break;
448
449     case OFPUTIL_NXAST_SET_QUEUE:
450         ofputil_put_NXAST_SET_QUEUE(b)->queue_id = htonl(str_to_u32(arg));
451         break;
452
453     case OFPUTIL_NXAST_POP_QUEUE:
454         ofputil_put_NXAST_POP_QUEUE(b);
455         break;
456
457     case OFPUTIL_NXAST_REG_MOVE:
458         nxm_parse_reg_move(ofputil_put_NXAST_REG_MOVE(b), arg);
459         break;
460
461     case OFPUTIL_NXAST_REG_LOAD:
462         nxm_parse_reg_load(ofputil_put_NXAST_REG_LOAD(b), arg);
463         break;
464
465     case OFPUTIL_NXAST_NOTE:
466         parse_note(b, arg);
467         break;
468
469     case OFPUTIL_NXAST_SET_TUNNEL64:
470         ofputil_put_NXAST_SET_TUNNEL64(b)->tun_id = htonll(str_to_u64(arg));
471         break;
472
473     case OFPUTIL_NXAST_MULTIPATH:
474         multipath_parse(ofputil_put_NXAST_MULTIPATH(b), arg);
475         break;
476
477     case OFPUTIL_NXAST_AUTOPATH:
478         autopath_parse(ofputil_put_NXAST_AUTOPATH(b), arg);
479         break;
480
481     case OFPUTIL_NXAST_BUNDLE:
482         bundle_parse(b, arg);
483         break;
484
485     case OFPUTIL_NXAST_BUNDLE_LOAD:
486         bundle_parse_load(b, arg);
487         break;
488
489     case OFPUTIL_NXAST_RESUBMIT_TABLE:
490     case OFPUTIL_NXAST_OUTPUT_REG:
491         NOT_REACHED();
492     }
493 }
494
495 static void
496 str_to_action(char *str, struct ofpbuf *b)
497 {
498     bool drop = false;
499     int n_actions;
500     char *pos;
501
502     pos = str;
503     n_actions = 0;
504     for (;;) {
505         char empty_string[] = "";
506         char *act, *arg;
507         size_t actlen;
508         uint16_t port;
509         int code;
510
511         pos += strspn(pos, ", \t\r\n");
512         if (*pos == '\0') {
513             break;
514         }
515
516         if (drop) {
517             ovs_fatal(0, "Drop actions must not be followed by other actions");
518         }
519
520         act = pos;
521         actlen = strcspn(pos, ":(, \t\r\n");
522         if (act[actlen] == ':') {
523             /* The argument can be separated by a colon. */
524             size_t arglen;
525
526             arg = act + actlen + 1;
527             arglen = strcspn(arg, ", \t\r\n");
528             pos = arg + arglen + (arg[arglen] != '\0');
529             arg[arglen] = '\0';
530         } else if (act[actlen] == '(') {
531             /* The argument can be surrounded by balanced parentheses.  The
532              * outermost set of parentheses is removed. */
533             int level = 1;
534             size_t arglen;
535
536             arg = act + actlen + 1;
537             for (arglen = 0; level > 0; arglen++) {
538                 switch (arg[arglen]) {
539                 case '\0':
540                     ovs_fatal(0, "unbalanced parentheses in argument to %s "
541                               "action", act);
542
543                 case '(':
544                     level++;
545                     break;
546
547                 case ')':
548                     level--;
549                     break;
550                 }
551             }
552             arg[arglen - 1] = '\0';
553             pos = arg + arglen;
554         } else {
555             /* There might be no argument at all. */
556             arg = empty_string;
557             pos = act + actlen + (act[actlen] != '\0');
558         }
559         act[actlen] = '\0';
560
561         code = ofputil_action_code_from_name(act);
562         if (code >= 0) {
563             parse_named_action(code, b, arg);
564         } else if (!strcasecmp(act, "drop")) {
565             /* A drop action in OpenFlow occurs by just not setting
566              * an action. */
567             drop = true;
568             if (n_actions) {
569                 ovs_fatal(0, "Drop actions must not be preceded by other "
570                           "actions");
571             }
572         } else if (!strcasecmp(act, "CONTROLLER")) {
573             struct ofp_action_output *oao;
574             oao = put_output_action(b, OFPP_CONTROLLER);
575
576             /* Unless a numeric argument is specified, we send the whole
577              * packet to the controller. */
578             if (arg[0] && (strspn(arg, "0123456789") == strlen(arg))) {
579                oao->max_len = htons(str_to_u32(arg));
580             } else {
581                 oao->max_len = htons(UINT16_MAX);
582             }
583         } else if (ofputil_port_from_string(act, &port)) {
584             put_output_action(b, port);
585         } else {
586             ovs_fatal(0, "Unknown action: %s", act);
587         }
588         n_actions++;
589     }
590 }
591
592 struct protocol {
593     const char *name;
594     uint16_t dl_type;
595     uint8_t nw_proto;
596 };
597
598 static bool
599 parse_protocol(const char *name, const struct protocol **p_out)
600 {
601     static const struct protocol protocols[] = {
602         { "ip", ETH_TYPE_IP, 0 },
603         { "arp", ETH_TYPE_ARP, 0 },
604         { "icmp", ETH_TYPE_IP, IPPROTO_ICMP },
605         { "tcp", ETH_TYPE_IP, IPPROTO_TCP },
606         { "udp", ETH_TYPE_IP, IPPROTO_UDP },
607         { "ipv6", ETH_TYPE_IPV6, 0 },
608         { "ip6", ETH_TYPE_IPV6, 0 },
609         { "icmp6", ETH_TYPE_IPV6, IPPROTO_ICMPV6 },
610         { "tcp6", ETH_TYPE_IPV6, IPPROTO_TCP },
611         { "udp6", ETH_TYPE_IPV6, IPPROTO_UDP },
612     };
613     const struct protocol *p;
614
615     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
616         if (!strcmp(p->name, name)) {
617             *p_out = p;
618             return true;
619         }
620     }
621     *p_out = NULL;
622     return false;
623 }
624
625 BUILD_ASSERT_DECL(FLOW_WC_SEQ == 1);
626 #define FIELDS                                              \
627     FIELD(F_TUN_ID,      "tun_id",      0)                  \
628     FIELD(F_IN_PORT,     "in_port",     FWW_IN_PORT)        \
629     FIELD(F_DL_VLAN,     "dl_vlan",     0)                  \
630     FIELD(F_DL_VLAN_PCP, "dl_vlan_pcp", 0)                  \
631     FIELD(F_VLAN_TCI,    "vlan_tci",    0)                  \
632     FIELD(F_DL_SRC,      "dl_src",      FWW_DL_SRC)         \
633     FIELD(F_DL_DST,      "dl_dst",      FWW_DL_DST | FWW_ETH_MCAST) \
634     FIELD(F_DL_TYPE,     "dl_type",     FWW_DL_TYPE)        \
635     FIELD(F_NW_SRC,      "nw_src",      0)                  \
636     FIELD(F_NW_DST,      "nw_dst",      0)                  \
637     FIELD(F_NW_PROTO,    "nw_proto",    FWW_NW_PROTO)       \
638     FIELD(F_NW_TOS,      "nw_tos",      FWW_NW_TOS)         \
639     FIELD(F_TP_SRC,      "tp_src",      FWW_TP_SRC)         \
640     FIELD(F_TP_DST,      "tp_dst",      FWW_TP_DST)         \
641     FIELD(F_ICMP_TYPE,   "icmp_type",   FWW_TP_SRC)         \
642     FIELD(F_ICMP_CODE,   "icmp_code",   FWW_TP_DST)         \
643     FIELD(F_ARP_SHA,     "arp_sha",     FWW_ARP_SHA)        \
644     FIELD(F_ARP_THA,     "arp_tha",     FWW_ARP_THA)        \
645     FIELD(F_IPV6_SRC,    "ipv6_src",    0)                  \
646     FIELD(F_IPV6_DST,    "ipv6_dst",    0)                  \
647     FIELD(F_ND_TARGET,   "nd_target",   FWW_ND_TARGET)      \
648     FIELD(F_ND_SLL,      "nd_sll",      FWW_ARP_SHA)        \
649     FIELD(F_ND_TLL,      "nd_tll",      FWW_ARP_THA)
650
651 enum field_index {
652 #define FIELD(ENUM, NAME, WILDCARD) ENUM,
653     FIELDS
654 #undef FIELD
655     N_FIELDS
656 };
657
658 struct field {
659     enum field_index index;
660     const char *name;
661     flow_wildcards_t wildcard;  /* FWW_* bit. */
662 };
663
664 static void
665 ofp_fatal(const char *flow, bool verbose, const char *format, ...)
666 {
667     va_list args;
668
669     if (verbose) {
670         fprintf(stderr, "%s:\n", flow);
671     }
672
673     va_start(args, format);
674     ovs_fatal_valist(0, format, args);
675 }
676
677 static bool
678 parse_field_name(const char *name, const struct field **f_out)
679 {
680     static const struct field fields[N_FIELDS] = {
681 #define FIELD(ENUM, NAME, WILDCARD) { ENUM, NAME, WILDCARD },
682         FIELDS
683 #undef FIELD
684     };
685     const struct field *f;
686
687     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
688         if (!strcmp(f->name, name)) {
689             *f_out = f;
690             return true;
691         }
692     }
693     *f_out = NULL;
694     return false;
695 }
696
697 static void
698 parse_field_value(struct cls_rule *rule, enum field_index index,
699                   const char *value)
700 {
701     uint8_t mac[ETH_ADDR_LEN], mac_mask[ETH_ADDR_LEN];
702     ovs_be64 tun_id, tun_mask;
703     ovs_be32 ip, mask;
704     ovs_be16 tci, tci_mask;
705     struct in6_addr ipv6, ipv6_mask;
706     uint16_t port_no;
707
708     switch (index) {
709     case F_TUN_ID:
710         str_to_tun_id(value, &tun_id, &tun_mask);
711         cls_rule_set_tun_id_masked(rule, tun_id, tun_mask);
712         break;
713
714     case F_IN_PORT:
715         if (!ofputil_port_from_string(value, &port_no)) {
716             port_no = atoi(value);
717         }
718         cls_rule_set_in_port(rule, port_no);
719         break;
720
721     case F_DL_VLAN:
722         cls_rule_set_dl_vlan(rule, htons(str_to_u32(value)));
723         break;
724
725     case F_DL_VLAN_PCP:
726         cls_rule_set_dl_vlan_pcp(rule, str_to_u32(value));
727         break;
728
729     case F_VLAN_TCI:
730         str_to_vlan_tci(value, &tci, &tci_mask);
731         cls_rule_set_dl_tci_masked(rule, tci, tci_mask);
732         break;
733
734     case F_DL_SRC:
735         str_to_mac(value, mac);
736         cls_rule_set_dl_src(rule, mac);
737         break;
738
739     case F_DL_DST:
740         str_to_eth_dst(value, mac, mac_mask);
741         cls_rule_set_dl_dst_masked(rule, mac, mac_mask);
742         break;
743
744     case F_DL_TYPE:
745         cls_rule_set_dl_type(rule, htons(str_to_u32(value)));
746         break;
747
748     case F_NW_SRC:
749         str_to_ip(value, &ip, &mask);
750         cls_rule_set_nw_src_masked(rule, ip, mask);
751         break;
752
753     case F_NW_DST:
754         str_to_ip(value, &ip, &mask);
755         cls_rule_set_nw_dst_masked(rule, ip, mask);
756         break;
757
758     case F_NW_PROTO:
759         cls_rule_set_nw_proto(rule, str_to_u32(value));
760         break;
761
762     case F_NW_TOS:
763         cls_rule_set_nw_tos(rule, str_to_u32(value));
764         break;
765
766     case F_TP_SRC:
767         cls_rule_set_tp_src(rule, htons(str_to_u32(value)));
768         break;
769
770     case F_TP_DST:
771         cls_rule_set_tp_dst(rule, htons(str_to_u32(value)));
772         break;
773
774     case F_ICMP_TYPE:
775         cls_rule_set_icmp_type(rule, str_to_u32(value));
776         break;
777
778     case F_ICMP_CODE:
779         cls_rule_set_icmp_code(rule, str_to_u32(value));
780         break;
781
782     case F_ARP_SHA:
783         str_to_mac(value, mac);
784         cls_rule_set_arp_sha(rule, mac);
785         break;
786
787     case F_ARP_THA:
788         str_to_mac(value, mac);
789         cls_rule_set_arp_tha(rule, mac);
790         break;
791
792     case F_IPV6_SRC:
793         str_to_ipv6(value, &ipv6, &ipv6_mask);
794         cls_rule_set_ipv6_src_masked(rule, &ipv6, &ipv6_mask);
795         break;
796
797     case F_IPV6_DST:
798         str_to_ipv6(value, &ipv6, &ipv6_mask);
799         cls_rule_set_ipv6_dst_masked(rule, &ipv6, &ipv6_mask);
800         break;
801
802     case F_ND_TARGET:
803         str_to_ipv6(value, &ipv6, NULL);
804         cls_rule_set_nd_target(rule, &ipv6);
805         break;
806
807     case F_ND_SLL:
808         str_to_mac(value, mac);
809         cls_rule_set_arp_sha(rule, mac);
810         break;
811
812     case F_ND_TLL:
813         str_to_mac(value, mac);
814         cls_rule_set_arp_tha(rule, mac);
815         break;
816
817     case N_FIELDS:
818         NOT_REACHED();
819     }
820 }
821
822 static void
823 parse_reg_value(struct cls_rule *rule, int reg_idx, const char *value)
824 {
825     /* This uses an oversized destination field (64 bits when 32 bits would do)
826      * because some sscanf() implementations truncate the range of %i
827      * directives, so that e.g. "%"SCNi16 interprets input of "0xfedc" as a
828      * value of 0x7fff.  The other alternatives are to allow only a single
829      * radix (e.g. decimal or hexadecimal) or to write more sophisticated
830      * parsers. */
831     unsigned long long int reg_value, reg_mask;
832
833     if (!strcmp(value, "ANY") || !strcmp(value, "*")) {
834         cls_rule_set_reg_masked(rule, reg_idx, 0, 0);
835     } else if (sscanf(value, "%lli/%lli",
836                       &reg_value, &reg_mask) == 2) {
837         cls_rule_set_reg_masked(rule, reg_idx, reg_value, reg_mask);
838     } else if (sscanf(value, "%lli", &reg_value)) {
839         cls_rule_set_reg(rule, reg_idx, reg_value);
840     } else {
841         ovs_fatal(0, "register fields must take the form <value> "
842                   "or <value>/<mask>");
843     }
844 }
845
846 /* Convert 'str_' (as described in the Flow Syntax section of the ovs-ofctl man
847  * page) into 'fm' for sending the specified flow_mod 'command' to a switch.
848  * If 'actions' is specified, an action must be in 'string' and may be expanded
849  * or reallocated.
850  *
851  * To parse syntax for an OFPT_FLOW_MOD (or NXT_FLOW_MOD), use an OFPFC_*
852  * constant for 'command'.  To parse syntax for an OFPST_FLOW or
853  * OFPST_AGGREGATE (or NXST_FLOW or NXST_AGGREGATE), use -1 for 'command'. */
854 void
855 parse_ofp_str(struct ofputil_flow_mod *fm, int command, const char *str_,
856               bool verbose)
857 {
858     enum {
859         F_OUT_PORT = 1 << 0,
860         F_ACTIONS = 1 << 1,
861         F_COOKIE = 1 << 2,
862         F_TIMEOUT = 1 << 3,
863         F_PRIORITY = 1 << 4
864     } fields;
865     char *string = xstrdup(str_);
866     char *save_ptr = NULL;
867     char *name;
868
869     switch (command) {
870     case -1:
871         fields = F_OUT_PORT;
872         break;
873
874     case OFPFC_ADD:
875         fields = F_ACTIONS | F_COOKIE | F_TIMEOUT | F_PRIORITY;
876         break;
877
878     case OFPFC_DELETE:
879         fields = F_OUT_PORT;
880         break;
881
882     case OFPFC_DELETE_STRICT:
883         fields = F_OUT_PORT | F_PRIORITY;
884         break;
885
886     case OFPFC_MODIFY:
887         fields = F_ACTIONS | F_COOKIE;
888         break;
889
890     case OFPFC_MODIFY_STRICT:
891         fields = F_ACTIONS | F_COOKIE | F_PRIORITY;
892         break;
893
894     default:
895         NOT_REACHED();
896     }
897
898     cls_rule_init_catchall(&fm->cr, OFP_DEFAULT_PRIORITY);
899     fm->cookie = htonll(0);
900     fm->table_id = 0xff;
901     fm->command = command;
902     fm->idle_timeout = OFP_FLOW_PERMANENT;
903     fm->hard_timeout = OFP_FLOW_PERMANENT;
904     fm->buffer_id = UINT32_MAX;
905     fm->out_port = OFPP_NONE;
906     fm->flags = 0;
907     if (fields & F_ACTIONS) {
908         struct ofpbuf actions;
909         char *act_str;
910
911         act_str = strstr(string, "action");
912         if (!act_str) {
913             ofp_fatal(str_, verbose, "must specify an action");
914         }
915         *act_str = '\0';
916
917         act_str = strchr(act_str + 1, '=');
918         if (!act_str) {
919             ofp_fatal(str_, verbose, "must specify an action");
920         }
921
922         act_str++;
923
924         ofpbuf_init(&actions, sizeof(union ofp_action));
925         str_to_action(act_str, &actions);
926         fm->actions = ofpbuf_steal_data(&actions);
927         fm->n_actions = actions.size / sizeof(union ofp_action);
928     } else {
929         fm->actions = NULL;
930         fm->n_actions = 0;
931     }
932     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
933          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
934         const struct protocol *p;
935
936         if (parse_protocol(name, &p)) {
937             cls_rule_set_dl_type(&fm->cr, htons(p->dl_type));
938             if (p->nw_proto) {
939                 cls_rule_set_nw_proto(&fm->cr, p->nw_proto);
940             }
941         } else {
942             const struct field *f;
943             char *value;
944
945             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
946             if (!value) {
947                 ofp_fatal(str_, verbose, "field %s missing value", name);
948             }
949
950             if (!strcmp(name, "table")) {
951                 fm->table_id = atoi(value);
952             } else if (!strcmp(name, "out_port")) {
953                 fm->out_port = atoi(value);
954             } else if (fields & F_PRIORITY && !strcmp(name, "priority")) {
955                 fm->cr.priority = atoi(value);
956             } else if (fields & F_TIMEOUT && !strcmp(name, "idle_timeout")) {
957                 fm->idle_timeout = atoi(value);
958             } else if (fields & F_TIMEOUT && !strcmp(name, "hard_timeout")) {
959                 fm->hard_timeout = atoi(value);
960             } else if (fields & F_COOKIE && !strcmp(name, "cookie")) {
961                 fm->cookie = htonll(str_to_u64(value));
962             } else if (parse_field_name(name, &f)) {
963                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
964                     if (f->wildcard) {
965                         fm->cr.wc.wildcards |= f->wildcard;
966                         cls_rule_zero_wildcarded_fields(&fm->cr);
967                     } else if (f->index == F_NW_SRC) {
968                         cls_rule_set_nw_src_masked(&fm->cr, 0, 0);
969                     } else if (f->index == F_NW_DST) {
970                         cls_rule_set_nw_dst_masked(&fm->cr, 0, 0);
971                     } else if (f->index == F_IPV6_SRC) {
972                         cls_rule_set_ipv6_src_masked(&fm->cr,
973                                 &in6addr_any, &in6addr_any);
974                     } else if (f->index == F_IPV6_DST) {
975                         cls_rule_set_ipv6_dst_masked(&fm->cr,
976                                 &in6addr_any, &in6addr_any);
977                     } else if (f->index == F_DL_VLAN) {
978                         cls_rule_set_any_vid(&fm->cr);
979                     } else if (f->index == F_DL_VLAN_PCP) {
980                         cls_rule_set_any_pcp(&fm->cr);
981                     } else {
982                         NOT_REACHED();
983                     }
984                 } else {
985                     parse_field_value(&fm->cr, f->index, value);
986                 }
987             } else if (!strncmp(name, "reg", 3)
988                        && isdigit((unsigned char) name[3])) {
989                 unsigned int reg_idx = atoi(name + 3);
990                 if (reg_idx >= FLOW_N_REGS) {
991                     if (verbose) {
992                         fprintf(stderr, "%s:\n", str_);
993                     }
994                     ofp_fatal(str_, verbose, "only %d registers supported", FLOW_N_REGS);
995                 }
996                 parse_reg_value(&fm->cr, reg_idx, value);
997             } else if (!strcmp(name, "duration")
998                        || !strcmp(name, "n_packets")
999                        || !strcmp(name, "n_bytes")) {
1000                 /* Ignore these, so that users can feed the output of
1001                  * "ovs-ofctl dump-flows" back into commands that parse
1002                  * flows. */
1003             } else {
1004                 ofp_fatal(str_, verbose, "unknown keyword %s", name);
1005             }
1006         }
1007     }
1008
1009     free(string);
1010 }
1011
1012 /* Parses 'string' as an OFPT_FLOW_MOD or NXT_FLOW_MOD with command 'command'
1013  * (one of OFPFC_*) and appends the parsed OpenFlow message to 'packets'.
1014  * '*cur_format' should initially contain the flow format currently configured
1015  * on the connection; this function will add a message to change the flow
1016  * format and update '*cur_format', if this is necessary to add the parsed
1017  * flow. */
1018 void
1019 parse_ofp_flow_mod_str(struct list *packets, enum nx_flow_format *cur_format,
1020                        bool *flow_mod_table_id, char *string, uint16_t command,
1021                        bool verbose)
1022 {
1023     enum nx_flow_format min_format, next_format;
1024     struct cls_rule rule_copy;
1025     struct ofpbuf actions;
1026     struct ofpbuf *ofm;
1027     struct ofputil_flow_mod fm;
1028
1029     ofpbuf_init(&actions, 64);
1030     parse_ofp_str(&fm, command, string, verbose);
1031
1032     min_format = ofputil_min_flow_format(&fm.cr);
1033     next_format = MAX(*cur_format, min_format);
1034     if (next_format != *cur_format) {
1035         struct ofpbuf *sff = ofputil_make_set_flow_format(next_format);
1036         list_push_back(packets, &sff->list_node);
1037         *cur_format = next_format;
1038     }
1039
1040     /* Normalize a copy of the rule.  This ensures that non-normalized flows
1041      * get logged but doesn't affect what gets sent to the switch, so that the
1042      * switch can do whatever it likes with the flow. */
1043     rule_copy = fm.cr;
1044     ofputil_normalize_rule(&rule_copy, next_format);
1045
1046     if (fm.table_id != 0xff && !*flow_mod_table_id) {
1047         struct ofpbuf *sff = ofputil_make_flow_mod_table_id(true);
1048         list_push_back(packets, &sff->list_node);
1049         *flow_mod_table_id = true;
1050     }
1051
1052     ofm = ofputil_encode_flow_mod(&fm, *cur_format, *flow_mod_table_id);
1053     list_push_back(packets, &ofm->list_node);
1054
1055     ofpbuf_uninit(&actions);
1056 }
1057
1058 /* Similar to parse_ofp_flow_mod_str(), except that the string is read from
1059  * 'stream' and the command is always OFPFC_ADD.  Returns false if end-of-file
1060  * is reached before reading a flow, otherwise true. */
1061 bool
1062 parse_ofp_flow_mod_file(struct list *packets,
1063                         enum nx_flow_format *cur, bool *flow_mod_table_id,
1064                         FILE *stream, uint16_t command)
1065 {
1066     struct ds s;
1067     bool ok;
1068
1069     ds_init(&s);
1070     ok = ds_get_preprocessed_line(&s, stream) == 0;
1071     if (ok) {
1072         parse_ofp_flow_mod_str(packets, cur, flow_mod_table_id,
1073                                ds_cstr(&s), command, true);
1074     }
1075     ds_destroy(&s);
1076
1077     return ok;
1078 }
1079
1080 void
1081 parse_ofp_flow_stats_request_str(struct ofputil_flow_stats_request *fsr,
1082                                  bool aggregate, char *string)
1083 {
1084     struct ofputil_flow_mod fm;
1085
1086     parse_ofp_str(&fm, -1, string, false);
1087     fsr->aggregate = aggregate;
1088     fsr->match = fm.cr;
1089     fsr->out_port = fm.out_port;
1090     fsr->table_id = fm.table_id;
1091 }