Add support for vendor-defined and variable-length actions.
[sliver-openvswitch.git] / utilities / dpctl.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include <arpa/inet.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <sys/time.h>
46
47 #ifdef HAVE_NETLINK
48 #include "netdev.h"
49 #include "netlink.h"
50 #include "openflow-netlink.h"
51 #endif
52
53 #include "command-line.h"
54 #include "compiler.h"
55 #include "dpif.h"
56 #include "nicira-ext.h"
57 #include "ofp-print.h"
58 #include "ofpbuf.h"
59 #include "openflow.h"
60 #include "packets.h"
61 #include "random.h"
62 #include "socket-util.h"
63 #include "timeval.h"
64 #include "util.h"
65 #include "vconn-ssl.h"
66 #include "vconn.h"
67
68 #include "vlog.h"
69 #define THIS_MODULE VLM_dpctl
70
71 #define DEFAULT_IDLE_TIMEOUT 60
72
73 /* Maximum size of action buffer for adding and modify flows */
74 #define MAX_ACT_LEN 60
75
76 #define MOD_PORT_CMD_UP      "up"
77 #define MOD_PORT_CMD_DOWN    "down"
78 #define MOD_PORT_CMD_FLOOD   "flood"
79 #define MOD_PORT_CMD_NOFLOOD "noflood"
80
81
82 /* Settings that may be configured by the user. */
83 struct settings {
84     bool strict;        /* Use strict matching for flow mod commands */
85 };
86
87 struct command {
88     const char *name;
89     int min_args;
90     int max_args;
91     void (*handler)(const struct settings *, int argc, char *argv[]);
92 };
93
94 static struct command all_commands[];
95
96 static void usage(void) NO_RETURN;
97 static void parse_options(int argc, char *argv[], struct settings *);
98
99 int main(int argc, char *argv[])
100 {
101     struct settings s;
102     struct command *p;
103
104     set_program_name(argv[0]);
105     time_init();
106     vlog_init();
107     parse_options(argc, argv, &s);
108     signal(SIGPIPE, SIG_IGN);
109
110     argc -= optind;
111     argv += optind;
112     if (argc < 1)
113         ofp_fatal(0, "missing command name; use --help for help");
114
115     for (p = all_commands; p->name != NULL; p++) {
116         if (!strcmp(p->name, argv[0])) {
117             int n_arg = argc - 1;
118             if (n_arg < p->min_args)
119                 ofp_fatal(0, "'%s' command requires at least %d arguments",
120                           p->name, p->min_args);
121             else if (n_arg > p->max_args)
122                 ofp_fatal(0, "'%s' command takes at most %d arguments",
123                           p->name, p->max_args);
124             else {
125                 p->handler(&s, argc, argv);
126                 exit(0);
127             }
128         }
129     }
130     ofp_fatal(0, "unknown command '%s'; use --help for help", argv[0]);
131
132     return 0;
133 }
134
135 static void
136 parse_options(int argc, char *argv[], struct settings *s)
137 {
138     enum {
139         OPT_STRICT = UCHAR_MAX + 1
140     };
141     static struct option long_options[] = {
142         {"timeout", required_argument, 0, 't'},
143         {"verbose", optional_argument, 0, 'v'},
144         {"strict", no_argument, 0, OPT_STRICT},
145         {"help", no_argument, 0, 'h'},
146         {"version", no_argument, 0, 'V'},
147         VCONN_SSL_LONG_OPTIONS
148         {0, 0, 0, 0},
149     };
150     char *short_options = long_options_to_short_options(long_options);
151
152     /* Set defaults that we can figure out before parsing options. */
153     s->strict = false;
154
155     for (;;) {
156         unsigned long int timeout;
157         int c;
158
159         c = getopt_long(argc, argv, short_options, long_options, NULL);
160         if (c == -1) {
161             break;
162         }
163
164         switch (c) {
165         case 't':
166             timeout = strtoul(optarg, NULL, 10);
167             if (timeout <= 0) {
168                 ofp_fatal(0, "value %s on -t or --timeout is not at least 1",
169                           optarg);
170             } else {
171                 time_alarm(timeout);
172             }
173             break;
174
175         case 'h':
176             usage();
177
178         case 'V':
179             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
180             exit(EXIT_SUCCESS);
181
182         case 'v':
183             vlog_set_verbosity(optarg);
184             break;
185
186         case OPT_STRICT:
187             s->strict = true;
188             break;
189
190         VCONN_SSL_OPTION_HANDLERS
191
192         case '?':
193             exit(EXIT_FAILURE);
194
195         default:
196             abort();
197         }
198     }
199     free(short_options);
200 }
201
202 static void
203 usage(void)
204 {
205     printf("%s: OpenFlow switch management utility\n"
206            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
207 #ifdef HAVE_NETLINK
208            "\nFor local datapaths only:\n"
209            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
210            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
211            "  addif nl:DP_ID IFACE...     add each IFACE as a port on DP_ID\n"
212            "  delif nl:DP_ID IFACE...     delete each IFACE from DP_ID\n"
213 #endif
214            "\nFor local datapaths and remote switches:\n"
215            "  show SWITCH                 show basic information\n"
216            "  status SWITCH [KEY]         report statistics (about KEY)\n"
217            "  dump-desc SWITCH            print switch description\n"
218            "  dump-tables SWITCH          print table stats\n"
219            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
220            "  dump-ports SWITCH           print port statistics\n"
221            "  dump-flows SWITCH           print all flow entries\n"
222            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
223            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
224            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
225            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
226            "  add-flows SWITCH FILE       add flows from FILE\n"
227            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
228            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
229            "  monitor SWITCH              print packets received from SWITCH\n"
230            "\nFor local datapaths, remote switches, and controllers:\n"
231            "  probe VCONN                 probe whether VCONN is up\n"
232            "  ping VCONN [N]              latency of N-byte echos\n"
233            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
234            "where each SWITCH is an active OpenFlow connection method.\n",
235            program_name, program_name);
236     vconn_usage(true, false, false);
237     printf("\nOptions:\n"
238            "  --strict                    use strict match for flow commands\n"
239            "  -t, --timeout=SECS          give up after SECS seconds\n"
240            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
241            "  -v, --verbose               set maximum verbosity level\n"
242            "  -h, --help                  display this help message\n"
243            "  -V, --version               display version information\n");
244     exit(EXIT_SUCCESS);
245 }
246
247 static void run(int retval, const char *message, ...)
248     PRINTF_FORMAT(2, 3);
249
250 static void run(int retval, const char *message, ...)
251 {
252     if (retval) {
253         va_list args;
254
255         fprintf(stderr, "%s: ", program_name);
256         va_start(args, message);
257         vfprintf(stderr, message, args);
258         va_end(args);
259         if (retval == EOF) {
260             fputs(": unexpected end of file\n", stderr);
261         } else {
262             fprintf(stderr, ": %s\n", strerror(retval));
263         }
264
265         exit(EXIT_FAILURE);
266     }
267 }
268 \f
269 #ifdef HAVE_NETLINK
270 /* Netlink-only commands. */
271
272 static int if_up(const char *netdev_name)
273 {
274     struct netdev *netdev;
275     int retval;
276
277     retval = netdev_open(netdev_name, NETDEV_ETH_TYPE_NONE, &netdev);
278     if (!retval) {
279         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
280         netdev_close(netdev);
281     }
282     return retval;
283 }
284
285 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
286 {
287     if (strncmp(name, "nl:", 3)
288         || strlen(name) < 4
289         || name[strspn(name + 3, "0123456789") + 3]) {
290         ofp_fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
291     }
292     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
293 }
294
295 static void do_add_dp(const struct settings *s, int argc UNUSED, char *argv[])
296 {
297     struct dpif dp;
298     open_nl_vconn(argv[1], false, &dp);
299     run(dpif_add_dp(&dp), "add_dp");
300     dpif_close(&dp);
301 }
302
303 static void do_del_dp(const struct settings *s, int argc UNUSED, char *argv[])
304 {
305     struct dpif dp;
306     open_nl_vconn(argv[1], false, &dp);
307     run(dpif_del_dp(&dp), "del_dp");
308     dpif_close(&dp);
309 }
310
311 static void add_del_ports(int argc UNUSED, char *argv[],
312                           int (*function)(struct dpif *, const char *netdev),
313                           const char *operation, const char *preposition)
314 {
315     struct dpif dp;
316     bool failure = false;
317     int i;
318
319     open_nl_vconn(argv[1], false, &dp);
320     for (i = 2; i < argc; i++) {
321         int retval = function(&dp, argv[i]);
322         if (retval) {
323             ofp_error(retval, "failed to %s %s %s %s",
324                       operation, argv[i], preposition, argv[1]);
325             failure = true;
326         }
327     }
328     dpif_close(&dp);
329     if (failure) {
330         exit(EXIT_FAILURE);
331     }
332 }
333
334 static int ifup_and_add_port(struct dpif *dpif, const char *netdev)
335 {
336     int retval = if_up(netdev);
337     return retval ? retval : dpif_add_port(dpif, netdev);
338 }
339
340 static void do_add_port(const struct settings *s, int argc UNUSED, 
341         char *argv[])
342 {
343     add_del_ports(argc, argv, ifup_and_add_port, "add", "to");
344 }
345
346 static void do_del_port(const struct settings *s, int argc UNUSED, 
347         char *argv[])
348 {
349     add_del_ports(argc, argv, dpif_del_port, "remove", "from");
350 }
351 #endif /* HAVE_NETLINK */
352 \f
353 /* Generic commands. */
354
355 static void
356 open_vconn(const char *name, struct vconn **vconnp)
357 {
358     run(vconn_open_block(name, OFP_VERSION, vconnp), "connecting to %s", name);
359 }
360
361 static void *
362 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
363 {
364     struct ofp_stats_request *rq;
365     rq = make_openflow((offsetof(struct ofp_stats_request, body)
366                         + body_len), OFPT_STATS_REQUEST, bufferp);
367     rq->type = htons(type);
368     rq->flags = htons(0);
369     return rq->body;
370 }
371
372 static void
373 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
374 {
375     update_openflow_length(buffer);
376     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
377 }
378
379 static void
380 dump_transaction(const char *vconn_name, struct ofpbuf *request)
381 {
382     struct vconn *vconn;
383     struct ofpbuf *reply;
384
385     update_openflow_length(request);
386     open_vconn(vconn_name, &vconn);
387     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
388     ofp_print(stdout, reply->data, reply->size, 1);
389     vconn_close(vconn);
390 }
391
392 static void
393 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
394 {
395     struct ofpbuf *request;
396     make_openflow(sizeof(struct ofp_header), request_type, &request);
397     dump_transaction(vconn_name, request);
398 }
399
400 static void
401 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
402 {
403     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
404     struct vconn *vconn;
405     bool done = false;
406
407     open_vconn(vconn_name, &vconn);
408     send_openflow_buffer(vconn, request);
409     while (!done) {
410         uint32_t recv_xid;
411         struct ofpbuf *reply;
412
413         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
414         recv_xid = ((struct ofp_header *) reply->data)->xid;
415         if (send_xid == recv_xid) {
416             struct ofp_stats_reply *osr;
417
418             ofp_print(stdout, reply->data, reply->size, 1);
419
420             osr = ofpbuf_at(reply, 0, sizeof *osr);
421             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
422         } else {
423             VLOG_DBG("received reply with xid %08"PRIx32" "
424                      "!= expected %08"PRIx32, recv_xid, send_xid);
425         }
426         ofpbuf_delete(reply);
427     }
428     vconn_close(vconn);
429 }
430
431 static void
432 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
433 {
434     struct ofpbuf *request;
435     alloc_stats_request(0, stats_type, &request);
436     dump_stats_transaction(vconn_name, request);
437 }
438
439 static void
440 do_show(const struct settings *s, int argc UNUSED, char *argv[])
441 {
442     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
443     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
444 }
445
446 static void
447 do_status(const struct settings *s, int argc, char *argv[])
448 {
449     struct nicira_header *request, *reply;
450     struct vconn *vconn;
451     struct ofpbuf *b;
452
453     request = make_openflow(sizeof *request, OFPT_VENDOR, &b);
454     request->vendor_id = htonl(NX_VENDOR_ID);
455     request->subtype = htonl(NXT_STATUS_REQUEST);
456     if (argc > 2) {
457         ofpbuf_put(b, argv[2], strlen(argv[2]));
458     }
459     open_vconn(argv[1], &vconn);
460     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
461     vconn_close(vconn);
462
463     if (b->size < sizeof *reply) {
464         ofp_fatal(0, "short reply (%zu bytes)", b->size);
465     }
466     reply = b->data;
467     if (reply->header.type != OFPT_VENDOR
468         || reply->vendor_id != ntohl(NX_VENDOR_ID)
469         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
470         ofp_print(stderr, b->data, b->size, 2);
471         ofp_fatal(0, "bad reply");
472     }
473
474     fwrite(reply + 1, b->size, 1, stdout);
475 }
476
477 static void
478 do_dump_desc(const struct settings *s, int argc, char *argv[])
479 {
480     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
481 }
482
483 static void
484 do_dump_tables(const struct settings *s, int argc, char *argv[])
485 {
486     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
487 }
488
489
490 static uint32_t
491 str_to_int(const char *str) 
492 {
493     char *tail;
494     uint32_t value;
495
496     errno = 0;
497     value = strtoul(str, &tail, 0);
498     if (errno == EINVAL || errno == ERANGE || *tail) {
499         ofp_fatal(0, "invalid numeric format %s", str);
500     }
501     return value;
502 }
503
504 static void
505 str_to_mac(const char *str, uint8_t mac[6]) 
506 {
507     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
508                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
509         ofp_fatal(0, "invalid mac address %s", str);
510     }
511 }
512
513 static uint32_t
514 str_to_ip(const char *str_, uint32_t *ip)
515 {
516     char *str = xstrdup(str_);
517     char *save_ptr = NULL;
518     const char *name, *netmask;
519     struct in_addr in_addr;
520     int n_wild, retval;
521
522     name = strtok_r(str, "//", &save_ptr);
523     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
524     if (retval) {
525         ofp_fatal(0, "%s: could not convert to IP address", str);
526     }
527     *ip = in_addr.s_addr;
528
529     netmask = strtok_r(NULL, "//", &save_ptr);
530     if (netmask) {
531         uint8_t o[4];
532         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
533                    &o[0], &o[1], &o[2], &o[3]) == 4) {
534             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
535             int i;
536
537             /* Find first 1-bit. */
538             for (i = 0; i < 32; i++) {
539                 if (nm & (1u << i)) {
540                     break;
541                 }
542             }
543             n_wild = i;
544
545             /* Verify that the rest of the bits are 1-bits. */
546             for (; i < 32; i++) {
547                 if (!(nm & (1u << i))) {
548                     ofp_fatal(0, "%s: %s is not a valid netmask",
549                               str, netmask);
550                 }
551             }
552         } else {
553             int prefix = atoi(netmask);
554             if (prefix <= 0 || prefix > 32) {
555                 ofp_fatal(0, "%s: network prefix bits not between 1 and 32",
556                           str);
557             }
558             n_wild = 32 - prefix;
559         }
560     } else {
561         n_wild = 0;
562     }
563
564     free(str);
565     return n_wild;
566 }
567
568 static void
569 str_to_action(char *str, struct ofp_action_header *actions, 
570         size_t *actions_len) 
571 {
572     size_t len = *actions_len;
573     char *act, *arg;
574     char *saveptr = NULL;
575     uint8_t *p = (uint8_t *)actions;
576     
577     memset(actions, 0, len);
578     for (act = strtok_r(str, ", \t\r\n", &saveptr); 
579          (len >= sizeof(struct ofp_action_header)) && act;
580          act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
581     {
582         uint16_t port;
583         struct ofp_action_header *ah = (struct ofp_action_header *)p;
584         int act_len = sizeof *ah;
585         port = OFPP_MAX;
586
587         /* Arguments are separated by colons */
588         arg = strchr(act, ':');
589         if (arg) {
590             *arg = '\0';
591             arg++;
592         } 
593
594         if (!strcasecmp(act, "mod_vlan_vid")) {
595             struct ofp_action_vlan_vid *va = (struct ofp_action_vlan_vid *)ah;
596
597             if (len < sizeof *va) {
598                 ofp_fatal(0, "Insufficient room for vlan vid action\n");
599             }
600
601             act_len = sizeof *va;
602             va->type = htons(OFPAT_SET_VLAN_VID);
603             va->vlan_vid = htons(str_to_int(arg));
604         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
605             struct ofp_action_vlan_pcp *va = (struct ofp_action_vlan_pcp *)ah;
606
607             if (len < sizeof *va) {
608                 ofp_fatal(0, "Insufficient room for vlan pcp action\n");
609             }
610
611             act_len = sizeof *va;
612             va->type = htons(OFPAT_SET_VLAN_PCP);
613             va->vlan_pcp = str_to_int(arg);
614         } else if (!strcasecmp(act, "strip_vlan")) {
615             ah->type = htons(OFPAT_STRIP_VLAN);
616         } else if (!strcasecmp(act, "output")) {
617             port = str_to_int(arg);
618         } else if (!strcasecmp(act, "TABLE")) {
619             port = OFPP_TABLE;
620         } else if (!strcasecmp(act, "NORMAL")) {
621             port = OFPP_NORMAL;
622         } else if (!strcasecmp(act, "FLOOD")) {
623             port = OFPP_FLOOD;
624         } else if (!strcasecmp(act, "ALL")) {
625             port = OFPP_ALL;
626         } else if (!strcasecmp(act, "CONTROLLER")) {
627             struct ofp_action_output *ca = (struct ofp_action_output *)ah;
628
629             if (act_len < sizeof *ca) {
630                 ofp_fatal(0, "Insufficient room for controller action\n");
631             }
632
633             act_len = sizeof *ca;
634             ca->type = htons(OFPAT_OUTPUT);
635             ca->port = htons(OFPP_CONTROLLER);
636
637             /* Unless a numeric argument is specified, we send the whole
638              * packet to the controller. */
639             if (arg && (strspn(act, "0123456789") == strlen(act))) {
640                ca->max_len= htons(str_to_int(arg));
641             }
642         } else if (!strcasecmp(act, "LOCAL")) {
643             port = OFPP_LOCAL;
644         } else if (strspn(act, "0123456789") == strlen(act)) {
645             port = str_to_int(act);
646         } else {
647             ofp_fatal(0, "Unknown action: %s", act);
648         }
649
650         if (port != OFPP_MAX) {
651             struct ofp_action_output *oa = (struct ofp_action_output *)p;
652
653             if (act_len < sizeof *oa) {
654                 ofp_fatal(0, "Insufficient room for output action\n");
655             }
656
657             act_len = sizeof *oa;
658             oa->type = htons(OFPAT_OUTPUT);
659             oa->port = htons(port);
660         }
661
662         ah->len = htons(act_len);
663         p += act_len;
664         len -= act_len;
665     }
666
667     *actions_len -= len;
668 }
669
670 struct protocol {
671     const char *name;
672     uint16_t dl_type;
673     uint8_t nw_proto;
674 };
675
676 static bool
677 parse_protocol(const char *name, const struct protocol **p_out)
678 {
679     static const struct protocol protocols[] = {
680         { "ip", ETH_TYPE_IP },
681         { "arp", ETH_TYPE_ARP },
682         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
683         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
684         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
685     };
686     const struct protocol *p;
687
688     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
689         if (!strcmp(p->name, name)) {
690             *p_out = p;
691             return true;
692         }
693     }
694     *p_out = NULL;
695     return false;
696 }
697
698 struct field {
699     const char *name;
700     uint32_t wildcard;
701     enum { F_U8, F_U16, F_MAC, F_IP } type;
702     size_t offset, shift;
703 };
704
705 static bool
706 parse_field(const char *name, const struct field **f_out) 
707 {
708 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
709     static const struct field fields[] = { 
710         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
711         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
712         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
713         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
714         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
715         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
716           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
717         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
718           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
719         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
720         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
721         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
722     };
723     const struct field *f;
724
725     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
726         if (!strcmp(f->name, name)) {
727             *f_out = f;
728             return true;
729         }
730     }
731     *f_out = NULL;
732     return false;
733 }
734
735 static void
736 str_to_flow(char *string, struct ofp_match *match, 
737             struct ofp_action_header *actions, size_t *actions_len, 
738             uint8_t *table_idx, uint16_t *priority, 
739             uint16_t *idle_timeout, uint16_t *hard_timeout)
740 {
741
742     char *name;
743     uint32_t wildcards;
744
745     if (table_idx) {
746         *table_idx = 0xff;
747     }
748     if (priority) {
749         *priority = OFP_DEFAULT_PRIORITY;
750     }
751     if (idle_timeout) {
752         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
753     }
754     if (hard_timeout) {
755         *hard_timeout = OFP_FLOW_PERMANENT;
756     }
757     if (actions) {
758         char *act_str = strstr(string, "action");
759         if (!act_str) {
760             ofp_fatal(0, "must specify an action");
761         }
762         *(act_str-1) = '\0';
763
764         act_str = strchr(act_str, '=');
765         if (!act_str) {
766             ofp_fatal(0, "must specify an action");
767         }
768
769         act_str++;
770
771         str_to_action(act_str, actions, actions_len);
772     }
773     memset(match, 0, sizeof *match);
774     wildcards = OFPFW_ALL;
775     for (name = strtok(string, "=, \t\r\n"); name;
776          name = strtok(NULL, "=, \t\r\n")) {
777         const struct protocol *p;
778
779         if (parse_protocol(name, &p)) {
780             wildcards &= ~OFPFW_DL_TYPE;
781             match->dl_type = htons(p->dl_type);
782             if (p->nw_proto) {
783                 wildcards &= ~OFPFW_NW_PROTO;
784                 match->nw_proto = p->nw_proto;
785             }
786         } else {
787             const struct field *f;
788             char *value;
789
790             value = strtok(NULL, ", \t\r\n");
791             if (!value) {
792                 ofp_fatal(0, "field %s missing value", name);
793             }
794         
795             if (table_idx && !strcmp(name, "table")) {
796                 *table_idx = atoi(value);
797             } else if (priority && !strcmp(name, "priority")) {
798                 *priority = atoi(value);
799             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
800                 *idle_timeout = atoi(value);
801             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
802                 *hard_timeout = atoi(value);
803             } else if (parse_field(name, &f)) {
804                 void *data = (char *) match + f->offset;
805                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
806                     wildcards |= f->wildcard;
807                 } else {
808                     wildcards &= ~f->wildcard;
809                     if (f->type == F_U8) {
810                         *(uint8_t *) data = str_to_int(value);
811                     } else if (f->type == F_U16) {
812                         *(uint16_t *) data = htons(str_to_int(value));
813                     } else if (f->type == F_MAC) {
814                         str_to_mac(value, data);
815                     } else if (f->type == F_IP) {
816                         wildcards |= str_to_ip(value, data) << f->shift;
817                     } else {
818                         NOT_REACHED();
819                     }
820                 }
821             } else {
822                 ofp_fatal(0, "unknown keyword %s", name);
823             }
824         }
825     }
826     match->wildcards = htonl(wildcards);
827 }
828
829 static void do_dump_flows(const struct settings *s, int argc, char *argv[])
830 {
831     struct ofp_flow_stats_request *req;
832     struct ofpbuf *request;
833
834     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
835     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
836                 &req->table_id, NULL, NULL, NULL);
837     memset(req->pad, 0, sizeof req->pad);
838
839     dump_stats_transaction(argv[1], request);
840 }
841
842 static void do_dump_aggregate(const struct settings *s, int argc, 
843         char *argv[])
844 {
845     struct ofp_aggregate_stats_request *req;
846     struct ofpbuf *request;
847
848     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
849     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
850                 &req->table_id, NULL, NULL, NULL);
851     memset(req->pad, 0, sizeof req->pad);
852
853     dump_stats_transaction(argv[1], request);
854 }
855
856 static void do_add_flow(const struct settings *s, int argc, char *argv[])
857 {
858     struct vconn *vconn;
859     struct ofpbuf *buffer;
860     struct ofp_flow_mod *ofm;
861     uint16_t priority, idle_timeout, hard_timeout;
862     size_t size;
863     size_t actions_len = MAX_ACT_LEN;
864
865     /* Parse and send. */
866     size = sizeof *ofm + actions_len;
867     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
868     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
869                 NULL, &priority, &idle_timeout, &hard_timeout);
870     ofm->command = htons(OFPFC_ADD);
871     ofm->idle_timeout = htons(idle_timeout);
872     ofm->hard_timeout = htons(hard_timeout);
873     ofm->buffer_id = htonl(UINT32_MAX);
874     ofm->priority = htons(priority);
875     ofm->reserved = htonl(0);
876
877     /* xxx Should we use the ofpbuf library? */
878     buffer->size -= MAX_ACT_LEN - actions_len;
879
880     open_vconn(argv[1], &vconn);
881     send_openflow_buffer(vconn, buffer);
882     vconn_close(vconn);
883 }
884
885 static void do_add_flows(const struct settings *s, int argc, char *argv[])
886 {
887     struct vconn *vconn;
888     FILE *file;
889     char line[1024];
890
891     file = fopen(argv[2], "r");
892     if (file == NULL) {
893         ofp_fatal(errno, "%s: open", argv[2]);
894     }
895
896     open_vconn(argv[1], &vconn);
897     while (fgets(line, sizeof line, file)) {
898         struct ofpbuf *buffer;
899         struct ofp_flow_mod *ofm;
900         uint16_t priority, idle_timeout, hard_timeout;
901         size_t size;
902         size_t actions_len = MAX_ACT_LEN;
903
904         char *comment;
905
906         /* Delete comments. */
907         comment = strchr(line, '#');
908         if (comment) {
909             *comment = '\0';
910         }
911
912         /* Drop empty lines. */
913         if (line[strspn(line, " \t\n")] == '\0') {
914             continue;
915         }
916
917         /* Parse and send. */
918         size = sizeof *ofm + actions_len;
919         ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
920         str_to_flow(line, &ofm->match, &ofm->actions[0], &actions_len, 
921                     NULL, &priority, &idle_timeout, &hard_timeout);
922         ofm->command = htons(OFPFC_ADD);
923         ofm->idle_timeout = htons(idle_timeout);
924         ofm->hard_timeout = htons(hard_timeout);
925         ofm->buffer_id = htonl(UINT32_MAX);
926         ofm->priority = htons(priority);
927         ofm->reserved = htonl(0);
928
929         /* xxx Should we use the ofpbuf library? */
930         buffer->size -= MAX_ACT_LEN - actions_len;
931
932         send_openflow_buffer(vconn, buffer);
933     }
934     vconn_close(vconn);
935     fclose(file);
936 }
937
938 static void do_mod_flows(const struct settings *s, int argc, char *argv[])
939 {
940     uint16_t priority, idle_timeout, hard_timeout;
941     struct vconn *vconn;
942     struct ofpbuf *buffer;
943     struct ofp_flow_mod *ofm;
944     size_t size;
945     size_t actions_len = MAX_ACT_LEN;
946
947     /* Parse and send. */
948     size = sizeof *ofm + actions_len;
949     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
950     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
951                 NULL, &priority, &idle_timeout, &hard_timeout);
952     if (s->strict) {
953         ofm->command = htons(OFPFC_MODIFY_STRICT);
954     } else {
955         ofm->command = htons(OFPFC_MODIFY);
956     }
957     ofm->idle_timeout = htons(idle_timeout);
958     ofm->hard_timeout = htons(hard_timeout);
959     ofm->buffer_id = htonl(UINT32_MAX);
960     ofm->priority = htons(priority);
961     ofm->reserved = htonl(0);
962
963     /* xxx Should we use the buffer library? */
964     buffer->size -= MAX_ACT_LEN - actions_len;
965
966     open_vconn(argv[1], &vconn);
967     send_openflow_buffer(vconn, buffer);
968     vconn_close(vconn);
969 }
970
971 static void do_del_flows(const struct settings *s, int argc, char *argv[])
972 {
973     struct vconn *vconn;
974     uint16_t priority;
975     struct ofpbuf *buffer;
976     struct ofp_flow_mod *ofm;
977     size_t size;
978
979     /* Parse and send. */
980     size = sizeof *ofm;
981     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
982     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
983                 &priority, NULL, NULL);
984     if (s->strict) {
985         ofm->command = htons(OFPFC_DELETE_STRICT);
986     } else {
987         ofm->command = htons(OFPFC_DELETE);
988     }
989     ofm->idle_timeout = htons(0);
990     ofm->hard_timeout = htons(0);
991     ofm->buffer_id = htonl(UINT32_MAX);
992     ofm->priority = htons(priority);
993     ofm->reserved = htonl(0);
994
995     open_vconn(argv[1], &vconn);
996     send_openflow_buffer(vconn, buffer);
997     vconn_close(vconn);
998 }
999
1000 static void
1001 do_monitor(const struct settings *s, int argc UNUSED, char *argv[])
1002 {
1003     struct vconn *vconn;
1004     const char *name;
1005
1006     /* If the user specified, e.g., "nl:0", append ":1" to it to ensure that
1007      * the connection will subscribe to listen for asynchronous messages, such
1008      * as packet-in messages. */
1009     if (!strncmp(argv[1], "nl:", 3) && strrchr(argv[1], ':') == &argv[1][2]) {
1010         name = xasprintf("%s:1", argv[1]);
1011     } else {
1012         name = argv[1];
1013     }
1014     open_vconn(argv[1], &vconn);
1015     for (;;) {
1016         struct ofpbuf *b;
1017         run(vconn_recv_block(vconn, &b), "vconn_recv");
1018         ofp_print(stderr, b->data, b->size, 2);
1019         ofpbuf_delete(b);
1020     }
1021 }
1022
1023 static void
1024 do_dump_ports(const struct settings *s, int argc, char *argv[])
1025 {
1026     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
1027 }
1028
1029 static void
1030 do_probe(const struct settings *s, int argc, char *argv[])
1031 {
1032     struct ofpbuf *request;
1033     struct vconn *vconn;
1034     struct ofpbuf *reply;
1035
1036     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1037     open_vconn(argv[1], &vconn);
1038     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1039     if (reply->size != request->size) {
1040         ofp_fatal(0, "reply does not match request");
1041     }
1042     ofpbuf_delete(reply);
1043     vconn_close(vconn);
1044 }
1045
1046 static void
1047 do_mod_port(const struct settings *s, int argc, char *argv[])
1048 {
1049     struct ofpbuf *request, *reply;
1050     struct ofp_switch_features *osf;
1051     struct ofp_port_mod *opm;
1052     struct vconn *vconn;
1053     char *endptr;
1054     int n_ports;
1055     int port_idx;
1056     int port_no;
1057     
1058
1059     /* Check if the argument is a port index.  Otherwise, treat it as
1060      * the port name. */
1061     port_no = strtol(argv[2], &endptr, 10);
1062     if (port_no == 0 && endptr == argv[2]) {
1063         port_no = -1;
1064     }
1065
1066     /* Send a "Features Request" to get the information we need in order 
1067      * to modify the port. */
1068     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
1069     open_vconn(argv[1], &vconn);
1070     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1071
1072     osf = reply->data;
1073     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
1074
1075     for (port_idx = 0; port_idx < n_ports; port_idx++) {
1076         if (port_no != -1) {
1077             /* Check argument as a port index */
1078             if (osf->ports[port_idx].port_no == htons(port_no)) {
1079                 break;
1080             }
1081         } else {
1082             /* Check argument as an interface name */
1083             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
1084                         sizeof osf->ports[0].name)) {
1085                 break;
1086             }
1087
1088         }
1089     }
1090     if (port_idx == n_ports) {
1091         ofp_fatal(0, "couldn't find monitored port: %s", argv[2]);
1092     }
1093
1094     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1095     opm->port_no = osf->ports[port_idx].port_no;
1096     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
1097     opm->config = htonl(0);
1098     opm->mask = htonl(0);
1099     opm->advertise = htonl(0);
1100
1101     printf("modifying port: %s\n", osf->ports[port_idx].name);
1102
1103     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
1104         opm->mask |= htonl(OFPPC_PORT_DOWN);
1105     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
1106                 sizeof MOD_PORT_CMD_DOWN)) {
1107         opm->mask |= htonl(OFPPC_PORT_DOWN);
1108         opm->config |= htonl(OFPPC_PORT_DOWN);
1109     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
1110                 sizeof MOD_PORT_CMD_FLOOD)) {
1111         opm->mask |= htonl(OFPPC_NO_FLOOD);
1112     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
1113                 sizeof MOD_PORT_CMD_NOFLOOD)) {
1114         opm->mask |= htonl(OFPPC_NO_FLOOD);
1115         opm->config |= htonl(OFPPC_NO_FLOOD);
1116     } else {
1117         ofp_fatal(0, "unknown mod-port command '%s'", argv[3]);
1118     }
1119
1120     send_openflow_buffer(vconn, request);
1121
1122     ofpbuf_delete(reply);
1123     vconn_close(vconn);
1124 }
1125
1126 static void
1127 do_ping(const struct settings *s, int argc, char *argv[])
1128 {
1129     size_t max_payload = 65535 - sizeof(struct ofp_header);
1130     unsigned int payload;
1131     struct vconn *vconn;
1132     int i;
1133
1134     payload = argc > 2 ? atoi(argv[2]) : 64;
1135     if (payload > max_payload) {
1136         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1137     }
1138
1139     open_vconn(argv[1], &vconn);
1140     for (i = 0; i < 10; i++) {
1141         struct timeval start, end;
1142         struct ofpbuf *request, *reply;
1143         struct ofp_header *rq_hdr, *rpy_hdr;
1144
1145         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1146                                OFPT_ECHO_REQUEST, &request);
1147         random_bytes(rq_hdr + 1, payload);
1148
1149         gettimeofday(&start, NULL);
1150         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1151         gettimeofday(&end, NULL);
1152
1153         rpy_hdr = reply->data;
1154         if (reply->size != request->size
1155             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1156             || rpy_hdr->xid != rq_hdr->xid
1157             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1158             printf("Reply does not match request.  Request:\n");
1159             ofp_print(stdout, request, request->size, 2);
1160             printf("Reply:\n");
1161             ofp_print(stdout, reply, reply->size, 2);
1162         }
1163         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1164                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1165                    (1000*(double)(end.tv_sec - start.tv_sec))
1166                    + (.001*(end.tv_usec - start.tv_usec)));
1167         ofpbuf_delete(request);
1168         ofpbuf_delete(reply);
1169     }
1170     vconn_close(vconn);
1171 }
1172
1173 static void
1174 do_benchmark(const struct settings *s, int argc, char *argv[])
1175 {
1176     size_t max_payload = 65535 - sizeof(struct ofp_header);
1177     struct timeval start, end;
1178     unsigned int payload_size, message_size;
1179     struct vconn *vconn;
1180     double duration;
1181     int count;
1182     int i;
1183
1184     payload_size = atoi(argv[2]);
1185     if (payload_size > max_payload) {
1186         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1187     }
1188     message_size = sizeof(struct ofp_header) + payload_size;
1189
1190     count = atoi(argv[3]);
1191
1192     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1193            count, message_size, count * message_size);
1194
1195     open_vconn(argv[1], &vconn);
1196     gettimeofday(&start, NULL);
1197     for (i = 0; i < count; i++) {
1198         struct ofpbuf *request, *reply;
1199         struct ofp_header *rq_hdr;
1200
1201         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1202         memset(rq_hdr + 1, 0, payload_size);
1203         run(vconn_transact(vconn, request, &reply), "transact");
1204         ofpbuf_delete(reply);
1205     }
1206     gettimeofday(&end, NULL);
1207     vconn_close(vconn);
1208
1209     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1210                 + (.001*(end.tv_usec - start.tv_usec)));
1211     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1212            duration, count / (duration / 1000.0),
1213            count * message_size / (duration / 1000.0));
1214 }
1215
1216 static void do_help(const struct settings *s, int argc UNUSED, 
1217         char *argv[] UNUSED)
1218 {
1219     usage();
1220 }
1221
1222 static struct command all_commands[] = {
1223 #ifdef HAVE_NETLINK
1224     { "adddp", 1, 1, do_add_dp },
1225     { "deldp", 1, 1, do_del_dp },
1226     { "addif", 2, INT_MAX, do_add_port },
1227     { "delif", 2, INT_MAX, do_del_port },
1228 #endif
1229
1230     { "show", 1, 1, do_show },
1231     { "status", 1, 2, do_status },
1232
1233     { "help", 0, INT_MAX, do_help },
1234     { "monitor", 1, 1, do_monitor },
1235     { "dump-desc", 1, 1, do_dump_desc },
1236     { "dump-tables", 1, 1, do_dump_tables },
1237     { "dump-flows", 1, 2, do_dump_flows },
1238     { "dump-aggregate", 1, 2, do_dump_aggregate },
1239     { "add-flow", 2, 2, do_add_flow },
1240     { "add-flows", 2, 2, do_add_flows },
1241     { "mod-flows", 2, 2, do_mod_flows },
1242     { "del-flows", 1, 2, do_del_flows },
1243     { "dump-ports", 1, 1, do_dump_ports },
1244     { "mod-port", 3, 3, do_mod_port },
1245     { "probe", 1, 1, do_probe },
1246     { "ping", 1, 2, do_ping },
1247     { "benchmark", 3, 3, do_benchmark },
1248     { NULL, 0, 0, NULL },
1249 };