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