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