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