Rename utility functions to avoid partner namespace conflicts.
[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 <arpa/inet.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <sys/time.h>
46
47 #ifdef HAVE_NETLINK
48 #include "netdev.h"
49 #include "netlink.h"
50 #include "openflow-netlink.h"
51 #endif
52
53 #include "command-line.h"
54 #include "compiler.h"
55 #include "dpif.h"
56 #include "ofp-print.h"
57 #include "ofpbuf.h"
58 #include "openflow.h"
59 #include "packets.h"
60 #include "random.h"
61 #include "socket-util.h"
62 #include "timeval.h"
63 #include "util.h"
64 #include "vconn-ssl.h"
65 #include "vconn.h"
66
67 #include "vlog.h"
68 #define THIS_MODULE VLM_dpctl
69
70 #define DEFAULT_IDLE_TIMEOUT 60
71 #define MAX_ADD_ACTS 5
72
73 #define MOD_PORT_CMD_UP      "up"
74 #define MOD_PORT_CMD_DOWN    "down"
75 #define MOD_PORT_CMD_FLOOD   "flood"
76 #define MOD_PORT_CMD_NOFLOOD "noflood"
77
78 struct command {
79     const char *name;
80     int min_args;
81     int max_args;
82     void (*handler)(int argc, char *argv[]);
83 };
84
85 static struct command all_commands[];
86
87 static void usage(void) NO_RETURN;
88 static void parse_options(int argc, char *argv[]);
89
90 int main(int argc, char *argv[])
91 {
92     struct command *p;
93
94     set_program_name(argv[0]);
95     time_init();
96     vlog_init();
97     parse_options(argc, argv);
98     signal(SIGPIPE, SIG_IGN);
99
100     argc -= optind;
101     argv += optind;
102     if (argc < 1)
103         ofp_fatal(0, "missing command name; use --help for help");
104
105     for (p = all_commands; p->name != NULL; p++) {
106         if (!strcmp(p->name, argv[0])) {
107             int n_arg = argc - 1;
108             if (n_arg < p->min_args)
109                 ofp_fatal(0, "'%s' command requires at least %d arguments",
110                           p->name, p->min_args);
111             else if (n_arg > p->max_args)
112                 ofp_fatal(0, "'%s' command takes at most %d arguments",
113                           p->name, p->max_args);
114             else {
115                 p->handler(argc, argv);
116                 exit(0);
117             }
118         }
119     }
120     ofp_fatal(0, "unknown command '%s'; use --help for help", argv[0]);
121
122     return 0;
123 }
124
125 static void
126 parse_options(int argc, char *argv[])
127 {
128     static struct option long_options[] = {
129         {"timeout", required_argument, 0, 't'},
130         {"verbose", optional_argument, 0, 'v'},
131         {"help", no_argument, 0, 'h'},
132         {"version", no_argument, 0, 'V'},
133         VCONN_SSL_LONG_OPTIONS
134         {0, 0, 0, 0},
135     };
136     char *short_options = long_options_to_short_options(long_options);
137
138     for (;;) {
139         unsigned long int timeout;
140         int c;
141
142         c = getopt_long(argc, argv, short_options, long_options, NULL);
143         if (c == -1) {
144             break;
145         }
146
147         switch (c) {
148         case 't':
149             timeout = strtoul(optarg, NULL, 10);
150             if (timeout <= 0) {
151                 ofp_fatal(0, "value %s on -t or --timeout is not at least 1",
152                           optarg);
153             } else {
154                 time_alarm(timeout);
155             }
156             break;
157
158         case 'h':
159             usage();
160
161         case 'V':
162             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
163             exit(EXIT_SUCCESS);
164
165         case 'v':
166             vlog_set_verbosity(optarg);
167             break;
168
169         VCONN_SSL_OPTION_HANDLERS
170
171         case '?':
172             exit(EXIT_FAILURE);
173
174         default:
175             abort();
176         }
177     }
178     free(short_options);
179 }
180
181 static void
182 usage(void)
183 {
184     printf("%s: OpenFlow switch management utility\n"
185            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
186 #ifdef HAVE_NETLINK
187            "\nFor local datapaths only:\n"
188            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
189            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
190            "  addif nl:DP_ID IFACE...     add each IFACE as a port on DP_ID\n"
191            "  delif nl:DP_ID IFACE...     delete each IFACE from DP_ID\n"
192            "  monitor nl:DP_ID            print packets received\n"
193 #endif
194            "\nFor local datapaths and remote switches:\n"
195            "  show SWITCH                 show basic information\n"
196            "  status SWITCH [KEY]         report statistics (about KEY)\n"
197            "  dump-desc SWITCH            print switch description\n"
198            "  dump-tables SWITCH          print table stats\n"
199            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
200            "  dump-ports SWITCH           print port statistics\n"
201            "  dump-flows SWITCH           print all flow entries\n"
202            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
203            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
204            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
205            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
206            "  add-flows SWITCH FILE       add flows from FILE\n"
207            "  del-flows SWITCH FLOW       delete matching FLOWs\n"
208            "\nFor local datapaths, remote switches, and controllers:\n"
209            "  probe VCONN                 probe whether VCONN is up\n"
210            "  ping VCONN [N]              latency of N-byte echos\n"
211            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
212            "where each SWITCH is an active OpenFlow connection method.\n",
213            program_name, program_name);
214     vconn_usage(true, false);
215     printf("\nOptions:\n"
216            "  -t, --timeout=SECS          give up after SECS seconds\n"
217            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
218            "  -v, --verbose               set maximum verbosity level\n"
219            "  -h, --help                  display this help message\n"
220            "  -V, --version               display version information\n");
221     exit(EXIT_SUCCESS);
222 }
223
224 static void run(int retval, const char *message, ...)
225     PRINTF_FORMAT(2, 3);
226
227 static void run(int retval, const char *message, ...)
228 {
229     if (retval) {
230         va_list args;
231
232         fprintf(stderr, "%s: ", program_name);
233         va_start(args, message);
234         vfprintf(stderr, message, args);
235         va_end(args);
236         if (retval == EOF) {
237             fputs(": unexpected end of file\n", stderr);
238         } else {
239             fprintf(stderr, ": %s\n", strerror(retval));
240         }
241
242         exit(EXIT_FAILURE);
243     }
244 }
245 \f
246 #ifdef HAVE_NETLINK
247 /* Netlink-only commands. */
248
249 static int if_up(const char *netdev_name)
250 {
251     struct netdev *netdev;
252     int retval;
253
254     retval = netdev_open(netdev_name, NETDEV_ETH_TYPE_NONE, &netdev);
255     if (!retval) {
256         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
257         netdev_close(netdev);
258     }
259     return retval;
260 }
261
262 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
263 {
264     if (strncmp(name, "nl:", 3)
265         || strlen(name) < 4
266         || name[strspn(name + 3, "0123456789") + 3]) {
267         ofp_fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
268     }
269     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
270 }
271
272 static void do_add_dp(int argc UNUSED, char *argv[])
273 {
274     struct dpif dp;
275     open_nl_vconn(argv[1], false, &dp);
276     run(dpif_add_dp(&dp), "add_dp");
277     dpif_close(&dp);
278 }
279
280 static void do_del_dp(int argc UNUSED, char *argv[])
281 {
282     struct dpif dp;
283     open_nl_vconn(argv[1], false, &dp);
284     run(dpif_del_dp(&dp), "del_dp");
285     dpif_close(&dp);
286 }
287
288 static void add_del_ports(int argc UNUSED, char *argv[],
289                           int (*function)(struct dpif *, const char *netdev),
290                           const char *operation, const char *preposition)
291 {
292     struct dpif dp;
293     bool failure = false;
294     int i;
295
296     open_nl_vconn(argv[1], false, &dp);
297     for (i = 2; i < argc; i++) {
298         int retval = function(&dp, argv[i]);
299         if (retval) {
300             ofp_error(retval, "failed to %s %s %s %s",
301                       operation, argv[i], preposition, argv[1]);
302             failure = true;
303         }
304     }
305     dpif_close(&dp);
306     if (failure) {
307         exit(EXIT_FAILURE);
308     }
309 }
310
311 static int ifup_and_add_port(struct dpif *dpif, const char *netdev)
312 {
313     int retval = if_up(netdev);
314     return retval ? retval : dpif_add_port(dpif, netdev);
315 }
316
317 static void do_add_port(int argc UNUSED, char *argv[])
318 {
319     add_del_ports(argc, argv, ifup_and_add_port, "add", "to");
320 }
321
322 static void do_del_port(int argc UNUSED, char *argv[])
323 {
324     add_del_ports(argc, argv, dpif_del_port, "remove", "from");
325 }
326
327 static void do_monitor(int argc UNUSED, char *argv[])
328 {
329     struct dpif dp;
330     open_nl_vconn(argv[1], true, &dp);
331     for (;;) {
332         struct ofpbuf *b;
333         run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
334         ofp_print(stderr, b->data, b->size, 2);
335         ofpbuf_delete(b);
336     }
337 }
338 #endif /* HAVE_NETLINK */
339 \f
340 /* Generic commands. */
341
342 static void *
343 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
344 {
345     struct ofp_stats_request *rq;
346     rq = make_openflow((offsetof(struct ofp_stats_request, body)
347                         + body_len), OFPT_STATS_REQUEST, bufferp);
348     rq->type = htons(type);
349     rq->flags = htons(0);
350     return rq->body;
351 }
352
353 static void
354 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
355 {
356     update_openflow_length(buffer);
357     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
358 }
359
360 static void
361 dump_transaction(const char *vconn_name, struct ofpbuf *request)
362 {
363     struct vconn *vconn;
364     struct ofpbuf *reply;
365
366     update_openflow_length(request);
367     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
368     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
369     ofp_print(stdout, reply->data, reply->size, 1);
370     vconn_close(vconn);
371 }
372
373 static void
374 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
375 {
376     struct ofpbuf *request;
377     make_openflow(sizeof(struct ofp_header), request_type, &request);
378     dump_transaction(vconn_name, request);
379 }
380
381 static void
382 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
383 {
384     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
385     struct vconn *vconn;
386     bool done = false;
387
388     run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
389     send_openflow_buffer(vconn, request);
390     while (!done) {
391         uint32_t recv_xid;
392         struct ofpbuf *reply;
393
394         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
395         recv_xid = ((struct ofp_header *) reply->data)->xid;
396         if (send_xid == recv_xid) {
397             struct ofp_stats_reply *osr;
398
399             ofp_print(stdout, reply->data, reply->size, 1);
400
401             osr = ofpbuf_at(reply, 0, sizeof *osr);
402             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
403         } else {
404             VLOG_DBG("received reply with xid %08"PRIx32" "
405                      "!= expected %08"PRIx32, recv_xid, send_xid);
406         }
407         ofpbuf_delete(reply);
408     }
409     vconn_close(vconn);
410 }
411
412 static void
413 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
414 {
415     struct ofpbuf *request;
416     alloc_stats_request(0, stats_type, &request);
417     dump_stats_transaction(vconn_name, request);
418 }
419
420 static void
421 do_show(int argc UNUSED, char *argv[])
422 {
423     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
424     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
425 }
426
427 static void
428 do_status(int argc, char *argv[])
429 {
430     struct ofpbuf *request;
431     alloc_stats_request(0, OFPST_SWITCH, &request);
432     if (argc > 2) {
433         ofpbuf_put(request, argv[2], strlen(argv[2]));
434     }
435     dump_stats_transaction(argv[1], request);
436 }
437
438 static void
439 do_dump_desc(int argc, char *argv[])
440 {
441     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
442 }
443
444 static void
445 do_dump_tables(int argc, char *argv[])
446 {
447     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
448 }
449
450
451 static uint32_t
452 str_to_int(const char *str) 
453 {
454     char *tail;
455     uint32_t value;
456
457     errno = 0;
458     value = strtoul(str, &tail, 0);
459     if (errno == EINVAL || errno == ERANGE || *tail) {
460         ofp_fatal(0, "invalid numeric format %s", str);
461     }
462     return value;
463 }
464
465 static void
466 str_to_mac(const char *str, uint8_t mac[6]) 
467 {
468     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
469                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
470         ofp_fatal(0, "invalid mac address %s", str);
471     }
472 }
473
474 static uint32_t
475 str_to_ip(const char *str_, uint32_t *ip)
476 {
477     char *str = xstrdup(str_);
478     char *save_ptr = NULL;
479     const char *name, *netmask;
480     struct in_addr in_addr;
481     int n_wild, retval;
482
483     name = strtok_r(str, "//", &save_ptr);
484     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
485     if (retval) {
486         ofp_fatal(0, "%s: could not convert to IP address", str);
487     }
488     *ip = in_addr.s_addr;
489
490     netmask = strtok_r(NULL, "//", &save_ptr);
491     if (netmask) {
492         uint8_t o[4];
493         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
494                    &o[0], &o[1], &o[2], &o[3]) == 4) {
495             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
496             int i;
497
498             /* Find first 1-bit. */
499             for (i = 0; i < 32; i++) {
500                 if (nm & (1u << i)) {
501                     break;
502                 }
503             }
504             n_wild = i;
505
506             /* Verify that the rest of the bits are 1-bits. */
507             for (; i < 32; i++) {
508                 if (!(nm & (1u << i))) {
509                     ofp_fatal(0, "%s: %s is not a valid netmask",
510                               str, netmask);
511                 }
512             }
513         } else {
514             int prefix = atoi(netmask);
515             if (prefix <= 0 || prefix > 32) {
516                 ofp_fatal(0, "%s: network prefix bits not between 1 and 32",
517                           str);
518             }
519             n_wild = 32 - prefix;
520         }
521     } else {
522         n_wild = 0;
523     }
524
525     free(str);
526     return n_wild;
527 }
528
529 static void
530 str_to_action(char *str, struct ofp_action *action, int *n_actions) 
531 {
532     uint16_t port;
533     int i;
534     int max_actions = *n_actions;
535     char *act, *arg;
536     char *saveptr = NULL;
537     
538     memset(action, 0, sizeof(*action) * max_actions);
539     for (i=0, act = strtok_r(str, ", \t\r\n", &saveptr); 
540          i<max_actions && act;
541          i++, act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
542     {
543         port = OFPP_MAX;
544
545         /* Arguments are separated by colons */
546         arg = strchr(act, ':');
547         if (arg) {
548             *arg = '\0';
549             arg++;
550         } 
551
552         if (!strcasecmp(act, "mod_vlan")) {
553             action[i].type = htons(OFPAT_SET_DL_VLAN);
554
555             if (!strcasecmp(arg, "strip")) {
556                 action[i].arg.vlan_id = htons(OFP_VLAN_NONE);
557             } else {
558                 action[i].arg.vlan_id = htons(str_to_int(arg));
559             }
560         } else if (!strcasecmp(act, "output")) {
561             port = str_to_int(arg);
562         } else if (!strcasecmp(act, "TABLE")) {
563             port = OFPP_TABLE;
564         } else if (!strcasecmp(act, "NORMAL")) {
565             port = OFPP_NORMAL;
566         } else if (!strcasecmp(act, "FLOOD")) {
567             port = OFPP_FLOOD;
568         } else if (!strcasecmp(act, "ALL")) {
569             port = OFPP_ALL;
570         } else if (!strcasecmp(act, "CONTROLLER")) {
571             port = OFPP_CONTROLLER;
572             if (arg) {
573                 if (!strcasecmp(arg, "all")) {
574                     action[i].arg.output.max_len= htons(0);
575                 } else {
576                     action[i].arg.output.max_len= htons(str_to_int(arg));
577                 }
578             }
579         } else if (!strcasecmp(act, "LOCAL")) {
580             port = OFPP_LOCAL;
581         } else if (strspn(act, "0123456789") == strlen(act)) {
582             port = str_to_int(act);
583         } else {
584             ofp_fatal(0, "Unknown action: %s", act);
585         }
586
587         if (port != OFPP_MAX) {
588             action[i].type = htons(OFPAT_OUTPUT);
589             action[i].arg.output.port = htons(port);
590         }
591     }
592
593     *n_actions = i;
594 }
595
596 struct protocol {
597     const char *name;
598     uint16_t dl_type;
599     uint8_t nw_proto;
600 };
601
602 static bool
603 parse_protocol(const char *name, const struct protocol **p_out)
604 {
605     static const struct protocol protocols[] = {
606         { "ip", ETH_TYPE_IP },
607         { "arp", ETH_TYPE_ARP },
608         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
609         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
610         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
611     };
612     const struct protocol *p;
613
614     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
615         if (!strcmp(p->name, name)) {
616             *p_out = p;
617             return true;
618         }
619     }
620     *p_out = NULL;
621     return false;
622 }
623
624 struct field {
625     const char *name;
626     uint32_t wildcard;
627     enum { F_U8, F_U16, F_MAC, F_IP } type;
628     size_t offset, shift;
629 };
630
631 static bool
632 parse_field(const char *name, const struct field **f_out) 
633 {
634 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
635     static const struct field fields[] = { 
636         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
637         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
638         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
639         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
640         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
641         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
642           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
643         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
644           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
645         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
646         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
647         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
648     };
649     const struct field *f;
650
651     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
652         if (!strcmp(f->name, name)) {
653             *f_out = f;
654             return true;
655         }
656     }
657     *f_out = NULL;
658     return false;
659 }
660
661 static void
662 str_to_flow(char *string, struct ofp_match *match, 
663             struct ofp_action *action, int *n_actions, uint8_t *table_idx, 
664             uint16_t *priority, uint16_t *idle_timeout, uint16_t *hard_timeout)
665 {
666
667     char *name;
668     uint32_t wildcards;
669
670     if (table_idx) {
671         *table_idx = 0xff;
672     }
673     if (priority) {
674         *priority = OFP_DEFAULT_PRIORITY;
675     }
676     if (idle_timeout) {
677         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
678     }
679     if (hard_timeout) {
680         *hard_timeout = OFP_FLOW_PERMANENT;
681     }
682     if (action) {
683         char *act_str = strstr(string, "action");
684         if (!act_str) {
685             ofp_fatal(0, "must specify an action");
686         }
687         *(act_str-1) = '\0';
688
689         act_str = strchr(act_str, '=');
690         if (!act_str) {
691             ofp_fatal(0, "must specify an action");
692         }
693
694         act_str++;
695
696         str_to_action(act_str, action, n_actions);
697     }
698     memset(match, 0, sizeof *match);
699     wildcards = OFPFW_ALL;
700     for (name = strtok(string, "=, \t\r\n"); name;
701          name = strtok(NULL, "=, \t\r\n")) {
702         const struct protocol *p;
703
704         if (parse_protocol(name, &p)) {
705             wildcards &= ~OFPFW_DL_TYPE;
706             match->dl_type = htons(p->dl_type);
707             if (p->nw_proto) {
708                 wildcards &= ~OFPFW_NW_PROTO;
709                 match->nw_proto = p->nw_proto;
710             }
711         } else {
712             const struct field *f;
713             char *value;
714
715             value = strtok(NULL, ", \t\r\n");
716             if (!value) {
717                 ofp_fatal(0, "field %s missing value", name);
718             }
719         
720             if (table_idx && !strcmp(name, "table")) {
721                 *table_idx = atoi(value);
722             } else if (priority && !strcmp(name, "priority")) {
723                 *priority = atoi(value);
724             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
725                 *idle_timeout = atoi(value);
726             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
727                 *hard_timeout = atoi(value);
728             } else if (parse_field(name, &f)) {
729                 void *data = (char *) match + f->offset;
730                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
731                     wildcards |= f->wildcard;
732                 } else {
733                     wildcards &= ~f->wildcard;
734                     if (f->type == F_U8) {
735                         *(uint8_t *) data = str_to_int(value);
736                     } else if (f->type == F_U16) {
737                         *(uint16_t *) data = htons(str_to_int(value));
738                     } else if (f->type == F_MAC) {
739                         str_to_mac(value, data);
740                     } else if (f->type == F_IP) {
741                         wildcards |= str_to_ip(value, data) << f->shift;
742                     } else {
743                         NOT_REACHED();
744                     }
745                 }
746             } else {
747                 ofp_fatal(0, "unknown keyword %s", name);
748             }
749         }
750     }
751     match->wildcards = htonl(wildcards);
752 }
753
754 static void do_dump_flows(int argc, char *argv[])
755 {
756     struct ofp_flow_stats_request *req;
757     struct ofpbuf *request;
758
759     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
760     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
761                 &req->table_id, NULL, NULL, NULL);
762     memset(req->pad, 0, sizeof req->pad);
763
764     dump_stats_transaction(argv[1], request);
765 }
766
767 static void do_dump_aggregate(int argc, char *argv[])
768 {
769     struct ofp_aggregate_stats_request *req;
770     struct ofpbuf *request;
771
772     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
773     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
774                 &req->table_id, NULL, NULL, NULL);
775     memset(req->pad, 0, sizeof req->pad);
776
777     dump_stats_transaction(argv[1], request);
778 }
779
780 static void do_add_flow(int argc, char *argv[])
781 {
782     struct vconn *vconn;
783     struct ofpbuf *buffer;
784     struct ofp_flow_mod *ofm;
785     uint16_t priority, idle_timeout, hard_timeout;
786     size_t size;
787     int n_actions = MAX_ADD_ACTS;
788
789     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
790
791     /* Parse and send. */
792     size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
793     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
794     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &n_actions, 
795                 NULL, &priority, &idle_timeout, &hard_timeout);
796     ofm->command = htons(OFPFC_ADD);
797     ofm->idle_timeout = htons(idle_timeout);
798     ofm->hard_timeout = htons(hard_timeout);
799     ofm->buffer_id = htonl(UINT32_MAX);
800     ofm->priority = htons(priority);
801     ofm->reserved = htonl(0);
802
803     /* xxx Should we use the ofpbuf library? */
804     buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
805
806     send_openflow_buffer(vconn, buffer);
807     vconn_close(vconn);
808 }
809
810 static void do_add_flows(int argc, char *argv[])
811 {
812     struct vconn *vconn;
813
814     FILE *file;
815     char line[1024];
816
817     file = fopen(argv[2], "r");
818     if (file == NULL) {
819         ofp_fatal(errno, "%s: open", argv[2]);
820     }
821
822     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
823     while (fgets(line, sizeof line, file)) {
824         struct ofpbuf *buffer;
825         struct ofp_flow_mod *ofm;
826         uint16_t priority, idle_timeout, hard_timeout;
827         size_t size;
828         int n_actions = MAX_ADD_ACTS;
829
830         char *comment;
831
832         /* Delete comments. */
833         comment = strchr(line, '#');
834         if (comment) {
835             *comment = '\0';
836         }
837
838         /* Drop empty lines. */
839         if (line[strspn(line, " \t\n")] == '\0') {
840             continue;
841         }
842
843         /* Parse and send. */
844         size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
845         ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
846         str_to_flow(line, &ofm->match, &ofm->actions[0], &n_actions, 
847                     NULL, &priority, &idle_timeout, &hard_timeout);
848         ofm->command = htons(OFPFC_ADD);
849         ofm->idle_timeout = htons(idle_timeout);
850         ofm->hard_timeout = htons(hard_timeout);
851         ofm->buffer_id = htonl(UINT32_MAX);
852         ofm->priority = htons(priority);
853         ofm->reserved = htonl(0);
854
855         /* xxx Should we use the ofpbuf library? */
856         buffer->size -= (MAX_ADD_ACTS - n_actions) * sizeof ofm->actions[0];
857
858         send_openflow_buffer(vconn, buffer);
859     }
860     vconn_close(vconn);
861     fclose(file);
862 }
863
864 static void do_del_flows(int argc, char *argv[])
865 {
866     struct vconn *vconn;
867     uint16_t priority;
868
869     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
870     struct ofpbuf *buffer;
871     struct ofp_flow_mod *ofm;
872     size_t size;
873
874
875     /* Parse and send. */
876     size = sizeof *ofm;
877     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
878     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
879                 &priority, NULL, NULL);
880     ofm->command = htons(OFPFC_DELETE);
881     ofm->idle_timeout = htons(0);
882     ofm->hard_timeout = htons(0);
883     ofm->buffer_id = htonl(UINT32_MAX);
884     ofm->priority = htons(priority);
885     ofm->reserved = htonl(0);
886
887     send_openflow_buffer(vconn, buffer);
888
889     vconn_close(vconn);
890 }
891
892 static void
893 do_dump_ports(int argc, char *argv[])
894 {
895     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
896 }
897
898 static void
899 do_probe(int argc, char *argv[])
900 {
901     struct ofpbuf *request;
902     struct vconn *vconn;
903     struct ofpbuf *reply;
904
905     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
906     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
907     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
908     if (reply->size != request->size) {
909         ofp_fatal(0, "reply does not match request");
910     }
911     ofpbuf_delete(reply);
912     vconn_close(vconn);
913 }
914
915 static void
916 do_mod_port(int argc, char *argv[])
917 {
918     struct ofpbuf *request, *reply;
919     struct ofp_switch_features *osf;
920     struct ofp_port_mod *opm;
921     struct vconn *vconn;
922     char *endptr;
923     int n_ports;
924     int port_idx;
925     int port_no;
926     
927
928     /* Check if the argument is a port index.  Otherwise, treat it as
929      * the port name. */
930     port_no = strtol(argv[2], &endptr, 10);
931     if (port_no == 0 && endptr == argv[2]) {
932         port_no = -1;
933     }
934
935     /* Send a "Features Request" to get the information we need in order 
936      * to modify the port. */
937     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
938     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
939     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
940
941     osf = reply->data;
942     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
943
944     for (port_idx = 0; port_idx < n_ports; port_idx++) {
945         if (port_no != -1) {
946             /* Check argument as a port index */
947             if (osf->ports[port_idx].port_no == htons(port_no)) {
948                 break;
949             }
950         } else {
951             /* Check argument as an interface name */
952             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
953                         sizeof osf->ports[0].name)) {
954                 break;
955             }
956
957         }
958     }
959     if (port_idx == n_ports) {
960         ofp_fatal(0, "couldn't find monitored port: %s", argv[2]);
961     }
962
963     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
964     memcpy(&opm->desc, &osf->ports[port_idx], sizeof osf->ports[0]);
965     opm->mask = 0;
966     opm->desc.flags = 0;
967
968     printf("modifying port: %s\n", osf->ports[port_idx].name);
969
970     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
971         opm->mask |= htonl(OFPPFL_PORT_DOWN);
972     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
973                 sizeof MOD_PORT_CMD_DOWN)) {
974         opm->mask |= htonl(OFPPFL_PORT_DOWN);
975         opm->desc.flags |= htonl(OFPPFL_PORT_DOWN);
976     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
977                 sizeof MOD_PORT_CMD_FLOOD)) {
978         opm->mask |= htonl(OFPPFL_NO_FLOOD);
979     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
980                 sizeof MOD_PORT_CMD_NOFLOOD)) {
981         opm->mask |= htonl(OFPPFL_NO_FLOOD);
982         opm->desc.flags |= htonl(OFPPFL_NO_FLOOD);
983     } else {
984         ofp_fatal(0, "unknown mod-port command '%s'", argv[3]);
985     }
986
987     send_openflow_buffer(vconn, request);
988
989     ofpbuf_delete(reply);
990     vconn_close(vconn);
991 }
992
993 static void
994 do_ping(int argc, char *argv[])
995 {
996     size_t max_payload = 65535 - sizeof(struct ofp_header);
997     unsigned int payload;
998     struct vconn *vconn;
999     int i;
1000
1001     payload = argc > 2 ? atoi(argv[2]) : 64;
1002     if (payload > max_payload) {
1003         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1004     }
1005
1006     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
1007     for (i = 0; i < 10; i++) {
1008         struct timeval start, end;
1009         struct ofpbuf *request, *reply;
1010         struct ofp_header *rq_hdr, *rpy_hdr;
1011
1012         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1013                                OFPT_ECHO_REQUEST, &request);
1014         random_bytes(rq_hdr + 1, payload);
1015
1016         gettimeofday(&start, NULL);
1017         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1018         gettimeofday(&end, NULL);
1019
1020         rpy_hdr = reply->data;
1021         if (reply->size != request->size
1022             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1023             || rpy_hdr->xid != rq_hdr->xid
1024             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1025             printf("Reply does not match request.  Request:\n");
1026             ofp_print(stdout, request, request->size, 2);
1027             printf("Reply:\n");
1028             ofp_print(stdout, reply, reply->size, 2);
1029         }
1030         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1031                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1032                    (1000*(double)(end.tv_sec - start.tv_sec))
1033                    + (.001*(end.tv_usec - start.tv_usec)));
1034         ofpbuf_delete(request);
1035         ofpbuf_delete(reply);
1036     }
1037     vconn_close(vconn);
1038 }
1039
1040 static void
1041 do_benchmark(int argc, char *argv[])
1042 {
1043     size_t max_payload = 65535 - sizeof(struct ofp_header);
1044     struct timeval start, end;
1045     unsigned int payload_size, message_size;
1046     struct vconn *vconn;
1047     double duration;
1048     int count;
1049     int i;
1050
1051     payload_size = atoi(argv[2]);
1052     if (payload_size > max_payload) {
1053         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1054     }
1055     message_size = sizeof(struct ofp_header) + payload_size;
1056
1057     count = atoi(argv[3]);
1058
1059     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1060            count, message_size, count * message_size);
1061
1062     run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
1063     gettimeofday(&start, NULL);
1064     for (i = 0; i < count; i++) {
1065         struct ofpbuf *request, *reply;
1066         struct ofp_header *rq_hdr;
1067
1068         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1069         memset(rq_hdr + 1, 0, payload_size);
1070         run(vconn_transact(vconn, request, &reply), "transact");
1071         ofpbuf_delete(reply);
1072     }
1073     gettimeofday(&end, NULL);
1074     vconn_close(vconn);
1075
1076     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1077                 + (.001*(end.tv_usec - start.tv_usec)));
1078     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1079            duration, count / (duration / 1000.0),
1080            count * message_size / (duration / 1000.0));
1081 }
1082
1083 static void do_help(int argc UNUSED, char *argv[] UNUSED)
1084 {
1085     usage();
1086 }
1087
1088 static struct command all_commands[] = {
1089 #ifdef HAVE_NETLINK
1090     { "adddp", 1, 1, do_add_dp },
1091     { "deldp", 1, 1, do_del_dp },
1092     { "addif", 2, INT_MAX, do_add_port },
1093     { "delif", 2, INT_MAX, do_del_port },
1094 #endif
1095
1096     { "show", 1, 1, do_show },
1097     { "status", 1, 2, do_status },
1098
1099     { "help", 0, INT_MAX, do_help },
1100     { "monitor", 1, 1, do_monitor },
1101     { "dump-desc", 1, 1, do_dump_desc },
1102     { "dump-tables", 1, 1, do_dump_tables },
1103     { "dump-flows", 1, 2, do_dump_flows },
1104     { "dump-aggregate", 1, 2, do_dump_aggregate },
1105     { "add-flow", 2, 2, do_add_flow },
1106     { "add-flows", 2, 2, do_add_flows },
1107     { "del-flows", 1, 2, do_del_flows },
1108     { "dump-ports", 1, 1, do_dump_ports },
1109     { "mod-port", 3, 3, do_mod_port },
1110     { "probe", 1, 1, do_probe },
1111     { "ping", 1, 2, do_ping },
1112     { "benchmark", 3, 3, do_benchmark },
1113     { NULL, 0, 0, NULL },
1114 };