Modify OpenFlow commands related to ports to be more expressive.
[sliver-openvswitch.git] / lib / vconn.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "vconn-provider.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <poll.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include "dynamic-string.h"
44 #include "flow.h"
45 #include "ofp-print.h"
46 #include "ofpbuf.h"
47 #include "openflow.h"
48 #include "poll-loop.h"
49 #include "random.h"
50 #include "util.h"
51
52 #define THIS_MODULE VLM_vconn
53 #include "vlog.h"
54
55 /* State of an active vconn.*/
56 enum vconn_state {
57     /* This is the ordinary progression of states. */
58     VCS_CONNECTING,             /* Underlying vconn is not connected. */
59     VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
60     VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
61     VCS_CONNECTED,              /* Connection established. */
62
63     /* These states are entered only when something goes wrong. */
64     VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
65     VCS_DISCONNECTED            /* Connection failed or connection closed. */
66 };
67
68 static struct vconn_class *vconn_classes[] = {
69     &tcp_vconn_class,
70     &unix_vconn_class,
71 #ifdef HAVE_NETLINK
72     &netlink_vconn_class,
73 #endif
74 #ifdef HAVE_OPENSSL
75     &ssl_vconn_class,
76 #endif
77 };
78
79 static struct pvconn_class *pvconn_classes[] = {
80     &ptcp_pvconn_class,
81     &punix_pvconn_class,
82 #ifdef HAVE_OPENSSL
83     &pssl_pvconn_class,
84 #endif
85 };
86
87 /* High rate limit because most of the rate-limiting here is individual
88  * OpenFlow messages going over the vconn.  If those are enabled then we
89  * really need to see them. */
90 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(600, 600);
91
92 static int do_recv(struct vconn *, struct ofpbuf **);
93 static int do_send(struct vconn *, struct ofpbuf *);
94
95 /* Check the validity of the vconn class structures. */
96 static void
97 check_vconn_classes(void)
98 {
99 #ifndef NDEBUG
100     size_t i;
101
102     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
103         struct vconn_class *class = vconn_classes[i];
104         assert(class->name != NULL);
105         assert(class->open != NULL);
106         if (class->close || class->recv || class->send || class->wait) {
107             assert(class->close != NULL);
108             assert(class->recv != NULL);
109             assert(class->send != NULL);
110             assert(class->wait != NULL);
111         } else {
112             /* This class delegates to another one. */
113         }
114     }
115
116     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
117         struct pvconn_class *class = pvconn_classes[i];
118         assert(class->name != NULL);
119         assert(class->listen != NULL);
120         if (class->close || class->accept || class->wait) {
121             assert(class->close != NULL);
122             assert(class->accept != NULL);
123             assert(class->wait != NULL);
124         } else {
125             /* This class delegates to another one. */
126         }
127     }
128 #endif
129 }
130
131 /* Prints information on active (if 'active') and passive (if 'passive')
132  * connection methods supported by the vconn.  If 'bootstrap' is true, also
133  * advertises options to bootstrap the CA certificate. */
134 void
135 vconn_usage(bool active, bool passive, bool bootstrap UNUSED)
136 {
137     /* Really this should be implemented via callbacks into the vconn
138      * providers, but that seems too heavy-weight to bother with at the
139      * moment. */
140     
141     printf("\n");
142     if (active) {
143         printf("Active OpenFlow connection methods:\n");
144 #ifdef HAVE_NETLINK
145         printf("  nl:DP_IDX               "
146                "local datapath DP_IDX\n");
147 #endif
148         printf("  tcp:HOST[:PORT]         "
149                "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT);
150 #ifdef HAVE_OPENSSL
151         printf("  ssl:HOST[:PORT]         "
152                "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT);
153 #endif
154         printf("  unix:FILE               Unix domain socket named FILE\n");
155     }
156
157     if (passive) {
158         printf("Passive OpenFlow connection methods:\n");
159         printf("  ptcp:[PORT]             "
160                "listen to TCP PORT (default: %d)\n",
161                OFP_TCP_PORT);
162 #ifdef HAVE_OPENSSL
163         printf("  pssl:[PORT]             "
164                "listen for SSL on PORT (default: %d)\n",
165                OFP_SSL_PORT);
166 #endif
167         printf("  punix:FILE              "
168                "listen on Unix domain socket FILE\n");
169     }
170
171 #ifdef HAVE_OPENSSL
172     printf("PKI configuration (required to use SSL):\n"
173            "  -p, --private-key=FILE  file with private key\n"
174            "  -c, --certificate=FILE  file with certificate for private key\n"
175            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
176     if (bootstrap) {
177         printf("  --bootstrap-ca-cert=FILE  file with peer CA certificate "
178                "to read or create\n");
179     }
180 #endif
181 }
182
183 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
184  * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
185  * are vconn class-specific.
186  *
187  * The vconn will automatically negotiate an OpenFlow protocol version
188  * acceptable to both peers on the connection.  The version negotiated will be
189  * no lower than 'min_version' and no higher than OFP_VERSION.
190  *
191  * Returns 0 if successful, otherwise a positive errno value.  If successful,
192  * stores a pointer to the new connection in '*vconnp', otherwise a null
193  * pointer.  */
194 int
195 vconn_open(const char *name, int min_version, struct vconn **vconnp)
196 {
197     size_t prefix_len;
198     size_t i;
199
200     check_vconn_classes();
201
202     *vconnp = NULL;
203     prefix_len = strcspn(name, ":");
204     if (prefix_len == strlen(name)) {
205         return EAFNOSUPPORT;
206     }
207     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
208         struct vconn_class *class = vconn_classes[i];
209         if (strlen(class->name) == prefix_len
210             && !memcmp(class->name, name, prefix_len)) {
211             struct vconn *vconn;
212             char *suffix_copy = xstrdup(name + prefix_len + 1);
213             int retval = class->open(name, suffix_copy, &vconn);
214             free(suffix_copy);
215             if (!retval) {
216                 assert(vconn->state != VCS_CONNECTING
217                        || vconn->class->connect);
218                 vconn->min_version = min_version;
219                 *vconnp = vconn;
220             }
221             return retval;
222         }
223     }
224     return EAFNOSUPPORT;
225 }
226
227 int
228 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
229 {
230     struct vconn *vconn;
231     int error;
232
233     error = vconn_open(name, min_version, &vconn);
234     while (error == EAGAIN) {
235         vconn_connect_wait(vconn);
236         poll_block();
237         error = vconn_connect(vconn);
238         assert(error != EINPROGRESS);
239     }
240     if (error) {
241         vconn_close(vconn);
242         *vconnp = NULL;
243     } else {
244         *vconnp = vconn;
245     }
246     return error;
247 }
248
249 /* Closes 'vconn'. */
250 void
251 vconn_close(struct vconn *vconn)
252 {
253     if (vconn != NULL) {
254         char *name = vconn->name;
255         (vconn->class->close)(vconn);
256         free(name);
257     }
258 }
259
260 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
261 const char *
262 vconn_get_name(const struct vconn *vconn)
263 {
264     return vconn->name;
265 }
266
267 /* Returns the IP address of the peer, or 0 if the peer is not connected over
268  * an IP-based protocol or if its IP address is not yet known. */
269 uint32_t
270 vconn_get_ip(const struct vconn *vconn) 
271 {
272     return vconn->ip;
273 }
274
275 static void
276 vcs_connecting(struct vconn *vconn) 
277 {
278     int retval = (vconn->class->connect)(vconn);
279     assert(retval != EINPROGRESS);
280     if (!retval) {
281         vconn->state = VCS_SEND_HELLO;
282     } else if (retval != EAGAIN) {
283         vconn->state = VCS_DISCONNECTED;
284         vconn->error = retval;
285     }
286 }
287
288 static void
289 vcs_send_hello(struct vconn *vconn)
290 {
291     struct ofpbuf *b;
292     int retval;
293
294     make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
295     retval = do_send(vconn, b);
296     if (!retval) {
297         vconn->state = VCS_RECV_HELLO;
298     } else {
299         ofpbuf_delete(b);
300         if (retval != EAGAIN) {
301             vconn->state = VCS_DISCONNECTED;
302             vconn->error = retval;
303         }
304     }
305 }
306
307 static void
308 vcs_recv_hello(struct vconn *vconn)
309 {
310     struct ofpbuf *b;
311     int retval;
312
313     retval = do_recv(vconn, &b);
314     if (!retval) {
315         struct ofp_header *oh = b->data;
316
317         if (oh->type == OFPT_HELLO) {
318             if (b->size > sizeof *oh) {
319                 struct ds msg = DS_EMPTY_INITIALIZER;
320                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
321                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
322                 VLOG_WARN_RL(&rl, ds_cstr(&msg));
323                 ds_destroy(&msg);
324             }
325
326             vconn->version = MIN(OFP_VERSION, oh->version);
327             if (vconn->version < vconn->min_version) {
328                 VLOG_WARN_RL(&rl, "%s: version negotiation failed: we support "
329                              "versions 0x%02x to 0x%02x inclusive but peer "
330                              "supports no later than version 0x%02"PRIx8,
331                              vconn->name, vconn->min_version, OFP_VERSION,
332                              oh->version);
333                 vconn->state = VCS_SEND_ERROR;
334             } else {
335                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
336                          "(we support versions 0x%02x to 0x%02x inclusive, "
337                          "peer no later than version 0x%02"PRIx8")",
338                          vconn->name, vconn->version, vconn->min_version,
339                          OFP_VERSION, oh->version);
340                 vconn->state = VCS_CONNECTED;
341             }
342             ofpbuf_delete(b);
343             return;
344         } else {
345             char *s = ofp_to_string(b->data, b->size, 1);
346             VLOG_WARN_RL(&rl, "%s: received message while expecting hello: %s",
347                          vconn->name, s);
348             free(s);
349             retval = EPROTO;
350             ofpbuf_delete(b);
351         }
352     }
353
354     if (retval != EAGAIN) {
355         vconn->state = VCS_DISCONNECTED;
356         vconn->error = retval;
357     }
358 }
359
360 static void
361 vcs_send_error(struct vconn *vconn)
362 {
363     struct ofp_error_msg *error;
364     struct ofpbuf *b;
365     char s[128];
366     int retval;
367
368     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
369              "you support no later than version 0x%02"PRIx8".",
370              vconn->min_version, OFP_VERSION, vconn->version);
371     error = make_openflow(sizeof *error, OFPT_ERROR, &b);
372     error->type = htons(OFPET_HELLO_FAILED);
373     error->code = htons(OFPHFC_INCOMPATIBLE);
374     ofpbuf_put(b, s, strlen(s));
375     retval = do_send(vconn, b);
376     if (retval) {
377         ofpbuf_delete(b);
378     }
379     if (retval != EAGAIN) {
380         vconn->state = VCS_DISCONNECTED;
381         vconn->error = retval ? retval : EPROTO;
382     }
383 }
384
385 /* Tries to complete the connection on 'vconn', which must be an active
386  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
387  * was successful or a positive errno value if it failed.  If the
388  * connection is still in progress, returns EAGAIN. */
389 int
390 vconn_connect(struct vconn *vconn)
391 {
392     enum vconn_state last_state;
393
394     assert(vconn->min_version >= 0);
395     do {
396         last_state = vconn->state;
397         switch (vconn->state) {
398         case VCS_CONNECTING:
399             vcs_connecting(vconn);
400             break;
401
402         case VCS_SEND_HELLO:
403             vcs_send_hello(vconn);
404             break;
405
406         case VCS_RECV_HELLO:
407             vcs_recv_hello(vconn);
408             break;
409
410         case VCS_CONNECTED:
411             return 0;
412
413         case VCS_SEND_ERROR:
414             vcs_send_error(vconn);
415             break;
416
417         case VCS_DISCONNECTED:
418             return vconn->error;
419
420         default:
421             NOT_REACHED();
422         }
423     } while (vconn->state != last_state);
424
425     return EAGAIN;
426 }
427
428 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
429  * vconn.  If successful, stores the received message into '*msgp' and returns
430  * 0.  The caller is responsible for destroying the message with
431  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
432  * null pointer into '*msgp'.  On normal connection close, returns EOF.
433  *
434  * vconn_recv will not block waiting for a packet to arrive.  If no packets
435  * have been received, it returns EAGAIN immediately. */
436 int
437 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
438 {
439     int retval = vconn_connect(vconn);
440     if (!retval) {
441         retval = do_recv(vconn, msgp);
442     }
443     return retval;
444 }
445
446 static int
447 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
448 {
449     int retval;
450
451     retval = (vconn->class->recv)(vconn, msgp);
452     if (!retval) {
453         struct ofp_header *oh;
454
455         if (VLOG_IS_DBG_ENABLED()) {
456             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
457             VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
458             free(s);
459         }
460
461         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
462         if (oh->version != vconn->version
463             && oh->type != OFPT_HELLO
464             && oh->type != OFPT_ERROR
465             && oh->type != OFPT_ECHO_REQUEST
466             && oh->type != OFPT_ECHO_REPLY
467             && oh->type != OFPT_VENDOR)
468         {
469             if (vconn->version < 0) {
470                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
471                             "before version negotiation complete",
472                             vconn->name, oh->version);
473             } else {
474                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
475                             "!= expected %02x",
476                             vconn->name, oh->version, vconn->version);
477             }
478             ofpbuf_delete(*msgp);
479             retval = EPROTO;
480         }
481     }
482     if (retval) {
483         *msgp = NULL;
484     }
485     return retval;
486 }
487
488 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
489  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
490  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
491  * ever will be delivered to the peer, only that it has been queued for
492  * transmission.
493  *
494  * Returns a positive errno value on failure, in which case the caller
495  * retains ownership of 'msg'.
496  *
497  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
498  * transmission, it returns EAGAIN immediately. */
499 int
500 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
501 {
502     int retval = vconn_connect(vconn);
503     if (!retval) {
504         retval = do_send(vconn, msg);
505     }
506     return retval;
507 }
508
509 static int
510 do_send(struct vconn *vconn, struct ofpbuf *msg)
511 {
512     int retval;
513
514     assert(msg->size >= sizeof(struct ofp_header));
515     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
516     if (!VLOG_IS_DBG_ENABLED()) {
517         retval = (vconn->class->send)(vconn, msg);
518     } else {
519         char *s = ofp_to_string(msg->data, msg->size, 1);
520         retval = (vconn->class->send)(vconn, msg);
521         if (retval != EAGAIN) {
522             VLOG_DBG_RL(&rl, "%s: sent (%s): %s",
523                         vconn->name, strerror(retval), s);
524         }
525         free(s);
526     }
527     return retval;
528 }
529
530 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
531 int
532 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
533 {
534     int retval;
535     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
536         vconn_send_wait(vconn);
537         poll_block();
538     }
539     return retval;
540 }
541
542 /* Same as vconn_recv, except that it waits until a message is received. */
543 int
544 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
545 {
546     int retval;
547     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
548         vconn_recv_wait(vconn);
549         poll_block();
550     }
551     return retval;
552 }
553
554 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
555  * matching transaction ID.  Returns 0 if successful, in which case the reply
556  * is stored in '*replyp' for the caller to examine and free.  Otherwise
557  * returns a positive errno value, or EOF, and sets '*replyp' to null.
558  *
559  * 'request' is always destroyed, regardless of the return value. */
560 int
561 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
562                struct ofpbuf **replyp)
563 {
564     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
565     int error;
566
567     *replyp = NULL;
568     error = vconn_send_block(vconn, request);
569     if (error) {
570         ofpbuf_delete(request);
571         return error;
572     }
573     for (;;) {
574         uint32_t recv_xid;
575         struct ofpbuf *reply;
576
577         error = vconn_recv_block(vconn, &reply);
578         if (error) {
579             return error;
580         }
581         recv_xid = ((struct ofp_header *) reply->data)->xid;
582         if (send_xid == recv_xid) {
583             *replyp = reply;
584             return 0;
585         }
586
587         VLOG_DBG_RL(&rl, "%s: received reply with xid %08"PRIx32" != expected "
588                     "%08"PRIx32, vconn->name, recv_xid, send_xid);
589         ofpbuf_delete(reply);
590     }
591 }
592
593 void
594 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
595 {
596     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
597
598     switch (vconn->state) {
599     case VCS_CONNECTING:
600         wait = WAIT_CONNECT;
601         break;
602
603     case VCS_SEND_HELLO:
604     case VCS_SEND_ERROR:
605         wait = WAIT_SEND;
606         break;
607
608     case VCS_RECV_HELLO:
609         wait = WAIT_RECV;
610         break;
611
612     case VCS_CONNECTED:
613         break;
614
615     case VCS_DISCONNECTED:
616         poll_immediate_wake();
617         return;
618     }
619     (vconn->class->wait)(vconn, wait);
620 }
621
622 void
623 vconn_connect_wait(struct vconn *vconn)
624 {
625     vconn_wait(vconn, WAIT_CONNECT);
626 }
627
628 void
629 vconn_recv_wait(struct vconn *vconn)
630 {
631     vconn_wait(vconn, WAIT_RECV);
632 }
633
634 void
635 vconn_send_wait(struct vconn *vconn)
636 {
637     vconn_wait(vconn, WAIT_SEND);
638 }
639
640 /* Attempts to start listening for OpenFlow connections.  'name' is a
641  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
642  * class's name and ARGS are vconn class-specific.
643  *
644  * Returns 0 if successful, otherwise a positive errno value.  If successful,
645  * stores a pointer to the new connection in '*pvconnp', otherwise a null
646  * pointer.  */
647 int
648 pvconn_open(const char *name, struct pvconn **pvconnp)
649 {
650     size_t prefix_len;
651     size_t i;
652
653     check_vconn_classes();
654
655     *pvconnp = NULL;
656     prefix_len = strcspn(name, ":");
657     if (prefix_len == strlen(name)) {
658         return EAFNOSUPPORT;
659     }
660     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
661         struct pvconn_class *class = pvconn_classes[i];
662         if (strlen(class->name) == prefix_len
663             && !memcmp(class->name, name, prefix_len)) {
664             char *suffix_copy = xstrdup(name + prefix_len + 1);
665             int retval = class->listen(name, suffix_copy, pvconnp);
666             free(suffix_copy);
667             if (retval) {
668                 *pvconnp = NULL;
669             }
670             return retval;
671         }
672     }
673     return EAFNOSUPPORT;
674 }
675
676 /* Closes 'pvconn'. */
677 void
678 pvconn_close(struct pvconn *pvconn)
679 {
680     if (pvconn != NULL) {
681         char *name = pvconn->name;
682         (pvconn->class->close)(pvconn);
683         free(name);
684     }
685 }
686
687 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
688  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
689  * errno value.
690  *
691  * The new vconn will automatically negotiate an OpenFlow protocol version
692  * acceptable to both peers on the connection.  The version negotiated will be
693  * no lower than 'min_version' and no higher than OFP_VERSION.
694  *
695  * pvconn_accept() will not block waiting for a connection.  If no connection
696  * is ready to be accepted, it returns EAGAIN immediately. */
697 int
698 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
699 {
700     int retval = (pvconn->class->accept)(pvconn, new_vconn);
701     if (retval) {
702         *new_vconn = NULL;
703     } else {
704         assert((*new_vconn)->state != VCS_CONNECTING
705                || (*new_vconn)->class->connect);
706         (*new_vconn)->min_version = min_version;
707     }
708     return retval;
709 }
710
711 void
712 pvconn_wait(struct pvconn *pvconn)
713 {
714     (pvconn->class->wait)(pvconn);
715 }
716
717 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
718  * containing an OpenFlow header with the given 'type' and a random transaction
719  * id.  Stores the new buffer in '*bufferp'.  The caller must free the buffer
720  * when it is no longer needed. */
721 void *
722 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp) 
723 {
724     return make_openflow_xid(openflow_len, type, random_uint32(), bufferp);
725 }
726
727 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
728  * containing an OpenFlow header with the given 'type' and transaction id
729  * 'xid'.  Stores the new buffer in '*bufferp'.  The caller must free the
730  * buffer when it is no longer needed. */
731 void *
732 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
733                   struct ofpbuf **bufferp)
734 {
735     struct ofpbuf *buffer;
736     struct ofp_header *oh;
737
738     assert(openflow_len >= sizeof *oh);
739     assert(openflow_len <= UINT16_MAX);
740     buffer = *bufferp = ofpbuf_new(openflow_len);
741     oh = ofpbuf_put_uninit(buffer, openflow_len);
742     memset(oh, 0, openflow_len);
743     oh->version = OFP_VERSION;
744     oh->type = type;
745     oh->length = htons(openflow_len);
746     oh->xid = xid;
747     return oh;
748 }
749
750 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
751  * 'buffer->size'. */
752 void
753 update_openflow_length(struct ofpbuf *buffer) 
754 {
755     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
756     oh->length = htons(buffer->size); 
757 }
758
759 struct ofpbuf *
760 make_add_flow(const struct flow *flow, uint32_t buffer_id,
761               uint16_t idle_timeout, size_t n_actions)
762 {
763     struct ofp_flow_mod *ofm;
764     size_t size = sizeof *ofm + n_actions * sizeof ofm->actions[0];
765     struct ofpbuf *out = ofpbuf_new(size);
766     ofm = ofpbuf_put_uninit(out, size);
767     memset(ofm, 0, size);
768     ofm->header.version = OFP_VERSION;
769     ofm->header.type = OFPT_FLOW_MOD;
770     ofm->header.length = htons(size);
771     ofm->match.wildcards = htonl(0);
772     ofm->match.in_port = flow->in_port;
773     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
774     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
775     ofm->match.dl_vlan = flow->dl_vlan;
776     ofm->match.dl_type = flow->dl_type;
777     ofm->match.nw_src = flow->nw_src;
778     ofm->match.nw_dst = flow->nw_dst;
779     ofm->match.nw_proto = flow->nw_proto;
780     ofm->match.tp_src = flow->tp_src;
781     ofm->match.tp_dst = flow->tp_dst;
782     ofm->command = htons(OFPFC_ADD);
783     ofm->idle_timeout = htons(idle_timeout);
784     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
785     ofm->buffer_id = htonl(buffer_id);
786     return out;
787 }
788
789 struct ofpbuf *
790 make_add_simple_flow(const struct flow *flow,
791                      uint32_t buffer_id, uint16_t out_port,
792                      uint16_t idle_timeout)
793 {
794     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout, 1);
795     struct ofp_flow_mod *ofm = buffer->data;
796     ofm->actions[0].type = htons(OFPAT_OUTPUT);
797     ofm->actions[0].arg.output.max_len = htons(0);
798     ofm->actions[0].arg.output.port = htons(out_port);
799     return buffer;
800 }
801
802 struct ofpbuf *
803 make_unbuffered_packet_out(const struct ofpbuf *packet,
804                            uint16_t in_port, uint16_t out_port)
805 {
806     struct ofp_packet_out *opo;
807     size_t size = sizeof *opo + sizeof opo->actions[0];
808     struct ofpbuf *out = ofpbuf_new(size + packet->size);
809     opo = ofpbuf_put_uninit(out, size);
810     memset(opo, 0, size);
811     opo->header.version = OFP_VERSION;
812     opo->header.type = OFPT_PACKET_OUT;
813     opo->buffer_id = htonl(UINT32_MAX);
814     opo->in_port = htons(in_port);
815     opo->n_actions = htons(1);
816     opo->actions[0].type = htons(OFPAT_OUTPUT);
817     opo->actions[0].arg.output.max_len = htons(0);
818     opo->actions[0].arg.output.port = htons(out_port);
819     ofpbuf_put(out, packet->data, packet->size);
820     update_openflow_length(out);
821     return out;
822 }
823
824 struct ofpbuf *
825 make_buffered_packet_out(uint32_t buffer_id,
826                          uint16_t in_port, uint16_t out_port)
827 {
828     struct ofp_packet_out *opo;
829     size_t size = sizeof *opo + sizeof opo->actions[0];
830     struct ofpbuf *out = ofpbuf_new(size);
831     opo = ofpbuf_put_uninit(out, size);
832     memset(opo, 0, size);
833     opo->header.version = OFP_VERSION;
834     opo->header.type = OFPT_PACKET_OUT;
835     opo->header.length = htons(size);
836     opo->buffer_id = htonl(buffer_id);
837     opo->in_port = htons(in_port);
838     opo->n_actions = htons(1);
839     opo->actions[0].type = htons(OFPAT_OUTPUT);
840     opo->actions[0].arg.output.max_len = htons(0);
841     opo->actions[0].arg.output.port = htons(out_port);
842     return out;
843 }
844
845 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
846 struct ofpbuf *
847 make_echo_request(void)
848 {
849     struct ofp_header *rq;
850     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
851     rq = ofpbuf_put_uninit(out, sizeof *rq);
852     rq->version = OFP_VERSION;
853     rq->type = OFPT_ECHO_REQUEST;
854     rq->length = htons(sizeof *rq);
855     rq->xid = 0;
856     return out;
857 }
858
859 /* Creates and returns an OFPT_ECHO_REPLY message matching the
860  * OFPT_ECHO_REQUEST message in 'rq'. */
861 struct ofpbuf *
862 make_echo_reply(const struct ofp_header *rq)
863 {
864     size_t size = ntohs(rq->length);
865     struct ofpbuf *out = ofpbuf_new(size);
866     struct ofp_header *reply = ofpbuf_put(out, rq, size);
867     reply->type = OFPT_ECHO_REPLY;
868     return out;
869 }
870
871 void
872 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
873            uint32_t ip, const char *name)
874 {
875     vconn->class = class;
876     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
877                     : !connect_status ? VCS_SEND_HELLO
878                     : VCS_DISCONNECTED);
879     vconn->error = connect_status;
880     vconn->version = -1;
881     vconn->min_version = -1;
882     vconn->ip = ip;
883     vconn->name = xstrdup(name);
884 }
885
886 void
887 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
888             const char *name)
889 {
890     pvconn->class = class;
891     pvconn->name = xstrdup(name);
892 }