Merge commit 'origin/citrix'
[cascardo/ovs.git] / lib / vconn.c
1 /*
2  * Copyright (c) 2008, 2009 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 "vconn-provider.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <poll.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "flow.h"
29 #include "ofp-print.h"
30 #include "ofpbuf.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
33 #include "packets.h"
34 #include "poll-loop.h"
35 #include "random.h"
36 #include "util.h"
37
38 #define THIS_MODULE VLM_vconn
39 #include "vlog.h"
40
41 /* State of an active vconn.*/
42 enum vconn_state {
43     /* This is the ordinary progression of states. */
44     VCS_CONNECTING,             /* Underlying vconn is not connected. */
45     VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
46     VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
47     VCS_CONNECTED,              /* Connection established. */
48
49     /* These states are entered only when something goes wrong. */
50     VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
51     VCS_DISCONNECTED            /* Connection failed or connection closed. */
52 };
53
54 static struct vconn_class *vconn_classes[] = {
55     &tcp_vconn_class,
56     &unix_vconn_class,
57 #ifdef HAVE_OPENSSL
58     &ssl_vconn_class,
59 #endif
60 };
61
62 static struct pvconn_class *pvconn_classes[] = {
63     &ptcp_pvconn_class,
64     &punix_pvconn_class,
65 #ifdef HAVE_OPENSSL
66     &pssl_pvconn_class,
67 #endif
68 };
69
70 /* Rate limit for individual OpenFlow messages going over the vconn, output at
71  * DBG level.  This is very high because, if these are enabled, it is because
72  * we really need to see them. */
73 static struct vlog_rate_limit ofmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
74
75 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
76  * in the peer and so there's not much point in showing a lot of them. */
77 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
78
79 static int do_recv(struct vconn *, struct ofpbuf **);
80 static int do_send(struct vconn *, struct ofpbuf *);
81
82 /* Check the validity of the vconn class structures. */
83 static void
84 check_vconn_classes(void)
85 {
86 #ifndef NDEBUG
87     size_t i;
88
89     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
90         struct vconn_class *class = vconn_classes[i];
91         assert(class->name != NULL);
92         assert(class->open != NULL);
93         if (class->close || class->recv || class->send || class->wait) {
94             assert(class->close != NULL);
95             assert(class->recv != NULL);
96             assert(class->send != NULL);
97             assert(class->wait != NULL);
98         } else {
99             /* This class delegates to another one. */
100         }
101     }
102
103     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
104         struct pvconn_class *class = pvconn_classes[i];
105         assert(class->name != NULL);
106         assert(class->listen != NULL);
107         if (class->close || class->accept || class->wait) {
108             assert(class->close != NULL);
109             assert(class->accept != NULL);
110             assert(class->wait != NULL);
111         } else {
112             /* This class delegates to another one. */
113         }
114     }
115 #endif
116 }
117
118 /* Prints information on active (if 'active') and passive (if 'passive')
119  * connection methods supported by the vconn.  If 'bootstrap' is true, also
120  * advertises options to bootstrap the CA certificate. */
121 void
122 vconn_usage(bool active, bool passive, bool bootstrap UNUSED)
123 {
124     /* Really this should be implemented via callbacks into the vconn
125      * providers, but that seems too heavy-weight to bother with at the
126      * moment. */
127     
128     printf("\n");
129     if (active) {
130         printf("Active OpenFlow connection methods:\n");
131         printf("  tcp:HOST[:PORT]         "
132                "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT);
133 #ifdef HAVE_OPENSSL
134         printf("  ssl:HOST[:PORT]         "
135                "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT);
136 #endif
137         printf("  unix:FILE               Unix domain socket named FILE\n");
138     }
139
140     if (passive) {
141         printf("Passive OpenFlow connection methods:\n");
142         printf("  ptcp:[PORT][:IP]        "
143                "listen to TCP PORT (default: %d) on IP\n",
144                OFP_TCP_PORT);
145 #ifdef HAVE_OPENSSL
146         printf("  pssl:[PORT][:IP]        "
147                "listen for SSL on PORT (default: %d) on IP\n",
148                OFP_SSL_PORT);
149 #endif
150         printf("  punix:FILE              "
151                "listen on Unix domain socket FILE\n");
152     }
153
154 #ifdef HAVE_OPENSSL
155     printf("PKI configuration (required to use SSL):\n"
156            "  -p, --private-key=FILE  file with private key\n"
157            "  -c, --certificate=FILE  file with certificate for private key\n"
158            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
159     if (bootstrap) {
160         printf("  --bootstrap-ca-cert=FILE  file with peer CA certificate "
161                "to read or create\n");
162     }
163 #endif
164 }
165
166 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
167  * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
168  * are vconn class-specific.
169  *
170  * The vconn will automatically negotiate an OpenFlow protocol version
171  * acceptable to both peers on the connection.  The version negotiated will be
172  * no lower than 'min_version' and no higher than OFP_VERSION.
173  *
174  * Returns 0 if successful, otherwise a positive errno value.  If successful,
175  * stores a pointer to the new connection in '*vconnp', otherwise a null
176  * pointer.  */
177 int
178 vconn_open(const char *name, int min_version, struct vconn **vconnp)
179 {
180     size_t prefix_len;
181     size_t i;
182
183     COVERAGE_INC(vconn_open);
184     check_vconn_classes();
185
186     *vconnp = NULL;
187     prefix_len = strcspn(name, ":");
188     if (prefix_len == strlen(name)) {
189         return EAFNOSUPPORT;
190     }
191     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
192         struct vconn_class *class = vconn_classes[i];
193         if (strlen(class->name) == prefix_len
194             && !memcmp(class->name, name, prefix_len)) {
195             struct vconn *vconn;
196             char *suffix_copy = xstrdup(name + prefix_len + 1);
197             int retval = class->open(name, suffix_copy, &vconn);
198             free(suffix_copy);
199             if (!retval) {
200                 assert(vconn->state != VCS_CONNECTING
201                        || vconn->class->connect);
202                 vconn->min_version = min_version;
203                 *vconnp = vconn;
204             }
205             return retval;
206         }
207     }
208     return EAFNOSUPPORT;
209 }
210
211 int
212 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
213 {
214     struct vconn *vconn;
215     int error;
216
217     error = vconn_open(name, min_version, &vconn);
218     while (error == EAGAIN) {
219         vconn_connect_wait(vconn);
220         poll_block();
221         error = vconn_connect(vconn);
222         assert(error != EINPROGRESS);
223     }
224     if (error) {
225         vconn_close(vconn);
226         *vconnp = NULL;
227     } else {
228         *vconnp = vconn;
229     }
230     return error;
231 }
232
233 /* Closes 'vconn'. */
234 void
235 vconn_close(struct vconn *vconn)
236 {
237     if (vconn != NULL) {
238         char *name = vconn->name;
239         (vconn->class->close)(vconn);
240         free(name);
241     }
242 }
243
244 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
245 const char *
246 vconn_get_name(const struct vconn *vconn)
247 {
248     return vconn->name;
249 }
250
251 /* Returns the IP address of the peer, or 0 if the peer is not connected over
252  * an IP-based protocol or if its IP address is not yet known. */
253 uint32_t
254 vconn_get_ip(const struct vconn *vconn) 
255 {
256     return vconn->ip;
257 }
258
259 static void
260 vcs_connecting(struct vconn *vconn) 
261 {
262     int retval = (vconn->class->connect)(vconn);
263     assert(retval != EINPROGRESS);
264     if (!retval) {
265         vconn->state = VCS_SEND_HELLO;
266     } else if (retval != EAGAIN) {
267         vconn->state = VCS_DISCONNECTED;
268         vconn->error = retval;
269     }
270 }
271
272 static void
273 vcs_send_hello(struct vconn *vconn)
274 {
275     struct ofpbuf *b;
276     int retval;
277
278     make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
279     retval = do_send(vconn, b);
280     if (!retval) {
281         vconn->state = VCS_RECV_HELLO;
282     } else {
283         ofpbuf_delete(b);
284         if (retval != EAGAIN) {
285             vconn->state = VCS_DISCONNECTED;
286             vconn->error = retval;
287         }
288     }
289 }
290
291 static void
292 vcs_recv_hello(struct vconn *vconn)
293 {
294     struct ofpbuf *b;
295     int retval;
296
297     retval = do_recv(vconn, &b);
298     if (!retval) {
299         struct ofp_header *oh = b->data;
300
301         if (oh->type == OFPT_HELLO) {
302             if (b->size > sizeof *oh) {
303                 struct ds msg = DS_EMPTY_INITIALIZER;
304                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
305                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
306                 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
307                 ds_destroy(&msg);
308             }
309
310             vconn->version = MIN(OFP_VERSION, oh->version);
311             if (vconn->version < vconn->min_version) {
312                 VLOG_WARN_RL(&bad_ofmsg_rl,
313                              "%s: version negotiation failed: we support "
314                              "versions 0x%02x to 0x%02x inclusive but peer "
315                              "supports no later than version 0x%02"PRIx8,
316                              vconn->name, vconn->min_version, OFP_VERSION,
317                              oh->version);
318                 vconn->state = VCS_SEND_ERROR;
319             } else {
320                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
321                          "(we support versions 0x%02x to 0x%02x inclusive, "
322                          "peer no later than version 0x%02"PRIx8")",
323                          vconn->name, vconn->version, vconn->min_version,
324                          OFP_VERSION, oh->version);
325                 vconn->state = VCS_CONNECTED;
326             }
327             ofpbuf_delete(b);
328             return;
329         } else {
330             char *s = ofp_to_string(b->data, b->size, 1);
331             VLOG_WARN_RL(&bad_ofmsg_rl,
332                          "%s: received message while expecting hello: %s",
333                          vconn->name, s);
334             free(s);
335             retval = EPROTO;
336             ofpbuf_delete(b);
337         }
338     }
339
340     if (retval != EAGAIN) {
341         vconn->state = VCS_DISCONNECTED;
342         vconn->error = retval == EOF ? ECONNRESET : retval;
343     }
344 }
345
346 static void
347 vcs_send_error(struct vconn *vconn)
348 {
349     struct ofp_error_msg *error;
350     struct ofpbuf *b;
351     char s[128];
352     int retval;
353
354     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
355              "you support no later than version 0x%02"PRIx8".",
356              vconn->min_version, OFP_VERSION, vconn->version);
357     error = make_openflow(sizeof *error, OFPT_ERROR, &b);
358     error->type = htons(OFPET_HELLO_FAILED);
359     error->code = htons(OFPHFC_INCOMPATIBLE);
360     ofpbuf_put(b, s, strlen(s));
361     update_openflow_length(b);
362     retval = do_send(vconn, b);
363     if (retval) {
364         ofpbuf_delete(b);
365     }
366     if (retval != EAGAIN) {
367         vconn->state = VCS_DISCONNECTED;
368         vconn->error = retval ? retval : EPROTO;
369     }
370 }
371
372 /* Tries to complete the connection on 'vconn', which must be an active
373  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
374  * was successful or a positive errno value if it failed.  If the
375  * connection is still in progress, returns EAGAIN. */
376 int
377 vconn_connect(struct vconn *vconn)
378 {
379     enum vconn_state last_state;
380
381     assert(vconn->min_version >= 0);
382     do {
383         last_state = vconn->state;
384         switch (vconn->state) {
385         case VCS_CONNECTING:
386             vcs_connecting(vconn);
387             break;
388
389         case VCS_SEND_HELLO:
390             vcs_send_hello(vconn);
391             break;
392
393         case VCS_RECV_HELLO:
394             vcs_recv_hello(vconn);
395             break;
396
397         case VCS_CONNECTED:
398             return 0;
399
400         case VCS_SEND_ERROR:
401             vcs_send_error(vconn);
402             break;
403
404         case VCS_DISCONNECTED:
405             return vconn->error;
406
407         default:
408             NOT_REACHED();
409         }
410     } while (vconn->state != last_state);
411
412     return EAGAIN;
413 }
414
415 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
416  * vconn.  If successful, stores the received message into '*msgp' and returns
417  * 0.  The caller is responsible for destroying the message with
418  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
419  * null pointer into '*msgp'.  On normal connection close, returns EOF.
420  *
421  * vconn_recv will not block waiting for a packet to arrive.  If no packets
422  * have been received, it returns EAGAIN immediately. */
423 int
424 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
425 {
426     int retval = vconn_connect(vconn);
427     if (!retval) {
428         retval = do_recv(vconn, msgp);
429     }
430     return retval;
431 }
432
433 static int
434 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
435 {
436     int retval = (vconn->class->recv)(vconn, msgp);
437     if (!retval) {
438         struct ofp_header *oh;
439
440         COVERAGE_INC(vconn_received);
441         if (VLOG_IS_DBG_ENABLED()) {
442             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
443             VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
444             free(s);
445         }
446
447         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
448         if (oh->version != vconn->version
449             && oh->type != OFPT_HELLO
450             && oh->type != OFPT_ERROR
451             && oh->type != OFPT_ECHO_REQUEST
452             && oh->type != OFPT_ECHO_REPLY
453             && oh->type != OFPT_VENDOR)
454         {
455             if (vconn->version < 0) {
456                 VLOG_ERR_RL(&bad_ofmsg_rl,
457                             "%s: received OpenFlow message type %"PRIu8" "
458                             "before version negotiation complete",
459                             vconn->name, oh->type);
460             } else {
461                 VLOG_ERR_RL(&bad_ofmsg_rl,
462                             "%s: received OpenFlow version 0x%02"PRIx8" "
463                             "!= expected %02x",
464                             vconn->name, oh->version, vconn->version);
465             }
466             ofpbuf_delete(*msgp);
467             retval = EPROTO;
468         }
469     }
470     if (retval) {
471         *msgp = NULL;
472     }
473     return retval;
474 }
475
476 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
477  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
478  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
479  * ever will be delivered to the peer, only that it has been queued for
480  * transmission.
481  *
482  * Returns a positive errno value on failure, in which case the caller
483  * retains ownership of 'msg'.
484  *
485  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
486  * transmission, it returns EAGAIN immediately. */
487 int
488 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
489 {
490     int retval = vconn_connect(vconn);
491     if (!retval) {
492         retval = do_send(vconn, msg);
493     }
494     return retval;
495 }
496
497 static int
498 do_send(struct vconn *vconn, struct ofpbuf *msg)
499 {
500     int retval;
501
502     assert(msg->size >= sizeof(struct ofp_header));
503     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
504     if (!VLOG_IS_DBG_ENABLED()) {
505         COVERAGE_INC(vconn_sent);
506         retval = (vconn->class->send)(vconn, msg);
507     } else {
508         char *s = ofp_to_string(msg->data, msg->size, 1);
509         retval = (vconn->class->send)(vconn, msg);
510         if (retval != EAGAIN) {
511             VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
512                         vconn->name, strerror(retval), s);
513         }
514         free(s);
515     }
516     return retval;
517 }
518
519 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
520 int
521 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
522 {
523     int retval;
524     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
525         vconn_send_wait(vconn);
526         poll_block();
527     }
528     return retval;
529 }
530
531 /* Same as vconn_recv, except that it waits until a message is received. */
532 int
533 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
534 {
535     int retval;
536     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
537         vconn_recv_wait(vconn);
538         poll_block();
539     }
540     return retval;
541 }
542
543 /* Waits until a message with a transaction ID matching 'xid' is recived on
544  * 'vconn'.  Returns 0 if successful, in which case the reply is stored in
545  * '*replyp' for the caller to examine and free.  Otherwise returns a positive
546  * errno value, or EOF, and sets '*replyp' to null.
547  *
548  * 'request' is always destroyed, regardless of the return value. */
549 int
550 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
551 {
552     for (;;) {
553         uint32_t recv_xid;
554         struct ofpbuf *reply;
555         int error;
556
557         error = vconn_recv_block(vconn, &reply);
558         if (error) {
559             *replyp = NULL;
560             return error;
561         }
562         recv_xid = ((struct ofp_header *) reply->data)->xid;
563         if (xid == recv_xid) {
564             *replyp = reply;
565             return 0;
566         }
567
568         VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
569                     " != expected %08"PRIx32, vconn->name, recv_xid, xid);
570         ofpbuf_delete(reply);
571     }
572 }
573
574 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
575  * matching transaction ID.  Returns 0 if successful, in which case the reply
576  * is stored in '*replyp' for the caller to examine and free.  Otherwise
577  * returns a positive errno value, or EOF, and sets '*replyp' to null.
578  *
579  * 'request' is always destroyed, regardless of the return value. */
580 int
581 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
582                struct ofpbuf **replyp)
583 {
584     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
585     int error;
586
587     *replyp = NULL;
588     error = vconn_send_block(vconn, request);
589     if (error) {
590         ofpbuf_delete(request);
591     }
592     return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
593 }
594
595 void
596 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
597 {
598     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
599
600     switch (vconn->state) {
601     case VCS_CONNECTING:
602         wait = WAIT_CONNECT;
603         break;
604
605     case VCS_SEND_HELLO:
606     case VCS_SEND_ERROR:
607         wait = WAIT_SEND;
608         break;
609
610     case VCS_RECV_HELLO:
611         wait = WAIT_RECV;
612         break;
613
614     case VCS_CONNECTED:
615         break;
616
617     case VCS_DISCONNECTED:
618         poll_immediate_wake();
619         return;
620     }
621     (vconn->class->wait)(vconn, wait);
622 }
623
624 void
625 vconn_connect_wait(struct vconn *vconn)
626 {
627     vconn_wait(vconn, WAIT_CONNECT);
628 }
629
630 void
631 vconn_recv_wait(struct vconn *vconn)
632 {
633     vconn_wait(vconn, WAIT_RECV);
634 }
635
636 void
637 vconn_send_wait(struct vconn *vconn)
638 {
639     vconn_wait(vconn, WAIT_SEND);
640 }
641
642 /* Attempts to start listening for OpenFlow connections.  'name' is a
643  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
644  * class's name and ARGS are vconn class-specific.
645  *
646  * Returns 0 if successful, otherwise a positive errno value.  If successful,
647  * stores a pointer to the new connection in '*pvconnp', otherwise a null
648  * pointer.  */
649 int
650 pvconn_open(const char *name, struct pvconn **pvconnp)
651 {
652     size_t prefix_len;
653     size_t i;
654
655     check_vconn_classes();
656
657     *pvconnp = NULL;
658     prefix_len = strcspn(name, ":");
659     if (prefix_len == strlen(name)) {
660         return EAFNOSUPPORT;
661     }
662     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
663         struct pvconn_class *class = pvconn_classes[i];
664         if (strlen(class->name) == prefix_len
665             && !memcmp(class->name, name, prefix_len)) {
666             char *suffix_copy = xstrdup(name + prefix_len + 1);
667             int retval = class->listen(name, suffix_copy, pvconnp);
668             free(suffix_copy);
669             if (retval) {
670                 *pvconnp = NULL;
671             }
672             return retval;
673         }
674     }
675     return EAFNOSUPPORT;
676 }
677
678 /* Returns the name that was used to open 'pvconn'.  The caller must not
679  * modify or free the name. */
680 const char *
681 pvconn_get_name(const struct pvconn *pvconn)
682 {
683     return pvconn->name;
684 }
685
686 /* Closes 'pvconn'. */
687 void
688 pvconn_close(struct pvconn *pvconn)
689 {
690     if (pvconn != NULL) {
691         char *name = pvconn->name;
692         (pvconn->class->close)(pvconn);
693         free(name);
694     }
695 }
696
697 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
698  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
699  * errno value.
700  *
701  * The new vconn will automatically negotiate an OpenFlow protocol version
702  * acceptable to both peers on the connection.  The version negotiated will be
703  * no lower than 'min_version' and no higher than OFP_VERSION.
704  *
705  * pvconn_accept() will not block waiting for a connection.  If no connection
706  * is ready to be accepted, it returns EAGAIN immediately. */
707 int
708 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
709 {
710     int retval = (pvconn->class->accept)(pvconn, new_vconn);
711     if (retval) {
712         *new_vconn = NULL;
713     } else {
714         assert((*new_vconn)->state != VCS_CONNECTING
715                || (*new_vconn)->class->connect);
716         (*new_vconn)->min_version = min_version;
717     }
718     return retval;
719 }
720
721 void
722 pvconn_wait(struct pvconn *pvconn)
723 {
724     (pvconn->class->wait)(pvconn);
725 }
726
727 /* XXX we should really use consecutive xids to avoid probabilistic
728  * failures. */
729 static inline uint32_t
730 alloc_xid(void)
731 {
732     return random_uint32();
733 }
734
735 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
736  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
737  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
738  * zeroed.
739  *
740  * The caller is responsible for freeing '*bufferp' when it is no longer
741  * needed.
742  *
743  * The OpenFlow header length is initially set to 'openflow_len'; if the
744  * message is later extended, the length should be updated with
745  * update_openflow_length() before sending.
746  *
747  * Returns the header. */
748 void *
749 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
750 {
751     *bufferp = ofpbuf_new(openflow_len);
752     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
753 }
754
755 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
756  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
757  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
758  * zeroed.
759  *
760  * The caller is responsible for freeing '*bufferp' when it is no longer
761  * needed.
762  *
763  * The OpenFlow header length is initially set to 'openflow_len'; if the
764  * message is later extended, the length should be updated with
765  * update_openflow_length() before sending.
766  *
767  * Returns the header. */
768 void *
769 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
770                   struct ofpbuf **bufferp)
771 {
772     *bufferp = ofpbuf_new(openflow_len);
773     return put_openflow_xid(openflow_len, type, xid, *bufferp);
774 }
775
776 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
777  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
778  * beyond the header, if any, are zeroed.
779  *
780  * The OpenFlow header length is initially set to 'openflow_len'; if the
781  * message is later extended, the length should be updated with
782  * update_openflow_length() before sending.
783  *
784  * Returns the header. */
785 void *
786 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
787 {
788     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
789 }
790
791 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
792  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
793  * the header, if any, are zeroed.
794  *
795  * The OpenFlow header length is initially set to 'openflow_len'; if the
796  * message is later extended, the length should be updated with
797  * update_openflow_length() before sending.
798  *
799  * Returns the header. */
800 void *
801 put_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
802                  struct ofpbuf *buffer)
803 {
804     struct ofp_header *oh;
805
806     assert(openflow_len >= sizeof *oh);
807     assert(openflow_len <= UINT16_MAX);
808
809     oh = ofpbuf_put_uninit(buffer, openflow_len);
810     oh->version = OFP_VERSION;
811     oh->type = type;
812     oh->length = htons(openflow_len);
813     oh->xid = xid;
814     memset(oh + 1, 0, openflow_len - sizeof *oh);
815     return oh;
816 }
817
818 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
819  * 'buffer->size'. */
820 void
821 update_openflow_length(struct ofpbuf *buffer) 
822 {
823     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
824     oh->length = htons(buffer->size); 
825 }
826
827 struct ofpbuf *
828 make_flow_mod(uint16_t command, const flow_t *flow, size_t actions_len)
829 {
830     struct ofp_flow_mod *ofm;
831     size_t size = sizeof *ofm + actions_len;
832     struct ofpbuf *out = ofpbuf_new(size);
833     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
834     ofm->header.version = OFP_VERSION;
835     ofm->header.type = OFPT_FLOW_MOD;
836     ofm->header.length = htons(size);
837     ofm->match.wildcards = htonl(0);
838     ofm->match.in_port = htons(flow->in_port == ODPP_LOCAL ? OFPP_LOCAL
839                                : flow->in_port);
840     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
841     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
842     ofm->match.dl_vlan = flow->dl_vlan;
843     ofm->match.dl_type = flow->dl_type;
844     ofm->match.nw_src = flow->nw_src;
845     ofm->match.nw_dst = flow->nw_dst;
846     ofm->match.nw_proto = flow->nw_proto;
847     ofm->match.tp_src = flow->tp_src;
848     ofm->match.tp_dst = flow->tp_dst;
849     ofm->command = htons(command);
850     return out;
851 }
852
853 struct ofpbuf *
854 make_add_flow(const flow_t *flow, uint32_t buffer_id,
855               uint16_t idle_timeout, size_t actions_len)
856 {
857     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, flow, actions_len);
858     struct ofp_flow_mod *ofm = out->data;
859     ofm->idle_timeout = htons(idle_timeout);
860     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
861     ofm->buffer_id = htonl(buffer_id);
862     return out;
863 }
864
865 struct ofpbuf *
866 make_del_flow(const flow_t *flow)
867 {
868     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, flow, 0);
869     struct ofp_flow_mod *ofm = out->data;
870     ofm->out_port = htons(OFPP_NONE);
871     return out;
872 }
873
874 struct ofpbuf *
875 make_add_simple_flow(const flow_t *flow,
876                      uint32_t buffer_id, uint16_t out_port,
877                      uint16_t idle_timeout)
878 {
879     struct ofp_action_output *oao;
880     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout,
881                                           sizeof *oao);
882     oao = ofpbuf_put_zeros(buffer, sizeof *oao);
883     oao->type = htons(OFPAT_OUTPUT);
884     oao->len = htons(sizeof *oao);
885     oao->port = htons(out_port);
886     return buffer;
887 }
888
889 struct ofpbuf *
890 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
891                 uint16_t in_port,
892                 const struct ofp_action_header *actions, size_t n_actions)
893 {
894     size_t actions_len = n_actions * sizeof *actions;
895     struct ofp_packet_out *opo;
896     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
897     struct ofpbuf *out = ofpbuf_new(size);
898
899     opo = ofpbuf_put_uninit(out, sizeof *opo);
900     opo->header.version = OFP_VERSION;
901     opo->header.type = OFPT_PACKET_OUT;
902     opo->header.length = htons(size);
903     opo->header.xid = htonl(0);
904     opo->buffer_id = htonl(buffer_id);
905     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
906     opo->actions_len = htons(actions_len);
907     ofpbuf_put(out, actions, actions_len);
908     if (packet) {
909         ofpbuf_put(out, packet->data, packet->size);
910     }
911     return out;
912 }
913
914 struct ofpbuf *
915 make_unbuffered_packet_out(const struct ofpbuf *packet,
916                            uint16_t in_port, uint16_t out_port)
917 {
918     struct ofp_action_output action;
919     action.type = htons(OFPAT_OUTPUT);
920     action.len = htons(sizeof action);
921     action.port = htons(out_port);
922     return make_packet_out(packet, UINT32_MAX, in_port,
923                            (struct ofp_action_header *) &action, 1);
924 }
925
926 struct ofpbuf *
927 make_buffered_packet_out(uint32_t buffer_id,
928                          uint16_t in_port, uint16_t out_port)
929 {
930     struct ofp_action_output action;
931     action.type = htons(OFPAT_OUTPUT);
932     action.len = htons(sizeof action);
933     action.port = htons(out_port);
934     return make_packet_out(NULL, buffer_id, in_port,
935                            (struct ofp_action_header *) &action, 1);
936 }
937
938 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
939 struct ofpbuf *
940 make_echo_request(void)
941 {
942     struct ofp_header *rq;
943     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
944     rq = ofpbuf_put_uninit(out, sizeof *rq);
945     rq->version = OFP_VERSION;
946     rq->type = OFPT_ECHO_REQUEST;
947     rq->length = htons(sizeof *rq);
948     rq->xid = 0;
949     return out;
950 }
951
952 /* Creates and returns an OFPT_ECHO_REPLY message matching the
953  * OFPT_ECHO_REQUEST message in 'rq'. */
954 struct ofpbuf *
955 make_echo_reply(const struct ofp_header *rq)
956 {
957     size_t size = ntohs(rq->length);
958     struct ofpbuf *out = ofpbuf_new(size);
959     struct ofp_header *reply = ofpbuf_put(out, rq, size);
960     reply->type = OFPT_ECHO_REPLY;
961     return out;
962 }
963
964 static int
965 check_message_type(uint8_t got_type, uint8_t want_type) 
966 {
967     if (got_type != want_type) {
968         char *want_type_name = ofp_message_type_to_string(want_type);
969         char *got_type_name = ofp_message_type_to_string(got_type);
970         VLOG_WARN_RL(&bad_ofmsg_rl,
971                      "received bad message type %s (expected %s)",
972                      got_type_name, want_type_name);
973         free(want_type_name);
974         free(got_type_name);
975         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
976     }
977     return 0;
978 }
979
980 /* Checks that 'msg' has type 'type' and that it is exactly 'size' bytes long.
981  * Returns 0 if the checks pass, otherwise an OpenFlow error code (produced
982  * with ofp_mkerr()). */
983 int
984 check_ofp_message(const struct ofp_header *msg, uint8_t type, size_t size)
985 {
986     size_t got_size;
987     int error;
988
989     error = check_message_type(msg->type, type);
990     if (error) {
991         return error;
992     }
993
994     got_size = ntohs(msg->length);
995     if (got_size != size) {
996         char *type_name = ofp_message_type_to_string(type);
997         VLOG_WARN_RL(&bad_ofmsg_rl,
998                      "received %s message of length %"PRIu16" (expected %zu)",
999                      type_name, got_size, size);
1000         free(type_name);
1001         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1002     }
1003
1004     return 0;
1005 }
1006
1007 /* Checks that 'msg' has type 'type' and that 'msg' is 'size' plus a
1008  * nonnegative integer multiple of 'array_elt_size' bytes long.  Returns 0 if
1009  * the checks pass, otherwise an OpenFlow error code (produced with
1010  * ofp_mkerr()).
1011  *
1012  * If 'n_array_elts' is nonnull, then '*n_array_elts' is set to the number of
1013  * 'array_elt_size' blocks in 'msg' past the first 'min_size' bytes, when
1014  * successful. */
1015 int
1016 check_ofp_message_array(const struct ofp_header *msg, uint8_t type,
1017                         size_t min_size, size_t array_elt_size,
1018                         size_t *n_array_elts)
1019 {
1020     size_t got_size;
1021     int error;
1022
1023     assert(array_elt_size);
1024
1025     error = check_message_type(msg->type, type);
1026     if (error) {
1027         return error;
1028     }
1029
1030     got_size = ntohs(msg->length);
1031     if (got_size < min_size) {
1032         char *type_name = ofp_message_type_to_string(type);
1033         VLOG_WARN_RL(&bad_ofmsg_rl, "received %s message of length %"PRIu16" "
1034                      "(expected at least %zu)",
1035                      type_name, got_size, min_size);
1036         free(type_name);
1037         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1038     }
1039     if ((got_size - min_size) % array_elt_size) {
1040         char *type_name = ofp_message_type_to_string(type);
1041         VLOG_WARN_RL(&bad_ofmsg_rl,
1042                      "received %s message of bad length %"PRIu16": the "
1043                      "excess over %zu (%zu) is not evenly divisible by %zu "
1044                      "(remainder is %zu)",
1045                      type_name, got_size, min_size, got_size - min_size,
1046                      array_elt_size, (got_size - min_size) % array_elt_size);
1047         free(type_name);
1048         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1049     }
1050     if (n_array_elts) {
1051         *n_array_elts = (got_size - min_size) / array_elt_size;
1052     }
1053     return 0;
1054 }
1055
1056 int
1057 check_ofp_packet_out(const struct ofp_header *oh, struct ofpbuf *data,
1058                      int *n_actionsp, int max_ports)
1059 {
1060     const struct ofp_packet_out *opo;
1061     unsigned int actions_len, n_actions;
1062     size_t extra;
1063     int error;
1064
1065     *n_actionsp = 0;
1066     error = check_ofp_message_array(oh, OFPT_PACKET_OUT,
1067                                     sizeof *opo, 1, &extra);
1068     if (error) {
1069         return error;
1070     }
1071     opo = (const struct ofp_packet_out *) oh;
1072
1073     actions_len = ntohs(opo->actions_len);
1074     if (actions_len > extra) {
1075         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %zu bytes of actions "
1076                      "but message has room for only %zu bytes",
1077                      actions_len, extra);
1078         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1079     }
1080     if (actions_len % sizeof(union ofp_action)) {
1081         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out claims %zu bytes of actions, "
1082                      "which is not a multiple of %zu",
1083                      actions_len, sizeof(union ofp_action));
1084         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LENGTH);
1085     }
1086
1087     n_actions = actions_len / sizeof(union ofp_action);
1088     error = validate_actions((const union ofp_action *) opo->actions,
1089                              n_actions, max_ports);
1090     if (error) {
1091         return error;
1092     }
1093
1094     data->data = (void *) &opo->actions[n_actions];
1095     data->size = extra - actions_len;
1096     *n_actionsp = n_actions;
1097     return 0;
1098 }
1099
1100 const struct ofp_flow_stats *
1101 flow_stats_first(struct flow_stats_iterator *iter,
1102                  const struct ofp_stats_reply *osr)
1103 {
1104     iter->pos = osr->body;
1105     iter->end = osr->body + (ntohs(osr->header.length)
1106                              - offsetof(struct ofp_stats_reply, body));
1107     return flow_stats_next(iter);
1108 }
1109
1110 const struct ofp_flow_stats *
1111 flow_stats_next(struct flow_stats_iterator *iter)
1112 {
1113     ptrdiff_t bytes_left = iter->end - iter->pos;
1114     const struct ofp_flow_stats *fs;
1115     size_t length;
1116
1117     if (bytes_left < sizeof *fs) {
1118         if (bytes_left != 0) {
1119             VLOG_WARN_RL(&bad_ofmsg_rl,
1120                          "%td leftover bytes in flow stats reply", bytes_left);
1121         }
1122         return NULL;
1123     }
1124
1125     fs = (const void *) iter->pos;
1126     length = ntohs(fs->length);
1127     if (length < sizeof *fs) {
1128         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu is shorter than "
1129                      "min %zu", length, sizeof *fs);
1130         return NULL;
1131     } else if (length > bytes_left) {
1132         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu but only %td "
1133                      "bytes left", length, bytes_left);
1134         return NULL;
1135     } else if ((length - sizeof *fs) % sizeof fs->actions[0]) {
1136         VLOG_WARN_RL(&bad_ofmsg_rl, "flow stats length %zu has %zu bytes "
1137                      "left over in final action", length,
1138                      (length - sizeof *fs) % sizeof fs->actions[0]);
1139         return NULL;
1140     }
1141     iter->pos += length;
1142     return fs;
1143 }
1144
1145 /* Alignment of ofp_actions. */
1146 #define ACTION_ALIGNMENT 8
1147
1148 static int
1149 check_action_exact_len(const union ofp_action *a, unsigned int len,
1150                        unsigned int required_len)
1151 {
1152     if (len != required_len) {
1153         VLOG_DBG_RL(&bad_ofmsg_rl,
1154                     "action %u has invalid length %"PRIu16" (must be %u)\n",
1155                     a->type, ntohs(a->header.len), required_len);
1156         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1157     }
1158     return 0;
1159 }
1160
1161 static int
1162 check_action_port(int port, int max_ports)
1163 {
1164     switch (port) {
1165     case OFPP_IN_PORT:
1166     case OFPP_TABLE:
1167     case OFPP_NORMAL:
1168     case OFPP_FLOOD:
1169     case OFPP_ALL:
1170     case OFPP_CONTROLLER:
1171     case OFPP_LOCAL:
1172         return 0;
1173
1174     default:
1175         if (port >= 0 && port < max_ports) {
1176             return 0;
1177         }
1178         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1179         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1180     }
1181 }
1182
1183 static int
1184 check_nicira_action(const union ofp_action *a, unsigned int len)
1185 {
1186     const struct nx_action_header *nah;
1187
1188     if (len < 16) {
1189         VLOG_DBG_RL(&bad_ofmsg_rl,
1190                     "Nicira vendor action only %u bytes", len);
1191         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1192     }
1193     nah = (const struct nx_action_header *) a;
1194
1195     switch (ntohs(nah->subtype)) {
1196     case NXAST_RESUBMIT:
1197         return check_action_exact_len(a, len, 16);
1198     default:
1199         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1200     }
1201 }
1202
1203 static int
1204 check_action(const union ofp_action *a, unsigned int len, int max_ports)
1205 {
1206     int error;
1207
1208     switch (a->type) {
1209     case OFPAT_OUTPUT:
1210         error = check_action_port(ntohs(a->output.port), max_ports);
1211         if (error) {
1212             return error;
1213         }
1214         return check_action_exact_len(a, len, 8);
1215
1216     case OFPAT_SET_VLAN_VID:
1217     case OFPAT_SET_VLAN_PCP:
1218     case OFPAT_STRIP_VLAN:
1219     case OFPAT_SET_NW_SRC:
1220     case OFPAT_SET_NW_DST:
1221     case OFPAT_SET_TP_SRC:
1222     case OFPAT_SET_TP_DST:
1223         return check_action_exact_len(a, len, 8);
1224
1225     case OFPAT_SET_DL_SRC:
1226     case OFPAT_SET_DL_DST:
1227         return check_action_exact_len(a, len, 16);
1228
1229     case OFPAT_VENDOR:
1230         if (a->vendor.vendor == htonl(NX_VENDOR_ID)) {
1231             return check_nicira_action(a, len);
1232         } else {
1233             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR);
1234         }
1235         break;
1236
1237     default:
1238         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %"PRIu16, a->type);
1239         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
1240     }
1241
1242     if (!len) {
1243         VLOG_DBG_RL(&bad_ofmsg_rl, "action has invalid length 0");
1244         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1245     }
1246     if (len % ACTION_ALIGNMENT) {
1247         VLOG_DBG_RL(&bad_ofmsg_rl, "action length %u is not a multiple of %d",
1248                     len, ACTION_ALIGNMENT);
1249         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1250     }
1251     return 0;
1252 }
1253
1254 int
1255 validate_actions(const union ofp_action *actions, size_t n_actions,
1256                  int max_ports)
1257 {
1258     const union ofp_action *a;
1259
1260     for (a = actions; a < &actions[n_actions]; ) {
1261         unsigned int len = ntohs(a->header.len);
1262         unsigned int n_slots = len / ACTION_ALIGNMENT;
1263         unsigned int slots_left = &actions[n_actions] - a;
1264         int error;
1265
1266         if (n_slots > slots_left) {
1267             VLOG_DBG_RL(&bad_ofmsg_rl,
1268                         "action requires %u slots but only %td remain",
1269                         n_slots, slots_left);
1270             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1271         }
1272         error = check_action(a, len, max_ports);
1273         if (error) {
1274             return error;
1275         }
1276         a += n_slots;
1277     }
1278     return 0;
1279 }
1280
1281 /* The set of actions must either come from a trusted source or have been
1282  * previously validated with validate_actions(). */
1283 const union ofp_action *
1284 actions_first(struct actions_iterator *iter,
1285               const union ofp_action *oa, size_t n_actions)
1286 {
1287     iter->pos = oa;
1288     iter->end = oa + n_actions;
1289     return actions_next(iter);
1290 }
1291
1292 const union ofp_action *
1293 actions_next(struct actions_iterator *iter)
1294 {
1295     if (iter->pos < iter->end) {
1296         const union ofp_action *a = iter->pos;
1297         unsigned int len = ntohs(a->header.len);
1298         iter->pos += len / ACTION_ALIGNMENT;
1299         return a;
1300     } else {
1301         return NULL;
1302     }
1303 }
1304
1305 void
1306 normalize_match(struct ofp_match *m)
1307 {
1308     enum { OFPFW_NW = OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO };
1309     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
1310     uint32_t wc;
1311
1312     wc = ntohl(m->wildcards) & OFPFW_ALL;
1313     if (wc & OFPFW_DL_TYPE) {
1314         m->dl_type = 0;
1315
1316         /* Can't sensibly m on network or transport headers if the
1317          * data link type is unknown. */
1318         wc |= OFPFW_NW | OFPFW_TP;
1319         m->nw_src = m->nw_dst = m->nw_proto = 0;
1320         m->tp_src = m->tp_dst = 0;
1321     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
1322         if (wc & OFPFW_NW_PROTO) {
1323             m->nw_proto = 0;
1324
1325             /* Can't sensibly m on transport headers if the network
1326              * protocol is unknown. */
1327             wc |= OFPFW_TP;
1328             m->tp_src = m->tp_dst = 0;
1329         } else if (m->nw_proto == IPPROTO_TCP ||
1330                    m->nw_proto == IPPROTO_UDP ||
1331                    m->nw_proto == IPPROTO_ICMP) {
1332             if (wc & OFPFW_TP_SRC) {
1333                 m->tp_src = 0;
1334             }
1335             if (wc & OFPFW_TP_DST) {
1336                 m->tp_dst = 0;
1337             }
1338         } else {
1339             /* Transport layer fields will always be extracted as zeros, so we
1340              * can do an exact-m on those values.  */
1341             wc &= ~OFPFW_TP;
1342             m->tp_src = m->tp_dst = 0;
1343         }
1344         if (wc & OFPFW_NW_SRC_MASK) {
1345             m->nw_src &= flow_nw_bits_to_mask(wc, OFPFW_NW_SRC_SHIFT);
1346         }
1347         if (wc & OFPFW_NW_DST_MASK) {
1348             m->nw_dst &= flow_nw_bits_to_mask(wc, OFPFW_NW_DST_SHIFT);
1349         }
1350     } else {
1351         /* Network and transport layer fields will always be extracted as
1352          * zeros, so we can do an exact-m on those values. */
1353         wc &= ~(OFPFW_NW | OFPFW_TP);
1354         m->nw_proto = m->nw_src = m->nw_dst = 0;
1355         m->tp_src = m->tp_dst = 0;
1356     }
1357     if (wc & OFPFW_DL_SRC) {
1358         memset(m->dl_src, 0, sizeof m->dl_src);
1359     }
1360     if (wc & OFPFW_DL_DST) {
1361         memset(m->dl_dst, 0, sizeof m->dl_dst);
1362     }
1363     m->wildcards = htonl(wc);
1364 }
1365
1366 void
1367 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1368            uint32_t ip, const char *name, bool reconnectable)
1369 {
1370     vconn->class = class;
1371     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1372                     : !connect_status ? VCS_SEND_HELLO
1373                     : VCS_DISCONNECTED);
1374     vconn->error = connect_status;
1375     vconn->version = -1;
1376     vconn->min_version = -1;
1377     vconn->ip = ip;
1378     vconn->name = xstrdup(name);
1379     vconn->reconnectable = reconnectable;
1380 }
1381
1382 void
1383 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1384             const char *name)
1385 {
1386     pvconn->class = class;
1387     pvconn->name = xstrdup(name);
1388 }