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