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