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