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