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