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