Merge branch 'master' into next
[sliver-openvswitch.git] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <net/if.h>
23 #include <netinet/in.h>
24 #include <signal.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31
32 #include "command-line.h"
33 #include "compiler.h"
34 #include "dirs.h"
35 #include "dpif.h"
36 #include "dynamic-string.h"
37 #include "netdev.h"
38 #include "netlink.h"
39 #include "odp-util.h"
40 #include "ofp-print.h"
41 #include "ofpbuf.h"
42 #include "openflow/nicira-ext.h"
43 #include "openflow/openflow.h"
44 #include "packets.h"
45 #include "random.h"
46 #include "socket-util.h"
47 #include "stream-ssl.h"
48 #include "timeval.h"
49 #include "util.h"
50 #include "vconn.h"
51
52 #include "vlog.h"
53 #define THIS_MODULE VLM_ofctl
54
55 #define DEFAULT_IDLE_TIMEOUT 60
56
57 #define MOD_PORT_CMD_UP      "up"
58 #define MOD_PORT_CMD_DOWN    "down"
59 #define MOD_PORT_CMD_FLOOD   "flood"
60 #define MOD_PORT_CMD_NOFLOOD "noflood"
61
62 /* Use strict matching for flow mod commands? */
63 static bool strict;
64
65 static const struct command all_commands[];
66
67 static void usage(void) NO_RETURN;
68 static void parse_options(int argc, char *argv[]);
69
70 int
71 main(int argc, char *argv[])
72 {
73     set_program_name(argv[0]);
74     time_init();
75     vlog_init();
76     parse_options(argc, argv);
77     signal(SIGPIPE, SIG_IGN);
78     run_command(argc - optind, argv + optind, all_commands);
79     return 0;
80 }
81
82 static void
83 parse_options(int argc, char *argv[])
84 {
85     enum {
86         OPT_STRICT = UCHAR_MAX + 1,
87         VLOG_OPTION_ENUMS
88     };
89     static struct option long_options[] = {
90         {"timeout", required_argument, 0, 't'},
91         {"strict", no_argument, 0, OPT_STRICT},
92         {"help", no_argument, 0, 'h'},
93         {"version", no_argument, 0, 'V'},
94         VLOG_LONG_OPTIONS,
95         STREAM_SSL_LONG_OPTIONS
96         {0, 0, 0, 0},
97     };
98     char *short_options = long_options_to_short_options(long_options);
99
100     for (;;) {
101         unsigned long int timeout;
102         int c;
103
104         c = getopt_long(argc, argv, short_options, long_options, NULL);
105         if (c == -1) {
106             break;
107         }
108
109         switch (c) {
110         case 't':
111             timeout = strtoul(optarg, NULL, 10);
112             if (timeout <= 0) {
113                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
114                           optarg);
115             } else {
116                 time_alarm(timeout);
117             }
118             break;
119
120         case 'h':
121             usage();
122
123         case 'V':
124             OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
125             exit(EXIT_SUCCESS);
126
127         case OPT_STRICT:
128             strict = true;
129             break;
130
131         VLOG_OPTION_HANDLERS
132         STREAM_SSL_OPTION_HANDLERS
133
134         case '?':
135             exit(EXIT_FAILURE);
136
137         default:
138             abort();
139         }
140     }
141     free(short_options);
142 }
143
144 static void
145 usage(void)
146 {
147     printf("%s: OpenFlow switch management utility\n"
148            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
149            "\nFor OpenFlow switches:\n"
150            "  show SWITCH                 show OpenFlow information\n"
151            "  status SWITCH [KEY]         report statistics (about KEY)\n"
152            "  dump-desc SWITCH            print switch description\n"
153            "  dump-tables SWITCH          print table stats\n"
154            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
155            "  dump-ports SWITCH           print port statistics\n"
156            "  dump-flows SWITCH           print all flow entries\n"
157            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
158            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
159            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
160            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
161            "  add-flows SWITCH FILE       add flows from FILE\n"
162            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
163            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
164            "  monitor SWITCH MISSLEN EXP  print packets received from SWITCH\n"
165            "\nFor OpenFlow switches and controllers:\n"
166            "  probe VCONN                 probe whether VCONN is up\n"
167            "  ping VCONN [N]              latency of N-byte echos\n"
168            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
169            "where each SWITCH is an active OpenFlow connection method.\n",
170            program_name, program_name);
171     vconn_usage(true, false, false);
172     vlog_usage();
173     printf("\nOther options:\n"
174            "  --strict                    use strict match for flow commands\n"
175            "  -t, --timeout=SECS          give up after SECS seconds\n"
176            "  -h, --help                  display this help message\n"
177            "  -V, --version               display version information\n");
178     exit(EXIT_SUCCESS);
179 }
180
181 static void run(int retval, const char *message, ...)
182     PRINTF_FORMAT(2, 3);
183
184 static void run(int retval, const char *message, ...)
185 {
186     if (retval) {
187         va_list args;
188
189         fprintf(stderr, "%s: ", program_name);
190         va_start(args, message);
191         vfprintf(stderr, message, args);
192         va_end(args);
193         if (retval == EOF) {
194             fputs(": unexpected end of file\n", stderr);
195         } else {
196             fprintf(stderr, ": %s\n", strerror(retval));
197         }
198
199         exit(EXIT_FAILURE);
200     }
201 }
202 \f
203 /* Generic commands. */
204
205 static void
206 open_vconn_socket(const char *name, struct vconn **vconnp)
207 {
208     char *vconn_name = xasprintf("unix:%s", name);
209     VLOG_INFO("connecting to %s", vconn_name);
210     run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
211         "connecting to %s", vconn_name);
212     free(vconn_name);
213 }
214
215 static void
216 open_vconn(const char *name, struct vconn **vconnp)
217 {
218     struct dpif *dpif;
219     struct stat s;
220     char *bridge_path, *datapath_name, *datapath_type;
221
222     bridge_path = xasprintf("%s/%s.mgmt", ovs_rundir, name);
223     dp_parse_name(name, &datapath_name, &datapath_type);
224
225     if (strstr(name, ":")) {
226         run(vconn_open_block(name, OFP_VERSION, vconnp),
227             "connecting to %s", name);
228     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
229         open_vconn_socket(name, vconnp);
230     } else if (!stat(bridge_path, &s) && S_ISSOCK(s.st_mode)) {
231         open_vconn_socket(bridge_path, vconnp);
232     } else if (!dpif_open(datapath_name, datapath_type, &dpif)) {
233         char dpif_name[IF_NAMESIZE + 1];
234         char *socket_name;
235
236         run(dpif_port_get_name(dpif, ODPP_LOCAL, dpif_name, sizeof dpif_name),
237             "obtaining name of %s", dpif_name);
238         dpif_close(dpif);
239         if (strcmp(dpif_name, name)) {
240             VLOG_INFO("datapath %s is named %s", name, dpif_name);
241         }
242
243         socket_name = xasprintf("%s/%s.mgmt", ovs_rundir, dpif_name);
244         if (stat(socket_name, &s)) {
245             ovs_fatal(errno, "cannot connect to %s: stat failed on %s",
246                       name, socket_name);
247         } else if (!S_ISSOCK(s.st_mode)) {
248             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
249                       name, socket_name);
250         }
251
252         open_vconn_socket(socket_name, vconnp);
253         free(socket_name);
254     } else {
255         ovs_fatal(0, "%s is not a valid connection method", name);
256     }
257
258     free(datapath_name);
259     free(datapath_type);
260     free(bridge_path);
261 }
262
263 static void *
264 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
265 {
266     struct ofp_stats_request *rq;
267     rq = make_openflow((offsetof(struct ofp_stats_request, body)
268                         + body_len), OFPT_STATS_REQUEST, bufferp);
269     rq->type = htons(type);
270     rq->flags = htons(0);
271     return rq->body;
272 }
273
274 static void
275 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
276 {
277     update_openflow_length(buffer);
278     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
279 }
280
281 static void
282 dump_transaction(const char *vconn_name, struct ofpbuf *request)
283 {
284     struct vconn *vconn;
285     struct ofpbuf *reply;
286
287     update_openflow_length(request);
288     open_vconn(vconn_name, &vconn);
289     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
290     ofp_print(stdout, reply->data, reply->size, 1);
291     vconn_close(vconn);
292 }
293
294 static void
295 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
296 {
297     struct ofpbuf *request;
298     make_openflow(sizeof(struct ofp_header), request_type, &request);
299     dump_transaction(vconn_name, request);
300 }
301
302 static void
303 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
304 {
305     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
306     struct vconn *vconn;
307     bool done = false;
308
309     open_vconn(vconn_name, &vconn);
310     send_openflow_buffer(vconn, request);
311     while (!done) {
312         uint32_t recv_xid;
313         struct ofpbuf *reply;
314
315         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
316         recv_xid = ((struct ofp_header *) reply->data)->xid;
317         if (send_xid == recv_xid) {
318             struct ofp_stats_reply *osr;
319
320             ofp_print(stdout, reply->data, reply->size, 1);
321
322             osr = ofpbuf_at(reply, 0, sizeof *osr);
323             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
324         } else {
325             VLOG_DBG("received reply with xid %08"PRIx32" "
326                      "!= expected %08"PRIx32, recv_xid, send_xid);
327         }
328         ofpbuf_delete(reply);
329     }
330     vconn_close(vconn);
331 }
332
333 static void
334 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
335 {
336     struct ofpbuf *request;
337     alloc_stats_request(0, stats_type, &request);
338     dump_stats_transaction(vconn_name, request);
339 }
340
341 static void
342 do_show(int argc UNUSED, char *argv[])
343 {
344     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
345     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
346 }
347
348 static void
349 do_status(int argc, char *argv[])
350 {
351     struct nicira_header *request, *reply;
352     struct vconn *vconn;
353     struct ofpbuf *b;
354
355     request = make_openflow(sizeof *request, OFPT_VENDOR, &b);
356     request->vendor = htonl(NX_VENDOR_ID);
357     request->subtype = htonl(NXT_STATUS_REQUEST);
358     if (argc > 2) {
359         ofpbuf_put(b, argv[2], strlen(argv[2]));
360         update_openflow_length(b);
361     }
362     open_vconn(argv[1], &vconn);
363     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
364     vconn_close(vconn);
365
366     if (b->size < sizeof *reply) {
367         ovs_fatal(0, "short reply (%zu bytes)", b->size);
368     }
369     reply = b->data;
370     if (reply->header.type != OFPT_VENDOR
371         || reply->vendor != ntohl(NX_VENDOR_ID)
372         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
373         ofp_print(stderr, b->data, b->size, 2);
374         ovs_fatal(0, "bad reply");
375     }
376
377     fwrite(reply + 1, b->size - sizeof *reply, 1, stdout);
378 }
379
380 static void
381 do_dump_desc(int argc UNUSED, char *argv[])
382 {
383     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
384 }
385
386 static void
387 do_dump_tables(int argc UNUSED, char *argv[])
388 {
389     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
390 }
391
392
393 static uint32_t
394 str_to_u32(const char *str) 
395 {
396     char *tail;
397     uint32_t value;
398
399     errno = 0;
400     value = strtoul(str, &tail, 0);
401     if (errno == EINVAL || errno == ERANGE || *tail) {
402         ovs_fatal(0, "invalid numeric format %s", str);
403     }
404     return value;
405 }
406
407 static void
408 str_to_mac(const char *str, uint8_t mac[6]) 
409 {
410     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
411         != ETH_ADDR_SCAN_COUNT) {
412         ovs_fatal(0, "invalid mac address %s", str);
413     }
414 }
415
416 static uint32_t
417 str_to_ip(const char *str_, uint32_t *ip)
418 {
419     char *str = xstrdup(str_);
420     char *save_ptr = NULL;
421     const char *name, *netmask;
422     struct in_addr in_addr;
423     int n_wild, retval;
424
425     name = strtok_r(str, "/", &save_ptr);
426     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
427     if (retval) {
428         ovs_fatal(0, "%s: could not convert to IP address", str);
429     }
430     *ip = in_addr.s_addr;
431
432     netmask = strtok_r(NULL, "/", &save_ptr);
433     if (netmask) {
434         uint8_t o[4];
435         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
436                    &o[0], &o[1], &o[2], &o[3]) == 4) {
437             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
438             int i;
439
440             /* Find first 1-bit. */
441             for (i = 0; i < 32; i++) {
442                 if (nm & (1u << i)) {
443                     break;
444                 }
445             }
446             n_wild = i;
447
448             /* Verify that the rest of the bits are 1-bits. */
449             for (; i < 32; i++) {
450                 if (!(nm & (1u << i))) {
451                     ovs_fatal(0, "%s: %s is not a valid netmask",
452                               str, netmask);
453                 }
454             }
455         } else {
456             int prefix = atoi(netmask);
457             if (prefix <= 0 || prefix > 32) {
458                 ovs_fatal(0, "%s: network prefix bits not between 1 and 32",
459                           str);
460             }
461             n_wild = 32 - prefix;
462         }
463     } else {
464         n_wild = 0;
465     }
466
467     free(str);
468     return n_wild;
469 }
470
471 static void *
472 put_action(struct ofpbuf *b, size_t size, uint16_t type)
473 {
474     struct ofp_action_header *ah = ofpbuf_put_zeros(b, size);
475     ah->type = htons(type);
476     ah->len = htons(size);
477     return ah;
478 }
479
480 static struct ofp_action_output *
481 put_output_action(struct ofpbuf *b, uint16_t port)
482 {
483     struct ofp_action_output *oao = put_action(b, sizeof *oao, OFPAT_OUTPUT);
484     oao->port = htons(port);
485     return oao;
486 }
487
488 static void
489 put_dl_addr_action(struct ofpbuf *b, uint16_t type, const char *addr)
490 {
491     struct ofp_action_dl_addr *oada = put_action(b, sizeof *oada, type);
492     str_to_mac(addr, oada->dl_addr);
493 }
494
495
496 static bool
497 parse_port_name(const char *name, uint16_t *port)
498 {
499     struct pair {
500         const char *name;
501         uint16_t value;
502     };
503     static const struct pair pairs[] = {
504 #define DEF_PAIR(NAME) {#NAME, OFPP_##NAME}
505         DEF_PAIR(IN_PORT),
506         DEF_PAIR(TABLE),
507         DEF_PAIR(NORMAL),
508         DEF_PAIR(FLOOD),
509         DEF_PAIR(ALL),
510         DEF_PAIR(CONTROLLER),
511         DEF_PAIR(LOCAL),
512         DEF_PAIR(NONE),
513 #undef DEF_PAIR
514     };
515     static const int n_pairs = ARRAY_SIZE(pairs);
516     size_t i;
517
518     for (i = 0; i < n_pairs; i++) {
519         if (!strcasecmp(name, pairs[i].name)) {
520             *port = pairs[i].value;
521             return true;
522         }
523     }
524     return false;
525 }
526
527 static void
528 str_to_action(char *str, struct ofpbuf *b)
529 {
530     char *act, *arg;
531     char *saveptr = NULL;
532     bool drop = false;
533     int n_actions;
534
535     for (act = strtok_r(str, ", \t\r\n", &saveptr), n_actions = 0; act;
536          act = strtok_r(NULL, ", \t\r\n", &saveptr), n_actions++) 
537     {
538         uint16_t port;
539
540         if (drop) {
541             ovs_fatal(0, "Drop actions must not be followed by other actions");
542         }
543
544         /* Arguments are separated by colons */
545         arg = strchr(act, ':');
546         if (arg) {
547             *arg = '\0';
548             arg++;
549         }
550
551         if (!strcasecmp(act, "mod_vlan_vid")) {
552             struct ofp_action_vlan_vid *va;
553             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_VID);
554             va->vlan_vid = htons(str_to_u32(arg));
555         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
556             struct ofp_action_vlan_pcp *va;
557             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_PCP);
558             va->vlan_pcp = str_to_u32(arg);
559         } else if (!strcasecmp(act, "strip_vlan")) {
560             struct ofp_action_header *ah;
561             ah = put_action(b, sizeof *ah, OFPAT_STRIP_VLAN);
562             ah->type = htons(OFPAT_STRIP_VLAN);
563         } else if (!strcasecmp(act, "mod_dl_src")) {
564             put_dl_addr_action(b, OFPAT_SET_DL_SRC, arg);
565         } else if (!strcasecmp(act, "mod_dl_dst")) {
566             put_dl_addr_action(b, OFPAT_SET_DL_DST, arg);
567         } else if (!strcasecmp(act, "mod_nw_src")) {
568             struct ofp_action_nw_addr *na;
569             na = put_action(b, sizeof *na, OFPAT_SET_NW_SRC);
570             str_to_ip(arg, &na->nw_addr);
571         } else if (!strcasecmp(act, "mod_nw_dst")) {
572             struct ofp_action_nw_addr *na;
573             na = put_action(b, sizeof *na, OFPAT_SET_NW_DST);
574             str_to_ip(arg, &na->nw_addr);
575         } else if (!strcasecmp(act, "mod_tp_src")) {
576             struct ofp_action_tp_port *ta;
577             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_SRC);
578             ta->tp_port = htons(str_to_u32(arg));
579         } else if (!strcasecmp(act, "mod_tp_dst")) {
580             struct ofp_action_tp_port *ta;
581             ta = put_action(b, sizeof *ta, OFPAT_SET_TP_DST);
582             ta->tp_port = htons(str_to_u32(arg));
583         } else if (!strcasecmp(act, "output")) {
584             put_output_action(b, str_to_u32(arg));
585         } else if (!strcasecmp(act, "drop")) {
586             /* A drop action in OpenFlow occurs by just not setting 
587              * an action. */
588             drop = true;
589             if (n_actions) {
590                 ovs_fatal(0, "Drop actions must not be preceded by other "
591                           "actions");
592             }
593         } else if (!strcasecmp(act, "CONTROLLER")) {
594             struct ofp_action_output *oao;
595             oao = put_output_action(b, OFPP_CONTROLLER);
596
597             /* Unless a numeric argument is specified, we send the whole
598              * packet to the controller. */
599             if (arg && (strspn(act, "0123456789") == strlen(act))) {
600                oao->max_len = htons(str_to_u32(arg));
601             } else {
602                 oao->max_len = htons(UINT16_MAX);
603             }
604         } else if (parse_port_name(act, &port)) {
605             put_output_action(b, port);
606         } else if (strspn(act, "0123456789") == strlen(act)) {
607             put_output_action(b, str_to_u32(act));
608         } else {
609             ovs_fatal(0, "Unknown action: %s", act);
610         }
611     }
612 }
613
614 struct protocol {
615     const char *name;
616     uint16_t dl_type;
617     uint8_t nw_proto;
618 };
619
620 static bool
621 parse_protocol(const char *name, const struct protocol **p_out)
622 {
623     static const struct protocol protocols[] = {
624         { "ip", ETH_TYPE_IP, 0 },
625         { "arp", ETH_TYPE_ARP, 0 },
626         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
627         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
628         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
629     };
630     const struct protocol *p;
631
632     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
633         if (!strcmp(p->name, name)) {
634             *p_out = p;
635             return true;
636         }
637     }
638     *p_out = NULL;
639     return false;
640 }
641
642 struct field {
643     const char *name;
644     uint32_t wildcard;
645     enum { F_U8, F_U16, F_MAC, F_IP } type;
646     size_t offset, shift;
647 };
648
649 static bool
650 parse_field(const char *name, const struct field **f_out) 
651 {
652 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
653     static const struct field fields[] = { 
654         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port), 0 },
655         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan), 0 },
656         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src), 0 },
657         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst), 0 },
658         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type), 0 },
659         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
660           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
661         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
662           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
663         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto), 0 },
664         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src), 0 },
665         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst), 0 },
666         { "icmp_type", OFPFW_ICMP_TYPE, F_U16, F_OFS(icmp_type), 0 },
667         { "icmp_code", OFPFW_ICMP_CODE, F_U16, F_OFS(icmp_code), 0 }
668     };
669     const struct field *f;
670
671     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
672         if (!strcmp(f->name, name)) {
673             *f_out = f;
674             return true;
675         }
676     }
677     *f_out = NULL;
678     return false;
679 }
680
681 static void
682 str_to_flow(char *string, struct ofp_match *match, struct ofpbuf *actions,
683             uint8_t *table_idx, uint16_t *out_port, uint16_t *priority, 
684             uint16_t *idle_timeout, uint16_t *hard_timeout)
685 {
686     char *save_ptr = NULL;
687     char *name;
688     uint32_t wildcards;
689
690     if (table_idx) {
691         *table_idx = 0xff;
692     }
693     if (out_port) {
694         *out_port = OFPP_NONE;
695     }
696     if (priority) {
697         *priority = OFP_DEFAULT_PRIORITY;
698     }
699     if (idle_timeout) {
700         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
701     }
702     if (hard_timeout) {
703         *hard_timeout = OFP_FLOW_PERMANENT;
704     }
705     if (actions) {
706         char *act_str = strstr(string, "action");
707         if (!act_str) {
708             ovs_fatal(0, "must specify an action");
709         }
710         *(act_str-1) = '\0';
711
712         act_str = strchr(act_str, '=');
713         if (!act_str) {
714             ovs_fatal(0, "must specify an action");
715         }
716
717         act_str++;
718
719         str_to_action(act_str, actions);
720     }
721     memset(match, 0, sizeof *match);
722     wildcards = OFPFW_ALL;
723     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
724          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
725         const struct protocol *p;
726
727         if (parse_protocol(name, &p)) {
728             wildcards &= ~OFPFW_DL_TYPE;
729             match->dl_type = htons(p->dl_type);
730             if (p->nw_proto) {
731                 wildcards &= ~OFPFW_NW_PROTO;
732                 match->nw_proto = p->nw_proto;
733             }
734         } else {
735             const struct field *f;
736             char *value;
737
738             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
739             if (!value) {
740                 ovs_fatal(0, "field %s missing value", name);
741             }
742         
743             if (table_idx && !strcmp(name, "table")) {
744                 *table_idx = atoi(value);
745             } else if (out_port && !strcmp(name, "out_port")) {
746                 *out_port = atoi(value);
747             } else if (priority && !strcmp(name, "priority")) {
748                 *priority = atoi(value);
749             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
750                 *idle_timeout = atoi(value);
751             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
752                 *hard_timeout = atoi(value);
753             } else if (parse_field(name, &f)) {
754                 void *data = (char *) match + f->offset;
755                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
756                     wildcards |= f->wildcard;
757                 } else {
758                     wildcards &= ~f->wildcard;
759                     if (f->wildcard == OFPFW_IN_PORT
760                         && parse_port_name(value, (uint16_t *) data)) {
761                         /* Nothing to do. */
762                     } else if (f->type == F_U8) {
763                         *(uint8_t *) data = str_to_u32(value);
764                     } else if (f->type == F_U16) {
765                         *(uint16_t *) data = htons(str_to_u32(value));
766                     } else if (f->type == F_MAC) {
767                         str_to_mac(value, data);
768                     } else if (f->type == F_IP) {
769                         wildcards |= str_to_ip(value, data) << f->shift;
770                     } else {
771                         NOT_REACHED();
772                     }
773                 }
774             } else {
775                 ovs_fatal(0, "unknown keyword %s", name);
776             }
777         }
778     }
779     match->wildcards = htonl(wildcards);
780 }
781
782 static void
783 do_dump_flows(int argc, char *argv[])
784 {
785     struct ofp_flow_stats_request *req;
786     uint16_t out_port;
787     struct ofpbuf *request;
788
789     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
790     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL,
791                 &req->table_id, &out_port, NULL, NULL, NULL);
792     memset(&req->pad, 0, sizeof req->pad);
793     req->out_port = htons(out_port);
794
795     dump_stats_transaction(argv[1], request);
796 }
797
798 static void
799 do_dump_aggregate(int argc, char *argv[])
800 {
801     struct ofp_aggregate_stats_request *req;
802     struct ofpbuf *request;
803     uint16_t out_port;
804
805     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
806     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL,
807                 &req->table_id, &out_port, NULL, NULL, NULL);
808     memset(&req->pad, 0, sizeof req->pad);
809     req->out_port = htons(out_port);
810
811     dump_stats_transaction(argv[1], request);
812 }
813
814 static void
815 do_add_flow(int argc UNUSED, char *argv[])
816 {
817     struct vconn *vconn;
818     struct ofpbuf *buffer;
819     struct ofp_flow_mod *ofm;
820     uint16_t priority, idle_timeout, hard_timeout;
821     struct ofp_match match;
822
823     /* Parse and send.  str_to_flow() will expand and reallocate the data in
824      * 'buffer', so we can't keep pointers to across the str_to_flow() call. */
825     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
826     str_to_flow(argv[2], &match, buffer,
827                 NULL, NULL, &priority, &idle_timeout, &hard_timeout);
828     ofm = buffer->data;
829     ofm->match = match;
830     ofm->command = htons(OFPFC_ADD);
831     ofm->idle_timeout = htons(idle_timeout);
832     ofm->hard_timeout = htons(hard_timeout);
833     ofm->buffer_id = htonl(UINT32_MAX);
834     ofm->priority = htons(priority);
835     ofm->reserved = htonl(0);
836
837     open_vconn(argv[1], &vconn);
838     send_openflow_buffer(vconn, buffer);
839     vconn_close(vconn);
840 }
841
842 static void
843 do_add_flows(int argc UNUSED, char *argv[])
844 {
845     struct vconn *vconn;
846     FILE *file;
847     char line[1024];
848
849     file = fopen(argv[2], "r");
850     if (file == NULL) {
851         ovs_fatal(errno, "%s: open", argv[2]);
852     }
853
854     open_vconn(argv[1], &vconn);
855     while (fgets(line, sizeof line, file)) {
856         struct ofpbuf *buffer;
857         struct ofp_flow_mod *ofm;
858         uint16_t priority, idle_timeout, hard_timeout;
859         struct ofp_match match;
860
861         char *comment;
862
863         /* Delete comments. */
864         comment = strchr(line, '#');
865         if (comment) {
866             *comment = '\0';
867         }
868
869         /* Drop empty lines. */
870         if (line[strspn(line, " \t\n")] == '\0') {
871             continue;
872         }
873
874         /* Parse and send.  str_to_flow() will expand and reallocate the data
875          * in 'buffer', so we can't keep pointers to across the str_to_flow()
876          * call. */
877         ofm = make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
878         str_to_flow(line, &match, buffer,
879                     NULL, NULL, &priority, &idle_timeout, &hard_timeout);
880         ofm = buffer->data;
881         ofm->match = match;
882         ofm->command = htons(OFPFC_ADD);
883         ofm->idle_timeout = htons(idle_timeout);
884         ofm->hard_timeout = htons(hard_timeout);
885         ofm->buffer_id = htonl(UINT32_MAX);
886         ofm->priority = htons(priority);
887         ofm->reserved = htonl(0);
888
889         send_openflow_buffer(vconn, buffer);
890     }
891     vconn_close(vconn);
892     fclose(file);
893 }
894
895 static void
896 do_mod_flows(int argc UNUSED, char *argv[])
897 {
898     uint16_t priority, idle_timeout, hard_timeout;
899     struct vconn *vconn;
900     struct ofpbuf *buffer;
901     struct ofp_flow_mod *ofm;
902     struct ofp_match match;
903
904     /* Parse and send.  str_to_flow() will expand and reallocate the data in
905      * 'buffer', so we can't keep pointers to across the str_to_flow() call. */
906     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
907     str_to_flow(argv[2], &match, buffer,
908                 NULL, NULL, &priority, &idle_timeout, &hard_timeout);
909     ofm = buffer->data;
910     ofm->match = match;
911     if (strict) {
912         ofm->command = htons(OFPFC_MODIFY_STRICT);
913     } else {
914         ofm->command = htons(OFPFC_MODIFY);
915     }
916     ofm->idle_timeout = htons(idle_timeout);
917     ofm->hard_timeout = htons(hard_timeout);
918     ofm->buffer_id = htonl(UINT32_MAX);
919     ofm->priority = htons(priority);
920     ofm->reserved = htonl(0);
921
922     open_vconn(argv[1], &vconn);
923     send_openflow_buffer(vconn, buffer);
924     vconn_close(vconn);
925 }
926
927 static void do_del_flows(int argc, char *argv[])
928 {
929     struct vconn *vconn;
930     uint16_t priority;
931     uint16_t out_port;
932     struct ofpbuf *buffer;
933     struct ofp_flow_mod *ofm;
934
935     /* Parse and send. */
936     ofm = make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
937     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, NULL, 
938                 &out_port, &priority, NULL, NULL);
939     if (strict) {
940         ofm->command = htons(OFPFC_DELETE_STRICT);
941     } else {
942         ofm->command = htons(OFPFC_DELETE);
943     }
944     ofm->idle_timeout = htons(0);
945     ofm->hard_timeout = htons(0);
946     ofm->buffer_id = htonl(UINT32_MAX);
947     ofm->out_port = htons(out_port);
948     ofm->priority = htons(priority);
949     ofm->reserved = htonl(0);
950
951     open_vconn(argv[1], &vconn);
952     send_openflow_buffer(vconn, buffer);
953     vconn_close(vconn);
954 }
955
956 static void
957 do_monitor(int argc UNUSED, char *argv[])
958 {
959     struct vconn *vconn;
960
961     open_vconn(argv[1], &vconn);
962     if (argc > 2) {
963         int miss_send_len = atoi(argv[2]);
964         int send_flow_exp = argc > 3 ? atoi(argv[3]) : 0;
965         struct ofp_switch_config *osc;
966         struct ofpbuf *buf;
967
968         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &buf);
969         osc->flags = htons(send_flow_exp ? OFPC_SEND_FLOW_EXP : 0);
970         osc->miss_send_len = htons(miss_send_len);
971         send_openflow_buffer(vconn, buf);
972     }
973     for (;;) {
974         struct ofpbuf *b;
975         run(vconn_recv_block(vconn, &b), "vconn_recv");
976         ofp_print(stderr, b->data, b->size, 2);
977         ofpbuf_delete(b);
978     }
979 }
980
981 static void
982 do_dump_ports(int argc UNUSED, char *argv[])
983 {
984     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
985 }
986
987 static void
988 do_probe(int argc UNUSED, char *argv[])
989 {
990     struct ofpbuf *request;
991     struct vconn *vconn;
992     struct ofpbuf *reply;
993
994     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
995     open_vconn(argv[1], &vconn);
996     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
997     if (reply->size != sizeof(struct ofp_header)) {
998         ovs_fatal(0, "reply does not match request");
999     }
1000     ofpbuf_delete(reply);
1001     vconn_close(vconn);
1002 }
1003
1004 static void
1005 do_mod_port(int argc UNUSED, char *argv[])
1006 {
1007     struct ofpbuf *request, *reply;
1008     struct ofp_switch_features *osf;
1009     struct ofp_port_mod *opm;
1010     struct vconn *vconn;
1011     char *endptr;
1012     int n_ports;
1013     int port_idx;
1014     int port_no;
1015     
1016
1017     /* Check if the argument is a port index.  Otherwise, treat it as
1018      * the port name. */
1019     port_no = strtol(argv[2], &endptr, 10);
1020     if (port_no == 0 && endptr == argv[2]) {
1021         port_no = -1;
1022     }
1023
1024     /* Send a "Features Request" to get the information we need in order 
1025      * to modify the port. */
1026     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
1027     open_vconn(argv[1], &vconn);
1028     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1029
1030     osf = reply->data;
1031     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
1032
1033     for (port_idx = 0; port_idx < n_ports; port_idx++) {
1034         if (port_no != -1) {
1035             /* Check argument as a port index */
1036             if (osf->ports[port_idx].port_no == htons(port_no)) {
1037                 break;
1038             }
1039         } else {
1040             /* Check argument as an interface name */
1041             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
1042                         sizeof osf->ports[0].name)) {
1043                 break;
1044             }
1045
1046         }
1047     }
1048     if (port_idx == n_ports) {
1049         ovs_fatal(0, "couldn't find monitored port: %s", argv[2]);
1050     }
1051
1052     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1053     opm->port_no = osf->ports[port_idx].port_no;
1054     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
1055     opm->config = htonl(0);
1056     opm->mask = htonl(0);
1057     opm->advertise = htonl(0);
1058
1059     printf("modifying port: %s\n", osf->ports[port_idx].name);
1060
1061     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
1062         opm->mask |= htonl(OFPPC_PORT_DOWN);
1063     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
1064                 sizeof MOD_PORT_CMD_DOWN)) {
1065         opm->mask |= htonl(OFPPC_PORT_DOWN);
1066         opm->config |= htonl(OFPPC_PORT_DOWN);
1067     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
1068                 sizeof MOD_PORT_CMD_FLOOD)) {
1069         opm->mask |= htonl(OFPPC_NO_FLOOD);
1070     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
1071                 sizeof MOD_PORT_CMD_NOFLOOD)) {
1072         opm->mask |= htonl(OFPPC_NO_FLOOD);
1073         opm->config |= htonl(OFPPC_NO_FLOOD);
1074     } else {
1075         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1076     }
1077
1078     send_openflow_buffer(vconn, request);
1079
1080     ofpbuf_delete(reply);
1081     vconn_close(vconn);
1082 }
1083
1084 static void
1085 do_ping(int argc, char *argv[])
1086 {
1087     size_t max_payload = 65535 - sizeof(struct ofp_header);
1088     unsigned int payload;
1089     struct vconn *vconn;
1090     int i;
1091
1092     payload = argc > 2 ? atoi(argv[2]) : 64;
1093     if (payload > max_payload) {
1094         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1095     }
1096
1097     open_vconn(argv[1], &vconn);
1098     for (i = 0; i < 10; i++) {
1099         struct timeval start, end;
1100         struct ofpbuf *request, *reply;
1101         struct ofp_header *rq_hdr, *rpy_hdr;
1102
1103         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1104                                OFPT_ECHO_REQUEST, &request);
1105         random_bytes(rq_hdr + 1, payload);
1106
1107         gettimeofday(&start, NULL);
1108         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1109         gettimeofday(&end, NULL);
1110
1111         rpy_hdr = reply->data;
1112         if (reply->size != request->size
1113             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1114             || rpy_hdr->xid != rq_hdr->xid
1115             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1116             printf("Reply does not match request.  Request:\n");
1117             ofp_print(stdout, request, request->size, 2);
1118             printf("Reply:\n");
1119             ofp_print(stdout, reply, reply->size, 2);
1120         }
1121         printf("%zu bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1122                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1123                    (1000*(double)(end.tv_sec - start.tv_sec))
1124                    + (.001*(end.tv_usec - start.tv_usec)));
1125         ofpbuf_delete(request);
1126         ofpbuf_delete(reply);
1127     }
1128     vconn_close(vconn);
1129 }
1130
1131 static void
1132 do_benchmark(int argc UNUSED, char *argv[])
1133 {
1134     size_t max_payload = 65535 - sizeof(struct ofp_header);
1135     struct timeval start, end;
1136     unsigned int payload_size, message_size;
1137     struct vconn *vconn;
1138     double duration;
1139     int count;
1140     int i;
1141
1142     payload_size = atoi(argv[2]);
1143     if (payload_size > max_payload) {
1144         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1145     }
1146     message_size = sizeof(struct ofp_header) + payload_size;
1147
1148     count = atoi(argv[3]);
1149
1150     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1151            count, message_size, count * message_size);
1152
1153     open_vconn(argv[1], &vconn);
1154     gettimeofday(&start, NULL);
1155     for (i = 0; i < count; i++) {
1156         struct ofpbuf *request, *reply;
1157         struct ofp_header *rq_hdr;
1158
1159         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1160         memset(rq_hdr + 1, 0, payload_size);
1161         run(vconn_transact(vconn, request, &reply), "transact");
1162         ofpbuf_delete(reply);
1163     }
1164     gettimeofday(&end, NULL);
1165     vconn_close(vconn);
1166
1167     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1168                 + (.001*(end.tv_usec - start.tv_usec)));
1169     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1170            duration, count / (duration / 1000.0),
1171            count * message_size / (duration / 1000.0));
1172 }
1173
1174 static void
1175 do_help(int argc UNUSED, char *argv[] UNUSED)
1176 {
1177     usage();
1178 }
1179
1180 static const struct command all_commands[] = {
1181     { "show", 1, 1, do_show },
1182     { "status", 1, 2, do_status },
1183     { "monitor", 1, 3, do_monitor },
1184     { "dump-desc", 1, 1, do_dump_desc },
1185     { "dump-tables", 1, 1, do_dump_tables },
1186     { "dump-flows", 1, 2, do_dump_flows },
1187     { "dump-aggregate", 1, 2, do_dump_aggregate },
1188     { "add-flow", 2, 2, do_add_flow },
1189     { "add-flows", 2, 2, do_add_flows },
1190     { "mod-flows", 2, 2, do_mod_flows },
1191     { "del-flows", 1, 2, do_del_flows },
1192     { "dump-ports", 1, 1, do_dump_ports },
1193     { "mod-port", 3, 3, do_mod_port },
1194     { "probe", 1, 1, do_probe },
1195     { "ping", 1, 2, do_ping },
1196     { "benchmark", 3, 3, do_benchmark },
1197     { "help", 0, INT_MAX, do_help },
1198     { NULL, 0, 0, NULL },
1199 };