Fix lib/dhparams.c build failure fallout from earlier build system changes.
[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 "nicira-ext.h"
52 #include "packets.h"
53 #include "util.h"
54
55 static void ofp_print_port_name(struct ds *string, uint16_t port);
56 static void ofp_print_match(struct ds *, const struct ofp_match *,
57                             int verbosity);
58
59 /* Returns a string that represents the contents of the Ethernet frame in the
60  * 'len' bytes starting at 'data' to 'stream' as output by tcpdump.
61  * 'total_len' specifies the full length of the Ethernet frame (of which 'len'
62  * bytes were captured).
63  *
64  * The caller must free the returned string.
65  *
66  * This starts and kills a tcpdump subprocess so it's quite expensive. */
67 char *
68 ofp_packet_to_string(const void *data, size_t len, size_t total_len)
69 {
70     struct pcap_hdr {
71         uint32_t magic_number;   /* magic number */
72         uint16_t version_major;  /* major version number */
73         uint16_t version_minor;  /* minor version number */
74         int32_t thiszone;        /* GMT to local correction */
75         uint32_t sigfigs;        /* accuracy of timestamps */
76         uint32_t snaplen;        /* max length of captured packets */
77         uint32_t network;        /* data link type */
78     } PACKED;
79
80     struct pcaprec_hdr {
81         uint32_t ts_sec;         /* timestamp seconds */
82         uint32_t ts_usec;        /* timestamp microseconds */
83         uint32_t incl_len;       /* number of octets of packet saved in file */
84         uint32_t orig_len;       /* actual length of packet */
85     } PACKED;
86
87     struct pcap_hdr ph;
88     struct pcaprec_hdr prh;
89
90     struct ds ds = DS_EMPTY_INITIALIZER;
91
92     char command[128];
93     FILE *pcap;
94     FILE *tcpdump;
95     int status;
96     int c;
97
98     pcap = tmpfile();
99     if (!pcap) {
100         ofp_error(errno, "tmpfile");
101         return xstrdup("<error>");
102     }
103
104     /* The pcap reader is responsible for figuring out endianness based on the
105      * magic number, so the lack of htonX calls here is intentional. */
106     ph.magic_number = 0xa1b2c3d4;
107     ph.version_major = 2;
108     ph.version_minor = 4;
109     ph.thiszone = 0;
110     ph.sigfigs = 0;
111     ph.snaplen = 1518;
112     ph.network = 1;             /* Ethernet */
113
114     prh.ts_sec = 0;
115     prh.ts_usec = 0;
116     prh.incl_len = len;
117     prh.orig_len = total_len;
118
119     fwrite(&ph, 1, sizeof ph, pcap);
120     fwrite(&prh, 1, sizeof prh, pcap);
121     fwrite(data, 1, len, pcap);
122
123     fflush(pcap);
124     if (ferror(pcap)) {
125         ofp_error(errno, "error writing temporary file");
126     }
127     rewind(pcap);
128
129     snprintf(command, sizeof command, "/usr/sbin/tcpdump -e -n -r /dev/fd/%d 2>/dev/null",
130              fileno(pcap));
131     tcpdump = popen(command, "r");
132     fclose(pcap);
133     if (!tcpdump) {
134         ofp_error(errno, "exec(\"%s\")", command);
135         return xstrdup("<error>");
136     }
137
138     while ((c = getc(tcpdump)) != EOF) {
139         ds_put_char(&ds, c);
140     }
141
142     status = pclose(tcpdump);
143     if (WIFEXITED(status)) {
144         if (WEXITSTATUS(status))
145             ofp_error(0, "tcpdump exited with status %d", WEXITSTATUS(status));
146     } else if (WIFSIGNALED(status)) {
147         ofp_error(0, "tcpdump exited with signal %d", WTERMSIG(status)); 
148     }
149     return ds_cstr(&ds);
150 }
151
152 /* Pretty-print the OFPT_PACKET_IN packet of 'len' bytes at 'oh' to 'stream'
153  * at the given 'verbosity' level. */
154 static void
155 ofp_packet_in(struct ds *string, const void *oh, size_t len, int verbosity)
156 {
157     const struct ofp_packet_in *op = oh;
158     size_t data_len;
159
160     ds_put_format(string, " total_len=%"PRIu16" in_port=",
161                   ntohs(op->total_len));
162     ofp_print_port_name(string, ntohs(op->in_port));
163
164     if (op->reason == OFPR_ACTION)
165         ds_put_cstr(string, " (via action)");
166     else if (op->reason != OFPR_NO_MATCH)
167         ds_put_format(string, " (***reason %"PRIu8"***)", op->reason);
168
169     data_len = len - offsetof(struct ofp_packet_in, data);
170     ds_put_format(string, " data_len=%zu", data_len);
171     if (htonl(op->buffer_id) == UINT32_MAX) {
172         ds_put_format(string, " (unbuffered)");
173         if (ntohs(op->total_len) != data_len)
174             ds_put_format(string, " (***total_len != data_len***)");
175     } else {
176         ds_put_format(string, " buffer=0x%08"PRIx32, ntohl(op->buffer_id));
177         if (ntohs(op->total_len) < data_len)
178             ds_put_format(string, " (***total_len < data_len***)");
179     }
180     ds_put_char(string, '\n');
181
182     if (verbosity > 0) {
183         struct flow flow;
184         struct ofpbuf packet;
185         struct ofp_match match;
186         packet.data = (void *) op->data;
187         packet.size = data_len;
188         flow_extract(&packet, ntohs(op->in_port), &flow);
189         match.wildcards = 0;
190         match.in_port = flow.in_port;
191         memcpy(match.dl_src, flow.dl_src, ETH_ADDR_LEN);
192         memcpy(match.dl_dst, flow.dl_dst, ETH_ADDR_LEN);
193         match.dl_vlan = flow.dl_vlan;
194         match.dl_type = flow.dl_type;
195         match.nw_proto = flow.nw_proto;
196         match.pad = 0;
197         match.nw_src = flow.nw_src;
198         match.nw_dst = flow.nw_dst;
199         match.tp_src = flow.tp_src;
200         match.tp_dst = flow.tp_dst;
201         ofp_print_match(string, &match, verbosity);
202         ds_put_char(string, '\n');
203     }
204     if (verbosity > 1) {
205         char *packet = ofp_packet_to_string(op->data, data_len,
206                                             ntohs(op->total_len)); 
207         ds_put_cstr(string, packet);
208         free(packet);
209     }
210 }
211
212 static void ofp_print_port_name(struct ds *string, uint16_t port) 
213 {
214     const char *name;
215     switch (port) {
216     case OFPP_IN_PORT:
217         name = "IN_PORT";
218         break;
219     case OFPP_TABLE:
220         name = "TABLE";
221         break;
222     case OFPP_NORMAL:
223         name = "NORMAL";
224         break;
225     case OFPP_FLOOD:
226         name = "FLOOD";
227         break;
228     case OFPP_ALL:
229         name = "ALL";
230         break;
231     case OFPP_CONTROLLER:
232         name = "CONTROLLER";
233         break;
234     case OFPP_LOCAL:
235         name = "LOCAL";
236         break;
237     case OFPP_NONE:
238         name = "NONE";
239         break;
240     default:
241         ds_put_format(string, "%"PRIu16, port);
242         return;
243     }
244     ds_put_cstr(string, name);
245 }
246
247 static void
248 ofp_print_nx_action(struct ds *string, const struct nx_action_header *nah)
249 {
250
251     if (nah->subtype == htonl(NXAST_SNAT)) {
252         const struct nx_action_snat *nas = (struct nx_action_snat *)nah;
253         uint16_t port = ntohs(nas->port);
254
255         if (port < OFPP_MAX) {
256             ds_put_format(string, "nat:%"PRIu16, port);
257         } else {
258             ds_put_format(string, "nat:%"PRIu16" (invalid port)", port);
259         }
260     } else {
261         ds_put_format(string, "***unknown Nicira action:%d***\n", 
262                 ntohl(nah->subtype));
263     }
264 }
265
266 static int
267 ofp_print_action(struct ds *string, const struct ofp_action_header *ah, 
268         size_t actions_len) 
269 {
270     uint16_t type;
271     size_t len;
272
273     struct openflow_action {
274         size_t min_size;
275         size_t max_size;
276     };
277
278     const struct openflow_action of_actions[] = {
279         [OFPAT_OUTPUT] = {
280             sizeof(struct ofp_action_output),
281             sizeof(struct ofp_action_output),
282         },
283         [OFPAT_SET_VLAN_VID] = {
284             sizeof(struct ofp_action_vlan_vid),
285             sizeof(struct ofp_action_vlan_vid),
286         },
287         [OFPAT_SET_VLAN_PCP] = {
288             sizeof(struct ofp_action_vlan_pcp),
289             sizeof(struct ofp_action_vlan_pcp),
290         },
291         [OFPAT_STRIP_VLAN] = {
292             sizeof(struct ofp_action_header),
293             sizeof(struct ofp_action_header),
294         },
295         [OFPAT_SET_DL_SRC] = {
296             sizeof(struct ofp_action_dl_addr),
297             sizeof(struct ofp_action_dl_addr),
298         },
299         [OFPAT_SET_DL_DST] = {
300             sizeof(struct ofp_action_dl_addr),
301             sizeof(struct ofp_action_dl_addr),
302         },
303         [OFPAT_SET_NW_SRC] = {
304             sizeof(struct ofp_action_nw_addr),
305             sizeof(struct ofp_action_nw_addr),
306         },
307         [OFPAT_SET_NW_DST] = {
308             sizeof(struct ofp_action_nw_addr),
309             sizeof(struct ofp_action_nw_addr),
310         },
311         [OFPAT_SET_TP_SRC] = {
312             sizeof(struct ofp_action_tp_port),
313             sizeof(struct ofp_action_tp_port),
314         },
315         [OFPAT_SET_TP_DST] = {
316             sizeof(struct ofp_action_tp_port),
317             sizeof(struct ofp_action_tp_port),
318         }
319         /* OFPAT_VENDOR is not here, since it would blow up the array size. */
320     };
321
322     if (actions_len < sizeof *ah) {
323         ds_put_format(string, "***action array too short for next action***\n");
324         return -1;
325     }
326
327     type = ntohs(ah->type);
328     len = ntohs(ah->len);
329     if (actions_len < len) {
330         ds_put_format(string, "***truncated action %"PRIu16"***\n", type);
331         return -1;
332     }
333
334     if ((len % 8) != 0) {
335         ds_put_format(string, 
336                 "***action %"PRIu16" length not a multiple of 8***\n",
337                 type);
338         return -1;
339     }
340
341     if (type < ARRAY_SIZE(of_actions)) {
342         const struct openflow_action *act = &of_actions[type];
343         if ((len < act->min_size) || (len > act->max_size)) {
344             ds_put_format(string, 
345                     "***action %"PRIu16" wrong length: %"PRIu16"***\n", 
346                     type, len);
347             return -1;
348         }
349     }
350     
351     switch (type) {
352     case OFPAT_OUTPUT: {
353         struct ofp_action_output *oa = (struct ofp_action_output *)ah;
354         uint16_t port = ntohs(oa->port); 
355         if (port < OFPP_MAX) {
356             ds_put_format(string, "output:%"PRIu16, port);
357         } else {
358             ofp_print_port_name(string, port);
359             if (port == OFPP_CONTROLLER) {
360                 if (oa->max_len) {
361                     ds_put_format(string, ":%"PRIu16, ntohs(oa->max_len));
362                 } else {
363                     ds_put_cstr(string, ":all");
364                 }
365             }
366         }
367         break;
368     }
369
370     case OFPAT_SET_VLAN_VID: {
371         struct ofp_action_vlan_vid *va = (struct ofp_action_vlan_vid *)ah;
372         ds_put_format(string, "mod_vlan_vid:%"PRIu16, ntohs(va->vlan_vid));
373         break;
374     }
375
376     case OFPAT_SET_VLAN_PCP: {
377         struct ofp_action_vlan_pcp *va = (struct ofp_action_vlan_pcp *)ah;
378         ds_put_format(string, "mod_vlan_pcp:%"PRIu8, va->vlan_pcp);
379         break;
380     }
381
382     case OFPAT_STRIP_VLAN:
383         ds_put_cstr(string, "strip_vlan");
384         break;
385
386     case OFPAT_SET_DL_SRC: {
387         struct ofp_action_dl_addr *da = (struct ofp_action_dl_addr *)ah;
388         ds_put_format(string, "mod_dl_src:"ETH_ADDR_FMT, 
389                 ETH_ADDR_ARGS(da->dl_addr));
390         break;
391     }
392
393     case OFPAT_SET_DL_DST: {
394         struct ofp_action_dl_addr *da = (struct ofp_action_dl_addr *)ah;
395         ds_put_format(string, "mod_dl_dst:"ETH_ADDR_FMT, 
396                 ETH_ADDR_ARGS(da->dl_addr));
397         break;
398     }
399
400     case OFPAT_SET_NW_SRC: {
401         struct ofp_action_nw_addr *na = (struct ofp_action_nw_addr *)ah;
402         ds_put_format(string, "mod_nw_src:"IP_FMT, IP_ARGS(na->nw_addr));
403         break;
404     }
405
406     case OFPAT_SET_NW_DST: {
407         struct ofp_action_nw_addr *na = (struct ofp_action_nw_addr *)ah;
408         ds_put_format(string, "mod_nw_dst:"IP_FMT, IP_ARGS(na->nw_addr));
409         break;
410     }
411
412     case OFPAT_SET_TP_SRC: {
413         struct ofp_action_tp_port *ta = (struct ofp_action_tp_port *)ah;
414         ds_put_format(string, "mod_tp_src:%d", ntohs(ta->tp_port));
415         break;
416     }
417
418     case OFPAT_SET_TP_DST: {
419         struct ofp_action_tp_port *ta = (struct ofp_action_tp_port *)ah;
420         ds_put_format(string, "mod_tp_dst:%d", ntohs(ta->tp_port));
421         break;
422     }
423
424     case OFPAT_VENDOR: {
425         struct ofp_action_vendor_header *avh 
426                 = (struct ofp_action_vendor_header *)ah;
427         if (len < sizeof *avh) {
428             ds_put_format(string, "***ofpat_vendor truncated***\n");
429             return -1;
430         }
431         if (avh->vendor == htonl(NX_VENDOR_ID)) {
432             ofp_print_nx_action(string, (struct nx_action_header *)avh);
433         } else {
434             ds_put_format(string, "vendor action:0x%x", ntohl(avh->vendor));
435         }
436         break;
437     }
438
439     default:
440         ds_put_format(string, "(decoder %"PRIu16" not implemented)", type);
441         break;
442     }
443
444     return len;
445 }
446
447 static void 
448 ofp_print_actions(struct ds *string, const struct ofp_action_header *action,
449                   size_t actions_len) 
450 {
451     uint8_t *p = (uint8_t *)action;
452     size_t len = 0;
453
454     ds_put_cstr(string, "actions=");
455     while (actions_len > 0) {
456         if (len) {
457             ds_put_cstr(string, ",");
458         }
459         len = ofp_print_action(string, (struct ofp_action_header *)p, 
460                 actions_len);
461         if (len < 0) {
462             return;
463         }
464         p += len;
465         actions_len -= len;
466     }
467 }
468
469 /* Pretty-print the OFPT_PACKET_OUT packet of 'len' bytes at 'oh' to 'string'
470  * at the given 'verbosity' level. */
471 static void ofp_packet_out(struct ds *string, const void *oh, size_t len,
472                            int verbosity) 
473 {
474     const struct ofp_packet_out *opo = oh;
475     size_t actions_len = ntohs(opo->actions_len);
476
477     ds_put_cstr(string, " in_port=");
478     ofp_print_port_name(string, ntohs(opo->in_port));
479
480     ds_put_format(string, " actions_len=%zu ", actions_len);
481     if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
482         ds_put_format(string, "***packet too short for action length***\n");
483         return;
484     }
485     ofp_print_actions(string, opo->actions, actions_len);
486
487     if (ntohl(opo->buffer_id) == UINT32_MAX) {
488         int data_len = len - sizeof *opo - actions_len;
489         ds_put_format(string, " data_len=%d", data_len);
490         if (verbosity > 0 && len > sizeof *opo) {
491             char *packet = ofp_packet_to_string(
492                     (uint8_t *)opo->actions + actions_len, data_len, data_len);
493             ds_put_char(string, '\n');
494             ds_put_cstr(string, packet);
495             free(packet);
496         }
497     } else {
498         ds_put_format(string, " buffer=0x%08"PRIx32, ntohl(opo->buffer_id));
499     }
500     ds_put_char(string, '\n');
501 }
502
503 /* qsort comparison function. */
504 static int
505 compare_ports(const void *a_, const void *b_)
506 {
507     const struct ofp_phy_port *a = a_;
508     const struct ofp_phy_port *b = b_;
509     uint16_t ap = ntohs(a->port_no);
510     uint16_t bp = ntohs(b->port_no);
511
512     return ap < bp ? -1 : ap > bp;
513 }
514
515 static void ofp_print_port_features(struct ds *string, uint32_t features)
516 {
517     if (features == 0) {
518         ds_put_cstr(string, "Unsupported\n");
519         return;
520     }
521     if (features & OFPPF_10MB_HD) {
522         ds_put_cstr(string, "10MB-HD ");
523     }
524     if (features & OFPPF_10MB_FD) {
525         ds_put_cstr(string, "10MB-FD ");
526     }
527     if (features & OFPPF_100MB_HD) {
528         ds_put_cstr(string, "100MB-HD ");
529     }
530     if (features & OFPPF_100MB_FD) {
531         ds_put_cstr(string, "100MB-FD ");
532     }
533     if (features & OFPPF_1GB_HD) {
534         ds_put_cstr(string, "1GB-HD ");
535     }
536     if (features & OFPPF_1GB_FD) {
537         ds_put_cstr(string, "1GB-FD ");
538     }
539     if (features & OFPPF_10GB_FD) {
540         ds_put_cstr(string, "10GB-FD ");
541     }
542     if (features & OFPPF_COPPER) {
543         ds_put_cstr(string, "COPPER ");
544     }
545     if (features & OFPPF_FIBER) {
546         ds_put_cstr(string, "FIBER ");
547     }
548     if (features & OFPPF_AUTONEG) {
549         ds_put_cstr(string, "AUTO_NEG ");
550     }
551     if (features & OFPPF_PAUSE) {
552         ds_put_cstr(string, "AUTO_PAUSE ");
553     }
554     if (features & OFPPF_PAUSE_ASYM) {
555         ds_put_cstr(string, "AUTO_PAUSE_ASYM ");
556     }
557     ds_put_char(string, '\n');
558 }
559
560 static void
561 ofp_print_phy_port(struct ds *string, const struct ofp_phy_port *port)
562 {
563     uint8_t name[OFP_MAX_PORT_NAME_LEN];
564     int j;
565
566     memcpy(name, port->name, sizeof name);
567     for (j = 0; j < sizeof name - 1; j++) {
568         if (!isprint(name[j])) {
569             break;
570         }
571     }
572     name[j] = '\0';
573
574     ds_put_char(string, ' ');
575     ofp_print_port_name(string, ntohs(port->port_no));
576     ds_put_format(string, "(%s): addr:"ETH_ADDR_FMT", config: %#x, state:%#x\n",
577             name, ETH_ADDR_ARGS(port->hw_addr), ntohl(port->config),
578             ntohl(port->state));
579     if (port->curr) {
580         ds_put_format(string, "     current:    ");
581         ofp_print_port_features(string, ntohl(port->curr));
582     }
583     if (port->advertised) {
584         ds_put_format(string, "     advertised: ");
585         ofp_print_port_features(string, ntohl(port->advertised));
586     }
587     if (port->supported) {
588         ds_put_format(string, "     supported:  ");
589         ofp_print_port_features(string, ntohl(port->supported));
590     }
591     if (port->peer) {
592         ds_put_format(string, "     peer:       ");
593         ofp_print_port_features(string, ntohl(port->peer));
594     }
595 }
596
597 /* Pretty-print the struct ofp_switch_features of 'len' bytes at 'oh' to
598  * 'string' at the given 'verbosity' level. */
599 static void
600 ofp_print_switch_features(struct ds *string, const void *oh, size_t len,
601                           int verbosity)
602 {
603     const struct ofp_switch_features *osf = oh;
604     struct ofp_phy_port *port_list;
605     int n_ports;
606     int i;
607
608     ds_put_format(string, " ver:0x%x, dpid:%"PRIx64"\n", 
609             osf->header.version, ntohll(osf->datapath_id));
610     ds_put_format(string, "n_tables:%d, n_buffers:%d\n", osf->n_tables,
611             ntohl(osf->n_buffers));
612     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
613            ntohl(osf->capabilities), ntohl(osf->actions));
614
615     if (ntohs(osf->header.length) >= sizeof *osf) {
616         len = MIN(len, ntohs(osf->header.length));
617     }
618     n_ports = (len - sizeof *osf) / sizeof *osf->ports;
619
620     port_list = xmemdup(osf->ports, len - sizeof *osf); 
621     qsort(port_list, n_ports, sizeof *port_list, compare_ports);
622     for (i = 0; i < n_ports; i++) {
623         ofp_print_phy_port(string, &port_list[i]);
624     }
625     free(port_list);
626 }
627
628 /* Pretty-print the struct ofp_switch_config of 'len' bytes at 'oh' to 'string'
629  * at the given 'verbosity' level. */
630 static void
631 ofp_print_switch_config(struct ds *string, const void *oh, size_t len,
632                         int verbosity)
633 {
634     const struct ofp_switch_config *osc = oh;
635     uint16_t flags;
636
637     flags = ntohs(osc->flags);
638     if (flags & OFPC_SEND_FLOW_EXP) {
639         flags &= ~OFPC_SEND_FLOW_EXP;
640         ds_put_format(string, " (sending flow expirations)");
641     }
642     if (flags) {
643         ds_put_format(string, " ***unknown flags 0x%04"PRIx16"***", flags);
644     }
645
646     ds_put_format(string, " miss_send_len=%"PRIu16"\n", ntohs(osc->miss_send_len));
647 }
648
649 static void print_wild(struct ds *string, const char *leader, int is_wild,
650             int verbosity, const char *format, ...) 
651             __attribute__((format(printf, 5, 6)));
652
653 static void print_wild(struct ds *string, const char *leader, int is_wild,
654                        int verbosity, const char *format, ...) 
655 {
656     if (is_wild && verbosity < 2) {
657         return;
658     }
659     ds_put_cstr(string, leader);
660     if (!is_wild) {
661         va_list args;
662
663         va_start(args, format);
664         ds_put_format_valist(string, format, args);
665         va_end(args);
666     } else {
667         ds_put_char(string, '*');
668     }
669     ds_put_char(string, ',');
670 }
671
672 static void
673 print_ip_netmask(struct ds *string, const char *leader, uint32_t ip,
674                  uint32_t wild_bits, int verbosity)
675 {
676     if (wild_bits >= 32 && verbosity < 2) {
677         return;
678     }
679     ds_put_cstr(string, leader);
680     if (wild_bits < 32) {
681         ds_put_format(string, IP_FMT, IP_ARGS(&ip));
682         if (wild_bits) {
683             ds_put_format(string, "/%d", 32 - wild_bits);
684         }
685     } else {
686         ds_put_char(string, '*');
687     }
688     ds_put_char(string, ',');
689 }
690
691 /* Pretty-print the ofp_match structure */
692 static void ofp_print_match(struct ds *f, const struct ofp_match *om, 
693         int verbosity)
694 {
695     uint32_t w = ntohl(om->wildcards);
696     bool skip_type = false;
697     bool skip_proto = false;
698
699     if (!(w & OFPFW_DL_TYPE)) {
700         skip_type = true;
701         if (om->dl_type == htons(ETH_TYPE_IP)) {
702             if (!(w & OFPFW_NW_PROTO)) {
703                 skip_proto = true;
704                 if (om->nw_proto == IP_TYPE_ICMP) {
705                     ds_put_cstr(f, "icmp,");
706                 } else if (om->nw_proto == IP_TYPE_TCP) {
707                     ds_put_cstr(f, "tcp,");
708                 } else if (om->nw_proto == IP_TYPE_UDP) {
709                     ds_put_cstr(f, "udp,");
710                 } else {
711                     ds_put_cstr(f, "ip,");
712                     skip_proto = false;
713                 }
714             } else {
715                 ds_put_cstr(f, "ip,");
716             }
717         } else if (om->dl_type == htons(ETH_TYPE_ARP)) {
718             ds_put_cstr(f, "arp,");
719         } else {
720             skip_type = false;
721         }
722     }
723     print_wild(f, "in_port=", w & OFPFW_IN_PORT, verbosity,
724                "%d", ntohs(om->in_port));
725     print_wild(f, "dl_vlan=", w & OFPFW_DL_VLAN, verbosity,
726                "0x%04x", ntohs(om->dl_vlan));
727     print_wild(f, "dl_src=", w & OFPFW_DL_SRC, verbosity,
728                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_src));
729     print_wild(f, "dl_dst=", w & OFPFW_DL_DST, verbosity,
730                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_dst));
731     if (!skip_type) {
732         print_wild(f, "dl_type=", w & OFPFW_DL_TYPE, verbosity,
733                    "0x%04x", ntohs(om->dl_type));
734     }
735     print_ip_netmask(f, "nw_src=", om->nw_src,
736                      (w & OFPFW_NW_SRC_MASK) >> OFPFW_NW_SRC_SHIFT, verbosity);
737     print_ip_netmask(f, "nw_dst=", om->nw_dst,
738                      (w & OFPFW_NW_DST_MASK) >> OFPFW_NW_DST_SHIFT, verbosity);
739     if (!skip_proto) {
740         print_wild(f, "nw_proto=", w & OFPFW_NW_PROTO, verbosity,
741                    "%u", om->nw_proto);
742     }
743     print_wild(f, "tp_src=", w & OFPFW_TP_SRC, verbosity,
744                "%d", ntohs(om->tp_src));
745     print_wild(f, "tp_dst=", w & OFPFW_TP_DST, verbosity,
746                "%d", ntohs(om->tp_dst));
747 }
748
749 /* Pretty-print the OFPT_FLOW_MOD packet of 'len' bytes at 'oh' to 'string'
750  * at the given 'verbosity' level. */
751 static void
752 ofp_print_flow_mod(struct ds *string, const void *oh, size_t len, 
753                    int verbosity)
754 {
755     const struct ofp_flow_mod *ofm = oh;
756
757     ofp_print_match(string, &ofm->match, verbosity);
758     switch (ntohs(ofm->command)) {
759     case OFPFC_ADD:
760         ds_put_cstr(string, " ADD: ");
761         break;
762     case OFPFC_MODIFY:
763         ds_put_cstr(string, " MOD: ");
764         break;
765     case OFPFC_MODIFY_STRICT:
766         ds_put_cstr(string, " MOD_STRICT: ");
767         break;
768     case OFPFC_DELETE:
769         ds_put_cstr(string, " DEL: ");
770         break;
771     case OFPFC_DELETE_STRICT:
772         ds_put_cstr(string, " DEL_STRICT: ");
773         break;
774     default:
775         ds_put_format(string, " cmd:%d ", ntohs(ofm->command));
776     }
777     ds_put_format(string, "idle:%d hard:%d pri:%d buf:%#x", 
778             ntohs(ofm->idle_timeout), ntohs(ofm->hard_timeout),
779             ofm->match.wildcards ? ntohs(ofm->priority) : (uint16_t)-1,
780             ntohl(ofm->buffer_id));
781     ofp_print_actions(string, ofm->actions,
782                       len - offsetof(struct ofp_flow_mod, actions));
783     ds_put_char(string, '\n');
784 }
785
786 /* Pretty-print the OFPT_FLOW_EXPIRED packet of 'len' bytes at 'oh' to 'string'
787  * at the given 'verbosity' level. */
788 static void
789 ofp_print_flow_expired(struct ds *string, const void *oh, size_t len, 
790                        int verbosity)
791 {
792     const struct ofp_flow_expired *ofe = oh;
793
794     ofp_print_match(string, &ofe->match, verbosity);
795     ds_put_cstr(string, " reason=");
796     switch (ofe->reason) {
797     case OFPER_IDLE_TIMEOUT:
798         ds_put_cstr(string, "idle");
799         break;
800     case OFPER_HARD_TIMEOUT:
801         ds_put_cstr(string, "hard");
802         break;
803     default:
804         ds_put_format(string, "**%"PRIu8"**", ofe->reason);
805         break;
806     }
807     ds_put_format(string, 
808          " pri%"PRIu16" secs%"PRIu32" pkts%"PRIu64" bytes%"PRIu64"\n", 
809          ofe->match.wildcards ? ntohs(ofe->priority) : (uint16_t)-1,
810          ntohl(ofe->duration), ntohll(ofe->packet_count), 
811          ntohll(ofe->byte_count));
812 }
813
814 static void
815 ofp_print_port_mod(struct ds *string, const void *oh, size_t len,
816                    int verbosity)
817 {
818     const struct ofp_port_mod *opm = oh;
819
820     ds_put_format(string, "port: %d: addr:"ETH_ADDR_FMT", config: %#x, mask:%#x\n",
821             ntohs(opm->port_no), ETH_ADDR_ARGS(opm->hw_addr), 
822             ntohl(opm->config), ntohl(opm->mask));
823     ds_put_format(string, "     advertise: ");
824     if (opm->advertise) {
825         ofp_print_port_features(string, ntohl(opm->advertise));
826     } else {
827         ds_put_format(string, "UNCHANGED\n");
828     }
829 }
830
831 struct error_type {
832     int type;
833     int code;
834     const char *name;
835 };
836
837 static const struct error_type error_types[] = {
838 #define ERROR_TYPE(TYPE) {TYPE, -1, #TYPE}
839 #define ERROR_CODE(TYPE, CODE) {TYPE, CODE, #CODE}
840     ERROR_TYPE(OFPET_HELLO_FAILED),
841     ERROR_CODE(OFPET_HELLO_FAILED, OFPHFC_INCOMPATIBLE),
842
843     ERROR_TYPE(OFPET_BAD_REQUEST),
844     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VERSION),
845     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE),
846     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT),
847     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VERSION),
848
849     ERROR_TYPE(OFPET_BAD_ACTION),
850     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE),
851     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_LEN),
852     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR),
853     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE),
854     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT),
855
856     ERROR_TYPE(OFPET_FLOW_MOD_FAILED),
857     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL)
858 };
859 #define N_ERROR_TYPES ARRAY_SIZE(error_types)
860
861 static const char *
862 lookup_error_type(int type)
863 {
864     const struct error_type *t;
865
866     for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
867         if (t->type == type && t->code == -1) {
868             return t->name;
869         }
870     }
871     return "?";
872 }
873
874 static const char *
875 lookup_error_code(int type, int code)
876 {
877     const struct error_type *t;
878
879     for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
880         if (t->type == type && t->code == code) {
881             return t->name;
882         }
883     }
884     return "?";
885 }
886
887 /* Pretty-print the OFPT_ERROR packet of 'len' bytes at 'oh' to 'string'
888  * at the given 'verbosity' level. */
889 static void
890 ofp_print_error_msg(struct ds *string, const void *oh, size_t len, 
891                        int verbosity)
892 {
893     const struct ofp_error_msg *oem = oh;
894     int type = ntohs(oem->type);
895     int code = ntohs(oem->code);
896     char *s;
897
898     ds_put_format(string, " type%d(%s) code%d(%s) payload:\n",
899                   type, lookup_error_type(type),
900                   code, lookup_error_code(type, code));
901
902     switch (type) {
903     case OFPET_HELLO_FAILED:
904         ds_put_printable(string, (char *) oem->data, len - sizeof *oem);
905         break;
906
907     case OFPET_BAD_REQUEST:
908         s = ofp_to_string(oem->data, len - sizeof *oem, 1);
909         ds_put_cstr(string, s);
910         free(s);
911         break;
912
913     default:
914         ds_put_hex_dump(string, oem->data, len - sizeof *oem, 0, true);
915         break;
916     }
917 }
918
919 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
920  * at the given 'verbosity' level. */
921 static void
922 ofp_print_port_status(struct ds *string, const void *oh, size_t len, 
923                       int verbosity)
924 {
925     const struct ofp_port_status *ops = oh;
926
927     if (ops->reason == OFPPR_ADD) {
928         ds_put_format(string, " ADD:");
929     } else if (ops->reason == OFPPR_DELETE) {
930         ds_put_format(string, " DEL:");
931     } else if (ops->reason == OFPPR_MODIFY) {
932         ds_put_format(string, " MOD:");
933     }
934
935     ofp_print_phy_port(string, &ops->desc);
936 }
937
938 static void
939 ofp_desc_stats_reply(struct ds *string, const void *body, size_t len,
940                      int verbosity)
941 {
942     const struct ofp_desc_stats *ods = body;
943
944     ds_put_format(string, "Manufacturer: %s\n", ods->mfr_desc);
945     ds_put_format(string, "Hardware: %s\n", ods->hw_desc);
946     ds_put_format(string, "Software: %s\n", ods->sw_desc);
947     ds_put_format(string, "Serial Num: %s\n", ods->serial_num);
948 }
949
950 static void
951 ofp_flow_stats_request(struct ds *string, const void *oh, size_t len,
952                       int verbosity) 
953 {
954     const struct ofp_flow_stats_request *fsr = oh;
955
956     if (fsr->table_id == 0xff) {
957         ds_put_format(string, " table_id=any, ");
958     } else {
959         ds_put_format(string, " table_id=%"PRIu8", ", fsr->table_id);
960     }
961
962     ofp_print_match(string, &fsr->match, verbosity);
963 }
964
965 static void
966 ofp_flow_stats_reply(struct ds *string, const void *body_, size_t len,
967                      int verbosity)
968 {
969     const char *body = body_;
970     const char *pos = body;
971     for (;;) {
972         const struct ofp_flow_stats *fs;
973         ptrdiff_t bytes_left = body + len - pos;
974         size_t length;
975
976         if (bytes_left < sizeof *fs) {
977             if (bytes_left != 0) {
978                 ds_put_format(string, " ***%td leftover bytes at end***",
979                               bytes_left);
980             }
981             break;
982         }
983
984         fs = (const void *) pos;
985         length = ntohs(fs->length);
986         if (length < sizeof *fs) {
987             ds_put_format(string, " ***length=%zu shorter than minimum %zu***",
988                           length, sizeof *fs);
989             break;
990         } else if (length > bytes_left) {
991             ds_put_format(string,
992                           " ***length=%zu but only %td bytes left***",
993                           length, bytes_left);
994             break;
995         } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
996             ds_put_format(string,
997                           " ***length=%zu has %zu bytes leftover in "
998                           "final action***",
999                           length,
1000                           (length - sizeof *fs) % sizeof fs->actions[0]);
1001             break;
1002         }
1003
1004         ds_put_format(string, "  duration=%"PRIu32"s, ", ntohl(fs->duration));
1005         ds_put_format(string, "table_id=%"PRIu8", ", fs->table_id);
1006         ds_put_format(string, "priority=%"PRIu16", ", 
1007                     fs->match.wildcards ? ntohs(fs->priority) : (uint16_t)-1);
1008         ds_put_format(string, "n_packets=%"PRIu64", ",
1009                     ntohll(fs->packet_count));
1010         ds_put_format(string, "n_bytes=%"PRIu64", ", ntohll(fs->byte_count));
1011         ds_put_format(string, "idle_timeout=%"PRIu16",",
1012                       ntohs(fs->idle_timeout));
1013         ds_put_format(string, "hard_timeout=%"PRIu16",",
1014                       ntohs(fs->hard_timeout));
1015         ofp_print_match(string, &fs->match, verbosity);
1016         ofp_print_actions(string, fs->actions, length - sizeof *fs);
1017         ds_put_char(string, '\n');
1018
1019         pos += length;
1020      }
1021 }
1022
1023 static void
1024 ofp_aggregate_stats_request(struct ds *string, const void *oh, size_t len,
1025                             int verbosity) 
1026 {
1027     const struct ofp_aggregate_stats_request *asr = oh;
1028
1029     if (asr->table_id == 0xff) {
1030         ds_put_format(string, " table_id=any, ");
1031     } else {
1032         ds_put_format(string, " table_id=%"PRIu8", ", asr->table_id);
1033     }
1034
1035     ofp_print_match(string, &asr->match, verbosity);
1036 }
1037
1038 static void
1039 ofp_aggregate_stats_reply(struct ds *string, const void *body_, size_t len,
1040                           int verbosity)
1041 {
1042     const struct ofp_aggregate_stats_reply *asr = body_;
1043
1044     ds_put_format(string, " packet_count=%"PRIu64, ntohll(asr->packet_count));
1045     ds_put_format(string, " byte_count=%"PRIu64, ntohll(asr->byte_count));
1046     ds_put_format(string, " flow_count=%"PRIu32, ntohl(asr->flow_count));
1047 }
1048
1049 static void print_port_stat(struct ds *string, const char *leader, 
1050                             uint64_t stat, int more)
1051 {
1052     ds_put_cstr(string, leader);
1053     if (stat != -1) {
1054         ds_put_format(string, "%"PRIu64, stat);
1055     } else {
1056         ds_put_char(string, '?');
1057     }
1058     if (more) {
1059         ds_put_cstr(string, ", ");
1060     } else {
1061         ds_put_cstr(string, "\n");
1062     }
1063 }
1064
1065 static void
1066 ofp_port_stats_reply(struct ds *string, const void *body, size_t len,
1067                      int verbosity)
1068 {
1069     const struct ofp_port_stats *ps = body;
1070     size_t n = len / sizeof *ps;
1071     ds_put_format(string, " %zu ports\n", n);
1072     if (verbosity < 1) {
1073         return;
1074     }
1075
1076     for (; n--; ps++) {
1077         ds_put_format(string, "  port %2"PRIu16": ", ntohs(ps->port_no));
1078
1079         ds_put_cstr(string, "rx ");
1080         print_port_stat(string, "pkts=", ntohll(ps->rx_packets), 1);
1081         print_port_stat(string, "bytes=", ntohll(ps->rx_bytes), 1);
1082         print_port_stat(string, "drop=", ntohll(ps->rx_dropped), 1);
1083         print_port_stat(string, "errs=", ntohll(ps->rx_errors), 1);
1084         print_port_stat(string, "frame=", ntohll(ps->rx_frame_err), 1);
1085         print_port_stat(string, "over=", ntohll(ps->rx_over_err), 1);
1086         print_port_stat(string, "crc=", ntohll(ps->rx_crc_err), 0);
1087
1088         ds_put_cstr(string, "           tx ");
1089         print_port_stat(string, "pkts=", ntohll(ps->tx_packets), 1);
1090         print_port_stat(string, "bytes=", ntohll(ps->tx_bytes), 1);
1091         print_port_stat(string, "drop=", ntohll(ps->tx_dropped), 1);
1092         print_port_stat(string, "errs=", ntohll(ps->tx_errors), 1);
1093         print_port_stat(string, "coll=", ntohll(ps->collisions), 0);
1094     }
1095 }
1096
1097 static void
1098 ofp_table_stats_reply(struct ds *string, const void *body, size_t len,
1099                      int verbosity)
1100 {
1101     const struct ofp_table_stats *ts = body;
1102     size_t n = len / sizeof *ts;
1103     ds_put_format(string, " %zu tables\n", n);
1104     if (verbosity < 1) {
1105         return;
1106     }
1107
1108     for (; n--; ts++) {
1109         char name[OFP_MAX_TABLE_NAME_LEN + 1];
1110         strncpy(name, ts->name, sizeof name);
1111         name[OFP_MAX_TABLE_NAME_LEN] = '\0';
1112
1113         ds_put_format(string, "  %d: %-8s: ", ts->table_id, name);
1114         ds_put_format(string, "wild=0x%05"PRIx32", ", ntohl(ts->wildcards));
1115         ds_put_format(string, "max=%6"PRIu32", ", ntohl(ts->max_entries));
1116         ds_put_format(string, "active=%"PRIu32"\n", ntohl(ts->active_count));
1117         ds_put_cstr(string, "               ");
1118         ds_put_format(string, "lookup=%"PRIu64", ", 
1119                     ntohll(ts->lookup_count));
1120         ds_put_format(string, "matched=%"PRIu64"\n",
1121                     ntohll(ts->matched_count));
1122      }
1123 }
1124
1125 static void
1126 vendor_stat(struct ds *string, const void *body, size_t len,
1127             int verbosity UNUSED)
1128 {
1129     ds_put_format(string, " vendor=%08"PRIx32, ntohl(*(uint32_t *) body));
1130     ds_put_format(string, " %zu bytes additional data",
1131                   len - sizeof(uint32_t));
1132 }
1133
1134 enum stats_direction {
1135     REQUEST,
1136     REPLY
1137 };
1138
1139 static void
1140 print_stats(struct ds *string, int type, const void *body, size_t body_len,
1141             int verbosity, enum stats_direction direction)
1142 {
1143     struct stats_msg {
1144         size_t min_body, max_body;
1145         void (*printer)(struct ds *, const void *, size_t len, int verbosity);
1146     };
1147
1148     struct stats_type {
1149         int type;
1150         const char *name;
1151         struct stats_msg request;
1152         struct stats_msg reply;
1153     };
1154
1155     static const struct stats_type stats_types[] = {
1156         {
1157             OFPST_DESC,
1158             "description",
1159             { 0, 0, NULL },
1160             { 0, SIZE_MAX, ofp_desc_stats_reply },
1161         },
1162         {
1163             OFPST_FLOW,
1164             "flow",
1165             { sizeof(struct ofp_flow_stats_request),
1166               sizeof(struct ofp_flow_stats_request),
1167               ofp_flow_stats_request },
1168             { 0, SIZE_MAX, ofp_flow_stats_reply },
1169         },
1170         {
1171             OFPST_AGGREGATE,
1172             "aggregate",
1173             { sizeof(struct ofp_aggregate_stats_request),
1174               sizeof(struct ofp_aggregate_stats_request),
1175               ofp_aggregate_stats_request },
1176             { sizeof(struct ofp_aggregate_stats_reply),
1177               sizeof(struct ofp_aggregate_stats_reply),
1178               ofp_aggregate_stats_reply },
1179         },
1180         {
1181             OFPST_TABLE,
1182             "table",
1183             { 0, 0, NULL },
1184             { 0, SIZE_MAX, ofp_table_stats_reply },
1185         },
1186         {
1187             OFPST_PORT,
1188             "port",
1189             { 0, 0, NULL, },
1190             { 0, SIZE_MAX, ofp_port_stats_reply },
1191         },
1192         {
1193             OFPST_VENDOR,
1194             "vendor-specific",
1195             { sizeof(uint32_t), SIZE_MAX, vendor_stat },
1196             { sizeof(uint32_t), SIZE_MAX, vendor_stat },
1197         },
1198         {
1199             -1,
1200             "unknown",
1201             { 0, 0, NULL, },
1202             { 0, 0, NULL, },
1203         },
1204     };
1205
1206     const struct stats_type *s;
1207     const struct stats_msg *m;
1208
1209     if (type >= ARRAY_SIZE(stats_types) || !stats_types[type].name) {
1210         ds_put_format(string, " ***unknown type %d***", type);
1211         return;
1212     }
1213     for (s = stats_types; s->type >= 0; s++) {
1214         if (s->type == type) {
1215             break;
1216         }
1217     }
1218     ds_put_format(string, " type=%d(%s)\n", type, s->name);
1219
1220     m = direction == REQUEST ? &s->request : &s->reply;
1221     if (body_len < m->min_body || body_len > m->max_body) {
1222         ds_put_format(string, " ***body_len=%zu not in %zu...%zu***",
1223                       body_len, m->min_body, m->max_body);
1224         return;
1225     }
1226     if (m->printer) {
1227         m->printer(string, body, body_len, verbosity);
1228     }
1229 }
1230
1231 static void
1232 ofp_stats_request(struct ds *string, const void *oh, size_t len, int verbosity)
1233 {
1234     const struct ofp_stats_request *srq = oh;
1235
1236     if (srq->flags) {
1237         ds_put_format(string, " ***unknown flags 0x%04"PRIx16"***",
1238                       ntohs(srq->flags));
1239     }
1240
1241     print_stats(string, ntohs(srq->type), srq->body,
1242                 len - offsetof(struct ofp_stats_request, body),
1243                 verbosity, REQUEST);
1244 }
1245
1246 static void
1247 ofp_stats_reply(struct ds *string, const void *oh, size_t len, int verbosity)
1248 {
1249     const struct ofp_stats_reply *srp = oh;
1250
1251     ds_put_cstr(string, " flags=");
1252     if (!srp->flags) {
1253         ds_put_cstr(string, "none");
1254     } else {
1255         uint16_t flags = ntohs(srp->flags);
1256         if (flags & OFPSF_REPLY_MORE) {
1257             ds_put_cstr(string, "[more]");
1258             flags &= ~OFPSF_REPLY_MORE;
1259         }
1260         if (flags) {
1261             ds_put_format(string, "[***unknown flags 0x%04"PRIx16"***]", flags);
1262         }
1263     }
1264
1265     print_stats(string, ntohs(srp->type), srp->body,
1266                 len - offsetof(struct ofp_stats_reply, body),
1267                 verbosity, REPLY);
1268 }
1269
1270 static void
1271 ofp_echo(struct ds *string, const void *oh, size_t len, int verbosity)
1272 {
1273     const struct ofp_header *hdr = oh;
1274
1275     ds_put_format(string, " %zu bytes of payload\n", len - sizeof *hdr);
1276     if (verbosity > 1) {
1277         ds_put_hex_dump(string, hdr, len - sizeof *hdr, 0, true); 
1278     }
1279 }
1280
1281 struct openflow_packet {
1282     uint8_t type;
1283     const char *name;
1284     size_t min_size;
1285     void (*printer)(struct ds *, const void *, size_t len, int verbosity);
1286 };
1287
1288 static const struct openflow_packet packets[] = {
1289     {
1290         OFPT_HELLO,
1291         "hello",
1292         sizeof (struct ofp_header),
1293         NULL,
1294     },
1295     {
1296         OFPT_FEATURES_REQUEST,
1297         "features_request",
1298         sizeof (struct ofp_header),
1299         NULL,
1300     },
1301     {
1302         OFPT_FEATURES_REPLY,
1303         "features_reply",
1304         sizeof (struct ofp_switch_features),
1305         ofp_print_switch_features,
1306     },
1307     {
1308         OFPT_GET_CONFIG_REQUEST,
1309         "get_config_request",
1310         sizeof (struct ofp_header),
1311         NULL,
1312     },
1313     {
1314         OFPT_GET_CONFIG_REPLY,
1315         "get_config_reply",
1316         sizeof (struct ofp_switch_config),
1317         ofp_print_switch_config,
1318     },
1319     {
1320         OFPT_SET_CONFIG,
1321         "set_config",
1322         sizeof (struct ofp_switch_config),
1323         ofp_print_switch_config,
1324     },
1325     {
1326         OFPT_PACKET_IN,
1327         "packet_in",
1328         offsetof(struct ofp_packet_in, data),
1329         ofp_packet_in,
1330     },
1331     {
1332         OFPT_PACKET_OUT,
1333         "packet_out",
1334         sizeof (struct ofp_packet_out),
1335         ofp_packet_out,
1336     },
1337     {
1338         OFPT_FLOW_MOD,
1339         "flow_mod",
1340         sizeof (struct ofp_flow_mod),
1341         ofp_print_flow_mod,
1342     },
1343     {
1344         OFPT_FLOW_EXPIRED,
1345         "flow_expired",
1346         sizeof (struct ofp_flow_expired),
1347         ofp_print_flow_expired,
1348     },
1349     {
1350         OFPT_PORT_MOD,
1351         "port_mod",
1352         sizeof (struct ofp_port_mod),
1353         ofp_print_port_mod,
1354     },
1355     {
1356         OFPT_PORT_STATUS,
1357         "port_status",
1358         sizeof (struct ofp_port_status),
1359         ofp_print_port_status
1360     },
1361     {
1362         OFPT_ERROR,
1363         "error_msg",
1364         sizeof (struct ofp_error_msg),
1365         ofp_print_error_msg,
1366     },
1367     {
1368         OFPT_STATS_REQUEST,
1369         "stats_request",
1370         sizeof (struct ofp_stats_request),
1371         ofp_stats_request,
1372     },
1373     {
1374         OFPT_STATS_REPLY,
1375         "stats_reply",
1376         sizeof (struct ofp_stats_reply),
1377         ofp_stats_reply,
1378     },
1379     {
1380         OFPT_ECHO_REQUEST,
1381         "echo_request",
1382         sizeof (struct ofp_header),
1383         ofp_echo,
1384     },
1385     {
1386         OFPT_ECHO_REPLY,
1387         "echo_reply",
1388         sizeof (struct ofp_header),
1389         ofp_echo,
1390     },
1391 };
1392
1393 /* Composes and returns a string representing the OpenFlow packet of 'len'
1394  * bytes at 'oh' at the given 'verbosity' level.  0 is a minimal amount of
1395  * verbosity and higher numbers increase verbosity.  The caller is responsible
1396  * for freeing the string. */
1397 char *
1398 ofp_to_string(const void *oh_, size_t len, int verbosity)
1399 {
1400     struct ds string = DS_EMPTY_INITIALIZER;
1401     const struct ofp_header *oh = oh_;
1402     const struct openflow_packet *pkt;
1403
1404     if (len < sizeof(struct ofp_header)) {
1405         ds_put_cstr(&string, "OpenFlow packet too short:\n");
1406         ds_put_hex_dump(&string, oh, len, 0, true);
1407         return ds_cstr(&string);
1408     } else if (oh->version != OFP_VERSION) {
1409         ds_put_format(&string, "Bad OpenFlow version %"PRIu8":\n", oh->version);
1410         ds_put_hex_dump(&string, oh, len, 0, true);
1411         return ds_cstr(&string);
1412     }
1413
1414     for (pkt = packets; ; pkt++) {
1415         if (pkt >= &packets[ARRAY_SIZE(packets)]) {
1416             ds_put_format(&string, "Unknown OpenFlow packet type %"PRIu8":\n",
1417                           oh->type);
1418             ds_put_hex_dump(&string, oh, len, 0, true);
1419             return ds_cstr(&string);
1420         } else if (oh->type == pkt->type) {
1421             break;
1422         }
1423     }
1424
1425     ds_put_format(&string, "%s (xid=0x%"PRIx32"):", pkt->name, oh->xid);
1426
1427     if (ntohs(oh->length) > len)
1428         ds_put_format(&string, " (***truncated to %zu bytes from %"PRIu16"***)",
1429                 len, ntohs(oh->length));
1430     else if (ntohs(oh->length) < len) {
1431         ds_put_format(&string, " (***only uses %"PRIu16" bytes out of %zu***)\n",
1432                 ntohs(oh->length), len);
1433         len = ntohs(oh->length);
1434     }
1435
1436     if (len < pkt->min_size) {
1437         ds_put_format(&string, " (***length=%zu < min_size=%zu***)\n",
1438                 len, pkt->min_size);
1439     } else if (!pkt->printer) {
1440         if (len > sizeof *oh) {
1441             ds_put_format(&string, " length=%"PRIu16" (decoder not implemented)\n",
1442                           ntohs(oh->length)); 
1443         }
1444     } else {
1445         pkt->printer(&string, oh, len, verbosity);
1446     }
1447     if (verbosity >= 3) {
1448         ds_put_hex_dump(&string, oh, len, 0, true);
1449     }
1450     if (string.string[string.length - 1] != '\n') {
1451         ds_put_char(&string, '\n');
1452     }
1453     return ds_cstr(&string);
1454 }
1455 \f
1456 static void
1457 print_and_free(FILE *stream, char *string) 
1458 {
1459     fputs(string, stream);
1460     free(string);
1461 }
1462
1463 /* Pretty-print the OpenFlow packet of 'len' bytes at 'oh' to 'stream' at the
1464  * given 'verbosity' level.  0 is a minimal amount of verbosity and higher
1465  * numbers increase verbosity. */
1466 void
1467 ofp_print(FILE *stream, const void *oh, size_t len, int verbosity)
1468 {
1469     print_and_free(stream, ofp_to_string(oh, len, verbosity));
1470 }
1471
1472 /* Dumps the contents of the Ethernet frame in the 'len' bytes starting at
1473  * 'data' to 'stream' using tcpdump.  'total_len' specifies the full length of
1474  * the Ethernet frame (of which 'len' bytes were captured).
1475  *
1476  * This starts and kills a tcpdump subprocess so it's quite expensive. */
1477 void
1478 ofp_print_packet(FILE *stream, const void *data, size_t len, size_t total_len)
1479 {
1480     print_and_free(stream, ofp_packet_to_string(data, len, total_len));
1481 }