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