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