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