338470095a2472b0d18bd8cd6808c287e9b1a91b
[sliver-openvswitch.git] / utilities / dpctl.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include <arpa/inet.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <sys/time.h>
46
47 #ifdef HAVE_NETLINK
48 #include "netdev.h"
49 #include "netlink.h"
50 #include "openflow/openflow-netlink.h"
51 #endif
52
53 #include "command-line.h"
54 #include "compiler.h"
55 #include "dpif.h"
56 #include "openflow/nicira-ext.h"
57 #include "ofp-print.h"
58 #include "ofpbuf.h"
59 #include "openflow/openflow.h"
60 #include "packets.h"
61 #include "random.h"
62 #include "socket-util.h"
63 #include "timeval.h"
64 #include "util.h"
65 #include "vconn-ssl.h"
66 #include "vconn.h"
67
68 #include "vlog.h"
69 #define THIS_MODULE VLM_dpctl
70
71 #define DEFAULT_IDLE_TIMEOUT 60
72
73 /* Maximum size of action buffer for adding and modify flows */
74 #define MAX_ACT_LEN 60
75
76 #define MOD_PORT_CMD_UP      "up"
77 #define MOD_PORT_CMD_DOWN    "down"
78 #define MOD_PORT_CMD_FLOOD   "flood"
79 #define MOD_PORT_CMD_NOFLOOD "noflood"
80
81
82 /* Settings that may be configured by the user. */
83 struct settings {
84     bool strict;        /* Use strict matching for flow mod commands */
85 };
86
87 struct command {
88     const char *name;
89     int min_args;
90     int max_args;
91     void (*handler)(const struct settings *, int argc, char *argv[]);
92 };
93
94 static struct command all_commands[];
95
96 static void usage(void) NO_RETURN;
97 static void parse_options(int argc, char *argv[], struct settings *);
98
99 int main(int argc, char *argv[])
100 {
101     struct settings s;
102     struct command *p;
103
104     set_program_name(argv[0]);
105     time_init();
106     vlog_init();
107     parse_options(argc, argv, &s);
108     signal(SIGPIPE, SIG_IGN);
109
110     argc -= optind;
111     argv += optind;
112     if (argc < 1)
113         ofp_fatal(0, "missing command name; use --help for help");
114
115     for (p = all_commands; p->name != NULL; p++) {
116         if (!strcmp(p->name, argv[0])) {
117             int n_arg = argc - 1;
118             if (n_arg < p->min_args)
119                 ofp_fatal(0, "'%s' command requires at least %d arguments",
120                           p->name, p->min_args);
121             else if (n_arg > p->max_args)
122                 ofp_fatal(0, "'%s' command takes at most %d arguments",
123                           p->name, p->max_args);
124             else {
125                 p->handler(&s, argc, argv);
126                 exit(0);
127             }
128         }
129     }
130     ofp_fatal(0, "unknown command '%s'; use --help for help", argv[0]);
131
132     return 0;
133 }
134
135 static void
136 parse_options(int argc, char *argv[], struct settings *s)
137 {
138     enum {
139         OPT_STRICT = UCHAR_MAX + 1
140     };
141     static struct option long_options[] = {
142         {"timeout", required_argument, 0, 't'},
143         {"verbose", optional_argument, 0, 'v'},
144         {"strict", no_argument, 0, OPT_STRICT},
145         {"help", no_argument, 0, 'h'},
146         {"version", no_argument, 0, 'V'},
147         VCONN_SSL_LONG_OPTIONS
148         {0, 0, 0, 0},
149     };
150     char *short_options = long_options_to_short_options(long_options);
151
152     /* Set defaults that we can figure out before parsing options. */
153     s->strict = false;
154
155     for (;;) {
156         unsigned long int timeout;
157         int c;
158
159         c = getopt_long(argc, argv, short_options, long_options, NULL);
160         if (c == -1) {
161             break;
162         }
163
164         switch (c) {
165         case 't':
166             timeout = strtoul(optarg, NULL, 10);
167             if (timeout <= 0) {
168                 ofp_fatal(0, "value %s on -t or --timeout is not at least 1",
169                           optarg);
170             } else {
171                 time_alarm(timeout);
172             }
173             break;
174
175         case 'h':
176             usage();
177
178         case 'V':
179             printf("%s %s compiled "__DATE__" "__TIME__"\n",
180                    program_name, VERSION BUILDNR);
181             exit(EXIT_SUCCESS);
182
183         case 'v':
184             vlog_set_verbosity(optarg);
185             break;
186
187         case OPT_STRICT:
188             s->strict = true;
189             break;
190
191         VCONN_SSL_OPTION_HANDLERS
192
193         case '?':
194             exit(EXIT_FAILURE);
195
196         default:
197             abort();
198         }
199     }
200     free(short_options);
201 }
202
203 static void
204 usage(void)
205 {
206     printf("%s: OpenFlow switch management utility\n"
207            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
208 #ifdef HAVE_NETLINK
209            "\nFor local datapaths only:\n"
210            "  adddp nl:DP_ID              add a new local datapath DP_ID\n"
211            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
212            "  addif nl:DP_ID IFACE...     add each IFACE as a port on DP_ID\n"
213            "  delif nl:DP_ID IFACE...     delete each IFACE from DP_ID\n"
214 #endif
215            "\nFor local datapaths and remote switches:\n"
216            "  show SWITCH                 show basic information\n"
217            "  status SWITCH [KEY]         report statistics (about KEY)\n"
218            "  dump-desc SWITCH            print switch description\n"
219            "  dump-tables SWITCH          print table stats\n"
220            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
221            "  dump-ports SWITCH           print port statistics\n"
222            "  dump-flows SWITCH           print all flow entries\n"
223            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
224            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
225            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
226 #ifdef SUPPORT_SNAT
227            "  add-snat SWITCH IFACE IP    add SNAT config to IFACE\n"
228            "  del-snat SWITCH IFACE       delete SNAT config on IFACE\n"
229 #endif
230            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
231            "  add-flows SWITCH FILE       add flows from FILE\n"
232            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
233            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
234            "  monitor SWITCH              print packets received from SWITCH\n"
235            "  execute SWITCH CMD [ARG...] execute CMD with ARGS on SWITCH\n"
236            "\nFor local datapaths, remote switches, and controllers:\n"
237            "  probe VCONN                 probe whether VCONN is up\n"
238            "  ping VCONN [N]              latency of N-byte echos\n"
239            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
240            "where each SWITCH is an active OpenFlow connection method.\n",
241            program_name, program_name);
242     vconn_usage(true, false, false);
243     vlog_usage();
244     printf("\nOther options:\n"
245            "  --strict                    use strict match for flow commands\n"
246            "  -t, --timeout=SECS          give up after SECS seconds\n"
247            "  -h, --help                  display this help message\n"
248            "  -V, --version               display version information\n");
249     exit(EXIT_SUCCESS);
250 }
251
252 static void run(int retval, const char *message, ...)
253     PRINTF_FORMAT(2, 3);
254
255 static void run(int retval, const char *message, ...)
256 {
257     if (retval) {
258         va_list args;
259
260         fprintf(stderr, "%s: ", program_name);
261         va_start(args, message);
262         vfprintf(stderr, message, args);
263         va_end(args);
264         if (retval == EOF) {
265             fputs(": unexpected end of file\n", stderr);
266         } else {
267             fprintf(stderr, ": %s\n", strerror(retval));
268         }
269
270         exit(EXIT_FAILURE);
271     }
272 }
273 \f
274 #ifdef HAVE_NETLINK
275 /* Netlink-only commands. */
276
277 static int if_up(const char *netdev_name)
278 {
279     struct netdev *netdev;
280     int retval;
281
282     retval = netdev_open(netdev_name, NETDEV_ETH_TYPE_NONE, &netdev);
283     if (!retval) {
284         retval = netdev_turn_flags_on(netdev, NETDEV_UP, true);
285         netdev_close(netdev);
286     }
287     return retval;
288 }
289
290 static void open_nl_vconn(const char *name, bool subscribe, struct dpif *dpif)
291 {
292     if (strncmp(name, "nl:", 3)
293         || strlen(name) < 4
294         || name[strspn(name + 3, "0123456789") + 3]) {
295         ofp_fatal(0, "%s: argument is not of the form \"nl:DP_ID\"", name);
296     }
297     run(dpif_open(atoi(name + 3), subscribe, dpif), "opening datapath");
298 }
299
300 static void do_add_dp(const struct settings *s, int argc UNUSED, char *argv[])
301 {
302     struct dpif dp;
303     open_nl_vconn(argv[1], false, &dp);
304     run(dpif_add_dp(&dp), "add_dp");
305     dpif_close(&dp);
306 }
307
308 static void do_del_dp(const struct settings *s, int argc UNUSED, char *argv[])
309 {
310     struct dpif dp;
311     open_nl_vconn(argv[1], false, &dp);
312     run(dpif_del_dp(&dp), "del_dp");
313     dpif_close(&dp);
314 }
315
316 static void add_del_ports(int argc UNUSED, char *argv[],
317                           int (*function)(struct dpif *, const char *netdev),
318                           const char *operation, const char *preposition)
319 {
320     struct dpif dp;
321     bool failure = false;
322     int i;
323
324     open_nl_vconn(argv[1], false, &dp);
325     for (i = 2; i < argc; i++) {
326         int retval = function(&dp, argv[i]);
327         if (retval) {
328             ofp_error(retval, "failed to %s %s %s %s",
329                       operation, argv[i], preposition, argv[1]);
330             failure = true;
331         }
332     }
333     dpif_close(&dp);
334     if (failure) {
335         exit(EXIT_FAILURE);
336     }
337 }
338
339 static int ifup_and_add_port(struct dpif *dpif, const char *netdev)
340 {
341     int retval = if_up(netdev);
342     return retval ? retval : dpif_add_port(dpif, netdev);
343 }
344
345 static void do_add_port(const struct settings *s, int argc UNUSED, 
346         char *argv[])
347 {
348     add_del_ports(argc, argv, ifup_and_add_port, "add", "to");
349 }
350
351 static void do_del_port(const struct settings *s, int argc UNUSED, 
352         char *argv[])
353 {
354     add_del_ports(argc, argv, dpif_del_port, "remove", "from");
355 }
356 #endif /* HAVE_NETLINK */
357 \f
358 /* Generic commands. */
359
360 static void
361 open_vconn(const char *name, struct vconn **vconnp)
362 {
363     run(vconn_open_block(name, OFP_VERSION, vconnp), "connecting to %s", name);
364 }
365
366 static void *
367 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
368 {
369     struct ofp_stats_request *rq;
370     rq = make_openflow((offsetof(struct ofp_stats_request, body)
371                         + body_len), OFPT_STATS_REQUEST, bufferp);
372     rq->type = htons(type);
373     rq->flags = htons(0);
374     return rq->body;
375 }
376
377 static void
378 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
379 {
380     update_openflow_length(buffer);
381     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
382 }
383
384 static void
385 dump_transaction(const char *vconn_name, struct ofpbuf *request)
386 {
387     struct vconn *vconn;
388     struct ofpbuf *reply;
389
390     update_openflow_length(request);
391     open_vconn(vconn_name, &vconn);
392     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
393     ofp_print(stdout, reply->data, reply->size, 1);
394     vconn_close(vconn);
395 }
396
397 static void
398 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
399 {
400     struct ofpbuf *request;
401     make_openflow(sizeof(struct ofp_header), request_type, &request);
402     dump_transaction(vconn_name, request);
403 }
404
405 static void
406 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
407 {
408     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
409     struct vconn *vconn;
410     bool done = false;
411
412     open_vconn(vconn_name, &vconn);
413     send_openflow_buffer(vconn, request);
414     while (!done) {
415         uint32_t recv_xid;
416         struct ofpbuf *reply;
417
418         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
419         recv_xid = ((struct ofp_header *) reply->data)->xid;
420         if (send_xid == recv_xid) {
421             struct ofp_stats_reply *osr;
422
423             ofp_print(stdout, reply->data, reply->size, 1);
424
425             osr = ofpbuf_at(reply, 0, sizeof *osr);
426             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
427         } else {
428             VLOG_DBG("received reply with xid %08"PRIx32" "
429                      "!= expected %08"PRIx32, recv_xid, send_xid);
430         }
431         ofpbuf_delete(reply);
432     }
433     vconn_close(vconn);
434 }
435
436 static void
437 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
438 {
439     struct ofpbuf *request;
440     alloc_stats_request(0, stats_type, &request);
441     dump_stats_transaction(vconn_name, request);
442 }
443
444 static void
445 do_show(const struct settings *s, int argc UNUSED, char *argv[])
446 {
447     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
448     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
449 }
450
451 static void
452 do_status(const struct settings *s, int argc, char *argv[])
453 {
454     struct nicira_header *request, *reply;
455     struct vconn *vconn;
456     struct ofpbuf *b;
457
458     request = make_openflow(sizeof *request, OFPT_VENDOR, &b);
459     request->vendor = htonl(NX_VENDOR_ID);
460     request->subtype = htonl(NXT_STATUS_REQUEST);
461     if (argc > 2) {
462         ofpbuf_put(b, argv[2], strlen(argv[2]));
463     }
464     open_vconn(argv[1], &vconn);
465     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
466     vconn_close(vconn);
467
468     if (b->size < sizeof *reply) {
469         ofp_fatal(0, "short reply (%zu bytes)", b->size);
470     }
471     reply = b->data;
472     if (reply->header.type != OFPT_VENDOR
473         || reply->vendor != ntohl(NX_VENDOR_ID)
474         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
475         ofp_print(stderr, b->data, b->size, 2);
476         ofp_fatal(0, "bad reply");
477     }
478
479     fwrite(reply + 1, b->size, 1, stdout);
480 }
481
482 static void
483 do_dump_desc(const struct settings *s, int argc, char *argv[])
484 {
485     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
486 }
487
488 static void
489 do_dump_tables(const struct settings *s, int argc, char *argv[])
490 {
491     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
492 }
493
494
495 static uint32_t
496 str_to_int(const char *str) 
497 {
498     char *tail;
499     uint32_t value;
500
501     errno = 0;
502     value = strtoul(str, &tail, 0);
503     if (errno == EINVAL || errno == ERANGE || *tail) {
504         ofp_fatal(0, "invalid numeric format %s", str);
505     }
506     return value;
507 }
508
509 static void
510 str_to_mac(const char *str, uint8_t mac[6]) 
511 {
512     if (sscanf(str, "%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8":%"SCNx8,
513                &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
514         ofp_fatal(0, "invalid mac address %s", str);
515     }
516 }
517
518 static uint32_t
519 str_to_ip(const char *str_, uint32_t *ip)
520 {
521     char *str = xstrdup(str_);
522     char *save_ptr = NULL;
523     const char *name, *netmask;
524     struct in_addr in_addr;
525     int n_wild, retval;
526
527     name = strtok_r(str, "//", &save_ptr);
528     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
529     if (retval) {
530         ofp_fatal(0, "%s: could not convert to IP address", str);
531     }
532     *ip = in_addr.s_addr;
533
534     netmask = strtok_r(NULL, "//", &save_ptr);
535     if (netmask) {
536         uint8_t o[4];
537         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
538                    &o[0], &o[1], &o[2], &o[3]) == 4) {
539             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
540             int i;
541
542             /* Find first 1-bit. */
543             for (i = 0; i < 32; i++) {
544                 if (nm & (1u << i)) {
545                     break;
546                 }
547             }
548             n_wild = i;
549
550             /* Verify that the rest of the bits are 1-bits. */
551             for (; i < 32; i++) {
552                 if (!(nm & (1u << i))) {
553                     ofp_fatal(0, "%s: %s is not a valid netmask",
554                               str, netmask);
555                 }
556             }
557         } else {
558             int prefix = atoi(netmask);
559             if (prefix <= 0 || prefix > 32) {
560                 ofp_fatal(0, "%s: network prefix bits not between 1 and 32",
561                           str);
562             }
563             n_wild = 32 - prefix;
564         }
565     } else {
566         n_wild = 0;
567     }
568
569     free(str);
570     return n_wild;
571 }
572
573 static void
574 str_to_action(char *str, struct ofp_action_header *actions, 
575         size_t *actions_len) 
576 {
577     size_t len = *actions_len;
578     char *act, *arg;
579     char *saveptr = NULL;
580     uint8_t *p = (uint8_t *)actions;
581     
582     memset(actions, 0, len);
583     for (act = strtok_r(str, ", \t\r\n", &saveptr); 
584          (len >= sizeof(struct ofp_action_header)) && act;
585          act = strtok_r(NULL, ", \t\r\n", &saveptr)) 
586     {
587         uint16_t port;
588         struct ofp_action_header *ah = (struct ofp_action_header *)p;
589         int act_len = sizeof *ah;
590         port = OFPP_MAX;
591
592         /* Arguments are separated by colons */
593         arg = strchr(act, ':');
594         if (arg) {
595             *arg = '\0';
596             arg++;
597         } 
598
599         if (!strcasecmp(act, "mod_vlan_vid")) {
600             struct ofp_action_vlan_vid *va = (struct ofp_action_vlan_vid *)ah;
601
602             if (len < sizeof *va) {
603                 ofp_fatal(0, "Insufficient room for vlan vid action\n");
604             }
605
606             act_len = sizeof *va;
607             va->type = htons(OFPAT_SET_VLAN_VID);
608             va->vlan_vid = htons(str_to_int(arg));
609         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
610             struct ofp_action_vlan_pcp *va = (struct ofp_action_vlan_pcp *)ah;
611
612             if (len < sizeof *va) {
613                 ofp_fatal(0, "Insufficient room for vlan pcp action\n");
614             }
615
616             act_len = sizeof *va;
617             va->type = htons(OFPAT_SET_VLAN_PCP);
618             va->vlan_pcp = str_to_int(arg);
619         } else if (!strcasecmp(act, "strip_vlan")) {
620             ah->type = htons(OFPAT_STRIP_VLAN);
621         } else if (!strcasecmp(act, "output")) {
622             port = str_to_int(arg);
623 #ifdef SUPPORT_SNAT
624         } else if (!strcasecmp(act, "nat")) {
625             struct nx_action_snat *sa = (struct nx_action_snat *)ah;
626
627             if (len < sizeof *sa) {
628                 ofp_fatal(0, "Insufficient room for SNAT action\n");
629             }
630
631             if (str_to_int(arg) > OFPP_MAX) {
632                 ofp_fatal(0, "Invalid nat port: %s\n", arg);
633             }
634
635             act_len = sizeof *sa;
636             sa->type = htons(OFPAT_VENDOR);
637             sa->vendor = htonl(NX_VENDOR_ID);
638             sa->subtype = htons(NXAST_SNAT);
639             sa->port = htons(str_to_int(arg));
640 #endif
641         } else if (!strcasecmp(act, "TABLE")) {
642             port = OFPP_TABLE;
643         } else if (!strcasecmp(act, "NORMAL")) {
644             port = OFPP_NORMAL;
645         } else if (!strcasecmp(act, "FLOOD")) {
646             port = OFPP_FLOOD;
647         } else if (!strcasecmp(act, "ALL")) {
648             port = OFPP_ALL;
649         } else if (!strcasecmp(act, "CONTROLLER")) {
650             struct ofp_action_output *ca = (struct ofp_action_output *)ah;
651
652             if (act_len < sizeof *ca) {
653                 ofp_fatal(0, "Insufficient room for controller action\n");
654             }
655
656             act_len = sizeof *ca;
657             ca->type = htons(OFPAT_OUTPUT);
658             ca->port = htons(OFPP_CONTROLLER);
659
660             /* Unless a numeric argument is specified, we send the whole
661              * packet to the controller. */
662             if (arg && (strspn(act, "0123456789") == strlen(act))) {
663                ca->max_len= htons(str_to_int(arg));
664             }
665         } else if (!strcasecmp(act, "LOCAL")) {
666             port = OFPP_LOCAL;
667         } else if (strspn(act, "0123456789") == strlen(act)) {
668             port = str_to_int(act);
669         } else {
670             ofp_fatal(0, "Unknown action: %s", act);
671         }
672
673         if (port != OFPP_MAX) {
674             struct ofp_action_output *oa = (struct ofp_action_output *)p;
675
676             if (act_len < sizeof *oa) {
677                 ofp_fatal(0, "Insufficient room for output action\n");
678             }
679
680             act_len = sizeof *oa;
681             oa->type = htons(OFPAT_OUTPUT);
682             oa->port = htons(port);
683         }
684
685         ah->len = htons(act_len);
686         p += act_len;
687         len -= act_len;
688     }
689
690     *actions_len -= len;
691 }
692
693 struct protocol {
694     const char *name;
695     uint16_t dl_type;
696     uint8_t nw_proto;
697 };
698
699 static bool
700 parse_protocol(const char *name, const struct protocol **p_out)
701 {
702     static const struct protocol protocols[] = {
703         { "ip", ETH_TYPE_IP },
704         { "arp", ETH_TYPE_ARP },
705         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
706         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
707         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
708     };
709     const struct protocol *p;
710
711     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
712         if (!strcmp(p->name, name)) {
713             *p_out = p;
714             return true;
715         }
716     }
717     *p_out = NULL;
718     return false;
719 }
720
721 struct field {
722     const char *name;
723     uint32_t wildcard;
724     enum { F_U8, F_U16, F_MAC, F_IP } type;
725     size_t offset, shift;
726 };
727
728 static bool
729 parse_field(const char *name, const struct field **f_out) 
730 {
731 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
732     static const struct field fields[] = { 
733         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port) },
734         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan) },
735         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src) },
736         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst) },
737         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type) },
738         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
739           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
740         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
741           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
742         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto) },
743         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src) },
744         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst) },
745         { "icmp_type", OFPFW_ICMP_TYPE, F_U16, F_OFS(icmp_type) },
746         { "icmp_code", OFPFW_ICMP_CODE, F_U16, F_OFS(icmp_code) }
747     };
748     const struct field *f;
749
750     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
751         if (!strcmp(f->name, name)) {
752             *f_out = f;
753             return true;
754         }
755     }
756     *f_out = NULL;
757     return false;
758 }
759
760 static void
761 str_to_flow(char *string, struct ofp_match *match, 
762             struct ofp_action_header *actions, size_t *actions_len, 
763             uint8_t *table_idx, uint16_t *priority, 
764             uint16_t *idle_timeout, uint16_t *hard_timeout)
765 {
766
767     char *name;
768     uint32_t wildcards;
769
770     if (table_idx) {
771         *table_idx = 0xff;
772     }
773     if (priority) {
774         *priority = OFP_DEFAULT_PRIORITY;
775     }
776     if (idle_timeout) {
777         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
778     }
779     if (hard_timeout) {
780         *hard_timeout = OFP_FLOW_PERMANENT;
781     }
782     if (actions) {
783         char *act_str = strstr(string, "action");
784         if (!act_str) {
785             ofp_fatal(0, "must specify an action");
786         }
787         *(act_str-1) = '\0';
788
789         act_str = strchr(act_str, '=');
790         if (!act_str) {
791             ofp_fatal(0, "must specify an action");
792         }
793
794         act_str++;
795
796         str_to_action(act_str, actions, actions_len);
797     }
798     memset(match, 0, sizeof *match);
799     wildcards = OFPFW_ALL;
800     for (name = strtok(string, "=, \t\r\n"); name;
801          name = strtok(NULL, "=, \t\r\n")) {
802         const struct protocol *p;
803
804         if (parse_protocol(name, &p)) {
805             wildcards &= ~OFPFW_DL_TYPE;
806             match->dl_type = htons(p->dl_type);
807             if (p->nw_proto) {
808                 wildcards &= ~OFPFW_NW_PROTO;
809                 match->nw_proto = p->nw_proto;
810             }
811         } else {
812             const struct field *f;
813             char *value;
814
815             value = strtok(NULL, ", \t\r\n");
816             if (!value) {
817                 ofp_fatal(0, "field %s missing value", name);
818             }
819         
820             if (table_idx && !strcmp(name, "table")) {
821                 *table_idx = atoi(value);
822             } else if (priority && !strcmp(name, "priority")) {
823                 *priority = atoi(value);
824             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
825                 *idle_timeout = atoi(value);
826             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
827                 *hard_timeout = atoi(value);
828             } else if (parse_field(name, &f)) {
829                 void *data = (char *) match + f->offset;
830                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
831                     wildcards |= f->wildcard;
832                 } else {
833                     wildcards &= ~f->wildcard;
834                     if (f->type == F_U8) {
835                         *(uint8_t *) data = str_to_int(value);
836                     } else if (f->type == F_U16) {
837                         *(uint16_t *) data = htons(str_to_int(value));
838                     } else if (f->type == F_MAC) {
839                         str_to_mac(value, data);
840                     } else if (f->type == F_IP) {
841                         wildcards |= str_to_ip(value, data) << f->shift;
842                     } else {
843                         NOT_REACHED();
844                     }
845                 }
846             } else {
847                 ofp_fatal(0, "unknown keyword %s", name);
848             }
849         }
850     }
851     match->wildcards = htonl(wildcards);
852 }
853
854 static void do_dump_flows(const struct settings *s, int argc, char *argv[])
855 {
856     struct ofp_flow_stats_request *req;
857     struct ofpbuf *request;
858
859     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
860     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
861                 &req->table_id, NULL, NULL, NULL);
862     memset(req->pad, 0, sizeof req->pad);
863
864     dump_stats_transaction(argv[1], request);
865 }
866
867 static void do_dump_aggregate(const struct settings *s, int argc, 
868         char *argv[])
869 {
870     struct ofp_aggregate_stats_request *req;
871     struct ofpbuf *request;
872
873     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
874     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
875                 &req->table_id, NULL, NULL, NULL);
876     memset(req->pad, 0, sizeof req->pad);
877
878     dump_stats_transaction(argv[1], request);
879 }
880
881 #ifdef SUPPORT_SNAT
882 static void do_add_snat(const struct settings *s, int argc, char *argv[])
883 {
884     struct vconn *vconn;
885     struct ofpbuf *buffer;
886     struct nx_act_config *nac;
887     size_t size;
888
889     /* Parse and send. */
890     size = sizeof *nac + sizeof nac->snat[0];
891     nac = make_openflow(size, OFPT_VENDOR, &buffer);
892
893     nac->header.vendor = htonl(NX_VENDOR_ID);
894     nac->header.subtype = htonl(NXT_ACT_SET_CONFIG);
895
896     nac->type = htons(NXAST_SNAT);
897     nac->snat[0].command = NXSC_ADD;
898     nac->snat[0].port = htons(str_to_int(argv[2]));
899     nac->snat[0].mac_timeout = htons(0);
900     str_to_ip(argv[3], &nac->snat[0].ip_addr_start);
901     str_to_ip(argv[3], &nac->snat[0].ip_addr_end);
902
903     open_vconn(argv[1], &vconn);
904     send_openflow_buffer(vconn, buffer);
905     vconn_close(vconn);
906 }
907
908 static void do_del_snat(const struct settings *s, int argc, char *argv[])
909 {
910     struct vconn *vconn;
911     struct ofpbuf *buffer;
912     struct nx_act_config *nac;
913     size_t size;
914
915     /* Parse and send. */
916     size = sizeof *nac + sizeof nac->snat[0];
917     nac = make_openflow(size, OFPT_VENDOR, &buffer);
918
919     nac->header.vendor = htonl(NX_VENDOR_ID);
920     nac->header.subtype = htonl(NXT_ACT_SET_CONFIG);
921
922     nac->type = htons(NXAST_SNAT);
923     nac->snat[0].command = NXSC_DELETE;
924     nac->snat[0].port = htons(str_to_int(argv[2]));
925     nac->snat[0].mac_timeout = htons(0);
926
927     open_vconn(argv[1], &vconn);
928     send_openflow_buffer(vconn, buffer);
929     vconn_close(vconn);
930 }
931 #endif /* SUPPORT_SNAT */
932
933 static void do_add_flow(const struct settings *s, int argc, char *argv[])
934 {
935     struct vconn *vconn;
936     struct ofpbuf *buffer;
937     struct ofp_flow_mod *ofm;
938     uint16_t priority, idle_timeout, hard_timeout;
939     size_t size;
940     size_t actions_len = MAX_ACT_LEN;
941
942     /* Parse and send. */
943     size = sizeof *ofm + actions_len;
944     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
945     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
946                 NULL, &priority, &idle_timeout, &hard_timeout);
947     ofm->command = htons(OFPFC_ADD);
948     ofm->idle_timeout = htons(idle_timeout);
949     ofm->hard_timeout = htons(hard_timeout);
950     ofm->buffer_id = htonl(UINT32_MAX);
951     ofm->priority = htons(priority);
952     ofm->reserved = htonl(0);
953
954     /* xxx Should we use the ofpbuf library? */
955     buffer->size -= MAX_ACT_LEN - actions_len;
956
957     open_vconn(argv[1], &vconn);
958     send_openflow_buffer(vconn, buffer);
959     vconn_close(vconn);
960 }
961
962 static void do_add_flows(const struct settings *s, int argc, char *argv[])
963 {
964     struct vconn *vconn;
965     FILE *file;
966     char line[1024];
967
968     file = fopen(argv[2], "r");
969     if (file == NULL) {
970         ofp_fatal(errno, "%s: open", argv[2]);
971     }
972
973     open_vconn(argv[1], &vconn);
974     while (fgets(line, sizeof line, file)) {
975         struct ofpbuf *buffer;
976         struct ofp_flow_mod *ofm;
977         uint16_t priority, idle_timeout, hard_timeout;
978         size_t size;
979         size_t actions_len = MAX_ACT_LEN;
980
981         char *comment;
982
983         /* Delete comments. */
984         comment = strchr(line, '#');
985         if (comment) {
986             *comment = '\0';
987         }
988
989         /* Drop empty lines. */
990         if (line[strspn(line, " \t\n")] == '\0') {
991             continue;
992         }
993
994         /* Parse and send. */
995         size = sizeof *ofm + actions_len;
996         ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
997         str_to_flow(line, &ofm->match, &ofm->actions[0], &actions_len, 
998                     NULL, &priority, &idle_timeout, &hard_timeout);
999         ofm->command = htons(OFPFC_ADD);
1000         ofm->idle_timeout = htons(idle_timeout);
1001         ofm->hard_timeout = htons(hard_timeout);
1002         ofm->buffer_id = htonl(UINT32_MAX);
1003         ofm->priority = htons(priority);
1004         ofm->reserved = htonl(0);
1005
1006         /* xxx Should we use the ofpbuf library? */
1007         buffer->size -= MAX_ACT_LEN - actions_len;
1008
1009         send_openflow_buffer(vconn, buffer);
1010     }
1011     vconn_close(vconn);
1012     fclose(file);
1013 }
1014
1015 static void do_mod_flows(const struct settings *s, int argc, char *argv[])
1016 {
1017     uint16_t priority, idle_timeout, hard_timeout;
1018     struct vconn *vconn;
1019     struct ofpbuf *buffer;
1020     struct ofp_flow_mod *ofm;
1021     size_t size;
1022     size_t actions_len = MAX_ACT_LEN;
1023
1024     /* Parse and send. */
1025     size = sizeof *ofm + actions_len;
1026     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
1027     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
1028                 NULL, &priority, &idle_timeout, &hard_timeout);
1029     if (s->strict) {
1030         ofm->command = htons(OFPFC_MODIFY_STRICT);
1031     } else {
1032         ofm->command = htons(OFPFC_MODIFY);
1033     }
1034     ofm->idle_timeout = htons(idle_timeout);
1035     ofm->hard_timeout = htons(hard_timeout);
1036     ofm->buffer_id = htonl(UINT32_MAX);
1037     ofm->priority = htons(priority);
1038     ofm->reserved = htonl(0);
1039
1040     /* xxx Should we use the buffer library? */
1041     buffer->size -= MAX_ACT_LEN - actions_len;
1042
1043     open_vconn(argv[1], &vconn);
1044     send_openflow_buffer(vconn, buffer);
1045     vconn_close(vconn);
1046 }
1047
1048 static void do_del_flows(const struct settings *s, int argc, char *argv[])
1049 {
1050     struct vconn *vconn;
1051     uint16_t priority;
1052     struct ofpbuf *buffer;
1053     struct ofp_flow_mod *ofm;
1054     size_t size;
1055
1056     /* Parse and send. */
1057     size = sizeof *ofm;
1058     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
1059     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
1060                 &priority, NULL, NULL);
1061     if (s->strict) {
1062         ofm->command = htons(OFPFC_DELETE_STRICT);
1063     } else {
1064         ofm->command = htons(OFPFC_DELETE);
1065     }
1066     ofm->idle_timeout = htons(0);
1067     ofm->hard_timeout = htons(0);
1068     ofm->buffer_id = htonl(UINT32_MAX);
1069     ofm->priority = htons(priority);
1070     ofm->reserved = htonl(0);
1071
1072     open_vconn(argv[1], &vconn);
1073     send_openflow_buffer(vconn, buffer);
1074     vconn_close(vconn);
1075 }
1076
1077 static void
1078 do_monitor(const struct settings *s, int argc UNUSED, char *argv[])
1079 {
1080     struct vconn *vconn;
1081     const char *name;
1082
1083     /* If the user specified, e.g., "nl:0", append ":1" to it to ensure that
1084      * the connection will subscribe to listen for asynchronous messages, such
1085      * as packet-in messages. */
1086     if (!strncmp(argv[1], "nl:", 3) && strrchr(argv[1], ':') == &argv[1][2]) {
1087         name = xasprintf("%s:1", argv[1]);
1088     } else {
1089         name = argv[1];
1090     }
1091     open_vconn(argv[1], &vconn);
1092     for (;;) {
1093         struct ofpbuf *b;
1094         run(vconn_recv_block(vconn, &b), "vconn_recv");
1095         ofp_print(stderr, b->data, b->size, 2);
1096         ofpbuf_delete(b);
1097     }
1098 }
1099
1100 static void
1101 do_dump_ports(const struct settings *s, int argc, char *argv[])
1102 {
1103     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
1104 }
1105
1106 static void
1107 do_probe(const struct settings *s, int argc, char *argv[])
1108 {
1109     struct ofpbuf *request;
1110     struct vconn *vconn;
1111     struct ofpbuf *reply;
1112
1113     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1114     open_vconn(argv[1], &vconn);
1115     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1116     if (reply->size != request->size) {
1117         ofp_fatal(0, "reply does not match request");
1118     }
1119     ofpbuf_delete(reply);
1120     vconn_close(vconn);
1121 }
1122
1123 static void
1124 do_mod_port(const struct settings *s, int argc, char *argv[])
1125 {
1126     struct ofpbuf *request, *reply;
1127     struct ofp_switch_features *osf;
1128     struct ofp_port_mod *opm;
1129     struct vconn *vconn;
1130     char *endptr;
1131     int n_ports;
1132     int port_idx;
1133     int port_no;
1134     
1135
1136     /* Check if the argument is a port index.  Otherwise, treat it as
1137      * the port name. */
1138     port_no = strtol(argv[2], &endptr, 10);
1139     if (port_no == 0 && endptr == argv[2]) {
1140         port_no = -1;
1141     }
1142
1143     /* Send a "Features Request" to get the information we need in order 
1144      * to modify the port. */
1145     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
1146     open_vconn(argv[1], &vconn);
1147     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1148
1149     osf = reply->data;
1150     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
1151
1152     for (port_idx = 0; port_idx < n_ports; port_idx++) {
1153         if (port_no != -1) {
1154             /* Check argument as a port index */
1155             if (osf->ports[port_idx].port_no == htons(port_no)) {
1156                 break;
1157             }
1158         } else {
1159             /* Check argument as an interface name */
1160             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
1161                         sizeof osf->ports[0].name)) {
1162                 break;
1163             }
1164
1165         }
1166     }
1167     if (port_idx == n_ports) {
1168         ofp_fatal(0, "couldn't find monitored port: %s", argv[2]);
1169     }
1170
1171     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1172     opm->port_no = osf->ports[port_idx].port_no;
1173     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
1174     opm->config = htonl(0);
1175     opm->mask = htonl(0);
1176     opm->advertise = htonl(0);
1177
1178     printf("modifying port: %s\n", osf->ports[port_idx].name);
1179
1180     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
1181         opm->mask |= htonl(OFPPC_PORT_DOWN);
1182     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
1183                 sizeof MOD_PORT_CMD_DOWN)) {
1184         opm->mask |= htonl(OFPPC_PORT_DOWN);
1185         opm->config |= htonl(OFPPC_PORT_DOWN);
1186     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
1187                 sizeof MOD_PORT_CMD_FLOOD)) {
1188         opm->mask |= htonl(OFPPC_NO_FLOOD);
1189     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
1190                 sizeof MOD_PORT_CMD_NOFLOOD)) {
1191         opm->mask |= htonl(OFPPC_NO_FLOOD);
1192         opm->config |= htonl(OFPPC_NO_FLOOD);
1193     } else {
1194         ofp_fatal(0, "unknown mod-port command '%s'", argv[3]);
1195     }
1196
1197     send_openflow_buffer(vconn, request);
1198
1199     ofpbuf_delete(reply);
1200     vconn_close(vconn);
1201 }
1202
1203 static void
1204 do_ping(const struct settings *s, int argc, char *argv[])
1205 {
1206     size_t max_payload = 65535 - sizeof(struct ofp_header);
1207     unsigned int payload;
1208     struct vconn *vconn;
1209     int i;
1210
1211     payload = argc > 2 ? atoi(argv[2]) : 64;
1212     if (payload > max_payload) {
1213         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1214     }
1215
1216     open_vconn(argv[1], &vconn);
1217     for (i = 0; i < 10; i++) {
1218         struct timeval start, end;
1219         struct ofpbuf *request, *reply;
1220         struct ofp_header *rq_hdr, *rpy_hdr;
1221
1222         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1223                                OFPT_ECHO_REQUEST, &request);
1224         random_bytes(rq_hdr + 1, payload);
1225
1226         gettimeofday(&start, NULL);
1227         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1228         gettimeofday(&end, NULL);
1229
1230         rpy_hdr = reply->data;
1231         if (reply->size != request->size
1232             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1233             || rpy_hdr->xid != rq_hdr->xid
1234             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1235             printf("Reply does not match request.  Request:\n");
1236             ofp_print(stdout, request, request->size, 2);
1237             printf("Reply:\n");
1238             ofp_print(stdout, reply, reply->size, 2);
1239         }
1240         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1241                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1242                    (1000*(double)(end.tv_sec - start.tv_sec))
1243                    + (.001*(end.tv_usec - start.tv_usec)));
1244         ofpbuf_delete(request);
1245         ofpbuf_delete(reply);
1246     }
1247     vconn_close(vconn);
1248 }
1249
1250 static void
1251 do_benchmark(const struct settings *s, int argc, char *argv[])
1252 {
1253     size_t max_payload = 65535 - sizeof(struct ofp_header);
1254     struct timeval start, end;
1255     unsigned int payload_size, message_size;
1256     struct vconn *vconn;
1257     double duration;
1258     int count;
1259     int i;
1260
1261     payload_size = atoi(argv[2]);
1262     if (payload_size > max_payload) {
1263         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1264     }
1265     message_size = sizeof(struct ofp_header) + payload_size;
1266
1267     count = atoi(argv[3]);
1268
1269     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1270            count, message_size, count * message_size);
1271
1272     open_vconn(argv[1], &vconn);
1273     gettimeofday(&start, NULL);
1274     for (i = 0; i < count; i++) {
1275         struct ofpbuf *request, *reply;
1276         struct ofp_header *rq_hdr;
1277
1278         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1279         memset(rq_hdr + 1, 0, payload_size);
1280         run(vconn_transact(vconn, request, &reply), "transact");
1281         ofpbuf_delete(reply);
1282     }
1283     gettimeofday(&end, NULL);
1284     vconn_close(vconn);
1285
1286     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1287                 + (.001*(end.tv_usec - start.tv_usec)));
1288     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1289            duration, count / (duration / 1000.0),
1290            count * message_size / (duration / 1000.0));
1291 }
1292
1293 static void
1294 do_execute(const struct settings *s, int argc, char *argv[])
1295 {
1296     struct vconn *vconn;
1297     struct ofpbuf *request;
1298     struct nicira_header *nicira;
1299     struct nx_command_reply *ncr;
1300     uint32_t xid;
1301     int i;
1302
1303     nicira = make_openflow(sizeof *nicira, OFPT_VENDOR, &request);
1304     xid = nicira->header.xid;
1305     nicira->vendor = htonl(NX_VENDOR_ID);
1306     nicira->subtype = htonl(NXT_COMMAND_REQUEST);
1307     ofpbuf_put(request, argv[2], strlen(argv[2]));
1308     for (i = 3; i < argc; i++) {
1309         ofpbuf_put_zeros(request, 1);
1310         ofpbuf_put(request, argv[i], strlen(argv[i]));
1311     }
1312     update_openflow_length(request);
1313
1314     open_vconn(argv[1], &vconn);
1315     run(vconn_send_block(vconn, request), "send");
1316
1317     for (;;) {
1318         struct ofpbuf *reply;
1319         uint32_t status;
1320
1321         run(vconn_recv_xid(vconn, xid, &reply), "recv_xid");
1322         if (reply->size < sizeof *ncr) {
1323             ofp_fatal(0, "reply is too short (%zu bytes < %zu bytes)",
1324                       reply->size, sizeof *ncr);
1325         }
1326         ncr = reply->data;
1327         if (ncr->nxh.header.type != OFPT_VENDOR
1328             || ncr->nxh.vendor != htonl(NX_VENDOR_ID)
1329             || ncr->nxh.subtype != htonl(NXT_COMMAND_REPLY)) {
1330             ofp_fatal(0, "reply is invalid");
1331         }
1332
1333         status = ntohl(ncr->status);
1334         if (status & NXT_STATUS_STARTED) {
1335             /* Wait for a second reply. */
1336             continue;
1337         } else if (status & NXT_STATUS_EXITED) {
1338             fprintf(stderr, "process terminated normally with exit code %d",
1339                     status & NXT_STATUS_EXITSTATUS);
1340         } else if (status & NXT_STATUS_SIGNALED) {
1341             fprintf(stderr, "process terminated by signal %d",
1342                     status & NXT_STATUS_TERMSIG);
1343         } else if (status & NXT_STATUS_ERROR) {
1344             fprintf(stderr, "error executing command");
1345         } else {
1346             fprintf(stderr, "process terminated for unknown reason");
1347         }
1348         if (status & NXT_STATUS_COREDUMP) {
1349             fprintf(stderr, " (core dumped)");
1350         }
1351         putc('\n', stderr);
1352
1353         fwrite(ncr + 1, reply->size - sizeof *ncr, 1, stdout);
1354         break;
1355     }
1356 }
1357
1358 static void do_help(const struct settings *s, int argc UNUSED, 
1359         char *argv[] UNUSED)
1360 {
1361     usage();
1362 }
1363
1364 static struct command all_commands[] = {
1365 #ifdef HAVE_NETLINK
1366     { "adddp", 1, 1, do_add_dp },
1367     { "deldp", 1, 1, do_del_dp },
1368     { "addif", 2, INT_MAX, do_add_port },
1369     { "delif", 2, INT_MAX, do_del_port },
1370 #endif
1371
1372     { "show", 1, 1, do_show },
1373     { "status", 1, 2, do_status },
1374
1375     { "help", 0, INT_MAX, do_help },
1376     { "monitor", 1, 1, do_monitor },
1377     { "dump-desc", 1, 1, do_dump_desc },
1378     { "dump-tables", 1, 1, do_dump_tables },
1379     { "dump-flows", 1, 2, do_dump_flows },
1380     { "dump-aggregate", 1, 2, do_dump_aggregate },
1381 #ifdef SUPPORT_SNAT
1382     { "add-snat", 3, 3, do_add_snat },
1383     { "del-snat", 2, 2, do_del_snat },
1384 #endif
1385     { "add-flow", 2, 2, do_add_flow },
1386     { "add-flows", 2, 2, do_add_flows },
1387     { "mod-flows", 2, 2, do_mod_flows },
1388     { "del-flows", 1, 2, do_del_flows },
1389     { "dump-ports", 1, 1, do_dump_ports },
1390     { "mod-port", 3, 3, do_mod_port },
1391     { "probe", 1, 1, do_probe },
1392     { "ping", 1, 2, do_ping },
1393     { "benchmark", 3, 3, do_benchmark },
1394     { "execute", 2, INT_MAX, do_execute },
1395     { NULL, 0, 0, NULL },
1396 };