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