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