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