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