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