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