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