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