Pretty-print port numbers when printing ofp_switch_features messages.
[openvswitch] / 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         ds_put_cstr(string, "output(");
222         ofp_print_port_name(string, ntohs(a->arg.output.port));
223         if (a->arg.output.port == htons(OFPP_CONTROLLER)) {
224             ds_put_format(string, ", max %"PRIu16" bytes", ntohs(a->arg.output.max_len));
225         }
226         ds_put_cstr(string, ")");
227         break;
228
229     default:
230         ds_put_format(string, "(decoder %"PRIu16" not implemented)", ntohs(a->type));
231         break;
232     }
233 }
234
235 static void ofp_print_actions(struct ds *string,
236                               const struct ofp_action actions[],
237                               size_t n_bytes) 
238 {
239     size_t i;
240
241     ds_put_cstr(string, " actions[");
242     for (i = 0; i < n_bytes / sizeof *actions; i++) {
243         if (i) {
244             ds_put_cstr(string, "; ");
245         }
246         ofp_print_action(string, &actions[i]);
247     }
248     if (n_bytes % sizeof *actions) {
249         if (i) {
250             ds_put_cstr(string, "; ");
251         }
252         ds_put_cstr(string, "; ***trailing garbage***");
253     }
254     ds_put_cstr(string, "]");
255 }
256
257 /* Pretty-print the OFPT_PACKET_OUT packet of 'len' bytes at 'oh' to 'string'
258  * at the given 'verbosity' level. */
259 static void ofp_packet_out(struct ds *string, const void *oh, size_t len,
260                            int verbosity) 
261 {
262     const struct ofp_packet_out *opo = oh;
263
264     ds_put_cstr(string, " in_port=");
265     ofp_print_port_name(string, ntohs(opo->in_port));
266
267     if (ntohl(opo->buffer_id) == UINT32_MAX) {
268         ds_put_cstr(string, " out_port=");
269         ofp_print_port_name(string, ntohs(opo->out_port));
270         if (verbosity > 0 && len > sizeof *opo) {
271             char *packet = ofp_packet_to_string(opo->u.data, len - sizeof *opo,
272                                                 len - sizeof *opo);
273             ds_put_char(string, '\n');
274             ds_put_cstr(string, packet);
275             free(packet);
276         }
277     } else {
278         ds_put_format(string, " buffer=%08"PRIx32, ntohl(opo->buffer_id));
279         ofp_print_actions(string, opo->u.actions, len - sizeof *opo);
280     }
281     ds_put_char(string, '\n');
282 }
283
284 /* qsort comparison function. */
285 static int
286 compare_ports(const void *a_, const void *b_)
287 {
288     const struct ofp_phy_port *a = a_;
289     const struct ofp_phy_port *b = b_;
290     uint16_t ap = ntohs(a->port_no);
291     uint16_t bp = ntohs(b->port_no);
292
293     return ap < bp ? -1 : ap > bp;
294 }
295
296 static void
297 ofp_print_phy_port(struct ds *string, const struct ofp_phy_port *port)
298 {
299     uint8_t name[OFP_MAX_PORT_NAME_LEN];
300     int j;
301
302     memcpy(name, port->name, sizeof name);
303     for (j = 0; j < sizeof name - 1; j++) {
304         if (!isprint(name[j])) {
305             break;
306         }
307     }
308     name[j] = '\0';
309
310     ds_put_char(string, ' ');
311     ofp_print_port_name(string, ntohs(port->port_no));
312     ds_put_format(string, "(%s): addr:"ETH_ADDR_FMT", speed:%d, flags:%#x, "
313             "feat:%#x\n", name, 
314             ETH_ADDR_ARGS(port->hw_addr), ntohl(port->speed),
315             ntohl(port->flags), ntohl(port->features));
316 }
317
318 /* Pretty-print the struct ofp_switch_features of 'len' bytes at 'oh' to
319  * 'string' at the given 'verbosity' level. */
320 static void
321 ofp_print_switch_features(struct ds *string, const void *oh, size_t len,
322                           int verbosity)
323 {
324     const struct ofp_switch_features *osf = oh;
325     struct ofp_phy_port port_list[OFPP_MAX];
326     int n_ports;
327     int i;
328
329     ds_put_format(string, "dp id:%"PRIx64"\n", ntohll(osf->datapath_id));
330     ds_put_format(string, "tables: exact:%d, compressed:%d, general:%d\n",
331            ntohl(osf->n_exact), 
332            ntohl(osf->n_compression), ntohl(osf->n_general));
333     ds_put_format(string, "buffers: size:%d, number:%d\n",
334            ntohl(osf->buffer_mb), ntohl(osf->n_buffers));
335     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
336            ntohl(osf->capabilities), ntohl(osf->actions));
337
338     if (ntohs(osf->header.length) >= sizeof *osf) {
339         len = MIN(len, ntohs(osf->header.length));
340     }
341     n_ports = (len - sizeof *osf) / sizeof *osf->ports;
342
343     memcpy(port_list, osf->ports, (len - sizeof *osf));
344     qsort(port_list, n_ports, sizeof port_list[0], compare_ports);
345     for (i = 0; i < n_ports; i++) {
346         ofp_print_phy_port(string, &port_list[i]);
347     }
348 }
349
350 /* Pretty-print the struct ofp_switch_config of 'len' bytes at 'oh' to 'string'
351  * at the given 'verbosity' level. */
352 static void
353 ofp_print_switch_config(struct ds *string, const void *oh, size_t len,
354                         int verbosity)
355 {
356     const struct ofp_switch_config *osc = oh;
357     uint16_t flags;
358
359     flags = ntohs(osc->flags);
360     if (flags & OFPC_SEND_FLOW_EXP) {
361         flags &= ~OFPC_SEND_FLOW_EXP;
362         ds_put_format(string, " (sending flow expirations)");
363     }
364     if (flags) {
365         ds_put_format(string, " ***unknown flags %04"PRIx16"***", flags);
366     }
367
368     ds_put_format(string, " miss_send_len=%"PRIu16"\n", ntohs(osc->miss_send_len));
369 }
370
371 static void print_wild(struct ds *string, const char *leader, int is_wild,
372             const char *format, ...) __attribute__((format(printf, 4, 5)));
373
374 static void print_wild(struct ds *string, const char *leader, int is_wild,
375                        const char *format, ...) 
376 {
377     ds_put_cstr(string, leader);
378     if (!is_wild) {
379         va_list args;
380
381         va_start(args, format);
382         ds_put_format_valist(string, format, args);
383         va_end(args);
384     } else {
385         ds_put_char(string, '?');
386     }
387 }
388
389 /* Pretty-print the ofp_match structure */
390 static void ofp_print_match(struct ds *f, const struct ofp_match *om)
391 {
392     uint16_t w = ntohs(om->wildcards);
393
394     print_wild(f, " inport", w & OFPFW_IN_PORT, "%d", ntohs(om->in_port));
395     print_wild(f, ":vlan", w & OFPFW_DL_VLAN, "%04x", ntohs(om->dl_vlan));
396     print_wild(f, " mac[", w & OFPFW_DL_SRC,
397                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_src));
398     print_wild(f, "->", w & OFPFW_DL_DST,
399                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_dst));
400     print_wild(f, "] type", w & OFPFW_DL_TYPE, "%04x", ntohs(om->dl_type));
401     print_wild(f, " ip[", w & OFPFW_NW_SRC, IP_FMT, IP_ARGS(&om->nw_src));
402     print_wild(f, "->", w & OFPFW_NW_DST, IP_FMT, IP_ARGS(&om->nw_dst));
403     print_wild(f, "] proto", w & OFPFW_NW_PROTO, "%u", om->nw_proto);
404     print_wild(f, " tport[", w & OFPFW_TP_SRC, "%d", ntohs(om->tp_src));
405     print_wild(f, "->", w & OFPFW_TP_DST, "%d", ntohs(om->tp_dst));
406     ds_put_cstr(f, "]");
407 }
408
409 /* Pretty-print the OFPT_FLOW_MOD packet of 'len' bytes at 'oh' to 'string'
410  * at the given 'verbosity' level. */
411 static void
412 ofp_print_flow_mod(struct ds *string, const void *oh, size_t len, 
413                    int verbosity)
414 {
415     const struct ofp_flow_mod *ofm = oh;
416
417     ofp_print_match(string, &ofm->match);
418     ds_put_format(string, " cmd:%d idle:%d pri:%d buf:%#x\n", 
419             ntohs(ofm->command), ntohs(ofm->max_idle), 
420             ofm->match.wildcards ? ntohs(ofm->priority) : (uint16_t)-1,
421             ntohl(ofm->buffer_id));
422 }
423
424 /* Pretty-print the OFPT_FLOW_EXPIRED packet of 'len' bytes at 'oh' to 'string'
425  * at the given 'verbosity' level. */
426 static void
427 ofp_print_flow_expired(struct ds *string, const void *oh, size_t len, 
428                        int verbosity)
429 {
430     const struct ofp_flow_expired *ofe = oh;
431
432     ofp_print_match(string, &ofe->match);
433     ds_put_format(string, 
434          " pri%"PRIu16" secs%"PRIu32" pkts%"PRIu64" bytes%"PRIu64"\n", 
435          ofe->match.wildcards ? ntohs(ofe->priority) : (uint16_t)-1,
436          ntohl(ofe->duration), ntohll(ofe->packet_count), 
437          ntohll(ofe->byte_count));
438 }
439
440 /* Pretty-print the OFPT_ERROR_MSG packet of 'len' bytes at 'oh' to 'string'
441  * at the given 'verbosity' level. */
442 static void
443 ofp_print_error_msg(struct ds *string, const void *oh, size_t len, 
444                        int verbosity)
445 {
446     const struct ofp_error_msg *oem = oh;
447
448     ds_put_format(string, 
449          " type%d code%d\n", ntohs(oem->type), ntohs(oem->code));
450 }
451
452 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
453  * at the given 'verbosity' level. */
454 static void
455 ofp_print_port_status(struct ds *string, const void *oh, size_t len, 
456                       int verbosity)
457 {
458     const struct ofp_port_status *ops = oh;
459
460     if (ops->reason == OFPPR_ADD) {
461         ds_put_format(string, "add:");
462     } else if (ops->reason == OFPPR_DELETE) {
463         ds_put_format(string, "del:");
464     } else if (ops->reason == OFPPR_MOD) {
465         ds_put_format(string, "mod:");
466     } else {
467         ds_put_format(string, "err:");
468     }
469
470     ofp_print_phy_port(string, &ops->desc);
471 }
472
473 static void
474 ofp_flow_stats_request(struct ds *string, const void *oh, size_t len,
475                       int verbosity) 
476 {
477     const struct ofp_flow_stats_request *fsr = oh;
478
479     if (fsr->table_id == 0xff) {
480         ds_put_format(string, " table_id=any, ");
481     } else {
482         ds_put_format(string, " table_id=%"PRIu8", ", fsr->table_id);
483     }
484
485     ofp_print_match(string, &fsr->match);
486 }
487
488 static void
489 ofp_flow_stats_reply(struct ds *string, const void *body_, size_t len,
490                      int verbosity)
491 {
492     const char *body = body_;
493     const char *pos = body;
494     for (;;) {
495         const struct ofp_flow_stats *fs;
496         ptrdiff_t bytes_left = body + len - pos;
497         size_t length;
498
499         if (bytes_left < sizeof *fs) {
500             if (bytes_left != 0) {
501                 ds_put_format(string, " ***%td leftover bytes at end***",
502                               bytes_left);
503             }
504             break;
505         }
506
507         fs = (const void *) pos;
508         length = ntohs(fs->length);
509         if (length < sizeof *fs) {
510             ds_put_format(string, " ***length=%zu shorter than minimum %zu***",
511                           length, sizeof *fs);
512             break;
513         } else if (length > bytes_left) {
514             ds_put_format(string,
515                           " ***length=%zu but only %td bytes left***",
516                           length, bytes_left);
517             break;
518         } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
519             ds_put_format(string,
520                           " ***length=%zu has %zu bytes leftover in "
521                           "final action***",
522                           length,
523                           (length - sizeof *fs) % sizeof fs->actions[0]);
524             break;
525         }
526
527         ds_put_format(string, "  duration=%"PRIu32"s, ", ntohl(fs->duration));
528         ds_put_format(string, "table_id=%"PRIu8", ", fs->table_id);
529         ds_put_format(string, "priority=%"PRIu16", ", 
530                     fs->match.wildcards ? ntohs(fs->priority) : (uint16_t)-1);
531         ds_put_format(string, "n_packets=%"PRIu64", ",
532                     ntohll(fs->packet_count));
533         ds_put_format(string, "n_bytes=%"PRIu64", ", ntohll(fs->byte_count));
534         ds_put_format(string, "max_idle=%"PRIu16",", ntohs(fs->max_idle));
535         ofp_print_match(string, &fs->match);
536         ofp_print_actions(string, fs->actions, length - sizeof *fs);
537         ds_put_char(string, '\n');
538
539         pos += length;
540      }
541 }
542
543 static void
544 ofp_aggregate_stats_request(struct ds *string, const void *oh, size_t len,
545                             int verbosity) 
546 {
547     const struct ofp_aggregate_stats_request *asr = oh;
548
549     if (asr->table_id == 0xff) {
550         ds_put_format(string, " table_id=any, ");
551     } else {
552         ds_put_format(string, " table_id=%"PRIu8", ", asr->table_id);
553     }
554
555     ofp_print_match(string, &asr->match);
556 }
557
558 static void
559 ofp_aggregate_stats_reply(struct ds *string, const void *body_, size_t len,
560                           int verbosity)
561 {
562     const struct ofp_aggregate_stats_reply *asr = body_;
563
564     ds_put_format(string, " packet_count=%"PRIu64, ntohll(asr->packet_count));
565     ds_put_format(string, " byte_count=%"PRIu64, ntohll(asr->byte_count));
566     ds_put_format(string, " flow_count=%"PRIu32, ntohl(asr->flow_count));
567 }
568
569 static void
570 ofp_port_stats_reply(struct ds *string, const void *body, size_t len,
571                      int verbosity)
572 {
573     const struct ofp_port_stats *ps = body;
574     size_t n = len / sizeof *ps;
575     ds_put_format(string, " %zu ports\n", n);
576     if (verbosity < 1) {
577         return;
578     }
579
580     for (; n--; ps++) {
581         ds_put_format(string, "  port %"PRIu16": ", ntohs(ps->port_no));
582         ds_put_format(string, "rx %"PRIu64", ", ntohll(ps->rx_count));
583         ds_put_format(string, "tx %"PRIu64", ", ntohll(ps->tx_count));
584         ds_put_format(string, "dropped %"PRIu64"\n", ntohll(ps->drop_count));
585     }
586 }
587
588 static void
589 ofp_table_stats_reply(struct ds *string, const void *body, size_t len,
590                      int verbosity)
591 {
592     const struct ofp_table_stats *ts = body;
593     size_t n = len / sizeof *ts;
594     ds_put_format(string, " %zu tables\n", n);
595     if (verbosity < 1) {
596         return;
597     }
598
599     for (; n--; ts++) {
600         char name[OFP_MAX_TABLE_NAME_LEN + 1];
601         strncpy(name, ts->name, sizeof name);
602         name[OFP_MAX_TABLE_NAME_LEN] = '\0';
603
604         ds_put_format(string, "  table %"PRIu8": ", ts->table_id);
605         ds_put_format(string, "name %-8s, ", name);
606         ds_put_format(string, "max %6"PRIu32", ", ntohl(ts->max_entries));
607         ds_put_format(string, "active %6"PRIu32", ", ntohl(ts->active_count));
608         ds_put_format(string, "matched %6"PRIu64"\n",
609                       ntohll(ts->matched_count));
610      }
611 }
612
613 enum stats_direction {
614     REQUEST,
615     REPLY
616 };
617
618 static void
619 print_stats(struct ds *string, int type, const void *body, size_t body_len,
620             int verbosity, enum stats_direction direction)
621 {
622     struct stats_msg {
623         size_t min_body, max_body;
624         void (*printer)(struct ds *, const void *, size_t len, int verbosity);
625     };
626
627     struct stats_type {
628         const char *name;
629         struct stats_msg request;
630         struct stats_msg reply;
631     };
632
633     static const struct stats_type stats_types[] = {
634         [OFPST_FLOW] = {
635             "flow",
636             { sizeof(struct ofp_flow_stats_request),
637               sizeof(struct ofp_flow_stats_request),
638               ofp_flow_stats_request },
639             { 0, SIZE_MAX, ofp_flow_stats_reply },
640         },
641         [OFPST_AGGREGATE] = {
642             "aggregate",
643             { sizeof(struct ofp_aggregate_stats_request),
644               sizeof(struct ofp_aggregate_stats_request),
645               ofp_aggregate_stats_request },
646             { sizeof(struct ofp_aggregate_stats_reply),
647               sizeof(struct ofp_aggregate_stats_reply),
648               ofp_aggregate_stats_reply },
649         },
650         [OFPST_TABLE] = {
651             "table",
652             { 0, 0, NULL },
653             { 0, SIZE_MAX, ofp_table_stats_reply },
654         },
655         [OFPST_PORT] = {
656             "port",
657             { 0, 0, NULL, },
658             { 0, SIZE_MAX, ofp_port_stats_reply },
659         },
660     };
661
662     const struct stats_type *s;
663     const struct stats_msg *m;
664
665     if (type >= ARRAY_SIZE(stats_types) || !stats_types[type].name) {
666         ds_put_format(string, " ***unknown type %d***", type);
667         return;
668     }
669     s = &stats_types[type];
670     ds_put_format(string, " type=%d(%s)\n", type, s->name);
671
672     m = direction == REQUEST ? &s->request : &s->reply;
673     if (body_len < m->min_body || body_len > m->max_body) {
674         ds_put_format(string, " ***body_len=%zu not in %zu...%zu***",
675                       body_len, m->min_body, m->max_body);
676         return;
677     }
678     if (m->printer) {
679         m->printer(string, body, body_len, verbosity);
680     }
681 }
682
683 static void
684 ofp_stats_request(struct ds *string, const void *oh, size_t len, int verbosity)
685 {
686     const struct ofp_stats_request *srq = oh;
687
688     if (srq->flags) {
689         ds_put_format(string, " ***unknown flags %04"PRIx16"***",
690                       ntohs(srq->flags));
691     }
692
693     print_stats(string, ntohs(srq->type), srq->body,
694                 len - offsetof(struct ofp_stats_request, body),
695                 verbosity, REQUEST);
696 }
697
698 static void
699 ofp_stats_reply(struct ds *string, const void *oh, size_t len, int verbosity)
700 {
701     const struct ofp_stats_reply *srp = oh;
702
703     ds_put_cstr(string, " flags=");
704     if (!srp->flags) {
705         ds_put_cstr(string, "none");
706     } else {
707         uint16_t flags = ntohs(srp->flags);
708         if (flags & OFPSF_REPLY_MORE) {
709             ds_put_cstr(string, "[more]");
710             flags &= ~OFPSF_REPLY_MORE;
711         }
712         if (flags) {
713             ds_put_format(string, "[***unknown%04"PRIx16"***]", flags);
714         }
715     }
716
717     print_stats(string, ntohs(srp->type), srp->body,
718                 len - offsetof(struct ofp_stats_reply, body),
719                 verbosity, REPLY);
720 }
721
722 struct openflow_packet {
723     const char *name;
724     size_t min_size;
725     void (*printer)(struct ds *, const void *, size_t len, int verbosity);
726 };
727
728 static const struct openflow_packet packets[] = {
729     [OFPT_FEATURES_REQUEST] = {
730         "features_request",
731         sizeof (struct ofp_header),
732         NULL,
733     },
734     [OFPT_FEATURES_REPLY] = {
735         "features_reply",
736         sizeof (struct ofp_switch_features),
737         ofp_print_switch_features,
738     },
739     [OFPT_GET_CONFIG_REQUEST] = {
740         "get_config_request",
741         sizeof (struct ofp_header),
742         NULL,
743     },
744     [OFPT_GET_CONFIG_REPLY] = {
745         "get_config_reply",
746         sizeof (struct ofp_switch_config),
747         ofp_print_switch_config,
748     },
749     [OFPT_SET_CONFIG] = {
750         "set_config",
751         sizeof (struct ofp_switch_config),
752         ofp_print_switch_config,
753     },
754     [OFPT_PACKET_IN] = {
755         "packet_in",
756         offsetof(struct ofp_packet_in, data),
757         ofp_packet_in,
758     },
759     [OFPT_PACKET_OUT] = {
760         "packet_out",
761         sizeof (struct ofp_packet_out),
762         ofp_packet_out,
763     },
764     [OFPT_FLOW_MOD] = {
765         "flow_mod",
766         sizeof (struct ofp_flow_mod),
767         ofp_print_flow_mod,
768     },
769     [OFPT_FLOW_EXPIRED] = {
770         "flow_expired",
771         sizeof (struct ofp_flow_expired),
772         ofp_print_flow_expired,
773     },
774     [OFPT_PORT_MOD] = {
775         "port_mod",
776         sizeof (struct ofp_port_mod),
777         NULL,
778     },
779     [OFPT_PORT_STATUS] = {
780         "port_status",
781         sizeof (struct ofp_port_status),
782         ofp_print_port_status
783     },
784     [OFPT_ERROR_MSG] = {
785         "error_msg",
786         sizeof (struct ofp_error_msg),
787         ofp_print_error_msg,
788     },
789     [OFPT_STATS_REQUEST] = {
790         "stats_request",
791         sizeof (struct ofp_stats_request),
792         ofp_stats_request,
793     },
794     [OFPT_STATS_REPLY] = {
795         "stats_reply",
796         sizeof (struct ofp_stats_reply),
797         ofp_stats_reply,
798     },
799 };
800
801 /* Composes and returns a string representing the OpenFlow packet of 'len'
802  * bytes at 'oh' at the given 'verbosity' level.  0 is a minimal amount of
803  * verbosity and higher numbers increase verbosity.  The caller is responsible
804  * for freeing the string. */
805 char *
806 ofp_to_string(const void *oh_, size_t len, int verbosity)
807 {
808     struct ds string = DS_EMPTY_INITIALIZER;
809     const struct ofp_header *oh = oh_;
810     const struct openflow_packet *pkt;
811
812     if (len < sizeof(struct ofp_header)) {
813         ds_put_cstr(&string, "OpenFlow packet too short:\n");
814         ds_put_hex_dump(&string, oh, len, 0, true);
815         return ds_cstr(&string);
816     } else if (oh->version != OFP_VERSION) {
817         ds_put_format(&string, "Bad OpenFlow version %"PRIu8":\n", oh->version);
818         ds_put_hex_dump(&string, oh, len, 0, true);
819         return ds_cstr(&string);
820     } else if (oh->type >= ARRAY_SIZE(packets) || !packets[oh->type].name) {
821         ds_put_format(&string, "Unknown OpenFlow packet type %"PRIu8":\n",
822                 oh->type);
823         ds_put_hex_dump(&string, oh, len, 0, true);
824         return ds_cstr(&string);
825     }
826
827     pkt = &packets[oh->type];
828     ds_put_format(&string, "%s (xid=%"PRIx32"):", pkt->name, oh->xid);
829
830     if (ntohs(oh->length) > len)
831         ds_put_format(&string, " (***truncated to %zu bytes from %"PRIu16"***)",
832                 len, ntohs(oh->length));
833     else if (ntohs(oh->length) < len) {
834         ds_put_format(&string, " (***only uses %"PRIu16" bytes out of %zu***)\n",
835                 ntohs(oh->length), len);
836         len = ntohs(oh->length);
837     }
838
839     if (len < pkt->min_size) {
840         ds_put_format(&string, " (***length=%zu < min_size=%zu***)\n",
841                 len, pkt->min_size);
842     } else if (!pkt->printer) {
843         if (len > sizeof *oh) {
844             ds_put_format(&string, " length=%"PRIu16" (decoder not implemented)\n",
845                           ntohs(oh->length)); 
846         }
847     } else {
848         pkt->printer(&string, oh, len, verbosity);
849     }
850     if (verbosity >= 3) {
851         ds_put_hex_dump(&string, oh, len, 0, true);
852     }
853     if (string.string[string.length - 1] != '\n') {
854         ds_put_char(&string, '\n');
855     }
856     return ds_cstr(&string);
857 }
858 \f
859 static void
860 print_and_free(FILE *stream, char *string) 
861 {
862     fputs(string, stream);
863     free(string);
864 }
865
866 /* Pretty-print the OpenFlow packet of 'len' bytes at 'oh' to 'stream' at the
867  * given 'verbosity' level.  0 is a minimal amount of verbosity and higher
868  * numbers increase verbosity. */
869 void
870 ofp_print(FILE *stream, const void *oh, size_t len, int verbosity)
871 {
872     print_and_free(stream, ofp_to_string(oh, len, verbosity));
873 }
874
875 /* Dumps the contents of the Ethernet frame in the 'len' bytes starting at
876  * 'data' to 'stream' using tcpdump.  'total_len' specifies the full length of
877  * the Ethernet frame (of which 'len' bytes were captured).
878  *
879  * This starts and kills a tcpdump subprocess so it's quite expensive. */
880 void
881 ofp_print_packet(FILE *stream, const void *data, size_t len, size_t total_len)
882 {
883     print_and_free(stream, ofp_packet_to_string(data, len, total_len));
884 }