Add new functions for pretty-printing an OpenFlow message to a string.
[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 "ofp-print.h"
35 #include "xtoxll.h"
36
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <sys/wait.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <ctype.h>
44
45 #include "compiler.h"
46 #include "dynamic-string.h"
47 #include "util.h"
48 #include "openflow.h"
49 #include "packets.h"
50
51 /* Returns a string that represents the contents of the Ethernet frame in the
52  * 'len' bytes starting at 'data' to 'stream' as output by tcpdump.
53  * 'total_len' specifies the full length of the Ethernet frame (of which 'len'
54  * bytes were captured).
55  *
56  * The caller must free the returned string.
57  *
58  * This starts and kills a tcpdump subprocess so it's quite expensive. */
59 char *
60 ofp_packet_to_string(const void *data, size_t len, size_t total_len)
61 {
62     struct pcap_hdr {
63         uint32_t magic_number;   /* magic number */
64         uint16_t version_major;  /* major version number */
65         uint16_t version_minor;  /* minor version number */
66         int32_t thiszone;        /* GMT to local correction */
67         uint32_t sigfigs;        /* accuracy of timestamps */
68         uint32_t snaplen;        /* max length of captured packets */
69         uint32_t network;        /* data link type */
70     } PACKED;
71
72     struct pcaprec_hdr {
73         uint32_t ts_sec;         /* timestamp seconds */
74         uint32_t ts_usec;        /* timestamp microseconds */
75         uint32_t incl_len;       /* number of octets of packet saved in file */
76         uint32_t orig_len;       /* actual length of packet */
77     } PACKED;
78
79     struct pcap_hdr ph;
80     struct pcaprec_hdr prh;
81
82     struct ds ds = DS_EMPTY_INITIALIZER;
83
84     char command[128];
85     FILE *pcap;
86     FILE *tcpdump;
87     int status;
88     int c;
89
90     pcap = tmpfile();
91     if (!pcap) {
92         error(errno, "tmpfile");
93         return xstrdup("<error>");
94     }
95
96     /* The pcap reader is responsible for figuring out endianness based on the
97      * magic number, so the lack of htonX calls here is intentional. */
98     ph.magic_number = 0xa1b2c3d4;
99     ph.version_major = 2;
100     ph.version_minor = 4;
101     ph.thiszone = 0;
102     ph.sigfigs = 0;
103     ph.snaplen = 1518;
104     ph.network = 1;             /* Ethernet */
105
106     prh.ts_sec = 0;
107     prh.ts_usec = 0;
108     prh.incl_len = len;
109     prh.orig_len = total_len;
110
111     fwrite(&ph, 1, sizeof ph, pcap);
112     fwrite(&prh, 1, sizeof prh, pcap);
113     fwrite(data, 1, len, pcap);
114
115     fflush(pcap);
116     if (ferror(pcap)) {
117         error(errno, "error writing temporary file");
118     }
119     rewind(pcap);
120
121     snprintf(command, sizeof command, "tcpdump -n -r /dev/fd/%d 2>/dev/null",
122              fileno(pcap));
123     tcpdump = popen(command, "r");
124     fclose(pcap);
125     if (!tcpdump) {
126         error(errno, "exec(\"%s\")", command);
127         return xstrdup("<error>");
128     }
129
130     while ((c = getc(tcpdump)) != EOF) {
131         ds_put_char(&ds, c);
132     }
133
134     status = pclose(tcpdump);
135     if (WIFEXITED(status)) {
136         if (WEXITSTATUS(status))
137             error(0, "tcpdump exited with status %d", WEXITSTATUS(status));
138     } else if (WIFSIGNALED(status)) {
139         error(0, "tcpdump exited with signal %d", WTERMSIG(status)); 
140     }
141     return ds_cstr(&ds);
142 }
143
144 /* Pretty-print the OFPT_PACKET_IN packet of 'len' bytes at 'oh' to 'stream'
145  * at the given 'verbosity' level. */
146 static void
147 ofp_packet_in(struct ds *string, const void *oh, size_t len, int verbosity)
148 {
149     const struct ofp_packet_in *op = oh;
150     size_t data_len;
151
152     ds_put_format(string, " total_len=%"PRIu16" in_port=%"PRIu8,
153             ntohs(op->total_len), ntohs(op->in_port));
154
155     if (op->reason == OFPR_ACTION)
156         ds_put_cstr(string, " (via action)");
157     else if (op->reason != OFPR_NO_MATCH)
158         ds_put_format(string, " (***reason %"PRIu8"***)", op->reason);
159
160     data_len = len - offsetof(struct ofp_packet_in, data);
161     ds_put_format(string, " data_len=%zu", data_len);
162     if (htonl(op->buffer_id) == UINT32_MAX) {
163         ds_put_format(string, " (unbuffered)");
164         if (ntohs(op->total_len) != data_len)
165             ds_put_format(string, " (***total_len != data_len***)");
166     } else {
167         ds_put_format(string, " buffer=%08"PRIx32, ntohl(op->buffer_id));
168         if (ntohs(op->total_len) < data_len)
169             ds_put_format(string, " (***total_len < data_len***)");
170     }
171     ds_put_char(string, '\n');
172
173     if (verbosity > 0) {
174         char *packet = ofp_packet_to_string(op->data, data_len,
175                                             ntohs(op->total_len)); 
176         ds_put_cstr(string, packet);
177         free(packet);
178     }
179 }
180
181 static void ofp_print_port_name(struct ds *string, uint16_t port) 
182 {
183     if (port == UINT16_MAX) {
184         ds_put_cstr(string, "none");
185     } else if (port == OFPP_FLOOD) {
186         ds_put_cstr(string, "flood");
187     } else if (port == OFPP_CONTROLLER) {
188         ds_put_cstr(string, "controller");
189     } else {
190         ds_put_format(string, "%"PRIu16, port);
191     }
192 }
193
194 static void
195 ofp_print_action(struct ds *string, const struct ofp_action *a) 
196 {
197     switch (ntohs(a->type)) {
198     case OFPAT_OUTPUT:
199         ds_put_cstr(string, "output(");
200         ofp_print_port_name(string, ntohs(a->arg.output.port));
201         if (a->arg.output.port == htons(OFPP_CONTROLLER)) {
202             ds_put_format(string, ", max %"PRIu16" bytes", ntohs(a->arg.output.max_len));
203         }
204         ds_put_cstr(string, ")");
205         break;
206
207     default:
208         ds_put_format(string, "(decoder %"PRIu16" not implemented)", ntohs(a->type));
209         break;
210     }
211 }
212
213 static void ofp_print_actions(struct ds *string,
214                               const struct ofp_action actions[],
215                               size_t n_bytes) 
216 {
217     size_t i;
218
219     ds_put_cstr(string, " actions[");
220     for (i = 0; i < n_bytes / sizeof *actions; i++) {
221         if (i) {
222             ds_put_cstr(string, "; ");
223         }
224         ofp_print_action(string, &actions[i]);
225     }
226     if (n_bytes % sizeof *actions) {
227         if (i) {
228             ds_put_cstr(string, "; ");
229         }
230         ds_put_cstr(string, "; ***trailing garbage***");
231     }
232     ds_put_cstr(string, "]");
233 }
234
235 /* Pretty-print the OFPT_PACKET_OUT packet of 'len' bytes at 'oh' to 'string'
236  * at the given 'verbosity' level. */
237 static void ofp_packet_out(struct ds *string, const void *oh, size_t len,
238                            int verbosity) 
239 {
240     const struct ofp_packet_out *opo = oh;
241
242     ds_put_cstr(string, " in_port=");
243     ofp_print_port_name(string, ntohs(opo->in_port));
244
245     if (ntohl(opo->buffer_id) == UINT32_MAX) {
246         ds_put_cstr(string, " out_port=");
247         ofp_print_port_name(string, ntohs(opo->out_port));
248         if (verbosity > 0 && len > sizeof *opo) {
249             char *packet = ofp_packet_to_string(opo->u.data, len - sizeof *opo,
250                                                 len - sizeof *opo);
251             ds_put_cstr(string, packet);
252             free(packet);
253         }
254     } else {
255         ds_put_format(string, " buffer=%08"PRIx32, ntohl(opo->buffer_id));
256         ofp_print_actions(string, opo->u.actions, len - sizeof *opo);
257     }
258     ds_put_char(string, '\n');
259 }
260
261 /* qsort comparison function. */
262 static int
263 compare_ports(const void *a_, const void *b_)
264 {
265     const struct ofp_phy_port *a = a_;
266     const struct ofp_phy_port *b = b_;
267     uint16_t ap = ntohs(a->port_no);
268     uint16_t bp = ntohs(b->port_no);
269
270     return ap < bp ? -1 : ap > bp;
271 }
272
273 static void
274 ofp_print_phy_port(struct ds *string, const struct ofp_phy_port *port)
275 {
276     uint8_t name[OFP_MAX_PORT_NAME_LEN];
277     int j;
278
279     memcpy(name, port->name, sizeof name);
280     for (j = 0; j < sizeof name - 1; j++) {
281         if (!isprint(name[j])) {
282             break;
283         }
284     }
285     name[j] = '\0';
286
287     ds_put_format(string, " %2d(%s): addr:"ETH_ADDR_FMT", speed:%d, flags:%#x, "
288             "feat:%#x\n", ntohs(port->port_no), name, 
289             ETH_ADDR_ARGS(port->hw_addr), ntohl(port->speed),
290             ntohl(port->flags), ntohl(port->features));
291 }
292
293 /* Pretty-print the OFPT_DATA_HELLO packet of 'len' bytes at 'oh' to 'stream'
294  * at the given 'verbosity' level. */
295 void ofp_print_data_hello(struct ds *string, const void *oh, size_t len, 
296         int verbosity)
297 {
298     const struct ofp_data_hello *odh = oh;
299     struct ofp_phy_port port_list[OFPP_MAX];
300     int n_ports;
301     int i;
302
303
304     ds_put_format(string, "dp id:%"PRIx64"\n", ntohll(odh->datapath_id));
305     ds_put_format(string, "tables: exact:%d, mac:%d, compressed:%d, general:%d\n",
306            ntohl(odh->n_exact), ntohl(odh->n_mac_only),
307            ntohl(odh->n_compression), ntohl(odh->n_general));
308     ds_put_format(string, "buffers: size:%d, number:%d, miss_len:%d\n",
309            ntohl(odh->buffer_mb), ntohl(odh->n_buffers),
310            ntohs(odh->miss_send_len));
311     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
312            ntohl(odh->capabilities), ntohl(odh->actions));
313
314     if (ntohs(odh->header.length) >= sizeof *odh) {
315         len = MIN(len, ntohs(odh->header.length));
316     }
317     n_ports = (len - sizeof *odh) / sizeof *odh->ports;
318
319     memcpy(port_list, odh->ports, (len - sizeof *odh));
320     qsort(port_list, n_ports, sizeof port_list[0], compare_ports);
321     for (i = 0; i < n_ports; i++) {
322         ofp_print_phy_port(string, &port_list[i]);
323     }
324 }
325
326 static void print_wild(struct ds *string, const char *leader, int is_wild,
327             const char *format, ...) __attribute__((format(printf, 4, 5)));
328
329 static void print_wild(struct ds *string, const char *leader, int is_wild,
330                        const char *format, ...) 
331 {
332     ds_put_cstr(string, leader);
333     if (!is_wild) {
334         va_list args;
335
336         va_start(args, format);
337         ds_put_format_valist(string, format, args);
338         va_end(args);
339     } else {
340         ds_put_char(string, '?');
341     }
342 }
343
344 /* Pretty-print the ofp_match structure */
345 static void ofp_print_match(struct ds *f, const struct ofp_match *om)
346 {
347     uint16_t w = ntohs(om->wildcards);
348
349     print_wild(f, "inport", w & OFPFW_IN_PORT, "%04x", ntohs(om->in_port));
350     print_wild(f, ":vlan", w & OFPFW_DL_VLAN, "%04x", ntohs(om->dl_vlan));
351     print_wild(f, " mac[", w & OFPFW_DL_SRC,
352                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_src));
353     print_wild(f, "->", w & OFPFW_DL_DST,
354                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_dst));
355     print_wild(f, "] type", w & OFPFW_DL_TYPE, "%04x", ntohs(om->dl_type));
356     print_wild(f, " ip[", w & OFPFW_NW_SRC, IP_FMT, IP_ARGS(&om->nw_src));
357     print_wild(f, "->", w & OFPFW_NW_DST, IP_FMT, IP_ARGS(&om->nw_dst));
358     print_wild(f, "] proto", w & OFPFW_NW_PROTO, "%u", om->nw_proto);
359     print_wild(f, " tport[", w & OFPFW_TP_SRC, "%d", ntohs(om->tp_src));
360     print_wild(f, "->", w & OFPFW_TP_DST, "%d", ntohs(om->tp_dst));
361     ds_put_cstr(f, "]\n");
362 }
363
364 /* Pretty-print the OFPT_FLOW_MOD packet of 'len' bytes at 'oh' to 'string'
365  * at the given 'verbosity' level. */
366 static void
367 ofp_print_flow_mod(struct ds *string, const void *oh, size_t len, 
368                    int verbosity)
369 {
370     const struct ofp_flow_mod *ofm = oh;
371
372     ofp_print_match(string, &ofm->match);
373     ds_put_format(string, " cmd:%d idle:%d buf:%#x grp:%d\n", ntohs(ofm->command),
374          ntohs(ofm->max_idle), ntohl(ofm->buffer_id), ntohl(ofm->group_id));
375 }
376
377 /* Pretty-print the OFPT_FLOW_EXPIRED packet of 'len' bytes at 'oh' to 'string'
378  * at the given 'verbosity' level. */
379 void ofp_print_flow_expired(struct ds *string, const void *oh, size_t len, 
380         int verbosity)
381 {
382     const struct ofp_flow_expired *ofe = oh;
383
384     ofp_print_match(string, &ofe->match);
385     ds_put_format(string, 
386          " secs%d pkts%lld bytes%lld\n", ntohl(ofe->duration),
387          ntohll(ofe->packet_count), ntohll(ofe->byte_count));
388 }
389
390 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
391  * at the given 'verbosity' level. */
392 void ofp_print_port_status(struct ds *string, const void *oh, size_t len, 
393         int verbosity)
394 {
395     const struct ofp_port_status *ops = oh;
396
397     if (ops->reason == OFPPR_ADD) {
398         ds_put_format(string, "add:");
399     } else if (ops->reason == OFPPR_DELETE) {
400         ds_put_format(string, "del:");
401     } else if (ops->reason == OFPPR_MOD) {
402         ds_put_format(string, "mod:");
403     } else {
404         ds_put_format(string, "err:");
405     }
406
407     ofp_print_phy_port(string, &ops->desc);
408 }
409
410 struct openflow_packet {
411     const char *name;
412     size_t min_size;
413     void (*printer)(struct ds *, const void *, size_t len, int verbosity);
414 };
415
416 static const struct openflow_packet packets[] = {
417     [OFPT_CONTROL_HELLO] = {
418         "ofp_control_hello",
419         sizeof (struct ofp_control_hello),
420         NULL,
421     },
422     [OFPT_DATA_HELLO] = {
423         "ofp_data_hello",
424         sizeof (struct ofp_data_hello),
425         ofp_print_data_hello,
426     },
427     [OFPT_PACKET_IN] = {
428         "ofp_packet_in",
429         offsetof(struct ofp_packet_in, data),
430         ofp_packet_in,
431     },
432     [OFPT_PACKET_OUT] = {
433         "ofp_packet_out",
434         sizeof (struct ofp_packet_out),
435         ofp_packet_out,
436     },
437     [OFPT_FLOW_MOD] = {
438         "ofp_flow_mod",
439         sizeof (struct ofp_flow_mod),
440         ofp_print_flow_mod,
441     },
442     [OFPT_FLOW_EXPIRED] = {
443         "ofp_flow_expired",
444         sizeof (struct ofp_flow_expired),
445         ofp_print_flow_expired,
446     },
447     [OFPT_PORT_MOD] = {
448         "ofp_port_mod",
449         sizeof (struct ofp_port_mod),
450         NULL,
451     },
452     [OFPT_PORT_STATUS] = {
453         "ofp_port_status",
454         sizeof (struct ofp_port_status),
455         ofp_print_port_status
456     },
457 };
458
459 /* Composes and returns a string representing the OpenFlow packet of 'len'
460  * bytes at 'oh' at the given 'verbosity' level.  0 is a minimal amount of
461  * verbosity and higher numbers increase verbosity.  The caller is responsible
462  * for freeing the string. */
463 char *
464 ofp_to_string(const void *oh_, size_t len, int verbosity)
465 {
466     struct ds string = DS_EMPTY_INITIALIZER;
467     const struct ofp_header *oh = oh_;
468     const struct openflow_packet *pkt;
469
470     if (len < sizeof(struct ofp_header)) {
471         ds_put_cstr(&string, "OpenFlow packet too short:\n");
472         ds_put_hex_dump(&string, oh, len, 0, true);
473         return ds_cstr(&string);
474     } else if (oh->version != 1) {
475         ds_put_format(&string, "Bad OpenFlow version %"PRIu8":\n", oh->version);
476         ds_put_hex_dump(&string, oh, len, 0, true);
477         return ds_cstr(&string);
478     } else if (oh->type >= ARRAY_SIZE(packets) || !packets[oh->type].name) {
479         ds_put_format(&string, "Unknown OpenFlow packet type %"PRIu8":\n",
480                 oh->type);
481         ds_put_hex_dump(&string, oh, len, 0, true);
482         return ds_cstr(&string);
483     }
484
485     pkt = &packets[oh->type];
486     ds_put_format(&string, "%s (xid=%"PRIx32"):", pkt->name, oh->xid);
487
488     if (ntohs(oh->length) > len)
489         ds_put_format(&string, " (***truncated to %zu bytes from %"PRIu16"***)",
490                 len, ntohs(oh->length));
491     else if (ntohs(oh->length) < len) {
492         ds_put_format(&string, " (***only uses %"PRIu16" bytes out of %zu***)\n",
493                 ntohs(oh->length), len);
494         len = ntohs(oh->length);
495     }
496
497     if (len < pkt->min_size) {
498         ds_put_format(&string, " (***length=%zu < min_size=%zu***)\n",
499                 len, pkt->min_size);
500     } else if (!pkt->printer) {
501         ds_put_format(&string, " length=%zu (decoder not implemented)\n",
502                 ntohs(oh->length));
503     } else {
504         pkt->printer(&string, oh, len, verbosity);
505     }
506     if (verbosity >= 3) {
507         ds_put_hex_dump(&string, oh, len, 0, true);
508     }
509     return ds_cstr(&string);
510 }
511
512 char *
513 ofp_table_to_string(const struct ofp_table* ot)
514 {
515     return xasprintf("id: %d name: %-8s n_flows: %6d max_flows: %6d",
516                      ntohs(ot->table_id), ot->name, ntohl(ot->n_flows),
517                      ntohl(ot->max_flows));
518 }
519 \f
520 static void
521 print_and_free(FILE *stream, char *string) 
522 {
523     fputs(string, stream);
524     free(string);
525 }
526
527 /* Pretty-print the OpenFlow packet of 'len' bytes at 'oh' to 'stream' at the
528  * given 'verbosity' level.  0 is a minimal amount of verbosity and higher
529  * numbers increase verbosity. */
530 void
531 ofp_print(FILE *stream, const void *oh, size_t len, int verbosity)
532 {
533     print_and_free(stream, ofp_to_string(oh, len, verbosity));
534 }
535
536 /* Pretty print a openflow table */
537 void
538 ofp_print_table(FILE *stream, const struct ofp_table *ot)
539 {
540     print_and_free(stream, ofp_table_to_string(ot));
541 }
542
543 /* Dumps the contents of the Ethernet frame in the 'len' bytes starting at
544  * 'data' to 'stream' using tcpdump.  'total_len' specifies the full length of
545  * the Ethernet frame (of which 'len' bytes were captured).
546  *
547  * This starts and kills a tcpdump subprocess so it's quite expensive. */
548 void
549 ofp_print_packet(FILE *stream, const void *data, size_t len, size_t total_len)
550 {
551     print_and_free(stream, ofp_packet_to_string(data, len, total_len));
552 }