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