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