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