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