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