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