Prevent the secchan from dying due to SIGPIPE.
[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 <errno.h>
36 #include <getopt.h>
37 #include <inttypes.h>
38 #include <netinet/in.h>
39 #include <signal.h>
40 #include <stdarg.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/time.h>
45
46 #include "command-line.h"
47 #include "compiler.h"
48 #include "buffer.h"
49 #include "dpif.h"
50 #ifdef HAVE_NETLINK
51 #include "netlink.h"
52 #include "openflow-netlink.h"
53 #endif
54 #include "util.h"
55 #include "socket-util.h"
56 #include "openflow.h"
57 #include "ofp-print.h"
58 #include "random.h"
59 #include "timeval.h"
60 #include "vconn.h"
61 #include "vconn-ssl.h"
62
63 #include "vlog.h"
64 #define THIS_MODULE VLM_dpctl
65
66 #define DEFAULT_IDLE_TIMEOUT 60
67 #define MAX_ADD_ACTS 5
68
69 static const char* ifconfigbin = "/sbin/ifconfig";
70
71 struct command {
72     const char *name;
73     int min_args;
74     int max_args;
75     void (*handler)(int argc, char *argv[]);
76 };
77
78 static struct command all_commands[];
79
80 static void usage(void) NO_RETURN;
81 static void parse_options(int argc, char *argv[]);
82
83 int main(int argc, char *argv[])
84 {
85     struct command *p;
86
87     set_program_name(argv[0]);
88     time_init();
89     vlog_init();
90     parse_options(argc, argv);
91     signal(SIGPIPE, SIG_IGN);
92
93     argc -= optind;
94     argv += optind;
95     if (argc < 1)
96         fatal(0, "missing command name; use --help for help");
97
98     for (p = all_commands; p->name != NULL; p++) {
99         if (!strcmp(p->name, argv[0])) {
100             int n_arg = argc - 1;
101             if (n_arg < p->min_args)
102                 fatal(0, "'%s' command requires at least %d arguments",
103                       p->name, p->min_args);
104             else if (n_arg > p->max_args)
105                 fatal(0, "'%s' command takes at most %d arguments",
106                       p->name, p->max_args);
107             else {
108                 p->handler(argc, argv);
109                 exit(0);
110             }
111         }
112     }
113     fatal(0, "unknown command '%s'; use --help for help", argv[0]);
114
115     return 0;
116 }
117
118 static void
119 parse_options(int argc, char *argv[])
120 {
121     static struct option long_options[] = {
122         {"timeout", required_argument, 0, 't'},
123         {"verbose", optional_argument, 0, 'v'},
124         {"help", no_argument, 0, 'h'},
125         {"version", no_argument, 0, 'V'},
126         VCONN_SSL_LONG_OPTIONS
127         {0, 0, 0, 0},
128     };
129     char *short_options = long_options_to_short_options(long_options);
130
131     for (;;) {
132         unsigned long int timeout;
133         int c;
134
135         c = getopt_long(argc, argv, short_options, long_options, NULL);
136         if (c == -1) {
137             break;
138         }
139
140         switch (c) {
141         case 't':
142             timeout = strtoul(optarg, NULL, 10);
143             if (timeout <= 0) {
144                 fatal(0, "value %s on -t or --timeout is not at least 1",
145                       optarg);
146             } else {
147                 time_alarm(timeout);
148             }
149             break;
150
151         case 'h':
152             usage();
153
154         case 'V':
155             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
156             exit(EXIT_SUCCESS);
157
158         case 'v':
159             vlog_set_verbosity(optarg);
160             break;
161
162         VCONN_SSL_OPTION_HANDLERS
163
164         case '?':
165             exit(EXIT_FAILURE);
166
167         default:
168             abort();
169         }
170     }
171     free(short_options);
172 }
173
174 static void
175 usage(void)
176 {
177     printf("%s: OpenFlow switch management utility\n"
178            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
179 #ifdef HAVE_NETLINK
180            "\nFor local datapaths only:\n"
181            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
182            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
183            "  addif nl:DP_ID IFACE        add IFACE as a port on DP_ID\n"
184            "  delif nl:DP_ID IFACE        delete IFACE as a port on DP_ID\n"
185            "  monitor nl:DP_ID            print packets received\n"
186 #endif
187            "\nFor local datapaths and remote switches:\n"
188            "  show SWITCH                 show information\n"
189            "  dump-tables SWITCH          print table stats\n"
190            "  dump-ports SWITCH           print port statistics\n"
191            "  dump-flows SWITCH           print all flow entries\n"
192            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
193            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
194            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
195            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
196            "  add-flows SWITCH FILE       add flows from FILE\n"
197            "  del-flows SWITCH FLOW       delete matching FLOWs\n"
198            "\nFor local datapaths, remote switches, and controllers:\n"
199            "  probe VCONN                 probe whether VCONN is up\n"
200            "  ping VCONN [N]              latency of N-byte echos\n"
201            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
202            "where each SWITCH is an active OpenFlow connection method.\n",
203            program_name, program_name);
204     vconn_usage(true, false);
205     printf("\nOptions:\n"
206            "  -t, --timeout=SECS          give up after SECS seconds\n"
207            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
208            "  -v, --verbose               set maximum verbosity level\n"
209            "  -h, --help                  display this help message\n"
210            "  -V, --version               display version information\n");
211     exit(EXIT_SUCCESS);
212 }
213
214 static void run(int retval, const char *message, ...)
215     PRINTF_FORMAT(2, 3);
216
217 static void run(int retval, const char *message, ...)
218 {
219     if (retval) {
220         va_list args;
221
222         fprintf(stderr, "%s: ", program_name);
223         va_start(args, message);
224         vfprintf(stderr, message, args);
225         va_end(args);
226         if (retval == EOF) {
227             fputs(": unexpected end of file\n", stderr);
228         } else {
229             fprintf(stderr, ": %s\n", strerror(retval));
230         }
231
232         exit(EXIT_FAILURE);
233     }
234 }
235 \f
236 #ifdef HAVE_NETLINK
237 /* Netlink-only commands. */
238
239 static int  if_up(const char* intf)
240 {
241     char command[256];
242     snprintf(command, sizeof command, "%s %s up &> /dev/null",
243             ifconfigbin, intf);
244     return system(command);
245 }
246
247 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
248 {
249     if (strncmp(name, "nl:", 3)
250         || strlen(name) < 4
251         || name[strspn(name + 3, "0123456789") + 3]) {
252         fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
253     }
254     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
255 }
256
257 static void do_add_dp(int argc UNUSED, char *argv[])
258 {
259     struct dpif dp;
260     open_nl_vconn(argv[1], false, &dp);
261     run(dpif_add_dp(&dp), "add_dp");
262     dpif_close(&dp);
263 }
264
265 static void do_del_dp(int argc UNUSED, char *argv[])
266 {
267     struct dpif dp;
268     open_nl_vconn(argv[1], false, &dp);
269     run(dpif_del_dp(&dp), "del_dp");
270     dpif_close(&dp);
271 }
272
273 static void do_add_port(int argc UNUSED, char *argv[])
274 {
275     struct dpif dp;
276     if_up(argv[2]);
277     open_nl_vconn(argv[1], false, &dp);
278     run(dpif_add_port(&dp, argv[2]), "add_port");
279     dpif_close(&dp);
280 }
281
282 static void do_del_port(int argc UNUSED, char *argv[])
283 {
284     struct dpif dp;
285     open_nl_vconn(argv[1], false, &dp);
286     run(dpif_del_port(&dp, argv[2]), "del_port");
287     dpif_close(&dp);
288 }
289
290 static void do_monitor(int argc UNUSED, char *argv[])
291 {
292     struct dpif dp;
293     open_nl_vconn(argv[1], true, &dp);
294     for (;;) {
295         struct buffer *b;
296         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
297         ofp_print(stderr, b->data, b->size, 2);
298         buffer_delete(b);
299     }
300 }
301 #endif /* HAVE_NETLINK */
302 \f
303 /* Generic commands. */
304
305 static void *
306 alloc_stats_request(size_t body_len, uint16_t type, struct buffer **bufferp)
307 {
308     struct ofp_stats_request *rq;
309     rq = make_openflow((offsetof(struct ofp_stats_request, body)
310                         + body_len), OFPT_STATS_REQUEST, bufferp);
311     rq->type = htons(type);
312     rq->flags = htons(0);
313     return rq->body;
314 }
315
316 static void
317 send_openflow_buffer(struct vconn *vconn, struct buffer *buffer)
318 {
319     update_openflow_length(buffer);
320     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
321 }
322
323 static void
324 dump_transaction(const char *vconn_name, struct buffer *request)
325 {
326     struct vconn *vconn;
327     struct buffer *reply;
328
329     update_openflow_length(request);
330     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
331     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
332     ofp_print(stdout, reply->data, reply->size, 1);
333     vconn_close(vconn);
334 }
335
336 static void
337 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
338 {
339     struct buffer *request;
340     make_openflow(sizeof(struct ofp_header), request_type, &request);
341     dump_transaction(vconn_name, request);
342 }
343
344 static void
345 dump_stats_transaction(const char *vconn_name, struct buffer *request)
346 {
347     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
348     struct vconn *vconn;
349     bool done = false;
350
351     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
352     send_openflow_buffer(vconn, request);
353     while (!done) {
354         uint32_t recv_xid;
355         struct buffer *reply;
356
357         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
358         recv_xid = ((struct ofp_header *) reply->data)->xid;
359         if (send_xid == recv_xid) {
360             struct ofp_stats_reply *osr;
361
362             ofp_print(stdout, reply->data, reply->size, 1);
363
364             osr = buffer_at(reply, 0, sizeof *osr);
365             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
366         } else {
367             VLOG_DBG("received reply with xid %08"PRIx32" "
368                      "!= expected %08"PRIx32, recv_xid, send_xid);
369         }
370         buffer_delete(reply);
371     }
372     vconn_close(vconn);
373 }
374
375 static void
376 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
377 {
378     struct buffer *request;
379     alloc_stats_request(0, stats_type, &request);
380     dump_stats_transaction(vconn_name, request);
381 }
382
383 static void
384 do_show(int argc UNUSED, char *argv[])
385 {
386     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
387     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
388 }
389
390
391 static void
392 do_dump_tables(int argc, char *argv[])
393 {
394     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
395 }
396
397
398 static uint32_t
399 str_to_int(const char *str) 
400 {
401     uint32_t value;
402     if (sscanf(str, "%"SCNu32, &value) != 1) {
403         fatal(0, "invalid numeric format %s", str);
404     }
405     return value;
406 }
407
408 static void
409 str_to_mac(const char *str, uint8_t mac[6]) 
410 {
411     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
412                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
413         fatal(0, "invalid mac address %s", str);
414     }
415 }
416
417 static void
418 str_to_ip(const char *str, uint32_t *ip) 
419 {
420     struct in_addr in_addr;
421     int retval;
422
423     retval = lookup_ip(str, &in_addr);
424     if (retval) {
425         fatal(0, "%s: could not convert to IP address", str);
426     }
427     *ip = in_addr.s_addr;
428 }
429
430 static void
431 str_to_action(char *str, struct ofp_action *action, int *n_actions) 
432 {
433     uint16_t port;
434     int i;
435     int max_actions = *n_actions;
436     char *act, *arg;
437     char *saveptr = NULL;
438     
439     memset(action, 0, sizeof(*action) * max_actions);
440     for (i=0, act = strtok_r(str, ", \t\r\n", &saveptr); 
441          i<max_actions && act;
442          i++, act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
443     {
444         port = OFPP_MAX;
445
446         /* Arguments are separated by colons */
447         arg = strchr(act, ':');
448         if (arg) {
449             *arg = '\0';
450             arg++;
451         } 
452
453         if (!strcasecmp(act, "mod_vlan")) {
454             action[i].type = htons(OFPAT_SET_DL_VLAN);
455
456             if (!strcasecmp(arg, "strip")) {
457                 action[i].arg.vlan_id = htons(OFP_VLAN_NONE);
458             } else {
459                 action[i].arg.vlan_id = htons(str_to_int(arg));
460             }
461         } else if (!strcasecmp(act, "output")) {
462             port = str_to_int(arg);
463         } else if (!strcasecmp(act, "TABLE")) {
464             port = OFPP_TABLE;
465         } else if (!strcasecmp(act, "NORMAL")) {
466             port = OFPP_NORMAL;
467         } else if (!strcasecmp(act, "FLOOD")) {
468             port = OFPP_FLOOD;
469         } else if (!strcasecmp(act, "ALL")) {
470             port = OFPP_ALL;
471         } else if (!strcasecmp(act, "CONTROLLER")) {
472             port = OFPP_CONTROLLER;
473             if (arg) {
474                 if (!strcasecmp(arg, "all")) {
475                     action[i].arg.output.max_len= htons(0);
476                 } else {
477                     action[i].arg.output.max_len= htons(str_to_int(arg));
478                 }
479             }
480         } else if (!strcasecmp(act, "LOCAL")) {
481             port = OFPP_LOCAL;
482         } else if (strspn(act, "0123456789") == strlen(act)) {
483             port = str_to_int(act);
484         } else {
485             fatal(0, "Unknown action: %s", act);
486         }
487
488         if (port != OFPP_MAX) {
489             action[i].type = htons(OFPAT_OUTPUT);
490             action[i].arg.output.port = htons(port);
491         }
492     }
493
494     *n_actions = i;
495 }
496
497 static void
498 str_to_flow(char *string, struct ofp_match *match, 
499         struct ofp_action *action, int *n_actions, uint8_t *table_idx, 
500             uint16_t *priority, uint16_t *idle_timeout, uint16_t *hard_timeout)
501 {
502     struct field {
503         const char *name;
504         uint32_t wildcard;
505         enum { F_U8, F_U16, F_MAC, F_IP } type;
506         size_t offset;
507     };
508
509 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
510     static const struct field fields[] = { 
511         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
512         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
513         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
514         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
515         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
516         { "nw_src", OFPFW_NW_SRC, F_IP, F_OFS(nw_src) },
517         { "nw_dst", OFPFW_NW_DST, F_IP, F_OFS(nw_dst) },
518         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
519         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
520         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
521     };
522
523     char *name, *value;
524     uint32_t wildcards;
525     char *act_str;
526
527     if (table_idx) {
528         *table_idx = 0xff;
529     }
530     if (priority) {
531         *priority = OFP_DEFAULT_PRIORITY;
532     }
533     if (idle_timeout) {
534         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
535     }
536     if (hard_timeout) {
537         *hard_timeout = OFP_FLOW_PERMANENT;
538     }
539     if (action) {
540         act_str = strstr(string, "action");
541         if (!act_str) {
542             fatal(0, "must specify an action");
543         }
544         *(act_str-1) = '\0';
545
546         act_str = strchr(act_str, '=');
547         if (!act_str) {
548             fatal(0, "must specify an action");
549         }
550
551         act_str++;
552
553         str_to_action(act_str, action, n_actions);
554     }
555     memset(match, 0, sizeof *match);
556     wildcards = OFPFW_ALL;
557     for (name = strtok(string, "="), value = strtok(NULL, ", \t\r\n");
558          name && value;
559          name = strtok(NULL, "="), value = strtok(NULL, ", \t\r\n"))
560     {
561         const struct field *f;
562         void *data;
563
564         if (table_idx && !strcmp(name, "table")) {
565             *table_idx = atoi(value);
566             continue;
567         }
568
569         if (priority && !strcmp(name, "priority")) {
570             *priority = atoi(value);
571             continue;
572         }
573
574         if (idle_timeout && !strcmp(name, "idle_timeout")) {
575             *idle_timeout = atoi(value);
576             continue;
577         }
578
579         if (hard_timeout && !strcmp(name, "hard_timeout")) {
580             *hard_timeout = atoi(value);
581             continue;
582         }
583
584         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
585             if (!strcmp(f->name, name)) {
586                 goto found;
587             }
588         }
589         fprintf(stderr, "%s: unknown field %s (fields are",
590                 program_name, name);
591         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
592             if (f != fields) {
593                 putc(',', stderr);
594             }
595             fprintf(stderr, " %s", f->name);
596         }
597         fprintf(stderr, ")\n");
598         exit(1);
599
600     found:
601         data = (char *) match + f->offset;
602         if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
603             wildcards |= f->wildcard;
604         } else {
605             wildcards &= ~f->wildcard;
606             if (f->type == F_U8) {
607                 *(uint8_t *) data = str_to_int(value);
608             } else if (f->type == F_U16) {
609                 *(uint16_t *) data = htons(str_to_int(value));
610             } else if (f->type == F_MAC) {
611                 str_to_mac(value, data);
612             } else if (f->type == F_IP) {
613                 str_to_ip(value, data);
614             } else {
615                 NOT_REACHED();
616             }
617         }
618     }
619     if (name && !value) {
620         fatal(0, "field %s missing value", name);
621     }
622     match->wildcards = htons(wildcards);
623 }
624
625 static void do_dump_flows(int argc, char *argv[])
626 {
627     struct ofp_flow_stats_request *req;
628     struct buffer *request;
629
630     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
631     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
632                 &req->table_id, NULL, NULL, NULL);
633     memset(req->pad, 0, sizeof req->pad);
634
635     dump_stats_transaction(argv[1], request);
636 }
637
638 static void do_dump_aggregate(int argc, char *argv[])
639 {
640     struct ofp_aggregate_stats_request *req;
641     struct buffer *request;
642
643     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
644     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
645                 &req->table_id, NULL, NULL, NULL);
646     memset(req->pad, 0, sizeof req->pad);
647
648     dump_stats_transaction(argv[1], request);
649 }
650
651 static void do_add_flow(int argc, char *argv[])
652 {
653     struct vconn *vconn;
654     struct buffer *buffer;
655     struct ofp_flow_mod *ofm;
656     uint16_t priority, idle_timeout, hard_timeout;
657     size_t size;
658     int n_actions = MAX_ADD_ACTS;
659
660     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
661
662     /* Parse and send. */
663     size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
664     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
665     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &n_actions, 
666                 NULL, &priority, &idle_timeout, &hard_timeout);
667     ofm->command = htons(OFPFC_ADD);
668     ofm->idle_timeout = htons(idle_timeout);
669     ofm->hard_timeout = htons(hard_timeout);
670     ofm->buffer_id = htonl(UINT32_MAX);
671     ofm->priority = htons(priority);
672     ofm->reserved = htonl(0);
673
674     /* xxx Should we use the buffer library? */
675     buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
676
677     send_openflow_buffer(vconn, buffer);
678     vconn_close(vconn);
679 }
680
681 static void do_add_flows(int argc, char *argv[])
682 {
683     struct vconn *vconn;
684
685     FILE *file;
686     char line[1024];
687
688     file = fopen(argv[2], "r");
689     if (file == NULL) {
690         fatal(errno, "%s: open", argv[2]);
691     }
692
693     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
694     while (fgets(line, sizeof line, file)) {
695         struct buffer *buffer;
696         struct ofp_flow_mod *ofm;
697         uint16_t priority, idle_timeout, hard_timeout;
698         size_t size;
699         int n_actions = MAX_ADD_ACTS;
700
701         char *comment;
702
703         /* Delete comments. */
704         comment = strchr(line, '#');
705         if (comment) {
706             *comment = '\0';
707         }
708
709         /* Drop empty lines. */
710         if (line[strspn(line, " \t\n")] == '\0') {
711             continue;
712         }
713
714         /* Parse and send. */
715         size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
716         ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
717         str_to_flow(line, &ofm->match, &ofm->actions[0], &n_actions, 
718                     NULL, &priority, &idle_timeout, &hard_timeout);
719         ofm->command = htons(OFPFC_ADD);
720         ofm->idle_timeout = htons(idle_timeout);
721         ofm->hard_timeout = htons(hard_timeout);
722         ofm->buffer_id = htonl(UINT32_MAX);
723         ofm->priority = htons(priority);
724         ofm->reserved = htonl(0);
725
726         /* xxx Should we use the buffer library? */
727         buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
728
729         send_openflow_buffer(vconn, buffer);
730     }
731     vconn_close(vconn);
732     fclose(file);
733 }
734
735 static void do_del_flows(int argc, char *argv[])
736 {
737     struct vconn *vconn;
738     uint16_t priority;
739
740     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
741     struct buffer *buffer;
742     struct ofp_flow_mod *ofm;
743     size_t size;
744
745
746     /* Parse and send. */
747     size = sizeof *ofm;
748     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
749     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
750                 &priority, NULL, NULL);
751     ofm->command = htons(OFPFC_DELETE);
752     ofm->idle_timeout = htons(0);
753     ofm->hard_timeout = htons(0);
754     ofm->buffer_id = htonl(UINT32_MAX);
755     ofm->priority = htons(priority);
756     ofm->reserved = htonl(0);
757
758     send_openflow_buffer(vconn, buffer);
759
760     vconn_close(vconn);
761 }
762
763 static void
764 do_dump_ports(int argc, char *argv[])
765 {
766     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
767 }
768
769 static void
770 do_probe(int argc, char *argv[])
771 {
772     struct buffer *request;
773     struct vconn *vconn;
774     struct buffer *reply;
775
776     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
777     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
778     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
779     if (reply->size != request->size) {
780         fatal(0, "reply does not match request");
781     }
782     buffer_delete(reply);
783     vconn_close(vconn);
784 }
785
786 static void
787 do_ping(int argc, char *argv[])
788 {
789     size_t max_payload = 65535 - sizeof(struct ofp_header);
790     unsigned int payload;
791     struct vconn *vconn;
792     int i;
793
794     payload = argc > 2 ? atoi(argv[2]) : 64;
795     if (payload > max_payload) {
796         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
797     }
798
799     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
800     for (i = 0; i < 10; i++) {
801         struct timeval start, end;
802         struct buffer *request, *reply;
803         struct ofp_header *rq_hdr, *rpy_hdr;
804
805         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
806                                OFPT_ECHO_REQUEST, &request);
807         random_bytes(rq_hdr + 1, payload);
808
809         gettimeofday(&start, NULL);
810         run(vconn_transact(vconn, buffer_clone(request), &reply), "transact");
811         gettimeofday(&end, NULL);
812
813         rpy_hdr = reply->data;
814         if (reply->size != request->size
815             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
816             || rpy_hdr->xid != rq_hdr->xid
817             || rpy_hdr->type != OFPT_ECHO_REPLY) {
818             printf("Reply does not match request.  Request:\n");
819             ofp_print(stdout, request, request->size, 2);
820             printf("Reply:\n");
821             ofp_print(stdout, reply, reply->size, 2);
822         }
823         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
824                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
825                    (1000*(double)(end.tv_sec - start.tv_sec))
826                    + (.001*(end.tv_usec - start.tv_usec)));
827         buffer_delete(request);
828         buffer_delete(reply);
829     }
830     vconn_close(vconn);
831 }
832
833 static void
834 do_benchmark(int argc, char *argv[])
835 {
836     size_t max_payload = 65535 - sizeof(struct ofp_header);
837     struct timeval start, end;
838     unsigned int payload_size, message_size;
839     struct vconn *vconn;
840     double duration;
841     int count;
842     int i;
843
844     payload_size = atoi(argv[2]);
845     if (payload_size > max_payload) {
846         fatal(0, "payload must be between 0 and %zu bytes", max_payload);
847     }
848     message_size = sizeof(struct ofp_header) + payload_size;
849
850     count = atoi(argv[3]);
851
852     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
853            count, message_size, count * message_size);
854
855     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
856     gettimeofday(&start, NULL);
857     for (i = 0; i < count; i++) {
858         struct buffer *request, *reply;
859         struct ofp_header *rq_hdr;
860
861         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
862         memset(rq_hdr + 1, 0, payload_size);
863         run(vconn_transact(vconn, request, &reply), "transact");
864         buffer_delete(reply);
865     }
866     gettimeofday(&end, NULL);
867     vconn_close(vconn);
868
869     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
870                 + (.001*(end.tv_usec - start.tv_usec)));
871     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
872            duration, count / (duration / 1000.0),
873            count * message_size / (duration / 1000.0));
874 }
875
876 static void do_help(int argc UNUSED, char *argv[] UNUSED)
877 {
878     usage();
879 }
880
881 static struct command all_commands[] = {
882 #ifdef HAVE_NETLINK
883     { "adddp", 1, 1, do_add_dp },
884     { "deldp", 1, 1, do_del_dp },
885     { "addif", 2, 2, do_add_port },
886     { "delif", 2, 2, do_del_port },
887 #endif
888
889     { "show", 1, 1, do_show },
890
891     { "help", 0, INT_MAX, do_help },
892     { "monitor", 1, 1, do_monitor },
893     { "dump-tables", 1, 1, do_dump_tables },
894     { "dump-flows", 1, 2, do_dump_flows },
895     { "dump-aggregate", 1, 2, do_dump_aggregate },
896     { "add-flow", 2, 2, do_add_flow },
897     { "add-flows", 2, 2, do_add_flows },
898     { "del-flows", 1, 2, do_del_flows },
899     { "dump-ports", 1, 1, do_dump_ports },
900     { "probe", 1, 1, do_probe },
901     { "ping", 1, 2, do_ping },
902     { "benchmark", 3, 3, do_benchmark },
903     { NULL, 0, 0, NULL },
904 };