vport: Use EBUSY to represent already attached device.
[sliver-openvswitch.git] / lib / ofp-print.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <sys/wait.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <ctype.h>
28
29 #include "compiler.h"
30 #include "dynamic-string.h"
31 #include "flow.h"
32 #include "ofpbuf.h"
33 #include "openflow/openflow.h"
34 #include "openflow/nicira-ext.h"
35 #include "packets.h"
36 #include "pcap.h"
37 #include "util.h"
38 #include "xtoxll.h"
39
40 static void ofp_print_port_name(struct ds *string, uint16_t port);
41
42 /* Returns a string that represents the contents of the Ethernet frame in the
43  * 'len' bytes starting at 'data' to 'stream' as output by tcpdump.
44  * 'total_len' specifies the full length of the Ethernet frame (of which 'len'
45  * bytes were captured).
46  *
47  * The caller must free the returned string.
48  *
49  * This starts and kills a tcpdump subprocess so it's quite expensive. */
50 char *
51 ofp_packet_to_string(const void *data, size_t len, size_t total_len OVS_UNUSED)
52 {
53     struct ds ds = DS_EMPTY_INITIALIZER;
54     struct ofpbuf buf;
55
56     char command[128];
57     FILE *pcap;
58     FILE *tcpdump;
59     int status;
60     int c;
61
62     buf.data = (void *) data;
63     buf.size = len;
64
65     pcap = tmpfile();
66     if (!pcap) {
67         ovs_error(errno, "tmpfile");
68         return xstrdup("<error>");
69     }
70     pcap_write_header(pcap);
71     pcap_write(pcap, &buf);
72     fflush(pcap);
73     if (ferror(pcap)) {
74         ovs_error(errno, "error writing temporary file");
75     }
76     rewind(pcap);
77
78     snprintf(command, sizeof command, "/usr/sbin/tcpdump -e -n -r /dev/fd/%d 2>/dev/null",
79              fileno(pcap));
80     tcpdump = popen(command, "r");
81     fclose(pcap);
82     if (!tcpdump) {
83         ovs_error(errno, "exec(\"%s\")", command);
84         return xstrdup("<error>");
85     }
86
87     while ((c = getc(tcpdump)) != EOF) {
88         ds_put_char(&ds, c);
89     }
90
91     status = pclose(tcpdump);
92     if (WIFEXITED(status)) {
93         if (WEXITSTATUS(status))
94             ovs_error(0, "tcpdump exited with status %d", WEXITSTATUS(status));
95     } else if (WIFSIGNALED(status)) {
96         ovs_error(0, "tcpdump exited with signal %d", WTERMSIG(status)); 
97     }
98     return ds_cstr(&ds);
99 }
100
101 /* Pretty-print the OFPT_PACKET_IN packet of 'len' bytes at 'oh' to 'stream'
102  * at the given 'verbosity' level. */
103 static void
104 ofp_packet_in(struct ds *string, const void *oh, size_t len, int verbosity)
105 {
106     const struct ofp_packet_in *op = oh;
107     size_t data_len;
108
109     ds_put_format(string, " total_len=%"PRIu16" in_port=",
110                   ntohs(op->total_len));
111     ofp_print_port_name(string, ntohs(op->in_port));
112
113     if (op->reason == OFPR_ACTION)
114         ds_put_cstr(string, " (via action)");
115     else if (op->reason != OFPR_NO_MATCH)
116         ds_put_format(string, " (***reason %"PRIu8"***)", op->reason);
117
118     data_len = len - offsetof(struct ofp_packet_in, data);
119     ds_put_format(string, " data_len=%zu", data_len);
120     if (htonl(op->buffer_id) == UINT32_MAX) {
121         ds_put_format(string, " (unbuffered)");
122         if (ntohs(op->total_len) != data_len)
123             ds_put_format(string, " (***total_len != data_len***)");
124     } else {
125         ds_put_format(string, " buffer=0x%08"PRIx32, ntohl(op->buffer_id));
126         if (ntohs(op->total_len) < data_len)
127             ds_put_format(string, " (***total_len < data_len***)");
128     }
129     ds_put_char(string, '\n');
130
131     if (verbosity > 0) {
132         flow_t flow;
133         struct ofpbuf packet;
134         struct ofp_match match;
135         packet.data = (void *) op->data;
136         packet.size = data_len;
137         flow_extract(&packet, 0, ntohs(op->in_port), &flow);
138         flow_to_match(&flow, 0, false, &match);
139         ofp_print_match(string, &match, verbosity);
140         ds_put_char(string, '\n');
141     }
142     if (verbosity > 1) {
143         char *packet = ofp_packet_to_string(op->data, data_len,
144                                             ntohs(op->total_len)); 
145         ds_put_cstr(string, packet);
146         free(packet);
147     }
148 }
149
150 static void ofp_print_port_name(struct ds *string, uint16_t port) 
151 {
152     const char *name;
153     switch (port) {
154     case OFPP_IN_PORT:
155         name = "IN_PORT";
156         break;
157     case OFPP_TABLE:
158         name = "TABLE";
159         break;
160     case OFPP_NORMAL:
161         name = "NORMAL";
162         break;
163     case OFPP_FLOOD:
164         name = "FLOOD";
165         break;
166     case OFPP_ALL:
167         name = "ALL";
168         break;
169     case OFPP_CONTROLLER:
170         name = "CONTROLLER";
171         break;
172     case OFPP_LOCAL:
173         name = "LOCAL";
174         break;
175     case OFPP_NONE:
176         name = "NONE";
177         break;
178     default:
179         ds_put_format(string, "%"PRIu16, port);
180         return;
181     }
182     ds_put_cstr(string, name);
183 }
184
185 static void
186 ofp_print_nx_action(struct ds *string, const struct nx_action_header *nah)
187 {
188     switch (ntohs(nah->subtype)) {
189     case NXAST_RESUBMIT: {
190         const struct nx_action_resubmit *nar = (struct nx_action_resubmit *)nah;
191         ds_put_format(string, "resubmit:");
192         ofp_print_port_name(string, ntohs(nar->in_port));
193         break;
194     }
195
196     case NXAST_SET_TUNNEL: {
197         const struct nx_action_set_tunnel *nast =
198                                             (struct nx_action_set_tunnel *)nah;
199         ds_put_format(string, "set_tunnel:0x%08"PRIx32, ntohl(nast->tun_id));
200         break;
201     }
202
203     default:
204         ds_put_format(string, "***unknown Nicira action:%d***\n",
205                       ntohs(nah->subtype));
206     }
207 }
208
209 static int
210 ofp_print_action(struct ds *string, const struct ofp_action_header *ah, 
211         size_t actions_len) 
212 {
213     uint16_t type;
214     size_t len;
215
216     struct openflow_action {
217         size_t min_size;
218         size_t max_size;
219     };
220
221     const struct openflow_action of_actions[] = {
222         [OFPAT_OUTPUT] = {
223             sizeof(struct ofp_action_output),
224             sizeof(struct ofp_action_output),
225         },
226         [OFPAT_SET_VLAN_VID] = {
227             sizeof(struct ofp_action_vlan_vid),
228             sizeof(struct ofp_action_vlan_vid),
229         },
230         [OFPAT_SET_VLAN_PCP] = {
231             sizeof(struct ofp_action_vlan_pcp),
232             sizeof(struct ofp_action_vlan_pcp),
233         },
234         [OFPAT_STRIP_VLAN] = {
235             sizeof(struct ofp_action_header),
236             sizeof(struct ofp_action_header),
237         },
238         [OFPAT_SET_DL_SRC] = {
239             sizeof(struct ofp_action_dl_addr),
240             sizeof(struct ofp_action_dl_addr),
241         },
242         [OFPAT_SET_DL_DST] = {
243             sizeof(struct ofp_action_dl_addr),
244             sizeof(struct ofp_action_dl_addr),
245         },
246         [OFPAT_SET_NW_SRC] = {
247             sizeof(struct ofp_action_nw_addr),
248             sizeof(struct ofp_action_nw_addr),
249         },
250         [OFPAT_SET_NW_DST] = {
251             sizeof(struct ofp_action_nw_addr),
252             sizeof(struct ofp_action_nw_addr),
253         },
254         [OFPAT_SET_NW_TOS] = {
255             sizeof(struct ofp_action_nw_tos),
256             sizeof(struct ofp_action_nw_tos),
257         },
258         [OFPAT_SET_TP_SRC] = {
259             sizeof(struct ofp_action_tp_port),
260             sizeof(struct ofp_action_tp_port),
261         },
262         [OFPAT_SET_TP_DST] = {
263             sizeof(struct ofp_action_tp_port),
264             sizeof(struct ofp_action_tp_port),
265         }
266         /* OFPAT_VENDOR is not here, since it would blow up the array size. */
267     };
268
269     if (actions_len < sizeof *ah) {
270         ds_put_format(string, "***action array too short for next action***\n");
271         return -1;
272     }
273
274     type = ntohs(ah->type);
275     len = ntohs(ah->len);
276     if (actions_len < len) {
277         ds_put_format(string, "***truncated action %"PRIu16"***\n", type);
278         return -1;
279     }
280
281     if ((len % 8) != 0) {
282         ds_put_format(string, 
283                 "***action %"PRIu16" length not a multiple of 8***\n",
284                 type);
285         return -1;
286     }
287
288     if (type < ARRAY_SIZE(of_actions)) {
289         const struct openflow_action *act = &of_actions[type];
290         if ((len < act->min_size) || (len > act->max_size)) {
291             ds_put_format(string, 
292                     "***action %"PRIu16" wrong length: %zu***\n", type, len);
293             return -1;
294         }
295     }
296     
297     switch (type) {
298     case OFPAT_OUTPUT: {
299         struct ofp_action_output *oa = (struct ofp_action_output *)ah;
300         uint16_t port = ntohs(oa->port); 
301         if (port < OFPP_MAX) {
302             ds_put_format(string, "output:%"PRIu16, port);
303         } else {
304             ofp_print_port_name(string, port);
305             if (port == OFPP_CONTROLLER) {
306                 if (oa->max_len) {
307                     ds_put_format(string, ":%"PRIu16, ntohs(oa->max_len));
308                 } else {
309                     ds_put_cstr(string, ":all");
310                 }
311             }
312         }
313         break;
314     }
315
316     case OFPAT_SET_VLAN_VID: {
317         struct ofp_action_vlan_vid *va = (struct ofp_action_vlan_vid *)ah;
318         ds_put_format(string, "mod_vlan_vid:%"PRIu16, ntohs(va->vlan_vid));
319         break;
320     }
321
322     case OFPAT_SET_VLAN_PCP: {
323         struct ofp_action_vlan_pcp *va = (struct ofp_action_vlan_pcp *)ah;
324         ds_put_format(string, "mod_vlan_pcp:%"PRIu8, va->vlan_pcp);
325         break;
326     }
327
328     case OFPAT_STRIP_VLAN:
329         ds_put_cstr(string, "strip_vlan");
330         break;
331
332     case OFPAT_SET_DL_SRC: {
333         struct ofp_action_dl_addr *da = (struct ofp_action_dl_addr *)ah;
334         ds_put_format(string, "mod_dl_src:"ETH_ADDR_FMT, 
335                 ETH_ADDR_ARGS(da->dl_addr));
336         break;
337     }
338
339     case OFPAT_SET_DL_DST: {
340         struct ofp_action_dl_addr *da = (struct ofp_action_dl_addr *)ah;
341         ds_put_format(string, "mod_dl_dst:"ETH_ADDR_FMT, 
342                 ETH_ADDR_ARGS(da->dl_addr));
343         break;
344     }
345
346     case OFPAT_SET_NW_SRC: {
347         struct ofp_action_nw_addr *na = (struct ofp_action_nw_addr *)ah;
348         ds_put_format(string, "mod_nw_src:"IP_FMT, IP_ARGS(&na->nw_addr));
349         break;
350     }
351
352     case OFPAT_SET_NW_DST: {
353         struct ofp_action_nw_addr *na = (struct ofp_action_nw_addr *)ah;
354         ds_put_format(string, "mod_nw_dst:"IP_FMT, IP_ARGS(&na->nw_addr));
355         break;
356     }
357
358     case OFPAT_SET_NW_TOS: {
359         struct ofp_action_nw_tos *nt = (struct ofp_action_nw_tos *)ah;
360         ds_put_format(string, "mod_nw_tos:%d", nt->nw_tos);
361         break;
362     }
363
364     case OFPAT_SET_TP_SRC: {
365         struct ofp_action_tp_port *ta = (struct ofp_action_tp_port *)ah;
366         ds_put_format(string, "mod_tp_src:%d", ntohs(ta->tp_port));
367         break;
368     }
369
370     case OFPAT_SET_TP_DST: {
371         struct ofp_action_tp_port *ta = (struct ofp_action_tp_port *)ah;
372         ds_put_format(string, "mod_tp_dst:%d", ntohs(ta->tp_port));
373         break;
374     }
375
376     case OFPAT_VENDOR: {
377         struct ofp_action_vendor_header *avh 
378                 = (struct ofp_action_vendor_header *)ah;
379         if (len < sizeof *avh) {
380             ds_put_format(string, "***ofpat_vendor truncated***\n");
381             return -1;
382         }
383         if (avh->vendor == htonl(NX_VENDOR_ID)) {
384             ofp_print_nx_action(string, (struct nx_action_header *)avh);
385         } else {
386             ds_put_format(string, "vendor action:0x%x", ntohl(avh->vendor));
387         }
388         break;
389     }
390
391     default:
392         ds_put_format(string, "(decoder %"PRIu16" not implemented)", type);
393         break;
394     }
395
396     return len;
397 }
398
399 void 
400 ofp_print_actions(struct ds *string, const struct ofp_action_header *action,
401                   size_t actions_len) 
402 {
403     uint8_t *p = (uint8_t *)action;
404     int len = 0;
405
406     ds_put_cstr(string, "actions=");
407     if (!actions_len) {
408         ds_put_cstr(string, "drop");
409     }
410     while (actions_len > 0) {
411         if (len) {
412             ds_put_cstr(string, ",");
413         }
414         len = ofp_print_action(string, (struct ofp_action_header *)p, 
415                 actions_len);
416         if (len < 0) {
417             return;
418         }
419         p += len;
420         actions_len -= len;
421     }
422 }
423
424 /* Pretty-print the OFPT_PACKET_OUT packet of 'len' bytes at 'oh' to 'string'
425  * at the given 'verbosity' level. */
426 static void ofp_packet_out(struct ds *string, const void *oh, size_t len,
427                            int verbosity) 
428 {
429     const struct ofp_packet_out *opo = oh;
430     size_t actions_len = ntohs(opo->actions_len);
431
432     ds_put_cstr(string, " in_port=");
433     ofp_print_port_name(string, ntohs(opo->in_port));
434
435     ds_put_format(string, " actions_len=%zu ", actions_len);
436     if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
437         ds_put_format(string, "***packet too short for action length***\n");
438         return;
439     }
440     ofp_print_actions(string, opo->actions, actions_len);
441
442     if (ntohl(opo->buffer_id) == UINT32_MAX) {
443         int data_len = len - sizeof *opo - actions_len;
444         ds_put_format(string, " data_len=%d", data_len);
445         if (verbosity > 0 && len > sizeof *opo) {
446             char *packet = ofp_packet_to_string(
447                     (uint8_t *)opo->actions + actions_len, data_len, data_len);
448             ds_put_char(string, '\n');
449             ds_put_cstr(string, packet);
450             free(packet);
451         }
452     } else {
453         ds_put_format(string, " buffer=0x%08"PRIx32, ntohl(opo->buffer_id));
454     }
455     ds_put_char(string, '\n');
456 }
457
458 /* qsort comparison function. */
459 static int
460 compare_ports(const void *a_, const void *b_)
461 {
462     const struct ofp_phy_port *a = a_;
463     const struct ofp_phy_port *b = b_;
464     uint16_t ap = ntohs(a->port_no);
465     uint16_t bp = ntohs(b->port_no);
466
467     return ap < bp ? -1 : ap > bp;
468 }
469
470 static void ofp_print_port_features(struct ds *string, uint32_t features)
471 {
472     if (features == 0) {
473         ds_put_cstr(string, "Unsupported\n");
474         return;
475     }
476     if (features & OFPPF_10MB_HD) {
477         ds_put_cstr(string, "10MB-HD ");
478     }
479     if (features & OFPPF_10MB_FD) {
480         ds_put_cstr(string, "10MB-FD ");
481     }
482     if (features & OFPPF_100MB_HD) {
483         ds_put_cstr(string, "100MB-HD ");
484     }
485     if (features & OFPPF_100MB_FD) {
486         ds_put_cstr(string, "100MB-FD ");
487     }
488     if (features & OFPPF_1GB_HD) {
489         ds_put_cstr(string, "1GB-HD ");
490     }
491     if (features & OFPPF_1GB_FD) {
492         ds_put_cstr(string, "1GB-FD ");
493     }
494     if (features & OFPPF_10GB_FD) {
495         ds_put_cstr(string, "10GB-FD ");
496     }
497     if (features & OFPPF_COPPER) {
498         ds_put_cstr(string, "COPPER ");
499     }
500     if (features & OFPPF_FIBER) {
501         ds_put_cstr(string, "FIBER ");
502     }
503     if (features & OFPPF_AUTONEG) {
504         ds_put_cstr(string, "AUTO_NEG ");
505     }
506     if (features & OFPPF_PAUSE) {
507         ds_put_cstr(string, "AUTO_PAUSE ");
508     }
509     if (features & OFPPF_PAUSE_ASYM) {
510         ds_put_cstr(string, "AUTO_PAUSE_ASYM ");
511     }
512     ds_put_char(string, '\n');
513 }
514
515 static void
516 ofp_print_phy_port(struct ds *string, const struct ofp_phy_port *port)
517 {
518     uint8_t name[OFP_MAX_PORT_NAME_LEN];
519     int j;
520
521     memcpy(name, port->name, sizeof name);
522     for (j = 0; j < sizeof name - 1; j++) {
523         if (!isprint(name[j])) {
524             break;
525         }
526     }
527     name[j] = '\0';
528
529     ds_put_char(string, ' ');
530     ofp_print_port_name(string, ntohs(port->port_no));
531     ds_put_format(string, "(%s): addr:"ETH_ADDR_FMT", config: %#x, state:%#x\n",
532             name, ETH_ADDR_ARGS(port->hw_addr), ntohl(port->config),
533             ntohl(port->state));
534     if (port->curr) {
535         ds_put_format(string, "     current:    ");
536         ofp_print_port_features(string, ntohl(port->curr));
537     }
538     if (port->advertised) {
539         ds_put_format(string, "     advertised: ");
540         ofp_print_port_features(string, ntohl(port->advertised));
541     }
542     if (port->supported) {
543         ds_put_format(string, "     supported:  ");
544         ofp_print_port_features(string, ntohl(port->supported));
545     }
546     if (port->peer) {
547         ds_put_format(string, "     peer:       ");
548         ofp_print_port_features(string, ntohl(port->peer));
549     }
550 }
551
552 /* Pretty-print the struct ofp_switch_features of 'len' bytes at 'oh' to
553  * 'string' at the given 'verbosity' level. */
554 static void
555 ofp_print_switch_features(struct ds *string, const void *oh, size_t len,
556                           int verbosity OVS_UNUSED)
557 {
558     const struct ofp_switch_features *osf = oh;
559     struct ofp_phy_port *port_list;
560     int n_ports;
561     int i;
562
563     ds_put_format(string, " ver:0x%x, dpid:%016"PRIx64"\n", 
564             osf->header.version, ntohll(osf->datapath_id));
565     ds_put_format(string, "n_tables:%d, n_buffers:%d\n", osf->n_tables,
566             ntohl(osf->n_buffers));
567     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
568            ntohl(osf->capabilities), ntohl(osf->actions));
569
570     if (ntohs(osf->header.length) >= sizeof *osf) {
571         len = MIN(len, ntohs(osf->header.length));
572     }
573     n_ports = (len - sizeof *osf) / sizeof *osf->ports;
574
575     port_list = xmemdup(osf->ports, len - sizeof *osf); 
576     qsort(port_list, n_ports, sizeof *port_list, compare_ports);
577     for (i = 0; i < n_ports; i++) {
578         ofp_print_phy_port(string, &port_list[i]);
579     }
580     free(port_list);
581 }
582
583 /* Pretty-print the struct ofp_switch_config of 'len' bytes at 'oh' to 'string'
584  * at the given 'verbosity' level. */
585 static void
586 ofp_print_switch_config(struct ds *string, const void *oh,
587                         size_t len OVS_UNUSED, int verbosity OVS_UNUSED)
588 {
589     const struct ofp_switch_config *osc = oh;
590     uint16_t flags;
591
592     flags = ntohs(osc->flags);
593     if (flags) {
594         ds_put_format(string, " ***unknown flags 0x%04"PRIx16"***", flags);
595     }
596
597     ds_put_format(string, " miss_send_len=%"PRIu16"\n", ntohs(osc->miss_send_len));
598 }
599
600 static void print_wild(struct ds *string, const char *leader, int is_wild,
601             int verbosity, const char *format, ...) 
602             __attribute__((format(printf, 5, 6)));
603
604 static void print_wild(struct ds *string, const char *leader, int is_wild,
605                        int verbosity, const char *format, ...) 
606 {
607     if (is_wild && verbosity < 2) {
608         return;
609     }
610     ds_put_cstr(string, leader);
611     if (!is_wild) {
612         va_list args;
613
614         va_start(args, format);
615         ds_put_format_valist(string, format, args);
616         va_end(args);
617     } else {
618         ds_put_char(string, '*');
619     }
620     ds_put_char(string, ',');
621 }
622
623 static void
624 print_ip_netmask(struct ds *string, const char *leader, uint32_t ip,
625                  uint32_t wild_bits, int verbosity)
626 {
627     if (wild_bits >= 32 && verbosity < 2) {
628         return;
629     }
630     ds_put_cstr(string, leader);
631     if (wild_bits < 32) {
632         ds_put_format(string, IP_FMT, IP_ARGS(&ip));
633         if (wild_bits) {
634             ds_put_format(string, "/%d", 32 - wild_bits);
635         }
636     } else {
637         ds_put_char(string, '*');
638     }
639     ds_put_char(string, ',');
640 }
641
642 void
643 ofp_print_match(struct ds *f, const struct ofp_match *om, int verbosity)
644 {
645     char *s = ofp_match_to_string(om, verbosity);
646     ds_put_cstr(f, s);
647     free(s);
648 }
649
650 char *
651 ofp_match_to_string(const struct ofp_match *om, int verbosity)
652 {
653     struct ds f = DS_EMPTY_INITIALIZER;
654     uint32_t w = ntohl(om->wildcards);
655     bool skip_type = false;
656     bool skip_proto = false;
657
658     if (!(w & OFPFW_DL_TYPE)) {
659         skip_type = true;
660         if (om->dl_type == htons(ETH_TYPE_IP)) {
661             if (!(w & OFPFW_NW_PROTO)) {
662                 skip_proto = true;
663                 if (om->nw_proto == IP_TYPE_ICMP) {
664                     ds_put_cstr(&f, "icmp,");
665                 } else if (om->nw_proto == IP_TYPE_TCP) {
666                     ds_put_cstr(&f, "tcp,");
667                 } else if (om->nw_proto == IP_TYPE_UDP) {
668                     ds_put_cstr(&f, "udp,");
669                 } else {
670                     ds_put_cstr(&f, "ip,");
671                     skip_proto = false;
672                 }
673             } else {
674                 ds_put_cstr(&f, "ip,");
675             }
676         } else if (om->dl_type == htons(ETH_TYPE_ARP)) {
677             ds_put_cstr(&f, "arp,");
678         } else {
679             skip_type = false;
680         }
681     }
682     if (w & NXFW_TUN_ID) {
683         ds_put_cstr(&f, "tun_id_wild,");
684     }
685     print_wild(&f, "in_port=", w & OFPFW_IN_PORT, verbosity,
686                "%d", ntohs(om->in_port));
687     print_wild(&f, "dl_vlan=", w & OFPFW_DL_VLAN, verbosity,
688                "%d", ntohs(om->dl_vlan));
689     print_wild(&f, "dl_vlan_pcp=", w & OFPFW_DL_VLAN_PCP, verbosity,
690                "%d", om->dl_vlan_pcp);
691     print_wild(&f, "dl_src=", w & OFPFW_DL_SRC, verbosity,
692                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_src));
693     print_wild(&f, "dl_dst=", w & OFPFW_DL_DST, verbosity,
694                ETH_ADDR_FMT, ETH_ADDR_ARGS(om->dl_dst));
695     if (!skip_type) {
696         print_wild(&f, "dl_type=", w & OFPFW_DL_TYPE, verbosity,
697                    "0x%04x", ntohs(om->dl_type));
698     }
699     print_ip_netmask(&f, "nw_src=", om->nw_src,
700                      (w & OFPFW_NW_SRC_MASK) >> OFPFW_NW_SRC_SHIFT, verbosity);
701     print_ip_netmask(&f, "nw_dst=", om->nw_dst,
702                      (w & OFPFW_NW_DST_MASK) >> OFPFW_NW_DST_SHIFT, verbosity);
703     if (!skip_proto) {
704         if (om->dl_type == htons(ETH_TYPE_ARP)) {
705             print_wild(&f, "opcode=", w & OFPFW_NW_PROTO, verbosity,
706                        "%u", om->nw_proto);
707         } else {
708             print_wild(&f, "nw_proto=", w & OFPFW_NW_PROTO, verbosity,
709                        "%u", om->nw_proto);
710             print_wild(&f, "nw_tos=", w & OFPFW_NW_TOS, verbosity,
711                        "%u", om->nw_tos);
712         }
713     }
714     if (om->nw_proto == IP_TYPE_ICMP) {
715         print_wild(&f, "icmp_type=", w & OFPFW_ICMP_TYPE, verbosity,
716                    "%d", ntohs(om->icmp_type));
717         print_wild(&f, "icmp_code=", w & OFPFW_ICMP_CODE, verbosity,
718                    "%d", ntohs(om->icmp_code));
719     } else {
720         print_wild(&f, "tp_src=", w & OFPFW_TP_SRC, verbosity,
721                    "%d", ntohs(om->tp_src));
722         print_wild(&f, "tp_dst=", w & OFPFW_TP_DST, verbosity,
723                    "%d", ntohs(om->tp_dst));
724     }
725     return ds_cstr(&f);
726 }
727
728 /* Pretty-print the OFPT_FLOW_MOD packet of 'len' bytes at 'oh' to 'string'
729  * at the given 'verbosity' level. */
730 static void
731 ofp_print_flow_mod(struct ds *string, const void *oh, size_t len, 
732                    int verbosity)
733 {
734     const struct ofp_flow_mod *ofm = oh;
735
736     ofp_print_match(string, &ofm->match, verbosity);
737     switch (ntohs(ofm->command)) {
738     case OFPFC_ADD:
739         ds_put_cstr(string, " ADD: ");
740         break;
741     case OFPFC_MODIFY:
742         ds_put_cstr(string, " MOD: ");
743         break;
744     case OFPFC_MODIFY_STRICT:
745         ds_put_cstr(string, " MOD_STRICT: ");
746         break;
747     case OFPFC_DELETE:
748         ds_put_cstr(string, " DEL: ");
749         break;
750     case OFPFC_DELETE_STRICT:
751         ds_put_cstr(string, " DEL_STRICT: ");
752         break;
753     default:
754         ds_put_format(string, " cmd:%d ", ntohs(ofm->command));
755     }
756     ds_put_format(string, "cookie:0x%"PRIx64" idle:%d hard:%d pri:%d "
757             "buf:%#x flags:%"PRIx16" ", ntohll(ofm->cookie), 
758             ntohs(ofm->idle_timeout), ntohs(ofm->hard_timeout),
759             ofm->match.wildcards ? ntohs(ofm->priority) : (uint16_t)-1,
760             ntohl(ofm->buffer_id), ntohs(ofm->flags));
761     ofp_print_actions(string, ofm->actions,
762                       len - offsetof(struct ofp_flow_mod, actions));
763     ds_put_char(string, '\n');
764 }
765
766 /* Pretty-print the OFPT_FLOW_REMOVED packet of 'len' bytes at 'oh' to 'string'
767  * at the given 'verbosity' level. */
768 static void
769 ofp_print_flow_removed(struct ds *string, const void *oh, 
770                        size_t len OVS_UNUSED, int verbosity)
771 {
772     const struct ofp_flow_removed *ofr = oh;
773
774     ofp_print_match(string, &ofr->match, verbosity);
775     ds_put_cstr(string, " reason=");
776     switch (ofr->reason) {
777     case OFPRR_IDLE_TIMEOUT:
778         ds_put_cstr(string, "idle");
779         break;
780     case OFPRR_HARD_TIMEOUT:
781         ds_put_cstr(string, "hard");
782         break;
783     case OFPRR_DELETE:
784         ds_put_cstr(string, "delete");
785         break;
786     default:
787         ds_put_format(string, "**%"PRIu8"**", ofr->reason);
788         break;
789     }
790     ds_put_format(string, 
791          " cookie0x%"PRIx64" pri%"PRIu16" secs%"PRIu32" nsecs%"PRIu32
792          " idle%"PRIu16" pkts%"PRIu64" bytes%"PRIu64"\n", 
793          ntohll(ofr->cookie),
794          ofr->match.wildcards ? ntohs(ofr->priority) : (uint16_t)-1,
795          ntohl(ofr->duration_sec), ntohl(ofr->duration_nsec),
796          ntohs(ofr->idle_timeout), ntohll(ofr->packet_count), 
797          ntohll(ofr->byte_count));
798 }
799
800 static void
801 ofp_print_port_mod(struct ds *string, const void *oh, size_t len OVS_UNUSED,
802                    int verbosity OVS_UNUSED)
803 {
804     const struct ofp_port_mod *opm = oh;
805
806     ds_put_format(string, "port: %d: addr:"ETH_ADDR_FMT", config: %#x, mask:%#x\n",
807             ntohs(opm->port_no), ETH_ADDR_ARGS(opm->hw_addr), 
808             ntohl(opm->config), ntohl(opm->mask));
809     ds_put_format(string, "     advertise: ");
810     if (opm->advertise) {
811         ofp_print_port_features(string, ntohl(opm->advertise));
812     } else {
813         ds_put_format(string, "UNCHANGED\n");
814     }
815 }
816
817 struct error_type {
818     int type;
819     int code;
820     const char *name;
821 };
822
823 static const struct error_type error_types[] = {
824 #define ERROR_TYPE(TYPE) {TYPE, -1, #TYPE}
825 #define ERROR_CODE(TYPE, CODE) {TYPE, CODE, #CODE}
826     ERROR_TYPE(OFPET_HELLO_FAILED),
827     ERROR_CODE(OFPET_HELLO_FAILED, OFPHFC_INCOMPATIBLE),
828     ERROR_CODE(OFPET_HELLO_FAILED, OFPHFC_EPERM),
829
830     ERROR_TYPE(OFPET_BAD_REQUEST),
831     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VERSION),
832     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE),
833     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT),
834     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR),
835     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE),
836     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_EPERM),
837     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN),
838     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BUFFER_EMPTY),
839     ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BUFFER_UNKNOWN),
840
841     ERROR_TYPE(OFPET_BAD_ACTION),
842     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE),
843     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_LEN),
844     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR),
845     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE),
846     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT),
847     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT),
848     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_EPERM),
849     ERROR_CODE(OFPET_BAD_ACTION, OFPBAC_TOO_MANY),
850
851     ERROR_TYPE(OFPET_FLOW_MOD_FAILED),
852     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL),
853     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP),
854     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_EPERM),
855     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_EMERG_TIMEOUT),
856     ERROR_CODE(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND),
857
858     ERROR_TYPE(OFPET_PORT_MOD_FAILED),
859     ERROR_CODE(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT),
860     ERROR_CODE(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR)
861 };
862 #define N_ERROR_TYPES ARRAY_SIZE(error_types)
863
864 static const char *
865 lookup_error_type(int type)
866 {
867     const struct error_type *t;
868
869     for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
870         if (t->type == type && t->code == -1) {
871             return t->name;
872         }
873     }
874     return "?";
875 }
876
877 static const char *
878 lookup_error_code(int type, int code)
879 {
880     const struct error_type *t;
881
882     for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
883         if (t->type == type && t->code == code) {
884             return t->name;
885         }
886     }
887     return "?";
888 }
889
890 /* Pretty-print the OFPT_ERROR packet of 'len' bytes at 'oh' to 'string'
891  * at the given 'verbosity' level. */
892 static void
893 ofp_print_error_msg(struct ds *string, const void *oh, size_t len, 
894                        int verbosity OVS_UNUSED)
895 {
896     const struct ofp_error_msg *oem = oh;
897     int type = ntohs(oem->type);
898     int code = ntohs(oem->code);
899     char *s;
900
901     ds_put_format(string, " type%d(%s) code%d(%s) payload:\n",
902                   type, lookup_error_type(type),
903                   code, lookup_error_code(type, code));
904
905     switch (type) {
906     case OFPET_HELLO_FAILED:
907         ds_put_printable(string, (char *) oem->data, len - sizeof *oem);
908         break;
909
910     case OFPET_BAD_REQUEST:
911         s = ofp_to_string(oem->data, len - sizeof *oem, 1);
912         ds_put_cstr(string, s);
913         free(s);
914         break;
915
916     default:
917         ds_put_hex_dump(string, oem->data, len - sizeof *oem, 0, true);
918         break;
919     }
920 }
921
922 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
923  * at the given 'verbosity' level. */
924 static void
925 ofp_print_port_status(struct ds *string, const void *oh, size_t len OVS_UNUSED,
926                       int verbosity OVS_UNUSED)
927 {
928     const struct ofp_port_status *ops = oh;
929
930     if (ops->reason == OFPPR_ADD) {
931         ds_put_format(string, " ADD:");
932     } else if (ops->reason == OFPPR_DELETE) {
933         ds_put_format(string, " DEL:");
934     } else if (ops->reason == OFPPR_MODIFY) {
935         ds_put_format(string, " MOD:");
936     }
937
938     ofp_print_phy_port(string, &ops->desc);
939 }
940
941 static void
942 ofp_desc_stats_reply(struct ds *string, const void *body,
943                      size_t len OVS_UNUSED, int verbosity OVS_UNUSED)
944 {
945     const struct ofp_desc_stats *ods = body;
946
947     ds_put_format(string, "Manufacturer: %.*s\n", 
948             (int) sizeof ods->mfr_desc, ods->mfr_desc);
949     ds_put_format(string, "Hardware: %.*s\n",
950             (int) sizeof ods->hw_desc, ods->hw_desc);
951     ds_put_format(string, "Software: %.*s\n",
952             (int) sizeof ods->sw_desc, ods->sw_desc);
953     ds_put_format(string, "Serial Num: %.*s\n",
954             (int) sizeof ods->serial_num, ods->serial_num);
955     ds_put_format(string, "DP Description: %.*s\n",
956             (int) sizeof ods->dp_desc, ods->dp_desc);
957 }
958
959 static void
960 ofp_flow_stats_request(struct ds *string, const void *oh,
961                        size_t len OVS_UNUSED, int verbosity)
962 {
963     const struct ofp_flow_stats_request *fsr = oh;
964
965     if (fsr->table_id == 0xff) {
966         ds_put_format(string, " table_id=any, ");
967     } else {
968         ds_put_format(string, " table_id=%"PRIu8", ", fsr->table_id);
969     }
970
971     ofp_print_match(string, &fsr->match, verbosity);
972 }
973
974 static void
975 ofp_flow_stats_reply(struct ds *string, const void *body_, size_t len,
976                      int verbosity)
977 {
978     const char *body = body_;
979     const char *pos = body;
980     for (;;) {
981         const struct ofp_flow_stats *fs;
982         ptrdiff_t bytes_left = body + len - pos;
983         size_t length;
984
985         if (bytes_left < sizeof *fs) {
986             if (bytes_left != 0) {
987                 ds_put_format(string, " ***%td leftover bytes at end***",
988                               bytes_left);
989             }
990             break;
991         }
992
993         fs = (const void *) pos;
994         length = ntohs(fs->length);
995         if (length < sizeof *fs) {
996             ds_put_format(string, " ***length=%zu shorter than minimum %zu***",
997                           length, sizeof *fs);
998             break;
999         } else if (length > bytes_left) {
1000             ds_put_format(string,
1001                           " ***length=%zu but only %td bytes left***",
1002                           length, bytes_left);
1003             break;
1004         } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1005             ds_put_format(string,
1006                           " ***length=%zu has %zu bytes leftover in "
1007                           "final action***",
1008                           length,
1009                           (length - sizeof *fs) % sizeof fs->actions[0]);
1010             break;
1011         }
1012
1013         ds_put_format(string, "  cookie=0x%"PRIx64", ", ntohll(fs->cookie));
1014         ds_put_format(string, "duration_sec=%"PRIu32"s, ", 
1015                     ntohl(fs->duration_sec));
1016         ds_put_format(string, "duration_nsec=%"PRIu32"ns, ", 
1017                     ntohl(fs->duration_nsec));
1018         ds_put_format(string, "table_id=%"PRIu8", ", fs->table_id);
1019         ds_put_format(string, "priority=%"PRIu16", ", 
1020                     fs->match.wildcards ? ntohs(fs->priority) : (uint16_t)-1);
1021         ds_put_format(string, "n_packets=%"PRIu64", ",
1022                     ntohll(fs->packet_count));
1023         ds_put_format(string, "n_bytes=%"PRIu64", ", ntohll(fs->byte_count));
1024         if (fs->idle_timeout != htons(OFP_FLOW_PERMANENT)) {
1025             ds_put_format(string, "idle_timeout=%"PRIu16",",
1026                           ntohs(fs->idle_timeout));
1027         }
1028         if (fs->hard_timeout != htons(OFP_FLOW_PERMANENT)) {
1029             ds_put_format(string, "hard_timeout=%"PRIu16",",
1030                           ntohs(fs->hard_timeout));
1031         }
1032         ofp_print_match(string, &fs->match, verbosity);
1033         ofp_print_actions(string, fs->actions, length - sizeof *fs);
1034         ds_put_char(string, '\n');
1035
1036         pos += length;
1037      }
1038 }
1039
1040 static void
1041 ofp_aggregate_stats_request(struct ds *string, const void *oh,
1042                             size_t len OVS_UNUSED, int verbosity)
1043 {
1044     const struct ofp_aggregate_stats_request *asr = oh;
1045
1046     if (asr->table_id == 0xff) {
1047         ds_put_format(string, " table_id=any, ");
1048     } else {
1049         ds_put_format(string, " table_id=%"PRIu8", ", asr->table_id);
1050     }
1051
1052     ofp_print_match(string, &asr->match, verbosity);
1053 }
1054
1055 static void
1056 ofp_aggregate_stats_reply(struct ds *string, const void *body_,
1057                           size_t len OVS_UNUSED, int verbosity OVS_UNUSED)
1058 {
1059     const struct ofp_aggregate_stats_reply *asr = body_;
1060
1061     ds_put_format(string, " packet_count=%"PRIu64, ntohll(asr->packet_count));
1062     ds_put_format(string, " byte_count=%"PRIu64, ntohll(asr->byte_count));
1063     ds_put_format(string, " flow_count=%"PRIu32, ntohl(asr->flow_count));
1064 }
1065
1066 static void print_port_stat(struct ds *string, const char *leader, 
1067                             uint64_t stat, int more)
1068 {
1069     ds_put_cstr(string, leader);
1070     if (stat != -1) {
1071         ds_put_format(string, "%"PRIu64, stat);
1072     } else {
1073         ds_put_char(string, '?');
1074     }
1075     if (more) {
1076         ds_put_cstr(string, ", ");
1077     } else {
1078         ds_put_cstr(string, "\n");
1079     }
1080 }
1081
1082 static void
1083 ofp_port_stats_request(struct ds *string, const void *body_,
1084                        size_t len OVS_UNUSED, int verbosity OVS_UNUSED)
1085 {
1086     const struct ofp_port_stats_request *psr = body_;
1087     ds_put_format(string, "port_no=%"PRIu16, ntohs(psr->port_no));
1088 }
1089
1090 static void
1091 ofp_port_stats_reply(struct ds *string, const void *body, size_t len,
1092                      int verbosity)
1093 {
1094     const struct ofp_port_stats *ps = body;
1095     size_t n = len / sizeof *ps;
1096     ds_put_format(string, " %zu ports\n", n);
1097     if (verbosity < 1) {
1098         return;
1099     }
1100
1101     for (; n--; ps++) {
1102         ds_put_format(string, "  port %2"PRIu16": ", ntohs(ps->port_no));
1103
1104         ds_put_cstr(string, "rx ");
1105         print_port_stat(string, "pkts=", ntohll(ps->rx_packets), 1);
1106         print_port_stat(string, "bytes=", ntohll(ps->rx_bytes), 1);
1107         print_port_stat(string, "drop=", ntohll(ps->rx_dropped), 1);
1108         print_port_stat(string, "errs=", ntohll(ps->rx_errors), 1);
1109         print_port_stat(string, "frame=", ntohll(ps->rx_frame_err), 1);
1110         print_port_stat(string, "over=", ntohll(ps->rx_over_err), 1);
1111         print_port_stat(string, "crc=", ntohll(ps->rx_crc_err), 0);
1112
1113         ds_put_cstr(string, "           tx ");
1114         print_port_stat(string, "pkts=", ntohll(ps->tx_packets), 1);
1115         print_port_stat(string, "bytes=", ntohll(ps->tx_bytes), 1);
1116         print_port_stat(string, "drop=", ntohll(ps->tx_dropped), 1);
1117         print_port_stat(string, "errs=", ntohll(ps->tx_errors), 1);
1118         print_port_stat(string, "coll=", ntohll(ps->collisions), 0);
1119     }
1120 }
1121
1122 static void
1123 ofp_table_stats_reply(struct ds *string, const void *body, size_t len,
1124                      int verbosity)
1125 {
1126     const struct ofp_table_stats *ts = body;
1127     size_t n = len / sizeof *ts;
1128     ds_put_format(string, " %zu tables\n", n);
1129     if (verbosity < 1) {
1130         return;
1131     }
1132
1133     for (; n--; ts++) {
1134         char name[OFP_MAX_TABLE_NAME_LEN + 1];
1135         strncpy(name, ts->name, sizeof name);
1136         name[OFP_MAX_TABLE_NAME_LEN] = '\0';
1137
1138         ds_put_format(string, "  %d: %-8s: ", ts->table_id, name);
1139         ds_put_format(string, "wild=0x%05"PRIx32", ", ntohl(ts->wildcards));
1140         ds_put_format(string, "max=%6"PRIu32", ", ntohl(ts->max_entries));
1141         ds_put_format(string, "active=%"PRIu32"\n", ntohl(ts->active_count));
1142         ds_put_cstr(string, "               ");
1143         ds_put_format(string, "lookup=%"PRIu64", ", 
1144                     ntohll(ts->lookup_count));
1145         ds_put_format(string, "matched=%"PRIu64"\n",
1146                     ntohll(ts->matched_count));
1147      }
1148 }
1149
1150 static void
1151 vendor_stat(struct ds *string, const void *body, size_t len,
1152             int verbosity OVS_UNUSED)
1153 {
1154     ds_put_format(string, " vendor=%08"PRIx32, ntohl(*(uint32_t *) body));
1155     ds_put_format(string, " %zu bytes additional data",
1156                   len - sizeof(uint32_t));
1157 }
1158
1159 enum stats_direction {
1160     REQUEST,
1161     REPLY
1162 };
1163
1164 static void
1165 print_stats(struct ds *string, int type, const void *body, size_t body_len,
1166             int verbosity, enum stats_direction direction)
1167 {
1168     struct stats_msg {
1169         size_t min_body, max_body;
1170         void (*printer)(struct ds *, const void *, size_t len, int verbosity);
1171     };
1172
1173     struct stats_type {
1174         int type;
1175         const char *name;
1176         struct stats_msg request;
1177         struct stats_msg reply;
1178     };
1179
1180     static const struct stats_type stats_types[] = {
1181         {
1182             OFPST_DESC,
1183             "description",
1184             { 0, 0, NULL },
1185             { 0, SIZE_MAX, ofp_desc_stats_reply },
1186         },
1187         {
1188             OFPST_FLOW,
1189             "flow",
1190             { sizeof(struct ofp_flow_stats_request),
1191               sizeof(struct ofp_flow_stats_request),
1192               ofp_flow_stats_request },
1193             { 0, SIZE_MAX, ofp_flow_stats_reply },
1194         },
1195         {
1196             OFPST_AGGREGATE,
1197             "aggregate",
1198             { sizeof(struct ofp_aggregate_stats_request),
1199               sizeof(struct ofp_aggregate_stats_request),
1200               ofp_aggregate_stats_request },
1201             { sizeof(struct ofp_aggregate_stats_reply),
1202               sizeof(struct ofp_aggregate_stats_reply),
1203               ofp_aggregate_stats_reply },
1204         },
1205         {
1206             OFPST_TABLE,
1207             "table",
1208             { 0, 0, NULL },
1209             { 0, SIZE_MAX, ofp_table_stats_reply },
1210         },
1211         {
1212             OFPST_PORT,
1213             "port",
1214             { sizeof(struct ofp_port_stats_request), 
1215               sizeof(struct ofp_port_stats_request), 
1216               ofp_port_stats_request },
1217             { 0, SIZE_MAX, ofp_port_stats_reply },
1218         },
1219         {
1220             OFPST_VENDOR,
1221             "vendor-specific",
1222             { sizeof(uint32_t), SIZE_MAX, vendor_stat },
1223             { sizeof(uint32_t), SIZE_MAX, vendor_stat },
1224         },
1225         {
1226             -1,
1227             "unknown",
1228             { 0, 0, NULL, },
1229             { 0, 0, NULL, },
1230         },
1231     };
1232
1233     const struct stats_type *s;
1234     const struct stats_msg *m;
1235
1236     if (type >= ARRAY_SIZE(stats_types) || !stats_types[type].name) {
1237         ds_put_format(string, " ***unknown type %d***", type);
1238         return;
1239     }
1240     for (s = stats_types; s->type >= 0; s++) {
1241         if (s->type == type) {
1242             break;
1243         }
1244     }
1245     ds_put_format(string, " type=%d(%s)\n", type, s->name);
1246
1247     m = direction == REQUEST ? &s->request : &s->reply;
1248     if (body_len < m->min_body || body_len > m->max_body) {
1249         ds_put_format(string, " ***body_len=%zu not in %zu...%zu***",
1250                       body_len, m->min_body, m->max_body);
1251         return;
1252     }
1253     if (m->printer) {
1254         m->printer(string, body, body_len, verbosity);
1255     }
1256 }
1257
1258 static void
1259 ofp_stats_request(struct ds *string, const void *oh, size_t len, int verbosity)
1260 {
1261     const struct ofp_stats_request *srq = oh;
1262
1263     if (srq->flags) {
1264         ds_put_format(string, " ***unknown flags 0x%04"PRIx16"***",
1265                       ntohs(srq->flags));
1266     }
1267
1268     print_stats(string, ntohs(srq->type), srq->body,
1269                 len - offsetof(struct ofp_stats_request, body),
1270                 verbosity, REQUEST);
1271 }
1272
1273 static void
1274 ofp_stats_reply(struct ds *string, const void *oh, size_t len, int verbosity)
1275 {
1276     const struct ofp_stats_reply *srp = oh;
1277
1278     ds_put_cstr(string, " flags=");
1279     if (!srp->flags) {
1280         ds_put_cstr(string, "none");
1281     } else {
1282         uint16_t flags = ntohs(srp->flags);
1283         if (flags & OFPSF_REPLY_MORE) {
1284             ds_put_cstr(string, "[more]");
1285             flags &= ~OFPSF_REPLY_MORE;
1286         }
1287         if (flags) {
1288             ds_put_format(string, "[***unknown flags 0x%04"PRIx16"***]", flags);
1289         }
1290     }
1291
1292     print_stats(string, ntohs(srp->type), srp->body,
1293                 len - offsetof(struct ofp_stats_reply, body),
1294                 verbosity, REPLY);
1295 }
1296
1297 static void
1298 ofp_echo(struct ds *string, const void *oh, size_t len, int verbosity)
1299 {
1300     const struct ofp_header *hdr = oh;
1301
1302     ds_put_format(string, " %zu bytes of payload\n", len - sizeof *hdr);
1303     if (verbosity > 1) {
1304         ds_put_hex_dump(string, hdr, len - sizeof *hdr, 0, true); 
1305     }
1306 }
1307
1308 struct openflow_packet {
1309     uint8_t type;
1310     const char *name;
1311     size_t min_size;
1312     void (*printer)(struct ds *, const void *, size_t len, int verbosity);
1313 };
1314
1315 static const struct openflow_packet packets[] = {
1316     {
1317         OFPT_HELLO,
1318         "hello",
1319         sizeof (struct ofp_header),
1320         NULL,
1321     },
1322     {
1323         OFPT_FEATURES_REQUEST,
1324         "features_request",
1325         sizeof (struct ofp_header),
1326         NULL,
1327     },
1328     {
1329         OFPT_FEATURES_REPLY,
1330         "features_reply",
1331         sizeof (struct ofp_switch_features),
1332         ofp_print_switch_features,
1333     },
1334     {
1335         OFPT_GET_CONFIG_REQUEST,
1336         "get_config_request",
1337         sizeof (struct ofp_header),
1338         NULL,
1339     },
1340     {
1341         OFPT_GET_CONFIG_REPLY,
1342         "get_config_reply",
1343         sizeof (struct ofp_switch_config),
1344         ofp_print_switch_config,
1345     },
1346     {
1347         OFPT_SET_CONFIG,
1348         "set_config",
1349         sizeof (struct ofp_switch_config),
1350         ofp_print_switch_config,
1351     },
1352     {
1353         OFPT_PACKET_IN,
1354         "packet_in",
1355         offsetof(struct ofp_packet_in, data),
1356         ofp_packet_in,
1357     },
1358     {
1359         OFPT_PACKET_OUT,
1360         "packet_out",
1361         sizeof (struct ofp_packet_out),
1362         ofp_packet_out,
1363     },
1364     {
1365         OFPT_FLOW_MOD,
1366         "flow_mod",
1367         sizeof (struct ofp_flow_mod),
1368         ofp_print_flow_mod,
1369     },
1370     {
1371         OFPT_FLOW_REMOVED,
1372         "flow_removed",
1373         sizeof (struct ofp_flow_removed),
1374         ofp_print_flow_removed,
1375     },
1376     {
1377         OFPT_PORT_MOD,
1378         "port_mod",
1379         sizeof (struct ofp_port_mod),
1380         ofp_print_port_mod,
1381     },
1382     {
1383         OFPT_PORT_STATUS,
1384         "port_status",
1385         sizeof (struct ofp_port_status),
1386         ofp_print_port_status
1387     },
1388     {
1389         OFPT_ERROR,
1390         "error_msg",
1391         sizeof (struct ofp_error_msg),
1392         ofp_print_error_msg,
1393     },
1394     {
1395         OFPT_STATS_REQUEST,
1396         "stats_request",
1397         sizeof (struct ofp_stats_request),
1398         ofp_stats_request,
1399     },
1400     {
1401         OFPT_STATS_REPLY,
1402         "stats_reply",
1403         sizeof (struct ofp_stats_reply),
1404         ofp_stats_reply,
1405     },
1406     {
1407         OFPT_ECHO_REQUEST,
1408         "echo_request",
1409         sizeof (struct ofp_header),
1410         ofp_echo,
1411     },
1412     {
1413         OFPT_ECHO_REPLY,
1414         "echo_reply",
1415         sizeof (struct ofp_header),
1416         ofp_echo,
1417     },
1418     {
1419         OFPT_VENDOR,
1420         "vendor",
1421         sizeof (struct ofp_vendor_header),
1422         NULL,
1423     },
1424     {
1425         OFPT_BARRIER_REQUEST,
1426         "barrier_request",
1427         sizeof (struct ofp_header),
1428         NULL,
1429     },
1430     {
1431         OFPT_BARRIER_REPLY,
1432         "barrier_reply",
1433         sizeof (struct ofp_header),
1434         NULL,
1435     }
1436 };
1437
1438 /* Composes and returns a string representing the OpenFlow packet of 'len'
1439  * bytes at 'oh' at the given 'verbosity' level.  0 is a minimal amount of
1440  * verbosity and higher numbers increase verbosity.  The caller is responsible
1441  * for freeing the string. */
1442 char *
1443 ofp_to_string(const void *oh_, size_t len, int verbosity)
1444 {
1445     struct ds string = DS_EMPTY_INITIALIZER;
1446     const struct ofp_header *oh = oh_;
1447     const struct openflow_packet *pkt;
1448
1449     if (len < sizeof(struct ofp_header)) {
1450         ds_put_cstr(&string, "OpenFlow packet too short:\n");
1451         ds_put_hex_dump(&string, oh, len, 0, true);
1452         return ds_cstr(&string);
1453     } else if (oh->version != OFP_VERSION) {
1454         ds_put_format(&string, "Bad OpenFlow version %"PRIu8":\n", oh->version);
1455         ds_put_hex_dump(&string, oh, len, 0, true);
1456         return ds_cstr(&string);
1457     }
1458
1459     for (pkt = packets; ; pkt++) {
1460         if (pkt >= &packets[ARRAY_SIZE(packets)]) {
1461             ds_put_format(&string, "Unknown OpenFlow packet type %"PRIu8":\n",
1462                           oh->type);
1463             ds_put_hex_dump(&string, oh, len, 0, true);
1464             return ds_cstr(&string);
1465         } else if (oh->type == pkt->type) {
1466             break;
1467         }
1468     }
1469
1470     ds_put_format(&string, "%s (xid=0x%"PRIx32"):", pkt->name, oh->xid);
1471
1472     if (ntohs(oh->length) > len)
1473         ds_put_format(&string, " (***truncated to %zu bytes from %"PRIu16"***)",
1474                 len, ntohs(oh->length));
1475     else if (ntohs(oh->length) < len) {
1476         ds_put_format(&string, " (***only uses %"PRIu16" bytes out of %zu***)\n",
1477                 ntohs(oh->length), len);
1478         len = ntohs(oh->length);
1479     }
1480
1481     if (len < pkt->min_size) {
1482         ds_put_format(&string, " (***length=%zu < min_size=%zu***)\n",
1483                 len, pkt->min_size);
1484     } else if (!pkt->printer) {
1485         if (len > sizeof *oh) {
1486             ds_put_format(&string, " length=%"PRIu16" (decoder not implemented)\n",
1487                           ntohs(oh->length)); 
1488         }
1489     } else {
1490         pkt->printer(&string, oh, len, verbosity);
1491     }
1492     if (verbosity >= 3) {
1493         ds_put_hex_dump(&string, oh, len, 0, true);
1494     }
1495     if (string.string[string.length - 1] != '\n') {
1496         ds_put_char(&string, '\n');
1497     }
1498     return ds_cstr(&string);
1499 }
1500
1501 /* Returns the name for the specified OpenFlow message type as a string,
1502  * e.g. "OFPT_FEATURES_REPLY".  If no name is known, the string returned is a
1503  * hex number, e.g. "0x55".
1504  *
1505  * The caller must free the returned string when it is no longer needed. */
1506 char *
1507 ofp_message_type_to_string(uint8_t type)
1508 {
1509     struct ds s = DS_EMPTY_INITIALIZER;
1510     const struct openflow_packet *pkt;
1511     for (pkt = packets; ; pkt++) {
1512         if (pkt >= &packets[ARRAY_SIZE(packets)]) {
1513             ds_put_format(&s, "0x%02"PRIx8, type);
1514             break;
1515         } else if (type == pkt->type) {
1516             const char *p;
1517
1518             ds_put_cstr(&s, "OFPT_");
1519             for (p = pkt->name; *p; p++) {
1520                 ds_put_char(&s, toupper((unsigned char) *p));
1521             }
1522             break;
1523         }
1524     }
1525     return ds_cstr(&s);
1526 }
1527 \f
1528 static void
1529 print_and_free(FILE *stream, char *string) 
1530 {
1531     fputs(string, stream);
1532     free(string);
1533 }
1534
1535 /* Pretty-print the OpenFlow packet of 'len' bytes at 'oh' to 'stream' at the
1536  * given 'verbosity' level.  0 is a minimal amount of verbosity and higher
1537  * numbers increase verbosity. */
1538 void
1539 ofp_print(FILE *stream, const void *oh, size_t len, int verbosity)
1540 {
1541     print_and_free(stream, ofp_to_string(oh, len, verbosity));
1542 }
1543
1544 /* Dumps the contents of the Ethernet frame in the 'len' bytes starting at
1545  * 'data' to 'stream' using tcpdump.  'total_len' specifies the full length of
1546  * the Ethernet frame (of which 'len' bytes were captured).
1547  *
1548  * This starts and kills a tcpdump subprocess so it's quite expensive. */
1549 void
1550 ofp_print_packet(FILE *stream, const void *data, size_t len, size_t total_len)
1551 {
1552     print_and_free(stream, ofp_packet_to_string(data, len, total_len));
1553 }