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