Factor out common code from utilities that multiplex commands.
[openvswitch] / utilities / ovs-ofctl.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <arpa/inet.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <net/if.h>
23 #include <netinet/in.h>
24 #include <signal.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31
32 #include "command-line.h"
33 #include "compiler.h"
34 #include "dirs.h"
35 #include "dpif.h"
36 #include "dynamic-string.h"
37 #include "netdev.h"
38 #include "netlink.h"
39 #include "odp-util.h"
40 #include "ofp-print.h"
41 #include "ofpbuf.h"
42 #include "openflow/nicira-ext.h"
43 #include "openflow/openflow.h"
44 #include "packets.h"
45 #include "random.h"
46 #include "socket-util.h"
47 #include "timeval.h"
48 #include "util.h"
49 #include "vconn-ssl.h"
50 #include "vconn.h"
51
52 #include "vlog.h"
53 #define THIS_MODULE VLM_ofctl
54
55 #define DEFAULT_IDLE_TIMEOUT 60
56
57 #define MOD_PORT_CMD_UP      "up"
58 #define MOD_PORT_CMD_DOWN    "down"
59 #define MOD_PORT_CMD_FLOOD   "flood"
60 #define MOD_PORT_CMD_NOFLOOD "noflood"
61
62 /* Use strict matching for flow mod commands? */
63 static bool strict;
64
65 static const struct command all_commands[];
66
67 static void usage(void) NO_RETURN;
68 static void parse_options(int argc, char *argv[]);
69
70 int
71 main(int argc, char *argv[])
72 {
73     set_program_name(argv[0]);
74     time_init();
75     vlog_init();
76     parse_options(argc, argv);
77     signal(SIGPIPE, SIG_IGN);
78     run_command(argc - optind, argv + optind, all_commands);
79     return 0;
80 }
81
82 static void
83 parse_options(int argc, char *argv[])
84 {
85     enum {
86         OPT_STRICT = UCHAR_MAX + 1
87     };
88     static struct option long_options[] = {
89         {"timeout", required_argument, 0, 't'},
90         {"verbose", optional_argument, 0, 'v'},
91         {"strict", no_argument, 0, OPT_STRICT},
92         {"help", no_argument, 0, 'h'},
93         {"version", no_argument, 0, 'V'},
94         VCONN_SSL_LONG_OPTIONS
95         {0, 0, 0, 0},
96     };
97     char *short_options = long_options_to_short_options(long_options);
98
99     for (;;) {
100         unsigned long int timeout;
101         int c;
102
103         c = getopt_long(argc, argv, short_options, long_options, NULL);
104         if (c == -1) {
105             break;
106         }
107
108         switch (c) {
109         case 't':
110             timeout = strtoul(optarg, NULL, 10);
111             if (timeout <= 0) {
112                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
113                           optarg);
114             } else {
115                 time_alarm(timeout);
116             }
117             break;
118
119         case 'h':
120             usage();
121
122         case 'V':
123             OVS_PRINT_VERSION(OFP_VERSION, OFP_VERSION);
124             exit(EXIT_SUCCESS);
125
126         case 'v':
127             vlog_set_verbosity(optarg);
128             break;
129
130         case OPT_STRICT:
131             strict = true;
132             break;
133
134         VCONN_SSL_OPTION_HANDLERS
135
136         case '?':
137             exit(EXIT_FAILURE);
138
139         default:
140             abort();
141         }
142     }
143     free(short_options);
144 }
145
146 static void
147 usage(void)
148 {
149     printf("%s: OpenFlow switch management utility\n"
150            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
151            "\nFor OpenFlow switches:\n"
152            "  show SWITCH                 show OpenFlow information\n"
153            "  status SWITCH [KEY]         report statistics (about KEY)\n"
154            "  dump-desc SWITCH            print switch description\n"
155            "  dump-tables SWITCH          print table stats\n"
156            "  mod-port SWITCH IFACE ACT   modify port behavior\n"
157            "  dump-ports SWITCH           print port statistics\n"
158            "  dump-flows SWITCH           print all flow entries\n"
159            "  dump-flows SWITCH FLOW      print matching FLOWs\n"
160            "  dump-aggregate SWITCH       print aggregate flow statistics\n"
161            "  dump-aggregate SWITCH FLOW  print aggregate stats for FLOWs\n"
162            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
163            "  add-flows SWITCH FILE       add flows from FILE\n"
164            "  mod-flows SWITCH FLOW       modify actions of matching FLOWs\n"
165            "  del-flows SWITCH [FLOW]     delete matching FLOWs\n"
166            "  monitor SWITCH MISSLEN EXP  print packets received from SWITCH\n"
167            "  execute SWITCH CMD [ARG...] execute CMD with ARGS on SWITCH\n"
168            "\nFor OpenFlow switches and controllers:\n"
169            "  probe VCONN                 probe whether VCONN is up\n"
170            "  ping VCONN [N]              latency of N-byte echos\n"
171            "  benchmark VCONN N COUNT     bandwidth of COUNT N-byte echos\n"
172            "where each SWITCH is an active OpenFlow connection method.\n",
173            program_name, program_name);
174     vconn_usage(true, false, false);
175     vlog_usage();
176     printf("\nOther options:\n"
177            "  --strict                    use strict match for flow commands\n"
178            "  -t, --timeout=SECS          give up after SECS seconds\n"
179            "  -h, --help                  display this help message\n"
180            "  -V, --version               display version information\n");
181     exit(EXIT_SUCCESS);
182 }
183
184 static void run(int retval, const char *message, ...)
185     PRINTF_FORMAT(2, 3);
186
187 static void run(int retval, const char *message, ...)
188 {
189     if (retval) {
190         va_list args;
191
192         fprintf(stderr, "%s: ", program_name);
193         va_start(args, message);
194         vfprintf(stderr, message, args);
195         va_end(args);
196         if (retval == EOF) {
197             fputs(": unexpected end of file\n", stderr);
198         } else {
199             fprintf(stderr, ": %s\n", strerror(retval));
200         }
201
202         exit(EXIT_FAILURE);
203     }
204 }
205 \f
206 /* Generic commands. */
207
208 static void
209 open_vconn(const char *name, struct vconn **vconnp)
210 {
211     struct dpif *dpif;
212     struct stat s;
213
214     if (strstr(name, ":")) {
215         run(vconn_open_block(name, OFP_VERSION, vconnp),
216             "connecting to %s", name);
217     } else if (!stat(name, &s) && S_ISSOCK(s.st_mode)) {
218         char *vconn_name = xasprintf("unix:%s", name);
219         VLOG_INFO("connecting to %s", vconn_name);
220         run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
221             "connecting to %s", vconn_name);
222         free(vconn_name);
223     } else if (!dpif_open(name, &dpif)) {
224         char dpif_name[IF_NAMESIZE + 1];
225         char *socket_name;
226         char *vconn_name;
227
228         run(dpif_port_get_name(dpif, ODPP_LOCAL, dpif_name, sizeof dpif_name),
229             "obtaining name of %s", dpif_name);
230         dpif_close(dpif);
231         if (strcmp(dpif_name, name)) {
232             VLOG_INFO("datapath %s is named %s", name, dpif_name);
233         }
234
235         socket_name = xasprintf("%s/%s.mgmt", ovs_rundir, dpif_name);
236         if (stat(socket_name, &s)) {
237             ovs_fatal(errno, "cannot connect to %s: stat failed on %s",
238                       name, socket_name);
239         } else if (!S_ISSOCK(s.st_mode)) {
240             ovs_fatal(0, "cannot connect to %s: %s is not a socket",
241                       name, socket_name);
242         }
243
244         vconn_name = xasprintf("unix:%s", socket_name);
245         VLOG_INFO("connecting to %s", vconn_name);
246         run(vconn_open_block(vconn_name, OFP_VERSION, vconnp),
247             "connecting to %s", vconn_name);
248         free(socket_name);
249         free(vconn_name);
250     } else {
251         ovs_fatal(0, "%s is not a valid connection method", name);
252     }
253 }
254
255 static void *
256 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
257 {
258     struct ofp_stats_request *rq;
259     rq = make_openflow((offsetof(struct ofp_stats_request, body)
260                         + body_len), OFPT_STATS_REQUEST, bufferp);
261     rq->type = htons(type);
262     rq->flags = htons(0);
263     return rq->body;
264 }
265
266 static void
267 send_openflow_buffer(struct vconn *vconn, struct ofpbuf *buffer)
268 {
269     update_openflow_length(buffer);
270     run(vconn_send_block(vconn, buffer), "failed to send packet to switch");
271 }
272
273 static void
274 dump_transaction(const char *vconn_name, struct ofpbuf *request)
275 {
276     struct vconn *vconn;
277     struct ofpbuf *reply;
278
279     update_openflow_length(request);
280     open_vconn(vconn_name, &vconn);
281     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
282     ofp_print(stdout, reply->data, reply->size, 1);
283     vconn_close(vconn);
284 }
285
286 static void
287 dump_trivial_transaction(const char *vconn_name, uint8_t request_type)
288 {
289     struct ofpbuf *request;
290     make_openflow(sizeof(struct ofp_header), request_type, &request);
291     dump_transaction(vconn_name, request);
292 }
293
294 static void
295 dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
296 {
297     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
298     struct vconn *vconn;
299     bool done = false;
300
301     open_vconn(vconn_name, &vconn);
302     send_openflow_buffer(vconn, request);
303     while (!done) {
304         uint32_t recv_xid;
305         struct ofpbuf *reply;
306
307         run(vconn_recv_block(vconn, &reply), "OpenFlow packet receive failed");
308         recv_xid = ((struct ofp_header *) reply->data)->xid;
309         if (send_xid == recv_xid) {
310             struct ofp_stats_reply *osr;
311
312             ofp_print(stdout, reply->data, reply->size, 1);
313
314             osr = ofpbuf_at(reply, 0, sizeof *osr);
315             done = !osr || !(ntohs(osr->flags) & OFPSF_REPLY_MORE);
316         } else {
317             VLOG_DBG("received reply with xid %08"PRIx32" "
318                      "!= expected %08"PRIx32, recv_xid, send_xid);
319         }
320         ofpbuf_delete(reply);
321     }
322     vconn_close(vconn);
323 }
324
325 static void
326 dump_trivial_stats_transaction(const char *vconn_name, uint8_t stats_type)
327 {
328     struct ofpbuf *request;
329     alloc_stats_request(0, stats_type, &request);
330     dump_stats_transaction(vconn_name, request);
331 }
332
333 static void
334 do_show(int argc UNUSED, char *argv[])
335 {
336     dump_trivial_transaction(argv[1], OFPT_FEATURES_REQUEST);
337     dump_trivial_transaction(argv[1], OFPT_GET_CONFIG_REQUEST);
338 }
339
340 static void
341 do_status(int argc, char *argv[])
342 {
343     struct nicira_header *request, *reply;
344     struct vconn *vconn;
345     struct ofpbuf *b;
346
347     request = make_openflow(sizeof *request, OFPT_VENDOR, &b);
348     request->vendor = htonl(NX_VENDOR_ID);
349     request->subtype = htonl(NXT_STATUS_REQUEST);
350     if (argc > 2) {
351         ofpbuf_put(b, argv[2], strlen(argv[2]));
352         update_openflow_length(b);
353     }
354     open_vconn(argv[1], &vconn);
355     run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
356     vconn_close(vconn);
357
358     if (b->size < sizeof *reply) {
359         ovs_fatal(0, "short reply (%zu bytes)", b->size);
360     }
361     reply = b->data;
362     if (reply->header.type != OFPT_VENDOR
363         || reply->vendor != ntohl(NX_VENDOR_ID)
364         || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
365         ofp_print(stderr, b->data, b->size, 2);
366         ovs_fatal(0, "bad reply");
367     }
368
369     fwrite(reply + 1, b->size - sizeof *reply, 1, stdout);
370 }
371
372 static void
373 do_dump_desc(int argc UNUSED, char *argv[])
374 {
375     dump_trivial_stats_transaction(argv[1], OFPST_DESC);
376 }
377
378 static void
379 do_dump_tables(int argc UNUSED, char *argv[])
380 {
381     dump_trivial_stats_transaction(argv[1], OFPST_TABLE);
382 }
383
384
385 static uint32_t
386 str_to_u32(const char *str) 
387 {
388     char *tail;
389     uint32_t value;
390
391     errno = 0;
392     value = strtoul(str, &tail, 0);
393     if (errno == EINVAL || errno == ERANGE || *tail) {
394         ovs_fatal(0, "invalid numeric format %s", str);
395     }
396     return value;
397 }
398
399 static void
400 str_to_mac(const char *str, uint8_t mac[6]) 
401 {
402     if (sscanf(str, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
403         != ETH_ADDR_SCAN_COUNT) {
404         ovs_fatal(0, "invalid mac address %s", str);
405     }
406 }
407
408 static uint32_t
409 str_to_ip(const char *str_, uint32_t *ip)
410 {
411     char *str = xstrdup(str_);
412     char *save_ptr = NULL;
413     const char *name, *netmask;
414     struct in_addr in_addr;
415     int n_wild, retval;
416
417     name = strtok_r(str, "/", &save_ptr);
418     retval = name ? lookup_ip(name, &in_addr) : EINVAL;
419     if (retval) {
420         ovs_fatal(0, "%s: could not convert to IP address", str);
421     }
422     *ip = in_addr.s_addr;
423
424     netmask = strtok_r(NULL, "/", &save_ptr);
425     if (netmask) {
426         uint8_t o[4];
427         if (sscanf(netmask, "%"SCNu8".%"SCNu8".%"SCNu8".%"SCNu8,
428                    &o[0], &o[1], &o[2], &o[3]) == 4) {
429             uint32_t nm = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
430             int i;
431
432             /* Find first 1-bit. */
433             for (i = 0; i < 32; i++) {
434                 if (nm & (1u << i)) {
435                     break;
436                 }
437             }
438             n_wild = i;
439
440             /* Verify that the rest of the bits are 1-bits. */
441             for (; i < 32; i++) {
442                 if (!(nm & (1u << i))) {
443                     ovs_fatal(0, "%s: %s is not a valid netmask",
444                               str, netmask);
445                 }
446             }
447         } else {
448             int prefix = atoi(netmask);
449             if (prefix <= 0 || prefix > 32) {
450                 ovs_fatal(0, "%s: network prefix bits not between 1 and 32",
451                           str);
452             }
453             n_wild = 32 - prefix;
454         }
455     } else {
456         n_wild = 0;
457     }
458
459     free(str);
460     return n_wild;
461 }
462
463 static void *
464 put_action(struct ofpbuf *b, size_t size, uint16_t type)
465 {
466     struct ofp_action_header *ah = ofpbuf_put_zeros(b, size);
467     ah->type = htons(type);
468     ah->len = htons(size);
469     return ah;
470 }
471
472 static struct ofp_action_output *
473 put_output_action(struct ofpbuf *b, uint16_t port)
474 {
475     struct ofp_action_output *oao = put_action(b, sizeof *oao, OFPAT_OUTPUT);
476     oao->port = htons(port);
477     return oao;
478 }
479
480 static void
481 put_dl_addr_action(struct ofpbuf *b, uint16_t type, const char *addr)
482 {
483     struct ofp_action_dl_addr *oada = put_action(b, sizeof *oada, type);
484     str_to_mac(addr, oada->dl_addr);
485 }
486
487
488 static bool
489 parse_port_name(const char *name, uint16_t *port)
490 {
491     struct pair {
492         const char *name;
493         uint16_t value;
494     };
495     static const struct pair pairs[] = {
496 #define DEF_PAIR(NAME) {#NAME, OFPP_##NAME}
497         DEF_PAIR(IN_PORT),
498         DEF_PAIR(TABLE),
499         DEF_PAIR(NORMAL),
500         DEF_PAIR(FLOOD),
501         DEF_PAIR(ALL),
502         DEF_PAIR(CONTROLLER),
503         DEF_PAIR(LOCAL),
504         DEF_PAIR(NONE),
505 #undef DEF_PAIR
506     };
507     static const int n_pairs = ARRAY_SIZE(pairs);
508     size_t i;
509
510     for (i = 0; i < n_pairs; i++) {
511         if (!strcasecmp(name, pairs[i].name)) {
512             *port = pairs[i].value;
513             return true;
514         }
515     }
516     return false;
517 }
518
519 static void
520 str_to_action(char *str, struct ofpbuf *b)
521 {
522     char *act, *arg;
523     char *saveptr = NULL;
524     bool drop = false;
525     int n_actions;
526
527     for (act = strtok_r(str, ", \t\r\n", &saveptr), n_actions = 0; act;
528          act = strtok_r(NULL, ", \t\r\n", &saveptr), n_actions++) 
529     {
530         uint16_t port;
531
532         if (drop) {
533             ovs_fatal(0, "Drop actions must not be followed by other actions");
534         }
535
536         /* Arguments are separated by colons */
537         arg = strchr(act, ':');
538         if (arg) {
539             *arg = '\0';
540             arg++;
541         }
542
543         if (!strcasecmp(act, "mod_vlan_vid")) {
544             struct ofp_action_vlan_vid *va;
545             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_VID);
546             va->vlan_vid = htons(str_to_u32(arg));
547         } else if (!strcasecmp(act, "mod_vlan_pcp")) {
548             struct ofp_action_vlan_pcp *va;
549             va = put_action(b, sizeof *va, OFPAT_SET_VLAN_PCP);
550             va->vlan_pcp = str_to_u32(arg);
551         } else if (!strcasecmp(act, "strip_vlan")) {
552             struct ofp_action_header *ah;
553             ah = put_action(b, sizeof *ah, OFPAT_STRIP_VLAN);
554             ah->type = htons(OFPAT_STRIP_VLAN);
555         } else if (!strcasecmp(act, "mod_dl_src")) {
556             put_dl_addr_action(b, OFPAT_SET_DL_SRC, arg);
557         } else if (!strcasecmp(act, "mod_dl_dst")) {
558             put_dl_addr_action(b, OFPAT_SET_DL_DST, arg);
559         } else if (!strcasecmp(act, "output")) {
560             put_output_action(b, str_to_u32(arg));
561         } else if (!strcasecmp(act, "drop")) {
562             /* A drop action in OpenFlow occurs by just not setting 
563              * an action. */
564             drop = true;
565             if (n_actions) {
566                 ovs_fatal(0, "Drop actions must not be preceded by other "
567                           "actions");
568             }
569         } else if (!strcasecmp(act, "CONTROLLER")) {
570             struct ofp_action_output *oao;
571             oao = put_output_action(b, OFPP_CONTROLLER);
572
573             /* Unless a numeric argument is specified, we send the whole
574              * packet to the controller. */
575             if (arg && (strspn(act, "0123456789") == strlen(act))) {
576                oao->max_len = htons(str_to_u32(arg));
577             } else {
578                 oao->max_len = htons(UINT16_MAX);
579             }
580         } else if (parse_port_name(act, &port)) {
581             put_output_action(b, port);
582         } else if (strspn(act, "0123456789") == strlen(act)) {
583             put_output_action(b, str_to_u32(act));
584         } else {
585             ovs_fatal(0, "Unknown action: %s", act);
586         }
587     }
588 }
589
590 struct protocol {
591     const char *name;
592     uint16_t dl_type;
593     uint8_t nw_proto;
594 };
595
596 static bool
597 parse_protocol(const char *name, const struct protocol **p_out)
598 {
599     static const struct protocol protocols[] = {
600         { "ip", ETH_TYPE_IP, 0 },
601         { "arp", ETH_TYPE_ARP, 0 },
602         { "icmp", ETH_TYPE_IP, IP_TYPE_ICMP },
603         { "tcp", ETH_TYPE_IP, IP_TYPE_TCP },
604         { "udp", ETH_TYPE_IP, IP_TYPE_UDP },
605     };
606     const struct protocol *p;
607
608     for (p = protocols; p < &protocols[ARRAY_SIZE(protocols)]; p++) {
609         if (!strcmp(p->name, name)) {
610             *p_out = p;
611             return true;
612         }
613     }
614     *p_out = NULL;
615     return false;
616 }
617
618 struct field {
619     const char *name;
620     uint32_t wildcard;
621     enum { F_U8, F_U16, F_MAC, F_IP } type;
622     size_t offset, shift;
623 };
624
625 static bool
626 parse_field(const char *name, const struct field **f_out) 
627 {
628 #define F_OFS(MEMBER) offsetof(struct ofp_match, MEMBER)
629     static const struct field fields[] = { 
630         { "in_port", OFPFW_IN_PORT, F_U16, F_OFS(in_port), 0 },
631         { "dl_vlan", OFPFW_DL_VLAN, F_U16, F_OFS(dl_vlan), 0 },
632         { "dl_src", OFPFW_DL_SRC, F_MAC, F_OFS(dl_src), 0 },
633         { "dl_dst", OFPFW_DL_DST, F_MAC, F_OFS(dl_dst), 0 },
634         { "dl_type", OFPFW_DL_TYPE, F_U16, F_OFS(dl_type), 0 },
635         { "nw_src", OFPFW_NW_SRC_MASK, F_IP,
636           F_OFS(nw_src), OFPFW_NW_SRC_SHIFT },
637         { "nw_dst", OFPFW_NW_DST_MASK, F_IP,
638           F_OFS(nw_dst), OFPFW_NW_DST_SHIFT },
639         { "nw_proto", OFPFW_NW_PROTO, F_U8, F_OFS(nw_proto), 0 },
640         { "tp_src", OFPFW_TP_SRC, F_U16, F_OFS(tp_src), 0 },
641         { "tp_dst", OFPFW_TP_DST, F_U16, F_OFS(tp_dst), 0 },
642         { "icmp_type", OFPFW_ICMP_TYPE, F_U16, F_OFS(icmp_type), 0 },
643         { "icmp_code", OFPFW_ICMP_CODE, F_U16, F_OFS(icmp_code), 0 }
644     };
645     const struct field *f;
646
647     for (f = fields; f < &fields[ARRAY_SIZE(fields)]; f++) {
648         if (!strcmp(f->name, name)) {
649             *f_out = f;
650             return true;
651         }
652     }
653     *f_out = NULL;
654     return false;
655 }
656
657 static void
658 str_to_flow(char *string, struct ofp_match *match, struct ofpbuf *actions,
659             uint8_t *table_idx, uint16_t *out_port, uint16_t *priority, 
660             uint16_t *idle_timeout, uint16_t *hard_timeout)
661 {
662     char *save_ptr = NULL;
663     char *name;
664     uint32_t wildcards;
665
666     if (table_idx) {
667         *table_idx = 0xff;
668     }
669     if (out_port) {
670         *out_port = OFPP_NONE;
671     }
672     if (priority) {
673         *priority = OFP_DEFAULT_PRIORITY;
674     }
675     if (idle_timeout) {
676         *idle_timeout = DEFAULT_IDLE_TIMEOUT;
677     }
678     if (hard_timeout) {
679         *hard_timeout = OFP_FLOW_PERMANENT;
680     }
681     if (actions) {
682         char *act_str = strstr(string, "action");
683         if (!act_str) {
684             ovs_fatal(0, "must specify an action");
685         }
686         *(act_str-1) = '\0';
687
688         act_str = strchr(act_str, '=');
689         if (!act_str) {
690             ovs_fatal(0, "must specify an action");
691         }
692
693         act_str++;
694
695         str_to_action(act_str, actions);
696     }
697     memset(match, 0, sizeof *match);
698     wildcards = OFPFW_ALL;
699     for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
700          name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
701         const struct protocol *p;
702
703         if (parse_protocol(name, &p)) {
704             wildcards &= ~OFPFW_DL_TYPE;
705             match->dl_type = htons(p->dl_type);
706             if (p->nw_proto) {
707                 wildcards &= ~OFPFW_NW_PROTO;
708                 match->nw_proto = p->nw_proto;
709             }
710         } else {
711             const struct field *f;
712             char *value;
713
714             value = strtok_r(NULL, ", \t\r\n", &save_ptr);
715             if (!value) {
716                 ovs_fatal(0, "field %s missing value", name);
717             }
718         
719             if (table_idx && !strcmp(name, "table")) {
720                 *table_idx = atoi(value);
721             } else if (out_port && !strcmp(name, "out_port")) {
722                 *out_port = atoi(value);
723             } else if (priority && !strcmp(name, "priority")) {
724                 *priority = atoi(value);
725             } else if (idle_timeout && !strcmp(name, "idle_timeout")) {
726                 *idle_timeout = atoi(value);
727             } else if (hard_timeout && !strcmp(name, "hard_timeout")) {
728                 *hard_timeout = atoi(value);
729             } else if (parse_field(name, &f)) {
730                 void *data = (char *) match + f->offset;
731                 if (!strcmp(value, "*") || !strcmp(value, "ANY")) {
732                     wildcards |= f->wildcard;
733                 } else {
734                     wildcards &= ~f->wildcard;
735                     if (f->wildcard == OFPFW_IN_PORT
736                         && parse_port_name(value, (uint16_t *) data)) {
737                         /* Nothing to do. */
738                     } else if (f->type == F_U8) {
739                         *(uint8_t *) data = str_to_u32(value);
740                     } else if (f->type == F_U16) {
741                         *(uint16_t *) data = htons(str_to_u32(value));
742                     } else if (f->type == F_MAC) {
743                         str_to_mac(value, data);
744                     } else if (f->type == F_IP) {
745                         wildcards |= str_to_ip(value, data) << f->shift;
746                     } else {
747                         NOT_REACHED();
748                     }
749                 }
750             } else {
751                 ovs_fatal(0, "unknown keyword %s", name);
752             }
753         }
754     }
755     match->wildcards = htonl(wildcards);
756 }
757
758 static void
759 do_dump_flows(int argc, char *argv[])
760 {
761     struct ofp_flow_stats_request *req;
762     uint16_t out_port;
763     struct ofpbuf *request;
764
765     req = alloc_stats_request(sizeof *req, OFPST_FLOW, &request);
766     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL,
767                 &req->table_id, &out_port, NULL, NULL, NULL);
768     memset(&req->pad, 0, sizeof req->pad);
769     req->out_port = htons(out_port);
770
771     dump_stats_transaction(argv[1], request);
772 }
773
774 static void
775 do_dump_aggregate(int argc, char *argv[])
776 {
777     struct ofp_aggregate_stats_request *req;
778     struct ofpbuf *request;
779     uint16_t out_port;
780
781     req = alloc_stats_request(sizeof *req, OFPST_AGGREGATE, &request);
782     str_to_flow(argc > 2 ? argv[2] : "", &req->match, NULL,
783                 &req->table_id, &out_port, NULL, NULL, NULL);
784     memset(&req->pad, 0, sizeof req->pad);
785     req->out_port = htons(out_port);
786
787     dump_stats_transaction(argv[1], request);
788 }
789
790 static void
791 do_add_flow(int argc UNUSED, char *argv[])
792 {
793     struct vconn *vconn;
794     struct ofpbuf *buffer;
795     struct ofp_flow_mod *ofm;
796     uint16_t priority, idle_timeout, hard_timeout;
797     struct ofp_match match;
798
799     /* Parse and send.  str_to_flow() will expand and reallocate the data in
800      * 'buffer', so we can't keep pointers to across the str_to_flow() call. */
801     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
802     str_to_flow(argv[2], &match, buffer,
803                 NULL, NULL, &priority, &idle_timeout, &hard_timeout);
804     ofm = buffer->data;
805     ofm->match = match;
806     ofm->command = htons(OFPFC_ADD);
807     ofm->idle_timeout = htons(idle_timeout);
808     ofm->hard_timeout = htons(hard_timeout);
809     ofm->buffer_id = htonl(UINT32_MAX);
810     ofm->priority = htons(priority);
811     ofm->reserved = htonl(0);
812
813     open_vconn(argv[1], &vconn);
814     send_openflow_buffer(vconn, buffer);
815     vconn_close(vconn);
816 }
817
818 static void
819 do_add_flows(int argc UNUSED, char *argv[])
820 {
821     struct vconn *vconn;
822     FILE *file;
823     char line[1024];
824
825     file = fopen(argv[2], "r");
826     if (file == NULL) {
827         ovs_fatal(errno, "%s: open", argv[2]);
828     }
829
830     open_vconn(argv[1], &vconn);
831     while (fgets(line, sizeof line, file)) {
832         struct ofpbuf *buffer;
833         struct ofp_flow_mod *ofm;
834         uint16_t priority, idle_timeout, hard_timeout;
835         struct ofp_match match;
836
837         char *comment;
838
839         /* Delete comments. */
840         comment = strchr(line, '#');
841         if (comment) {
842             *comment = '\0';
843         }
844
845         /* Drop empty lines. */
846         if (line[strspn(line, " \t\n")] == '\0') {
847             continue;
848         }
849
850         /* Parse and send.  str_to_flow() will expand and reallocate the data
851          * in 'buffer', so we can't keep pointers to across the str_to_flow()
852          * call. */
853         ofm = make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
854         str_to_flow(line, &match, buffer,
855                     NULL, NULL, &priority, &idle_timeout, &hard_timeout);
856         ofm = buffer->data;
857         ofm->match = match;
858         ofm->command = htons(OFPFC_ADD);
859         ofm->idle_timeout = htons(idle_timeout);
860         ofm->hard_timeout = htons(hard_timeout);
861         ofm->buffer_id = htonl(UINT32_MAX);
862         ofm->priority = htons(priority);
863         ofm->reserved = htonl(0);
864
865         send_openflow_buffer(vconn, buffer);
866     }
867     vconn_close(vconn);
868     fclose(file);
869 }
870
871 static void
872 do_mod_flows(int argc UNUSED, char *argv[])
873 {
874     uint16_t priority, idle_timeout, hard_timeout;
875     struct vconn *vconn;
876     struct ofpbuf *buffer;
877     struct ofp_flow_mod *ofm;
878     struct ofp_match match;
879
880     /* Parse and send.  str_to_flow() will expand and reallocate the data in
881      * 'buffer', so we can't keep pointers to across the str_to_flow() call. */
882     make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
883     str_to_flow(argv[2], &match, buffer,
884                 NULL, NULL, &priority, &idle_timeout, &hard_timeout);
885     ofm = buffer->data;
886     ofm->match = match;
887     if (strict) {
888         ofm->command = htons(OFPFC_MODIFY_STRICT);
889     } else {
890         ofm->command = htons(OFPFC_MODIFY);
891     }
892     ofm->idle_timeout = htons(idle_timeout);
893     ofm->hard_timeout = htons(hard_timeout);
894     ofm->buffer_id = htonl(UINT32_MAX);
895     ofm->priority = htons(priority);
896     ofm->reserved = htonl(0);
897
898     open_vconn(argv[1], &vconn);
899     send_openflow_buffer(vconn, buffer);
900     vconn_close(vconn);
901 }
902
903 static void do_del_flows(int argc, char *argv[])
904 {
905     struct vconn *vconn;
906     uint16_t priority;
907     uint16_t out_port;
908     struct ofpbuf *buffer;
909     struct ofp_flow_mod *ofm;
910
911     /* Parse and send. */
912     ofm = make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &buffer);
913     str_to_flow(argc > 2 ? argv[2] : "", &ofm->match, NULL, NULL, 
914                 &out_port, &priority, NULL, NULL);
915     if (strict) {
916         ofm->command = htons(OFPFC_DELETE_STRICT);
917     } else {
918         ofm->command = htons(OFPFC_DELETE);
919     }
920     ofm->idle_timeout = htons(0);
921     ofm->hard_timeout = htons(0);
922     ofm->buffer_id = htonl(UINT32_MAX);
923     ofm->out_port = htons(out_port);
924     ofm->priority = htons(priority);
925     ofm->reserved = htonl(0);
926
927     open_vconn(argv[1], &vconn);
928     send_openflow_buffer(vconn, buffer);
929     vconn_close(vconn);
930 }
931
932 static void
933 do_monitor(int argc UNUSED, char *argv[])
934 {
935     struct vconn *vconn;
936
937     open_vconn(argv[1], &vconn);
938     if (argc > 2) {
939         int miss_send_len = atoi(argv[2]);
940         int send_flow_exp = argc > 3 ? atoi(argv[3]) : 0;
941         struct ofp_switch_config *osc;
942         struct ofpbuf *buf;
943
944         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &buf);
945         osc->flags = htons(send_flow_exp ? OFPC_SEND_FLOW_EXP : 0);
946         osc->miss_send_len = htons(miss_send_len);
947         send_openflow_buffer(vconn, buf);
948     }
949     for (;;) {
950         struct ofpbuf *b;
951         run(vconn_recv_block(vconn, &b), "vconn_recv");
952         ofp_print(stderr, b->data, b->size, 2);
953         ofpbuf_delete(b);
954     }
955 }
956
957 static void
958 do_dump_ports(int argc UNUSED, char *argv[])
959 {
960     dump_trivial_stats_transaction(argv[1], OFPST_PORT);
961 }
962
963 static void
964 do_probe(int argc UNUSED, char *argv[])
965 {
966     struct ofpbuf *request;
967     struct vconn *vconn;
968     struct ofpbuf *reply;
969
970     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
971     open_vconn(argv[1], &vconn);
972     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
973     if (reply->size != sizeof(struct ofp_header)) {
974         ovs_fatal(0, "reply does not match request");
975     }
976     ofpbuf_delete(reply);
977     vconn_close(vconn);
978 }
979
980 static void
981 do_mod_port(int argc UNUSED, char *argv[])
982 {
983     struct ofpbuf *request, *reply;
984     struct ofp_switch_features *osf;
985     struct ofp_port_mod *opm;
986     struct vconn *vconn;
987     char *endptr;
988     int n_ports;
989     int port_idx;
990     int port_no;
991     
992
993     /* Check if the argument is a port index.  Otherwise, treat it as
994      * the port name. */
995     port_no = strtol(argv[2], &endptr, 10);
996     if (port_no == 0 && endptr == argv[2]) {
997         port_no = -1;
998     }
999
1000     /* Send a "Features Request" to get the information we need in order 
1001      * to modify the port. */
1002     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
1003     open_vconn(argv[1], &vconn);
1004     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
1005
1006     osf = reply->data;
1007     n_ports = (reply->size - sizeof *osf) / sizeof *osf->ports;
1008
1009     for (port_idx = 0; port_idx < n_ports; port_idx++) {
1010         if (port_no != -1) {
1011             /* Check argument as a port index */
1012             if (osf->ports[port_idx].port_no == htons(port_no)) {
1013                 break;
1014             }
1015         } else {
1016             /* Check argument as an interface name */
1017             if (!strncmp((char *)osf->ports[port_idx].name, argv[2], 
1018                         sizeof osf->ports[0].name)) {
1019                 break;
1020             }
1021
1022         }
1023     }
1024     if (port_idx == n_ports) {
1025         ovs_fatal(0, "couldn't find monitored port: %s", argv[2]);
1026     }
1027
1028     opm = make_openflow(sizeof(struct ofp_port_mod), OFPT_PORT_MOD, &request);
1029     opm->port_no = osf->ports[port_idx].port_no;
1030     memcpy(opm->hw_addr, osf->ports[port_idx].hw_addr, sizeof opm->hw_addr);
1031     opm->config = htonl(0);
1032     opm->mask = htonl(0);
1033     opm->advertise = htonl(0);
1034
1035     printf("modifying port: %s\n", osf->ports[port_idx].name);
1036
1037     if (!strncasecmp(argv[3], MOD_PORT_CMD_UP, sizeof MOD_PORT_CMD_UP)) {
1038         opm->mask |= htonl(OFPPC_PORT_DOWN);
1039     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_DOWN, 
1040                 sizeof MOD_PORT_CMD_DOWN)) {
1041         opm->mask |= htonl(OFPPC_PORT_DOWN);
1042         opm->config |= htonl(OFPPC_PORT_DOWN);
1043     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_FLOOD, 
1044                 sizeof MOD_PORT_CMD_FLOOD)) {
1045         opm->mask |= htonl(OFPPC_NO_FLOOD);
1046     } else if (!strncasecmp(argv[3], MOD_PORT_CMD_NOFLOOD, 
1047                 sizeof MOD_PORT_CMD_NOFLOOD)) {
1048         opm->mask |= htonl(OFPPC_NO_FLOOD);
1049         opm->config |= htonl(OFPPC_NO_FLOOD);
1050     } else {
1051         ovs_fatal(0, "unknown mod-port command '%s'", argv[3]);
1052     }
1053
1054     send_openflow_buffer(vconn, request);
1055
1056     ofpbuf_delete(reply);
1057     vconn_close(vconn);
1058 }
1059
1060 static void
1061 do_ping(int argc, char *argv[])
1062 {
1063     size_t max_payload = 65535 - sizeof(struct ofp_header);
1064     unsigned int payload;
1065     struct vconn *vconn;
1066     int i;
1067
1068     payload = argc > 2 ? atoi(argv[2]) : 64;
1069     if (payload > max_payload) {
1070         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1071     }
1072
1073     open_vconn(argv[1], &vconn);
1074     for (i = 0; i < 10; i++) {
1075         struct timeval start, end;
1076         struct ofpbuf *request, *reply;
1077         struct ofp_header *rq_hdr, *rpy_hdr;
1078
1079         rq_hdr = make_openflow(sizeof(struct ofp_header) + payload,
1080                                OFPT_ECHO_REQUEST, &request);
1081         random_bytes(rq_hdr + 1, payload);
1082
1083         gettimeofday(&start, NULL);
1084         run(vconn_transact(vconn, ofpbuf_clone(request), &reply), "transact");
1085         gettimeofday(&end, NULL);
1086
1087         rpy_hdr = reply->data;
1088         if (reply->size != request->size
1089             || memcmp(rpy_hdr + 1, rq_hdr + 1, payload)
1090             || rpy_hdr->xid != rq_hdr->xid
1091             || rpy_hdr->type != OFPT_ECHO_REPLY) {
1092             printf("Reply does not match request.  Request:\n");
1093             ofp_print(stdout, request, request->size, 2);
1094             printf("Reply:\n");
1095             ofp_print(stdout, reply, reply->size, 2);
1096         }
1097         printf("%d bytes from %s: xid=%08"PRIx32" time=%.1f ms\n",
1098                reply->size - sizeof *rpy_hdr, argv[1], rpy_hdr->xid,
1099                    (1000*(double)(end.tv_sec - start.tv_sec))
1100                    + (.001*(end.tv_usec - start.tv_usec)));
1101         ofpbuf_delete(request);
1102         ofpbuf_delete(reply);
1103     }
1104     vconn_close(vconn);
1105 }
1106
1107 static void
1108 do_benchmark(int argc UNUSED, char *argv[])
1109 {
1110     size_t max_payload = 65535 - sizeof(struct ofp_header);
1111     struct timeval start, end;
1112     unsigned int payload_size, message_size;
1113     struct vconn *vconn;
1114     double duration;
1115     int count;
1116     int i;
1117
1118     payload_size = atoi(argv[2]);
1119     if (payload_size > max_payload) {
1120         ovs_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
1121     }
1122     message_size = sizeof(struct ofp_header) + payload_size;
1123
1124     count = atoi(argv[3]);
1125
1126     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
1127            count, message_size, count * message_size);
1128
1129     open_vconn(argv[1], &vconn);
1130     gettimeofday(&start, NULL);
1131     for (i = 0; i < count; i++) {
1132         struct ofpbuf *request, *reply;
1133         struct ofp_header *rq_hdr;
1134
1135         rq_hdr = make_openflow(message_size, OFPT_ECHO_REQUEST, &request);
1136         memset(rq_hdr + 1, 0, payload_size);
1137         run(vconn_transact(vconn, request, &reply), "transact");
1138         ofpbuf_delete(reply);
1139     }
1140     gettimeofday(&end, NULL);
1141     vconn_close(vconn);
1142
1143     duration = ((1000*(double)(end.tv_sec - start.tv_sec))
1144                 + (.001*(end.tv_usec - start.tv_usec)));
1145     printf("Finished in %.1f ms (%.0f packets/s) (%.0f bytes/s)\n",
1146            duration, count / (duration / 1000.0),
1147            count * message_size / (duration / 1000.0));
1148 }
1149
1150 static void
1151 do_execute(int argc, char *argv[])
1152 {
1153     struct vconn *vconn;
1154     struct ofpbuf *request;
1155     struct nicira_header *nicira;
1156     struct nx_command_reply *ncr;
1157     uint32_t xid;
1158     int i;
1159
1160     nicira = make_openflow(sizeof *nicira, OFPT_VENDOR, &request);
1161     xid = nicira->header.xid;
1162     nicira->vendor = htonl(NX_VENDOR_ID);
1163     nicira->subtype = htonl(NXT_COMMAND_REQUEST);
1164     ofpbuf_put(request, argv[2], strlen(argv[2]));
1165     for (i = 3; i < argc; i++) {
1166         ofpbuf_put_zeros(request, 1);
1167         ofpbuf_put(request, argv[i], strlen(argv[i]));
1168     }
1169     update_openflow_length(request);
1170
1171     open_vconn(argv[1], &vconn);
1172     run(vconn_send_block(vconn, request), "send");
1173
1174     for (;;) {
1175         struct ofpbuf *reply;
1176         uint32_t status;
1177
1178         run(vconn_recv_xid(vconn, xid, &reply), "recv_xid");
1179         if (reply->size < sizeof *ncr) {
1180             ovs_fatal(0, "reply is too short (%zu bytes < %zu bytes)",
1181                       reply->size, sizeof *ncr);
1182         }
1183         ncr = reply->data;
1184         if (ncr->nxh.header.type != OFPT_VENDOR
1185             || ncr->nxh.vendor != htonl(NX_VENDOR_ID)
1186             || ncr->nxh.subtype != htonl(NXT_COMMAND_REPLY)) {
1187             ovs_fatal(0, "reply is invalid");
1188         }
1189
1190         status = ntohl(ncr->status);
1191         if (status & NXT_STATUS_STARTED) {
1192             /* Wait for a second reply. */
1193             continue;
1194         } else if (status & NXT_STATUS_EXITED) {
1195             fprintf(stderr, "process terminated normally with exit code %d",
1196                     status & NXT_STATUS_EXITSTATUS);
1197         } else if (status & NXT_STATUS_SIGNALED) {
1198             fprintf(stderr, "process terminated by signal %d",
1199                     status & NXT_STATUS_TERMSIG);
1200         } else if (status & NXT_STATUS_ERROR) {
1201             fprintf(stderr, "error executing command");
1202         } else {
1203             fprintf(stderr, "process terminated for unknown reason");
1204         }
1205         if (status & NXT_STATUS_COREDUMP) {
1206             fprintf(stderr, " (core dumped)");
1207         }
1208         putc('\n', stderr);
1209
1210         fwrite(ncr + 1, reply->size - sizeof *ncr, 1, stdout);
1211         break;
1212     }
1213 }
1214
1215 static void
1216 do_help(int argc UNUSED, char *argv[] UNUSED)
1217 {
1218     usage();
1219 }
1220
1221 static const struct command all_commands[] = {
1222     { "show", 1, 1, do_show },
1223     { "status", 1, 2, do_status },
1224     { "monitor", 1, 3, do_monitor },
1225     { "dump-desc", 1, 1, do_dump_desc },
1226     { "dump-tables", 1, 1, do_dump_tables },
1227     { "dump-flows", 1, 2, do_dump_flows },
1228     { "dump-aggregate", 1, 2, do_dump_aggregate },
1229     { "add-flow", 2, 2, do_add_flow },
1230     { "add-flows", 2, 2, do_add_flows },
1231     { "mod-flows", 2, 2, do_mod_flows },
1232     { "del-flows", 1, 2, do_del_flows },
1233     { "dump-ports", 1, 1, do_dump_ports },
1234     { "mod-port", 3, 3, do_mod_port },
1235     { "probe", 1, 1, do_probe },
1236     { "ping", 1, 2, do_ping },
1237     { "benchmark", 3, 3, do_benchmark },
1238     { "execute", 2, INT_MAX, do_execute },
1239     { "help", 0, INT_MAX, do_help },
1240     { NULL, 0, 0, NULL },
1241 };