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