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