Break data_hello and control_hello messages into multiple messages.
[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 <errno.h>
35 #include <getopt.h>
36 #include <inttypes.h>
37 #include <netinet/in.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <sys/time.h>
42
43 #include "command-line.h"
44 #include "compiler.h"
45 #include "buffer.h"
46 #include "dpif.h"
47 #ifdef HAVE_NETLINK
48 #include "netlink.h"
49 #include "openflow-netlink.h"
50 #endif
51 #include "util.h"
52 #include "socket-util.h"
53 #include "openflow.h"
54 #include "ofp-print.h"
55 #include "vconn.h"
56 #include "vconn-ssl.h"
57
58 #include "vlog.h"
59 #define THIS_MODULE VLM_DPCTL
60
61 static const char* ifconfigbin = "/sbin/ifconfig";
62
63 struct command {
64     const char *name;
65     int min_args;
66     int max_args;
67     void (*handler)(int argc, char *argv[]);
68 };
69
70 static struct command all_commands[];
71
72 static void usage(void) NO_RETURN;
73 static void parse_options(int argc, char *argv[]);
74
75 int main(int argc, char *argv[])
76 {
77     struct command *p;
78
79     set_program_name(argv[0]);
80     vlog_init();
81     parse_options(argc, argv);
82
83     argc -= optind;
84     argv += optind;
85     if (argc < 1)
86         fatal(0, "missing command name; use --help for help");
87
88     for (p = all_commands; p->name != NULL; p++) {
89         if (!strcmp(p->name, argv[0])) {
90             int n_arg = argc - 1;
91             if (n_arg < p->min_args)
92                 fatal(0, "'%s' command requires at least %d arguments",
93                       p->name, p->min_args);
94             else if (n_arg > p->max_args)
95                 fatal(0, "'%s' command takes at most %d arguments",
96                       p->name, p->max_args);
97             else {
98                 p->handler(argc, argv);
99                 exit(0);
100             }
101         }
102     }
103     fatal(0, "unknown command '%s'; use --help for help", argv[0]);
104
105     return 0;
106 }
107
108 static void
109 parse_options(int argc, char *argv[])
110 {
111     static struct option long_options[] = {
112         {"verbose", optional_argument, 0, 'v'},
113         {"help", no_argument, 0, 'h'},
114         {"version", no_argument, 0, 'V'},
115 #ifdef HAVE_OPENSSL
116         {"private-key", required_argument, 0, 'p'},
117         {"certificate", required_argument, 0, 'c'},
118         {"ca-cert",     required_argument, 0, 'C'},
119 #endif
120         {0, 0, 0, 0},
121     };
122     char *short_options = long_options_to_short_options(long_options);
123
124     for (;;) {
125         int indexptr;
126         int c;
127
128         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
129         if (c == -1) {
130             break;
131         }
132
133         switch (c) {
134         case 'h':
135             usage();
136
137         case 'V':
138             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
139             exit(EXIT_SUCCESS);
140
141         case 'v':
142             vlog_set_verbosity(optarg);
143             break;
144
145 #ifdef HAVE_OPENSSL
146         case 'p':
147             vconn_ssl_set_private_key_file(optarg);
148             break;
149
150         case 'c':
151             vconn_ssl_set_certificate_file(optarg);
152             break;
153
154         case 'C':
155             vconn_ssl_set_ca_cert_file(optarg);
156             break;
157 #endif
158
159         case '?':
160             exit(EXIT_FAILURE);
161
162         default:
163             abort();
164         }
165     }
166     free(short_options);
167 }
168
169 static void
170 usage(void)
171 {
172     printf("%s: OpenFlow switch management utility\n"
173            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
174 #ifdef HAVE_NETLINK
175            "\nCommands that apply to local datapaths only:\n"
176            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
177            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
178            "  addif nl:DP_ID IFACE        add IFACE as a port on DP_ID\n"
179            "  delif nl:DP_ID IFACE        delete IFACE as a port on DP_ID\n"
180            "  benchmark-nl nl:DP_ID N SIZE   send N packets of SIZE bytes\n"
181 #endif
182            "\nCommands that also apply to remote switches:\n"
183            "  show VCONN                  show information about VCONN\n"
184            "  monitor VCONN               print packets received on VCONN\n"
185            "  dump-tables VCONN           print table stats for VCONN\n"
186            "  dump-flows VCONN T_ID       print all flow entries in table T_ID of VCONN\n"
187            "  dump-flows VCONN T_ID FLOW  print matching FLOWs in table T_ID of VCONN\n"
188            "  add-flows VCONN FILE        add flows from FILE to VCONN\n"
189            "where each VCONN is one of the following:\n"
190            "  tcp:HOST[:PORT]             PORT (default: %d) on remote TCP HOST\n",
191            program_name, program_name, OFP_TCP_PORT);
192 #ifdef HAVE_NETLINK
193     printf("  nl:DP_IDX                   via netlink to local datapath DP_IDX\n");
194 #endif
195 #ifdef HAVE_OPENSSL
196     printf("  ssl:HOST[:PORT]             SSL PORT (default: %d) on remote HOST\n"
197            "\nPKI configuration (required to use SSL):\n"
198            "  -p, --private-key=FILE      file with private key\n"
199            "  -c, --certificate=FILE      file with certificate for private key\n"
200            "  -C, --ca-cert=FILE          file with peer CA certificate\n",
201            OFP_SSL_PORT);
202 #endif
203     printf("\nOptions:\n"
204            "  -v, --verbose               set maximum verbosity level\n"
205            "  -h, --help                  display this help message\n"
206            "  -V, --version               display version information\n");
207     exit(EXIT_SUCCESS);
208 }
209
210 static void run(int retval, const char *name) 
211 {
212     if (retval) {
213         fatal(retval, "%s", name);
214     }
215 }
216 \f
217 #ifdef HAVE_NETLINK
218 /* Netlink-only commands. */
219
220 static int  if_up(const char* intf)
221 {
222     char command[256];
223     snprintf(command, sizeof command, "%s %s up &> /dev/null",
224             ifconfigbin, intf);
225     return system(command);
226 }
227
228 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
229 {
230     if (strncmp(name, "nl:", 3)
231         || strlen(name) < 4
232         || name[strspn(name + 3, "0123456789") + 3]) {
233         fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
234     }
235     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
236 }
237
238 static void do_add_dp(int argc UNUSED, char *argv[])
239 {
240     struct dpif dp;
241     open_nl_vconn(argv[1], false, &dp);
242     run(dpif_add_dp(&dp), "add_dp");
243     dpif_close(&dp);
244 }
245
246 static void do_del_dp(int argc UNUSED, char *argv[])
247 {
248     struct dpif dp;
249     open_nl_vconn(argv[1], false, &dp);
250     run(dpif_del_dp(&dp), "del_dp");
251     dpif_close(&dp);
252 }
253
254 static void do_add_port(int argc UNUSED, char *argv[])
255 {
256     struct dpif dp;
257     if_up(argv[2]);
258     open_nl_vconn(argv[1], false, &dp);
259     run(dpif_add_port(&dp, argv[2]), "add_port");
260     dpif_close(&dp);
261 }
262
263 static void do_del_port(int argc UNUSED, char *argv[])
264 {
265     struct dpif dp;
266     open_nl_vconn(argv[1], false, &dp);
267     run(dpif_del_port(&dp, argv[2]), "del_port");
268     dpif_close(&dp);
269 }
270
271 #define BENCHMARK_INCR   100
272
273 static void do_benchmark_nl(int argc UNUSED, char *argv[])
274 {
275     struct dpif dp;
276     uint32_t num_packets, i, milestone;
277     struct timeval start, end;
278
279     open_nl_vconn(argv[1], false, &dp);
280     num_packets = atoi(argv[2]);
281     milestone = BENCHMARK_INCR;
282     run(dpif_benchmark_nl(&dp, num_packets, atoi(argv[3])), "benchmark_nl");
283     if (gettimeofday(&start, NULL) == -1) {
284         run(errno, "gettimeofday");
285     }
286     for (i = 0; i < num_packets;i++) {
287         struct buffer *b;
288         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
289         if (i == milestone) {
290             gettimeofday(&end, NULL);
291             printf("%u packets received in %f ms\n",
292                    BENCHMARK_INCR,
293                    (1000*(double)(end.tv_sec - start.tv_sec))
294                    + (.001*(end.tv_usec - start.tv_usec)));
295             milestone += BENCHMARK_INCR;
296             start = end;
297         }
298         buffer_delete(b);
299     }
300     gettimeofday(&end, NULL);
301     printf("%u packets received in %f ms\n",
302            i - (milestone - BENCHMARK_INCR),
303            (1000*(double)(end.tv_sec - start.tv_sec))
304            + (.001*(end.tv_usec - start.tv_usec)));
305
306     dpif_close(&dp);
307 }
308 #endif /* HAVE_NETLINK */
309 \f
310 /* Generic commands. */
311
312 static void do_show(int argc UNUSED, char *argv[])
313 {
314 #if 0
315     struct dpif dp;
316     run(dpif_open(atoi(argv[1]), false, &dp), "dpif_open");
317     run(dpif_show(&dp), "show");
318     dpif_close(&dp);
319 #endif
320 }
321
322 static void do_monitor(int argc UNUSED, char *argv[])
323 {
324     struct dpif dp;
325     run(dpif_open(atoi(argv[1]), true, &dp), "dpif_open");
326     for (;;) {
327         struct buffer *b;
328         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
329         ofp_print(stderr, b->data, b->size, 2);
330         buffer_delete(b);
331     }
332 }
333
334 static void do_dump_tables(int argc, char *argv[])
335 {
336     struct dpif dp;
337     run(dpif_open(atoi(argv[1]), false, &dp), "dpif_open");
338     run(dpif_dump_tables(&dp), "dump_tables");
339     dpif_close(&dp);
340 }
341
342
343 static uint32_t
344 str_to_int(const char *str) 
345 {
346     uint32_t value;
347     if (sscanf(str, "%"SCNu32, &value) != 1) {
348         fatal(0, "invalid numeric format %s", str);
349     }
350     return value;
351 }
352
353 static void
354 str_to_mac(const char *str, uint8_t mac[6]) 
355 {
356     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
357                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
358         fatal(0, "invalid mac address %s", str);
359     }
360 }
361
362 static void
363 str_to_ip(const char *str, uint32_t *ip) 
364 {
365     struct in_addr in_addr;
366     int retval;
367
368     retval = lookup_ip(str, &in_addr);
369     if (retval) {
370         fatal(0, "%s: could not convert to IP address", str);
371     }
372     *ip = in_addr.s_addr;
373 }
374
375 static void
376 str_to_action(const char *str, struct ofp_action *action) 
377 {
378     uint16_t port;
379
380     if (!strcasecmp(str, "flood")) {
381         port = OFPP_FLOOD;
382     } else if (!strcasecmp(str, "controller")) {
383         port = OFPP_CONTROLLER;
384     } else {
385         port = str_to_int(str);
386     }
387
388     memset(action, 0, sizeof *action);
389     action->type = OFPAT_OUTPUT;
390     action->arg.output.port = htons(port);
391 }
392
393 static void
394 str_to_flow(char *string, struct ofp_match *match, struct ofp_action *action)
395 {
396     struct field {
397         const char *name;
398         uint32_t wildcard;
399         enum { F_U8, F_U16, F_MAC, F_IP } type;
400         size_t offset;
401     };
402
403 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
404     static const struct field fields[] = { 
405         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
406         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
407         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
408         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
409         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
410         { "nw_src", OFPFW_NW_SRC, F_IP, F_OFS(nw_src) },
411         { "nw_dst", OFPFW_NW_DST, F_IP, F_OFS(nw_dst) },
412         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
413         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
414         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
415     };
416
417     char *name, *value;
418     uint32_t wildcards;
419     bool got_action = false;
420
421     memset(match, 0, sizeof *match);
422     wildcards = OFPFW_ALL;
423     for (name = strtok(string, "="), value = strtok(NULL, " \t\n");
424          name && value;
425          name = strtok(NULL, "="), value = strtok(NULL, " \t\n"))
426     {
427         const struct field *f;
428         void *data;
429
430         if (action && !strcmp(name, "action")) {
431             got_action = true;
432             str_to_action(value, action);
433             continue;
434         }
435
436         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
437             if (!strcmp(f->name, name)) {
438                 goto found;
439             }
440         }
441         fprintf(stderr, "%s: unknown field %s (fields are",
442                 program_name, name);
443         for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
444             if (f != fields) {
445                 putc(',', stderr);
446             }
447             fprintf(stderr, " %s", f->name);
448         }
449         fprintf(stderr, ")\n");
450         exit(1);
451
452     found:
453         data = (char *) match + f->offset;
454         if (!strcmp(value, "*")) {
455             wildcards |= f->wildcard;
456         } else {
457             wildcards &= ~f->wildcard;
458             if (f->type == F_U8) {
459                 *(uint8_t *) data = str_to_int(value);
460             } else if (f->type == F_U16) {
461                 *(uint16_t *) data = htons(str_to_int(value));
462             } else if (f->type == F_MAC) {
463                 str_to_mac(value, data);
464             } else if (f->type == F_IP) {
465                 str_to_ip(value, data);
466             } else {
467                 NOT_REACHED();
468             }
469         }
470     }
471     if (name && !value) {
472         fatal(0, "field %s missing value", name);
473     }
474     if (action && !got_action) {
475         fatal(0, "must specify an action");
476     }
477     match->wildcards = htons(wildcards);
478 }
479
480 static void do_dump_flows(int argc, char *argv[])
481 {
482     struct dpif dp;
483     struct ofp_match match, *matchp;
484     run(dpif_open(atoi(argv[1]), false, &dp), "dpif_open");
485     if (argc == 4) {
486         str_to_flow(argv[3], &match, NULL);
487         matchp = &match;
488     } else {
489         matchp = NULL;
490     }
491     run(dpif_dump_flows(&dp, atoi(argv[2]), matchp), "dump_flows");
492     dpif_close(&dp);
493 }
494
495 static void do_add_flows(int argc, char *argv[])
496 {
497     struct vconn *vconn;
498     char vconn_name[16];
499
500     FILE *file;
501     char line[1024];
502
503     int retval;
504
505     file = fopen(argv[2], "r");
506     if (file == NULL) {
507         fatal(errno, "%s: open", argv[2]);
508     }
509
510     sprintf(vconn_name, "nl:%d", atoi(argv[1]));
511     retval = vconn_open(vconn_name, &vconn);
512     if (retval) {
513         fatal(retval, "opening datapath");
514     }
515
516     while (fgets(line, sizeof line, file)) {
517         struct buffer *buffer;
518         struct ofp_flow_mod *ofm;
519         size_t size;
520
521         char *comment;
522
523         /* Delete comments. */
524         comment = strchr(line, '#');
525         if (comment) {
526             *comment = '\0';
527         }
528
529         /* Drop empty lines. */
530         if (line[strspn(line, " \t\n")] == '\0') {
531             continue;
532         }
533
534         size = sizeof *ofm + sizeof ofm->actions[0];
535         buffer = buffer_new(size);
536         ofm = buffer_put_uninit(buffer, size);
537
538         /* Parse. */
539         memset(ofm, 0, size);
540         ofm->header.type = OFPT_FLOW_MOD;
541         ofm->header.version = OFP_VERSION;
542         ofm->header.length = htons(size);
543         ofm->command = htons(OFPFC_ADD);
544         ofm->max_idle = htons(50);
545         ofm->buffer_id = htonl(UINT32_MAX);
546         ofm->group_id = htonl(0);
547         str_to_flow(line, &ofm->match, &ofm->actions[0]);
548
549         retval = vconn_send_block(vconn, buffer);
550         if (retval) {
551             fatal(retval, "sending to datapath");
552         }
553     }
554     vconn_close(vconn);
555     fclose(file);
556 }
557
558 static void do_help(int argc UNUSED, char *argv[] UNUSED)
559 {
560     usage();
561 }
562
563 static struct command all_commands[] = {
564 #ifdef HAVE_NETLINK
565     { "adddp", 1, 1, do_add_dp },
566     { "deldp", 1, 1, do_del_dp },
567     { "addif", 2, 2, do_add_port },
568     { "delif", 2, 2, do_del_port },
569     { "benchmark-nl", 3, 3, do_benchmark_nl },
570 #endif
571
572     { "show", 1, 1, do_show },
573
574     { "help", 0, INT_MAX, do_help },
575     { "monitor", 1, 1, do_monitor },
576     { "dump-tables", 1, 1, do_dump_tables },
577     { "dump-flows", 2, 3, do_dump_flows },
578     { "add-flows", 2, 2, do_add_flows },
579 };