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