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