Add "execute" to dpctl usage message.
[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     };
746     const struct field *f;
747
748     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
749         if (!strcmp(f->name, name)) {
750             *f_out = f;
751             return true;
752         }
753     }
754     *f_out = NULL;
755     return false;
756 }
757
758 static void
759 str_to_flow(char *string, struct ofp_match *match, 
760             struct ofp_action_header *actions, size_t *actions_len, 
761             uint8_t *table_idx, uint16_t *priority, 
762             uint16_t *idle_timeout, uint16_t *hard_timeout)
763 {
764
765     char *name;
766     uint32_t wildcards;
767
768     if (table_idx) {
769         *table_idx = 0xff;
770     }
771     if (priority) {
772         *priority = OFP_DEFAULT_PRIORITY;
773     }
774     if (idle_timeout) {
775         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
776     }
777     if (hard_timeout) {
778         *hard_timeout = OFP_FLOW_PERMANENT;
779     }
780     if (actions) {
781         char *act_str = strstr(string, "action");
782         if (!act_str) {
783             ofp_fatal(0, "must specify an action");
784         }
785         *(act_str-1) = '\0';
786
787         act_str = strchr(act_str, '=');
788         if (!act_str) {
789             ofp_fatal(0, "must specify an action");
790         }
791
792         act_str++;
793
794         str_to_action(act_str, actions, actions_len);
795     }
796     memset(match, 0, sizeof *match);
797     wildcards = OFPFW_ALL;
798     for (name = strtok(string, "=, \t\r\n"); name;
799          name = strtok(NULL, "=, \t\r\n")) {
800         const struct protocol *p;
801
802         if (parse_protocol(name, &p)) {
803             wildcards &= ~OFPFW_DL_TYPE;
804             match->dl_type = htons(p->dl_type);
805             if (p->nw_proto) {
806                 wildcards &= ~OFPFW_NW_PROTO;
807                 match->nw_proto = p->nw_proto;
808             }
809         } else {
810             const struct field *f;
811             char *value;
812
813             value = strtok(NULL, ", \t\r\n");
814             if (!value) {
815                 ofp_fatal(0, "field %s missing value", name);
816             }
817         
818             if (table_idx && !strcmp(name, "table")) {
819                 *table_idx = atoi(value);
820             } else if (priority && !strcmp(name, "priority")) {
821                 *priority = atoi(value);
822             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
823                 *idle_timeout = atoi(value);
824             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
825                 *hard_timeout = atoi(value);
826             } else if (parse_field(name, &f)) {
827                 void *data = (char *) match + f->offset;
828                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
829                     wildcards |= f->wildcard;
830                 } else {
831                     wildcards &= ~f->wildcard;
832                     if (f->type == F_U8) {
833                         *(uint8_t *) data = str_to_int(value);
834                     } else if (f->type == F_U16) {
835                         *(uint16_t *) data = htons(str_to_int(value));
836                     } else if (f->type == F_MAC) {
837                         str_to_mac(value, data);
838                     } else if (f->type == F_IP) {
839                         wildcards |= str_to_ip(value, data) << f->shift;
840                     } else {
841                         NOT_REACHED();
842                     }
843                 }
844             } else {
845                 ofp_fatal(0, "unknown keyword %s", name);
846             }
847         }
848     }
849     match->wildcards = htonl(wildcards);
850 }
851
852 static void do_dump_flows(const struct settings *s, int argc, char *argv[])
853 {
854     struct ofp_flow_stats_request *req;
855     struct ofpbuf *request;
856
857     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
858     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0, 
859                 &req->table_id, NULL, NULL, NULL);
860     memset(req->pad, 0, sizeof req->pad);
861
862     dump_stats_transaction(argv[1], request);
863 }
864
865 static void do_dump_aggregate(const struct settings *s, int argc, 
866         char *argv[])
867 {
868     struct ofp_aggregate_stats_request *req;
869     struct ofpbuf *request;
870
871     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
872     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL, 0,
873                 &req->table_id, NULL, NULL, NULL);
874     memset(req->pad, 0, sizeof req->pad);
875
876     dump_stats_transaction(argv[1], request);
877 }
878
879 #ifdef SUPPORT_SNAT
880 static void do_add_snat(const struct settings *s, int argc, char *argv[])
881 {
882     struct vconn *vconn;
883     struct ofpbuf *buffer;
884     struct nx_act_config *nac;
885     size_t size;
886
887     /* Parse and send. */
888     size = sizeof *nac + sizeof nac->snat[0];
889     nac = make_openflow(size, OFPT_VENDOR, &buffer);
890
891     nac->header.vendor = htonl(NX_VENDOR_ID);
892     nac->header.subtype = htonl(NXT_ACT_SET_CONFIG);
893
894     nac->type = htons(NXAST_SNAT);
895     nac->snat[0].command = NXSC_ADD;
896     nac->snat[0].port = htons(str_to_int(argv[2]));
897     nac->snat[0].mac_timeout = htons(0);
898     str_to_ip(argv[3], &nac->snat[0].ip_addr_start);
899     str_to_ip(argv[3], &nac->snat[0].ip_addr_end);
900
901     open_vconn(argv[1], &vconn);
902     send_openflow_buffer(vconn, buffer);
903     vconn_close(vconn);
904 }
905
906 static void do_del_snat(const struct settings *s, int argc, char *argv[])
907 {
908     struct vconn *vconn;
909     struct ofpbuf *buffer;
910     struct nx_act_config *nac;
911     size_t size;
912
913     /* Parse and send. */
914     size = sizeof *nac + sizeof nac->snat[0];
915     nac = make_openflow(size, OFPT_VENDOR, &buffer);
916
917     nac->header.vendor = htonl(NX_VENDOR_ID);
918     nac->header.subtype = htonl(NXT_ACT_SET_CONFIG);
919
920     nac->type = htons(NXAST_SNAT);
921     nac->snat[0].command = NXSC_DELETE;
922     nac->snat[0].port = htons(str_to_int(argv[2]));
923     nac->snat[0].mac_timeout = htons(0);
924
925     open_vconn(argv[1], &vconn);
926     send_openflow_buffer(vconn, buffer);
927     vconn_close(vconn);
928 }
929 #endif /* SUPPORT_SNAT */
930
931 static void do_add_flow(const struct settings *s, int argc, char *argv[])
932 {
933     struct vconn *vconn;
934     struct ofpbuf *buffer;
935     struct ofp_flow_mod *ofm;
936     uint16_t priority, idle_timeout, hard_timeout;
937     size_t size;
938     size_t actions_len = MAX_ACT_LEN;
939
940     /* Parse and send. */
941     size = sizeof *ofm + actions_len;
942     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
943     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
944                 NULL, &priority, &idle_timeout, &hard_timeout);
945     ofm->command = htons(OFPFC_ADD);
946     ofm->idle_timeout = htons(idle_timeout);
947     ofm->hard_timeout = htons(hard_timeout);
948     ofm->buffer_id = htonl(UINT32_MAX);
949     ofm->priority = htons(priority);
950     ofm->reserved = htonl(0);
951
952     /* xxx Should we use the ofpbuf library? */
953     buffer->size -= MAX_ACT_LEN - actions_len;
954
955     open_vconn(argv[1], &vconn);
956     send_openflow_buffer(vconn, buffer);
957     vconn_close(vconn);
958 }
959
960 static void do_add_flows(const struct settings *s, int argc, char *argv[])
961 {
962     struct vconn *vconn;
963     FILE *file;
964     char line[1024];
965
966     file = fopen(argv[2], "r");
967     if (file == NULL) {
968         ofp_fatal(errno, "%s: open", argv[2]);
969     }
970
971     open_vconn(argv[1], &vconn);
972     while (fgets(line, sizeof line, file)) {
973         struct ofpbuf *buffer;
974         struct ofp_flow_mod *ofm;
975         uint16_t priority, idle_timeout, hard_timeout;
976         size_t size;
977         size_t actions_len = MAX_ACT_LEN;
978
979         char *comment;
980
981         /* Delete comments. */
982         comment = strchr(line, '#');
983         if (comment) {
984             *comment = '\0';
985         }
986
987         /* Drop empty lines. */
988         if (line[strspn(line, " \t\n")] == '\0') {
989             continue;
990         }
991
992         /* Parse and send. */
993         size = sizeof *ofm + actions_len;
994         ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
995         str_to_flow(line, &ofm->match, &ofm->actions[0], &actions_len, 
996                     NULL, &priority, &idle_timeout, &hard_timeout);
997         ofm->command = htons(OFPFC_ADD);
998         ofm->idle_timeout = htons(idle_timeout);
999         ofm->hard_timeout = htons(hard_timeout);
1000         ofm->buffer_id = htonl(UINT32_MAX);
1001         ofm->priority = htons(priority);
1002         ofm->reserved = htonl(0);
1003
1004         /* xxx Should we use the ofpbuf library? */
1005         buffer->size -= MAX_ACT_LEN - actions_len;
1006
1007         send_openflow_buffer(vconn, buffer);
1008     }
1009     vconn_close(vconn);
1010     fclose(file);
1011 }
1012
1013 static void do_mod_flows(const struct settings *s, int argc, char *argv[])
1014 {
1015     uint16_t priority, idle_timeout, hard_timeout;
1016     struct vconn *vconn;
1017     struct ofpbuf *buffer;
1018     struct ofp_flow_mod *ofm;
1019     size_t size;
1020     size_t actions_len = MAX_ACT_LEN;
1021
1022     /* Parse and send. */
1023     size = sizeof *ofm + actions_len;
1024     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
1025     str_to_flow(argv[2], &ofm->match, &ofm->actions[0], &actions_len, 
1026                 NULL, &priority, &idle_timeout, &hard_timeout);
1027     if (s->strict) {
1028         ofm->command = htons(OFPFC_MODIFY_STRICT);
1029     } else {
1030         ofm->command = htons(OFPFC_MODIFY);
1031     }
1032     ofm->idle_timeout = htons(idle_timeout);
1033     ofm->hard_timeout = htons(hard_timeout);
1034     ofm->buffer_id = htonl(UINT32_MAX);
1035     ofm->priority = htons(priority);
1036     ofm->reserved = htonl(0);
1037
1038     /* xxx Should we use the buffer library? */
1039     buffer->size -= MAX_ACT_LEN - actions_len;
1040
1041     open_vconn(argv[1], &vconn);
1042     send_openflow_buffer(vconn, buffer);
1043     vconn_close(vconn);
1044 }
1045
1046 static void do_del_flows(const struct settings *s, int argc, char *argv[])
1047 {
1048     struct vconn *vconn;
1049     uint16_t priority;
1050     struct ofpbuf *buffer;
1051     struct ofp_flow_mod *ofm;
1052     size_t size;
1053
1054     /* Parse and send. */
1055     size = sizeof *ofm;
1056     ofm = make_openflow(size, OFPT_FLOW_MOD, &buffer);
1057     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, 0, NULL, 
1058                 &priority, NULL, NULL);
1059     if (s->strict) {
1060         ofm->command = htons(OFPFC_DELETE_STRICT);
1061     } else {
1062         ofm->command = htons(OFPFC_DELETE);
1063     }
1064     ofm->idle_timeout = htons(0);
1065     ofm->hard_timeout = htons(0);
1066     ofm->buffer_id = htonl(UINT32_MAX);
1067     ofm->priority = htons(priority);
1068     ofm->reserved = htonl(0);
1069
1070     open_vconn(argv[1], &vconn);
1071     send_openflow_buffer(vconn, buffer);
1072     vconn_close(vconn);
1073 }
1074
1075 static void
1076 do_monitor(const struct settings *s, int argc UNUSED, char *argv[])
1077 {
1078     struct vconn *vconn;
1079     const char *name;
1080
1081     /* If the user specified, e.g., "nl:0", append ":1" to it to ensure that
1082      * the connection will subscribe to listen for asynchronous messages, such
1083      * as packet-in messages. */
1084     if (!strncmp(argv[1], "nl:", 3) && strrchr(argv[1], ':') == &argv[1][2]) {
1085         name = xasprintf("%s:1", argv[1]);
1086     } else {
1087         name = argv[1];
1088     }
1089     open_vconn(argv[1], &vconn);
1090     for (;;) {
1091         struct ofpbuf *b;
1092         run(vconn_recv_block(vconn, &b), "vconn_recv");
1093         ofp_print(stderr, b->data, b->size, 2);
1094         ofpbuf_delete(b);
1095     }
1096 }
1097
1098 static void
1099 do_dump_ports(const struct settings *s, int argc, char *argv[])
1100 {
1101     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
1102 }
1103
1104 static void
1105 do_probe(const struct settings *s, int argc, char *argv[])
1106 {
1107     struct ofpbuf *request;
1108     struct vconn *vconn;
1109     struct ofpbuf *reply;
1110
1111     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
1112     open_vconn(argv[1], &vconn);
1113     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1114     if (reply->size != request->size) {
1115         ofp_fatal(0, "reply does not match request");
1116     }
1117     ofpbuf_delete(reply);
1118     vconn_close(vconn);
1119 }
1120
1121 static void
1122 do_mod_port(const struct settings *s, int argc, char *argv[])
1123 {
1124     struct ofpbuf *request, *reply;
1125     struct ofp_switch_features *osf;
1126     struct ofp_port_mod *opm;
1127     struct vconn *vconn;
1128     char *endptr;
1129     int n_ports;
1130     int port_idx;
1131     int port_no;
1132     
1133
1134     /* Check if the argument is a port index.  Otherwise, treat it as
1135      * the port name. */
1136     port_no = strtol(argv[2], &endptr, 10);
1137     if (port_no == 0 && endptr == argv[2]) {
1138         port_no = -1;
1139     }
1140
1141     /* Send a "Features Request" to get the information we need in order 
1142      * to modify the port. */
1143     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
1144     open_vconn(argv[1], &vconn);
1145     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1146
1147     osf = reply->data;
1148     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
1149
1150     for (port_idx = 0; port_idx < n_ports; port_idx++) {
1151         if (port_no != -1) {
1152             /* Check argument as a port index */
1153             if (osf->ports[port_idx].port_no == htons(port_no)) {
1154                 break;
1155             }
1156         } else {
1157             /* Check argument as an interface name */
1158             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
1159                         sizeof osf->ports[0].name)) {
1160                 break;
1161             }
1162
1163         }
1164     }
1165     if (port_idx == n_ports) {
1166         ofp_fatal(0, "couldn't find monitored port: %s", argv[2]);
1167     }
1168
1169     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1170     opm->port_no = osf->ports[port_idx].port_no;
1171     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
1172     opm->config = htonl(0);
1173     opm->mask = htonl(0);
1174     opm->advertise = htonl(0);
1175
1176     printf("modifying port: %s\n", osf->ports[port_idx].name);
1177
1178     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
1179         opm->mask |= htonl(OFPPC_PORT_DOWN);
1180     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
1181                 sizeof MOD_PORT_CMD_DOWN)) {
1182         opm->mask |= htonl(OFPPC_PORT_DOWN);
1183         opm->config |= htonl(OFPPC_PORT_DOWN);
1184     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
1185                 sizeof MOD_PORT_CMD_FLOOD)) {
1186         opm->mask |= htonl(OFPPC_NO_FLOOD);
1187     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
1188                 sizeof MOD_PORT_CMD_NOFLOOD)) {
1189         opm->mask |= htonl(OFPPC_NO_FLOOD);
1190         opm->config |= htonl(OFPPC_NO_FLOOD);
1191     } else {
1192         ofp_fatal(0, "unknown mod-port command '%s'", argv[3]);
1193     }
1194
1195     send_openflow_buffer(vconn, request);
1196
1197     ofpbuf_delete(reply);
1198     vconn_close(vconn);
1199 }
1200
1201 static void
1202 do_ping(const struct settings *s, int argc, char *argv[])
1203 {
1204     size_t max_payload = 65535 - sizeof(struct ofp_header);
1205     unsigned int payload;
1206     struct vconn *vconn;
1207     int i;
1208
1209     payload = argc > 2 ? atoi(argv[2]) : 64;
1210     if (payload > max_payload) {
1211         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1212     }
1213
1214     open_vconn(argv[1], &vconn);
1215     for (i = 0; i < 10; i++) {
1216         struct timeval start, end;
1217         struct ofpbuf *request, *reply;
1218         struct ofp_header *rq_hdr, *rpy_hdr;
1219
1220         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1221                                OFPT_ECHO_REQUEST, &request);
1222         random_bytes(rq_hdr + 1, payload);
1223
1224         gettimeofday(&start, NULL);
1225         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1226         gettimeofday(&end, NULL);
1227
1228         rpy_hdr = reply->data;
1229         if (reply->size != request->size
1230             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1231             || rpy_hdr->xid != rq_hdr->xid
1232             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1233             printf("Reply does not match request.  Request:\n");
1234             ofp_print(stdout, request, request->size, 2);
1235             printf("Reply:\n");
1236             ofp_print(stdout, reply, reply->size, 2);
1237         }
1238         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1239                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1240                    (1000*(double)(end.tv_sec - start.tv_sec))
1241                    + (.001*(end.tv_usec - start.tv_usec)));
1242         ofpbuf_delete(request);
1243         ofpbuf_delete(reply);
1244     }
1245     vconn_close(vconn);
1246 }
1247
1248 static void
1249 do_benchmark(const struct settings *s, int argc, char *argv[])
1250 {
1251     size_t max_payload = 65535 - sizeof(struct ofp_header);
1252     struct timeval start, end;
1253     unsigned int payload_size, message_size;
1254     struct vconn *vconn;
1255     double duration;
1256     int count;
1257     int i;
1258
1259     payload_size = atoi(argv[2]);
1260     if (payload_size > max_payload) {
1261         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1262     }
1263     message_size = sizeof(struct ofp_header) + payload_size;
1264
1265     count = atoi(argv[3]);
1266
1267     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1268            count, message_size, count * message_size);
1269
1270     open_vconn(argv[1], &vconn);
1271     gettimeofday(&start, NULL);
1272     for (i = 0; i < count; i++) {
1273         struct ofpbuf *request, *reply;
1274         struct ofp_header *rq_hdr;
1275
1276         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1277         memset(rq_hdr + 1, 0, payload_size);
1278         run(vconn_transact(vconn, request, &reply), "transact");
1279         ofpbuf_delete(reply);
1280     }
1281     gettimeofday(&end, NULL);
1282     vconn_close(vconn);
1283
1284     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1285                 + (.001*(end.tv_usec - start.tv_usec)));
1286     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1287            duration, count / (duration / 1000.0),
1288            count * message_size / (duration / 1000.0));
1289 }
1290
1291 static void
1292 do_execute(const struct settings *s, int argc, char *argv[])
1293 {
1294     struct vconn *vconn;
1295     struct ofpbuf *request;
1296     struct nicira_header *nicira;
1297     struct nx_command_reply *ncr;
1298     uint32_t xid;
1299     int i;
1300
1301     nicira = make_openflow(sizeof *nicira, OFPT_VENDOR, &request);
1302     xid = nicira->header.xid;
1303     nicira->vendor = htonl(NX_VENDOR_ID);
1304     nicira->subtype = htonl(NXT_COMMAND_REQUEST);
1305     ofpbuf_put(request, argv[2], strlen(argv[2]));
1306     for (i = 3; i < argc; i++) {
1307         ofpbuf_put_zeros(request, 1);
1308         ofpbuf_put(request, argv[i], strlen(argv[i]));
1309     }
1310     update_openflow_length(request);
1311
1312     open_vconn(argv[1], &vconn);
1313     run(vconn_send_block(vconn, request), "send");
1314
1315     for (;;) {
1316         struct ofpbuf *reply;
1317         uint32_t status;
1318
1319         run(vconn_recv_xid(vconn, xid, &reply), "recv_xid");
1320         if (reply->size < sizeof *ncr) {
1321             ofp_fatal(0, "reply is too short (%zu bytes < %zu bytes)",
1322                       reply->size, sizeof *ncr);
1323         }
1324         ncr = reply->data;
1325         if (ncr->nxh.header.type != OFPT_VENDOR
1326             || ncr->nxh.vendor != htonl(NX_VENDOR_ID)
1327             || ncr->nxh.subtype != htonl(NXT_COMMAND_REPLY)) {
1328             ofp_fatal(0, "reply is invalid");
1329         }
1330
1331         status = ntohl(ncr->status);
1332         if (status & NXT_STATUS_STARTED) {
1333             /* Wait for a second reply. */
1334             continue;
1335         } else if (status & NXT_STATUS_EXITED) {
1336             fprintf(stderr, "process terminated normally with exit code %d",
1337                     status & NXT_STATUS_EXITSTATUS);
1338         } else if (status & NXT_STATUS_SIGNALED) {
1339             fprintf(stderr, "process terminated by signal %d",
1340                     status & NXT_STATUS_TERMSIG);
1341         } else if (status & NXT_STATUS_ERROR) {
1342             fprintf(stderr, "error executing command");
1343         } else {
1344             fprintf(stderr, "process terminated for unknown reason");
1345         }
1346         if (status & NXT_STATUS_COREDUMP) {
1347             fprintf(stderr, " (core dumped)");
1348         }
1349         putc('\n', stderr);
1350
1351         fwrite(ncr + 1, reply->size - sizeof *ncr, 1, stdout);
1352         break;
1353     }
1354 }
1355
1356 static void do_help(const struct settings *s, int argc UNUSED, 
1357         char *argv[] UNUSED)
1358 {
1359     usage();
1360 }
1361
1362 static struct command all_commands[] = {
1363 #ifdef HAVE_NETLINK
1364     { "adddp", 1, 1, do_add_dp },
1365     { "deldp", 1, 1, do_del_dp },
1366     { "addif", 2, INT_MAX, do_add_port },
1367     { "delif", 2, INT_MAX, do_del_port },
1368 #endif
1369
1370     { "show", 1, 1, do_show },
1371     { "status", 1, 2, do_status },
1372
1373     { "help", 0, INT_MAX, do_help },
1374     { "monitor", 1, 1, do_monitor },
1375     { "dump-desc", 1, 1, do_dump_desc },
1376     { "dump-tables", 1, 1, do_dump_tables },
1377     { "dump-flows", 1, 2, do_dump_flows },
1378     { "dump-aggregate", 1, 2, do_dump_aggregate },
1379 #ifdef SUPPORT_SNAT
1380     { "add-snat", 3, 3, do_add_snat },
1381     { "del-snat", 2, 2, do_del_snat },
1382 #endif
1383     { "add-flow", 2, 2, do_add_flow },
1384     { "add-flows", 2, 2, do_add_flows },
1385     { "mod-flows", 2, 2, do_mod_flows },
1386     { "del-flows", 1, 2, do_del_flows },
1387     { "dump-ports", 1, 1, do_dump_ports },
1388     { "mod-port", 3, 3, do_mod_port },
1389     { "probe", 1, 1, do_probe },
1390     { "ping", 1, 2, do_ping },
1391     { "benchmark", 3, 3, do_benchmark },
1392     { "execute", 2, INT_MAX, do_execute },
1393     { NULL, 0, 0, NULL },
1394 };