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