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