Improve flow handling in dpctl.
[sliver-openvswitch.git] / lib / ofp-print.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "ofp-print.h"
35 #include "xtoxll.h"
36
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <sys/wait.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <ctype.h>
44
45 #include "compiler.h"
46 #include "dynamic-string.h"
47 #include "util.h"
48 #include "openflow.h"
49 #include "packets.h"
50
51 static void ofp_print_port_name(struct ds *string, uint16_t port);
52
53 /* Returns a string that represents the contents of the Ethernet frame in the
54  * 'len' bytes starting at 'data' to 'stream' as output by tcpdump.
55  * 'total_len' specifies the full length of the Ethernet frame (of which 'len'
56  * bytes were captured).
57  *
58  * The caller must free the returned string.
59  *
60  * This starts and kills a tcpdump subprocess so it's quite expensive. */
61 char *
62 ofp_packet_to_string(const void *data, size_t len, size_t total_len)
63 {
64     struct pcap_hdr {
65         uint32_t magic_number;   /* magic number */
66         uint16_t version_major;  /* major version number */
67         uint16_t version_minor;  /* minor version number */
68         int32_t thiszone;        /* GMT to local correction */
69         uint32_t sigfigs;        /* accuracy of timestamps */
70         uint32_t snaplen;        /* max length of captured packets */
71         uint32_t network;        /* data link type */
72     } PACKED;
73
74     struct pcaprec_hdr {
75         uint32_t ts_sec;         /* timestamp seconds */
76         uint32_t ts_usec;        /* timestamp microseconds */
77         uint32_t incl_len;       /* number of octets of packet saved in file */
78         uint32_t orig_len;       /* actual length of packet */
79     } PACKED;
80
81     struct pcap_hdr ph;
82     struct pcaprec_hdr prh;
83
84     struct ds ds = DS_EMPTY_INITIALIZER;
85
86     char command[128];
87     FILE *pcap;
88     FILE *tcpdump;
89     int status;
90     int c;
91
92     pcap = tmpfile();
93     if (!pcap) {
94         error(errno, "tmpfile");
95         return xstrdup("<error>");
96     }
97
98     /* The pcap reader is responsible for figuring out endianness based on the
99      * magic number, so the lack of htonX calls here is intentional. */
100     ph.magic_number = 0xa1b2c3d4;
101     ph.version_major = 2;
102     ph.version_minor = 4;
103     ph.thiszone = 0;
104     ph.sigfigs = 0;
105     ph.snaplen = 1518;
106     ph.network = 1;             /* Ethernet */
107
108     prh.ts_sec = 0;
109     prh.ts_usec = 0;
110     prh.incl_len = len;
111     prh.orig_len = total_len;
112
113     fwrite(&ph, 1, sizeof ph, pcap);
114     fwrite(&prh, 1, sizeof prh, pcap);
115     fwrite(data, 1, len, pcap);
116
117     fflush(pcap);
118     if (ferror(pcap)) {
119         error(errno, "error writing temporary file");
120     }
121     rewind(pcap);
122
123     snprintf(command, sizeof command, "tcpdump -n -r /dev/fd/%d 2>/dev/null",
124              fileno(pcap));
125     tcpdump = popen(command, "r");
126     fclose(pcap);
127     if (!tcpdump) {
128         error(errno, "exec(\"%s\")", command);
129         return xstrdup("<error>");
130     }
131
132     while ((c = getc(tcpdump)) != EOF) {
133         ds_put_char(&ds, c);
134     }
135
136     status = pclose(tcpdump);
137     if (WIFEXITED(status)) {
138         if (WEXITSTATUS(status))
139             error(0, "tcpdump exited with status %d", WEXITSTATUS(status));
140     } else if (WIFSIGNALED(status)) {
141         error(0, "tcpdump exited with signal %d", WTERMSIG(status)); 
142     }
143     return ds_cstr(&ds);
144 }
145
146 /* Pretty-print the OFPT_PACKET_IN packet of 'len' bytes at 'oh' to 'stream'
147  * at the given 'verbosity' level. */
148 static void
149 ofp_packet_in(struct ds *string, const void *oh, size_t len, int verbosity)
150 {
151     const struct ofp_packet_in *op = oh;
152     size_t data_len;
153
154     ds_put_format(string, " total_len=%"PRIu16" in_port=",
155                   ntohs(op->total_len));
156     ofp_print_port_name(string, ntohs(op->in_port));
157
158     if (op->reason == OFPR_ACTION)
159         ds_put_cstr(string, " (via action)");
160     else if (op->reason != OFPR_NO_MATCH)
161         ds_put_format(string, " (***reason %"PRIu8"***)", op->reason);
162
163     data_len = len - offsetof(struct ofp_packet_in, data);
164     ds_put_format(string, " data_len=%zu", data_len);
165     if (htonl(op->buffer_id) == UINT32_MAX) {
166         ds_put_format(string, " (unbuffered)");
167         if (ntohs(op->total_len) != data_len)
168             ds_put_format(string, " (***total_len != data_len***)");
169     } else {
170         ds_put_format(string, " buffer=%08"PRIx32, ntohl(op->buffer_id));
171         if (ntohs(op->total_len) < data_len)
172             ds_put_format(string, " (***total_len < data_len***)");
173     }
174     ds_put_char(string, '\n');
175
176     if (verbosity > 0) {
177         char *packet = ofp_packet_to_string(op->data, data_len,
178                                             ntohs(op->total_len)); 
179         ds_put_cstr(string, packet);
180         free(packet);
181     }
182 }
183
184 static void ofp_print_port_name(struct ds *string, uint16_t port) 
185 {
186     const char *name;
187     switch (port) {
188     case OFPP_TABLE:
189         name = "TABLE";
190         break;
191     case OFPP_NORMAL:
192         name = "NORMAL";
193         break;
194     case OFPP_FLOOD:
195         name = "FLOOD";
196         break;
197     case OFPP_ALL:
198         name = "ALL";
199         break;
200     case OFPP_CONTROLLER:
201         name = "CONTROLLER";
202         break;
203     case OFPP_LOCAL:
204         name = "LOCAL";
205         break;
206     case OFPP_NONE:
207         name = "NONE";
208         break;
209     default:
210         ds_put_format(string, "%"PRIu16, port);
211         return;
212     }
213     ds_put_cstr(string, name);
214 }
215
216 static void
217 ofp_print_action(struct ds *string, const struct ofp_action *a) 
218 {
219     switch (ntohs(a->type)) {
220     case OFPAT_OUTPUT:
221         {
222             uint16_t port = ntohs(a->arg.output.port); 
223             if (port < OFPP_MAX) {
224                 ds_put_format(string, "output:%"PRIu16, port);
225             } else {
226                 ofp_print_port_name(string, port);
227                 if (port == OFPP_CONTROLLER) {
228                     if (a->arg.output.max_len) {
229                         ds_put_format(string, ":%"PRIu16, 
230                                 ntohs(a->arg.output.max_len));
231                     } else {
232                         ds_put_cstr(string, ":all");
233                     }
234                 }
235             }
236         }
237         break;
238
239     case OFPAT_SET_DL_VLAN:
240         ds_put_cstr(string, "mod_vlan:");
241         if (ntohs(a->arg.vlan_id) == OFP_VLAN_NONE) {
242             ds_put_cstr(string, "strip");
243         } else {
244             ds_put_format(string, "%"PRIu16, ntohs(a->arg.vlan_id));
245         }
246         break;
247
248     case OFPAT_SET_DL_SRC:
249         ds_put_format(string, "mod_dl_src:"ETH_ADDR_FMT, 
250                 ETH_ADDR_ARGS(a->arg.dl_addr));
251         break;
252
253     case OFPAT_SET_DL_DST:
254         ds_put_format(string, "mod_dl_dst:"ETH_ADDR_FMT, 
255                 ETH_ADDR_ARGS(a->arg.dl_addr));
256         break;
257
258     case OFPAT_SET_NW_SRC:
259         ds_put_format(string, "mod_nw_src:"IP_FMT, IP_ARGS(a->arg.nw_addr));
260         break;
261
262     case OFPAT_SET_NW_DST:
263         ds_put_format(string, "mod_nw_dst:"IP_FMT, IP_ARGS(a->arg.nw_addr));
264         break;
265
266     case OFPAT_SET_TP_SRC:
267         ds_put_format(string, "mod_tp_src:%d", ntohs(a->arg.tp));
268         break;
269
270     case OFPAT_SET_TP_DST:
271         ds_put_format(string, "mod_tp_dst:%d", ntohs(a->arg.tp));
272         break;
273
274     default:
275         ds_put_format(string, "(decoder %"PRIu16" not implemented)", 
276                 ntohs(a->type));
277         break;
278     }
279 }
280
281 static void ofp_print_actions(struct ds *string,
282                               const struct ofp_action actions[],
283                               size_t n_bytes) 
284 {
285     size_t i;
286     int n_actions = n_bytes / sizeof *actions;
287
288     ds_put_format(string, "action%s=", n_actions == 1 ? "" : "s");
289     for (i = 0; i < n_actions; i++) {
290         if (i) {
291             ds_put_cstr(string, ",");
292         }
293         ofp_print_action(string, &actions[i]);
294     }
295     if (n_bytes % sizeof *actions) {
296         if (i) {
297             ds_put_cstr(string, ",");
298         }
299         ds_put_cstr(string, ", ***trailing garbage***");
300     }
301 }
302
303 /* Pretty-print the OFPT_PACKET_OUT packet of 'len' bytes at 'oh' to 'string'
304  * at the given 'verbosity' level. */
305 static void ofp_packet_out(struct ds *string, const void *oh, size_t len,
306                            int verbosity) 
307 {
308     const struct ofp_packet_out *opo = oh;
309
310     ds_put_cstr(string, " in_port=");
311     ofp_print_port_name(string, ntohs(opo->in_port));
312
313     if (ntohl(opo->buffer_id) == UINT32_MAX) {
314         ds_put_cstr(string, " out_port=");
315         ofp_print_port_name(string, ntohs(opo->out_port));
316         if (verbosity > 0 && len > sizeof *opo) {
317             char *packet = ofp_packet_to_string(opo->u.data, len - sizeof *opo,
318                                                 len - sizeof *opo);
319             ds_put_char(string, '\n');
320             ds_put_cstr(string, packet);
321             free(packet);
322         }
323     } else {
324         ds_put_format(string, " buffer=%08"PRIx32, ntohl(opo->buffer_id));
325         ofp_print_actions(string, opo->u.actions, len - sizeof *opo);
326     }
327     ds_put_char(string, '\n');
328 }
329
330 /* qsort comparison function. */
331 static int
332 compare_ports(const void *a_, const void *b_)
333 {
334     const struct ofp_phy_port *a = a_;
335     const struct ofp_phy_port *b = b_;
336     uint16_t ap = ntohs(a->port_no);
337     uint16_t bp = ntohs(b->port_no);
338
339     return ap < bp ? -1 : ap > bp;
340 }
341
342 static void
343 ofp_print_phy_port(struct ds *string, const struct ofp_phy_port *port)
344 {
345     uint8_t name[OFP_MAX_PORT_NAME_LEN];
346     int j;
347
348     memcpy(name, port->name, sizeof name);
349     for (j = 0; j < sizeof name - 1; j++) {
350         if (!isprint(name[j])) {
351             break;
352         }
353     }
354     name[j] = '\0';
355
356     ds_put_char(string, ' ');
357     ofp_print_port_name(string, ntohs(port->port_no));
358     ds_put_format(string, "(%s): addr:"ETH_ADDR_FMT", speed:%d, flags:%#x, "
359             "feat:%#x\n", name, 
360             ETH_ADDR_ARGS(port->hw_addr), ntohl(port->speed),
361             ntohl(port->flags), ntohl(port->features));
362 }
363
364 /* Pretty-print the struct ofp_switch_features of 'len' bytes at 'oh' to
365  * 'string' at the given 'verbosity' level. */
366 static void
367 ofp_print_switch_features(struct ds *string, const void *oh, size_t len,
368                           int verbosity)
369 {
370     const struct ofp_switch_features *osf = oh;
371     struct ofp_phy_port port_list[OFPP_MAX];
372     int n_ports;
373     int i;
374
375     ds_put_format(string, "dp id:%"PRIx64"\n", ntohll(osf->datapath_id));
376     ds_put_format(string, "tables: exact:%d, compressed:%d, general:%d\n",
377            ntohl(osf->n_exact), 
378            ntohl(osf->n_compression), ntohl(osf->n_general));
379     ds_put_format(string, "buffers: size:%d, number:%d\n",
380            ntohl(osf->buffer_mb), ntohl(osf->n_buffers));
381     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
382            ntohl(osf->capabilities), ntohl(osf->actions));
383
384     if (ntohs(osf->header.length) >= sizeof *osf) {
385         len = MIN(len, ntohs(osf->header.length));
386     }
387     n_ports = (len - sizeof *osf) / sizeof *osf->ports;
388
389     memcpy(port_list, osf->ports, (len - sizeof *osf));
390     qsort(port_list, n_ports, sizeof port_list[0], compare_ports);
391     for (i = 0; i < n_ports; i++) {
392         ofp_print_phy_port(string, &port_list[i]);
393     }
394 }
395
396 /* Pretty-print the struct ofp_switch_config of 'len' bytes at 'oh' to 'string'
397  * at the given 'verbosity' level. */
398 static void
399 ofp_print_switch_config(struct ds *string, const void *oh, size_t len,
400                         int verbosity)
401 {
402     const struct ofp_switch_config *osc = oh;
403     uint16_t flags;
404
405     flags = ntohs(osc->flags);
406     if (flags & OFPC_SEND_FLOW_EXP) {
407         flags &= ~OFPC_SEND_FLOW_EXP;
408         ds_put_format(string, " (sending flow expirations)");
409     }
410     if (flags) {
411         ds_put_format(string, " ***unknown flags %04"PRIx16"***", flags);
412     }
413
414     ds_put_format(string, " miss_send_len=%"PRIu16"\n", ntohs(osc->miss_send_len));
415 }
416
417 static void print_wild(struct ds *string, const char *leader, int is_wild,
418             int verbosity, const char *format, ...) 
419             __attribute__((format(printf, 5, 6)));
420
421 static void print_wild(struct ds *string, const char *leader, int is_wild,
422                        int verbosity, const char *format, ...) 
423 {
424     if (is_wild && verbosity < 2) {
425         return;
426     }
427     ds_put_cstr(string, leader);
428     if (!is_wild) {
429         va_list args;
430
431         va_start(args, format);
432         ds_put_format_valist(string, format, args);
433         va_end(args);
434     } else {
435         ds_put_char(string, '*');
436     }
437 }
438
439 /* Pretty-print the ofp_match structure */
440 static void ofp_print_match(struct ds *f, const struct ofp_match *om, 
441         int verbosity)
442 {
443     uint16_t w = ntohs(om->wildcards);
444
445     print_wild(f, "in_port=", w & OFPFW_IN_PORT, verbosity,
446                "%d,", ntohs(om->in_port));
447     print_wild(f, "dl_vlan=", w & OFPFW_DL_VLAN, verbosity,
448                "%04x,", ntohs(om->dl_vlan));
449     print_wild(f, "dl_src=", w & OFPFW_DL_SRC, verbosity,
450                ETH_ADDR_FMT",", ETH_ADDR_ARGS(om->dl_src));
451     print_wild(f, "dl_dst=", w & OFPFW_DL_DST, verbosity,
452                ETH_ADDR_FMT",", ETH_ADDR_ARGS(om->dl_dst));
453     print_wild(f, "dl_type=", w & OFPFW_DL_TYPE, verbosity,
454                "%04x,", ntohs(om->dl_type));
455     print_wild(f, "nw_src=", w & OFPFW_NW_SRC, verbosity,
456                IP_FMT",", IP_ARGS(&om->nw_src));
457     print_wild(f, "nw_dst=", w & OFPFW_NW_DST, verbosity,
458                IP_FMT",", IP_ARGS(&om->nw_dst));
459     print_wild(f, "nw_proto=", w & OFPFW_NW_PROTO, verbosity,
460                "%u,", om->nw_proto);
461     print_wild(f, "tp_src=", w & OFPFW_TP_SRC, verbosity,
462                "%d,", ntohs(om->tp_src));
463     print_wild(f, "tp_dst=", w & OFPFW_TP_DST, verbosity,
464                "%d,", ntohs(om->tp_dst));
465 }
466
467 /* Pretty-print the OFPT_FLOW_MOD packet of 'len' bytes at 'oh' to 'string'
468  * at the given 'verbosity' level. */
469 static void
470 ofp_print_flow_mod(struct ds *string, const void *oh, size_t len, 
471                    int verbosity)
472 {
473     const struct ofp_flow_mod *ofm = oh;
474
475     ofp_print_match(string, &ofm->match, verbosity);
476     ds_put_format(string, " cmd:%d idle:%d pri:%d buf:%#x", 
477             ntohs(ofm->command), ntohs(ofm->max_idle), 
478             ofm->match.wildcards ? ntohs(ofm->priority) : (uint16_t)-1,
479             ntohl(ofm->buffer_id));
480     ofp_print_actions(string, ofm->actions,
481                       len - offsetof(struct ofp_flow_mod, actions));
482     ds_put_char(string, '\n');
483 }
484
485 /* Pretty-print the OFPT_FLOW_EXPIRED packet of 'len' bytes at 'oh' to 'string'
486  * at the given 'verbosity' level. */
487 static void
488 ofp_print_flow_expired(struct ds *string, const void *oh, size_t len, 
489                        int verbosity)
490 {
491     const struct ofp_flow_expired *ofe = oh;
492
493     ofp_print_match(string, &ofe->match, verbosity);
494     ds_put_format(string, 
495          " pri%"PRIu16" secs%"PRIu32" pkts%"PRIu64" bytes%"PRIu64"\n", 
496          ofe->match.wildcards ? ntohs(ofe->priority) : (uint16_t)-1,
497          ntohl(ofe->duration), ntohll(ofe->packet_count), 
498          ntohll(ofe->byte_count));
499 }
500
501 /* Pretty-print the OFPT_ERROR_MSG packet of 'len' bytes at 'oh' to 'string'
502  * at the given 'verbosity' level. */
503 static void
504 ofp_print_error_msg(struct ds *string, const void *oh, size_t len, 
505                        int verbosity)
506 {
507     const struct ofp_error_msg *oem = oh;
508
509     ds_put_format(string, 
510          " type%d code%d\n", ntohs(oem->type), ntohs(oem->code));
511 }
512
513 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
514  * at the given 'verbosity' level. */
515 static void
516 ofp_print_port_status(struct ds *string, const void *oh, size_t len, 
517                       int verbosity)
518 {
519     const struct ofp_port_status *ops = oh;
520
521     if (ops->reason == OFPPR_ADD) {
522         ds_put_format(string, "add:");
523     } else if (ops->reason == OFPPR_DELETE) {
524         ds_put_format(string, "del:");
525     } else if (ops->reason == OFPPR_MOD) {
526         ds_put_format(string, "mod:");
527     } else {
528         ds_put_format(string, "err:");
529     }
530
531     ofp_print_phy_port(string, &ops->desc);
532 }
533
534 static void
535 ofp_flow_stats_request(struct ds *string, const void *oh, size_t len,
536                       int verbosity) 
537 {
538     const struct ofp_flow_stats_request *fsr = oh;
539
540     if (fsr->table_id == 0xff) {
541         ds_put_format(string, " table_id=any, ");
542     } else {
543         ds_put_format(string, " table_id=%"PRIu8", ", fsr->table_id);
544     }
545
546     ofp_print_match(string, &fsr->match, verbosity);
547 }
548
549 static void
550 ofp_flow_stats_reply(struct ds *string, const void *body_, size_t len,
551                      int verbosity)
552 {
553     const char *body = body_;
554     const char *pos = body;
555     for (;;) {
556         const struct ofp_flow_stats *fs;
557         ptrdiff_t bytes_left = body + len - pos;
558         size_t length;
559
560         if (bytes_left < sizeof *fs) {
561             if (bytes_left != 0) {
562                 ds_put_format(string, " ***%td leftover bytes at end***",
563                               bytes_left);
564             }
565             break;
566         }
567
568         fs = (const void *) pos;
569         length = ntohs(fs->length);
570         if (length < sizeof *fs) {
571             ds_put_format(string, " ***length=%zu shorter than minimum %zu***",
572                           length, sizeof *fs);
573             break;
574         } else if (length > bytes_left) {
575             ds_put_format(string,
576                           " ***length=%zu but only %td bytes left***",
577                           length, bytes_left);
578             break;
579         } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
580             ds_put_format(string,
581                           " ***length=%zu has %zu bytes leftover in "
582                           "final action***",
583                           length,
584                           (length - sizeof *fs) % sizeof fs->actions[0]);
585             break;
586         }
587
588         ds_put_format(string, "  duration=%"PRIu32"s, ", ntohl(fs->duration));
589         ds_put_format(string, "table_id=%"PRIu8", ", fs->table_id);
590         ds_put_format(string, "priority=%"PRIu16", ", 
591                     fs->match.wildcards ? ntohs(fs->priority) : (uint16_t)-1);
592         ds_put_format(string, "n_packets=%"PRIu64", ",
593                     ntohll(fs->packet_count));
594         ds_put_format(string, "n_bytes=%"PRIu64", ", ntohll(fs->byte_count));
595         ds_put_format(string, "max_idle=%"PRIu16",", ntohs(fs->max_idle));
596         ofp_print_match(string, &fs->match, verbosity);
597         ofp_print_actions(string, fs->actions, length - sizeof *fs);
598         ds_put_char(string, '\n');
599
600         pos += length;
601      }
602 }
603
604 static void
605 ofp_aggregate_stats_request(struct ds *string, const void *oh, size_t len,
606                             int verbosity) 
607 {
608     const struct ofp_aggregate_stats_request *asr = oh;
609
610     if (asr->table_id == 0xff) {
611         ds_put_format(string, " table_id=any, ");
612     } else {
613         ds_put_format(string, " table_id=%"PRIu8", ", asr->table_id);
614     }
615
616     ofp_print_match(string, &asr->match, verbosity);
617 }
618
619 static void
620 ofp_aggregate_stats_reply(struct ds *string, const void *body_, size_t len,
621                           int verbosity)
622 {
623     const struct ofp_aggregate_stats_reply *asr = body_;
624
625     ds_put_format(string, " packet_count=%"PRIu64, ntohll(asr->packet_count));
626     ds_put_format(string, " byte_count=%"PRIu64, ntohll(asr->byte_count));
627     ds_put_format(string, " flow_count=%"PRIu32, ntohl(asr->flow_count));
628 }
629
630 static void
631 ofp_port_stats_reply(struct ds *string, const void *body, size_t len,
632                      int verbosity)
633 {
634     const struct ofp_port_stats *ps = body;
635     size_t n = len / sizeof *ps;
636     ds_put_format(string, " %zu ports\n", n);
637     if (verbosity < 1) {
638         return;
639     }
640
641     for (; n--; ps++) {
642         ds_put_format(string, "  port %"PRIu16": ", ntohs(ps->port_no));
643         ds_put_format(string, "rx %"PRIu64", ", ntohll(ps->rx_count));
644         ds_put_format(string, "tx %"PRIu64", ", ntohll(ps->tx_count));
645         ds_put_format(string, "dropped %"PRIu64"\n", ntohll(ps->drop_count));
646     }
647 }
648
649 static void
650 ofp_table_stats_reply(struct ds *string, const void *body, size_t len,
651                      int verbosity)
652 {
653     const struct ofp_table_stats *ts = body;
654     size_t n = len / sizeof *ts;
655     ds_put_format(string, " %zu tables\n", n);
656     if (verbosity < 1) {
657         return;
658     }
659
660     for (; n--; ts++) {
661         char name[OFP_MAX_TABLE_NAME_LEN + 1];
662         strncpy(name, ts->name, sizeof name);
663         name[OFP_MAX_TABLE_NAME_LEN] = '\0';
664
665         ds_put_format(string, "  table %"PRIu8": ", ts->table_id);
666         ds_put_format(string, "name %-8s, ", name);
667         ds_put_format(string, "max %6"PRIu32", ", ntohl(ts->max_entries));
668         ds_put_format(string, "active %6"PRIu32", ", ntohl(ts->active_count));
669         ds_put_format(string, "matched %6"PRIu64"\n",
670                       ntohll(ts->matched_count));
671      }
672 }
673
674 enum stats_direction {
675     REQUEST,
676     REPLY
677 };
678
679 static void
680 print_stats(struct ds *string, int type, const void *body, size_t body_len,
681             int verbosity, enum stats_direction direction)
682 {
683     struct stats_msg {
684         size_t min_body, max_body;
685         void (*printer)(struct ds *, const void *, size_t len, int verbosity);
686     };
687
688     struct stats_type {
689         const char *name;
690         struct stats_msg request;
691         struct stats_msg reply;
692     };
693
694     static const struct stats_type stats_types[] = {
695         [OFPST_FLOW] = {
696             "flow",
697             { sizeof(struct ofp_flow_stats_request),
698               sizeof(struct ofp_flow_stats_request),
699               ofp_flow_stats_request },
700             { 0, SIZE_MAX, ofp_flow_stats_reply },
701         },
702         [OFPST_AGGREGATE] = {
703             "aggregate",
704             { sizeof(struct ofp_aggregate_stats_request),
705               sizeof(struct ofp_aggregate_stats_request),
706               ofp_aggregate_stats_request },
707             { sizeof(struct ofp_aggregate_stats_reply),
708               sizeof(struct ofp_aggregate_stats_reply),
709               ofp_aggregate_stats_reply },
710         },
711         [OFPST_TABLE] = {
712             "table",
713             { 0, 0, NULL },
714             { 0, SIZE_MAX, ofp_table_stats_reply },
715         },
716         [OFPST_PORT] = {
717             "port",
718             { 0, 0, NULL, },
719             { 0, SIZE_MAX, ofp_port_stats_reply },
720         },
721     };
722
723     const struct stats_type *s;
724     const struct stats_msg *m;
725
726     if (type >= ARRAY_SIZE(stats_types) || !stats_types[type].name) {
727         ds_put_format(string, " ***unknown type %d***", type);
728         return;
729     }
730     s = &stats_types[type];
731     ds_put_format(string, " type=%d(%s)\n", type, s->name);
732
733     m = direction == REQUEST ? &s->request : &s->reply;
734     if (body_len < m->min_body || body_len > m->max_body) {
735         ds_put_format(string, " ***body_len=%zu not in %zu...%zu***",
736                       body_len, m->min_body, m->max_body);
737         return;
738     }
739     if (m->printer) {
740         m->printer(string, body, body_len, verbosity);
741     }
742 }
743
744 static void
745 ofp_stats_request(struct ds *string, const void *oh, size_t len, int verbosity)
746 {
747     const struct ofp_stats_request *srq = oh;
748
749     if (srq->flags) {
750         ds_put_format(string, " ***unknown flags %04"PRIx16"***",
751                       ntohs(srq->flags));
752     }
753
754     print_stats(string, ntohs(srq->type), srq->body,
755                 len - offsetof(struct ofp_stats_request, body),
756                 verbosity, REQUEST);
757 }
758
759 static void
760 ofp_stats_reply(struct ds *string, const void *oh, size_t len, int verbosity)
761 {
762     const struct ofp_stats_reply *srp = oh;
763
764     ds_put_cstr(string, " flags=");
765     if (!srp->flags) {
766         ds_put_cstr(string, "none");
767     } else {
768         uint16_t flags = ntohs(srp->flags);
769         if (flags & OFPSF_REPLY_MORE) {
770             ds_put_cstr(string, "[more]");
771             flags &= ~OFPSF_REPLY_MORE;
772         }
773         if (flags) {
774             ds_put_format(string, "[***unknown%04"PRIx16"***]", flags);
775         }
776     }
777
778     print_stats(string, ntohs(srp->type), srp->body,
779                 len - offsetof(struct ofp_stats_reply, body),
780                 verbosity, REPLY);
781 }
782
783 struct openflow_packet {
784     const char *name;
785     size_t min_size;
786     void (*printer)(struct ds *, const void *, size_t len, int verbosity);
787 };
788
789 static const struct openflow_packet packets[] = {
790     [OFPT_FEATURES_REQUEST] = {
791         "features_request",
792         sizeof (struct ofp_header),
793         NULL,
794     },
795     [OFPT_FEATURES_REPLY] = {
796         "features_reply",
797         sizeof (struct ofp_switch_features),
798         ofp_print_switch_features,
799     },
800     [OFPT_GET_CONFIG_REQUEST] = {
801         "get_config_request",
802         sizeof (struct ofp_header),
803         NULL,
804     },
805     [OFPT_GET_CONFIG_REPLY] = {
806         "get_config_reply",
807         sizeof (struct ofp_switch_config),
808         ofp_print_switch_config,
809     },
810     [OFPT_SET_CONFIG] = {
811         "set_config",
812         sizeof (struct ofp_switch_config),
813         ofp_print_switch_config,
814     },
815     [OFPT_PACKET_IN] = {
816         "packet_in",
817         offsetof(struct ofp_packet_in, data),
818         ofp_packet_in,
819     },
820     [OFPT_PACKET_OUT] = {
821         "packet_out",
822         sizeof (struct ofp_packet_out),
823         ofp_packet_out,
824     },
825     [OFPT_FLOW_MOD] = {
826         "flow_mod",
827         sizeof (struct ofp_flow_mod),
828         ofp_print_flow_mod,
829     },
830     [OFPT_FLOW_EXPIRED] = {
831         "flow_expired",
832         sizeof (struct ofp_flow_expired),
833         ofp_print_flow_expired,
834     },
835     [OFPT_PORT_MOD] = {
836         "port_mod",
837         sizeof (struct ofp_port_mod),
838         NULL,
839     },
840     [OFPT_PORT_STATUS] = {
841         "port_status",
842         sizeof (struct ofp_port_status),
843         ofp_print_port_status
844     },
845     [OFPT_ERROR_MSG] = {
846         "error_msg",
847         sizeof (struct ofp_error_msg),
848         ofp_print_error_msg,
849     },
850     [OFPT_STATS_REQUEST] = {
851         "stats_request",
852         sizeof (struct ofp_stats_request),
853         ofp_stats_request,
854     },
855     [OFPT_STATS_REPLY] = {
856         "stats_reply",
857         sizeof (struct ofp_stats_reply),
858         ofp_stats_reply,
859     },
860 };
861
862 /* Composes and returns a string representing the OpenFlow packet of 'len'
863  * bytes at 'oh' at the given 'verbosity' level.  0 is a minimal amount of
864  * verbosity and higher numbers increase verbosity.  The caller is responsible
865  * for freeing the string. */
866 char *
867 ofp_to_string(const void *oh_, size_t len, int verbosity)
868 {
869     struct ds string = DS_EMPTY_INITIALIZER;
870     const struct ofp_header *oh = oh_;
871     const struct openflow_packet *pkt;
872
873     if (len < sizeof(struct ofp_header)) {
874         ds_put_cstr(&string, "OpenFlow packet too short:\n");
875         ds_put_hex_dump(&string, oh, len, 0, true);
876         return ds_cstr(&string);
877     } else if (oh->version != OFP_VERSION) {
878         ds_put_format(&string, "Bad OpenFlow version %"PRIu8":\n", oh->version);
879         ds_put_hex_dump(&string, oh, len, 0, true);
880         return ds_cstr(&string);
881     } else if (oh->type >= ARRAY_SIZE(packets) || !packets[oh->type].name) {
882         ds_put_format(&string, "Unknown OpenFlow packet type %"PRIu8":\n",
883                 oh->type);
884         ds_put_hex_dump(&string, oh, len, 0, true);
885         return ds_cstr(&string);
886     }
887
888     pkt = &packets[oh->type];
889     ds_put_format(&string, "%s (xid=%"PRIx32"):", pkt->name, oh->xid);
890
891     if (ntohs(oh->length) > len)
892         ds_put_format(&string, " (***truncated to %zu bytes from %"PRIu16"***)",
893                 len, ntohs(oh->length));
894     else if (ntohs(oh->length) < len) {
895         ds_put_format(&string, " (***only uses %"PRIu16" bytes out of %zu***)\n",
896                 ntohs(oh->length), len);
897         len = ntohs(oh->length);
898     }
899
900     if (len < pkt->min_size) {
901         ds_put_format(&string, " (***length=%zu < min_size=%zu***)\n",
902                 len, pkt->min_size);
903     } else if (!pkt->printer) {
904         if (len > sizeof *oh) {
905             ds_put_format(&string, " length=%"PRIu16" (decoder not implemented)\n",
906                           ntohs(oh->length)); 
907         }
908     } else {
909         pkt->printer(&string, oh, len, verbosity);
910     }
911     if (verbosity >= 3) {
912         ds_put_hex_dump(&string, oh, len, 0, true);
913     }
914     if (string.string[string.length - 1] != '\n') {
915         ds_put_char(&string, '\n');
916     }
917     return ds_cstr(&string);
918 }
919 \f
920 static void
921 print_and_free(FILE *stream, char *string) 
922 {
923     fputs(string, stream);
924     free(string);
925 }
926
927 /* Pretty-print the OpenFlow packet of 'len' bytes at 'oh' to 'stream' at the
928  * given 'verbosity' level.  0 is a minimal amount of verbosity and higher
929  * numbers increase verbosity. */
930 void
931 ofp_print(FILE *stream, const void *oh, size_t len, int verbosity)
932 {
933     print_and_free(stream, ofp_to_string(oh, len, verbosity));
934 }
935
936 /* Dumps the contents of the Ethernet frame in the 'len' bytes starting at
937  * 'data' to 'stream' using tcpdump.  'total_len' specifies the full length of
938  * the Ethernet frame (of which 'len' bytes were captured).
939  *
940  * This starts and kills a tcpdump subprocess so it's quite expensive. */
941 void
942 ofp_print_packet(FILE *stream, const void *data, size_t len, size_t total_len)
943 {
944     print_and_free(stream, ofp_packet_to_string(data, len, total_len));
945 }