For SNAT, don't store the pre-fragment L2 header before actions are applied.
[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/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, "%s", 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     update_openflow_length(b);
376     retval = do_send(vconn, b);
377     if (retval) {
378         ofpbuf_delete(b);
379     }
380     if (retval != EAGAIN) {
381         vconn->state = VCS_DISCONNECTED;
382         vconn->error = retval ? retval : EPROTO;
383     }
384 }
385
386 /* Tries to complete the connection on 'vconn', which must be an active
387  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
388  * was successful or a positive errno value if it failed.  If the
389  * connection is still in progress, returns EAGAIN. */
390 int
391 vconn_connect(struct vconn *vconn)
392 {
393     enum vconn_state last_state;
394
395     assert(vconn->min_version >= 0);
396     do {
397         last_state = vconn->state;
398         switch (vconn->state) {
399         case VCS_CONNECTING:
400             vcs_connecting(vconn);
401             break;
402
403         case VCS_SEND_HELLO:
404             vcs_send_hello(vconn);
405             break;
406
407         case VCS_RECV_HELLO:
408             vcs_recv_hello(vconn);
409             break;
410
411         case VCS_CONNECTED:
412             return 0;
413
414         case VCS_SEND_ERROR:
415             vcs_send_error(vconn);
416             break;
417
418         case VCS_DISCONNECTED:
419             return vconn->error;
420
421         default:
422             NOT_REACHED();
423         }
424     } while (vconn->state != last_state);
425
426     return EAGAIN;
427 }
428
429 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
430  * vconn.  If successful, stores the received message into '*msgp' and returns
431  * 0.  The caller is responsible for destroying the message with
432  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
433  * null pointer into '*msgp'.  On normal connection close, returns EOF.
434  *
435  * vconn_recv will not block waiting for a packet to arrive.  If no packets
436  * have been received, it returns EAGAIN immediately. */
437 int
438 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
439 {
440     int retval = vconn_connect(vconn);
441     if (!retval) {
442         retval = do_recv(vconn, msgp);
443     }
444     return retval;
445 }
446
447 static int
448 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
449 {
450     int retval;
451
452     retval = (vconn->class->recv)(vconn, msgp);
453     if (!retval) {
454         struct ofp_header *oh;
455
456         if (VLOG_IS_DBG_ENABLED()) {
457             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
458             VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
459             free(s);
460         }
461
462         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
463         if (oh->version != vconn->version
464             && oh->type != OFPT_HELLO
465             && oh->type != OFPT_ERROR
466             && oh->type != OFPT_ECHO_REQUEST
467             && oh->type != OFPT_ECHO_REPLY
468             && oh->type != OFPT_VENDOR)
469         {
470             if (vconn->version < 0) {
471                 VLOG_ERR_RL(&rl, "%s: received OpenFlow message type %"PRIu8" "
472                             "before version negotiation complete",
473                             vconn->name, oh->type);
474             } else {
475                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version 0x%02"PRIx8" "
476                             "!= expected %02x",
477                             vconn->name, oh->version, vconn->version);
478             }
479             ofpbuf_delete(*msgp);
480             retval = EPROTO;
481         }
482     }
483     if (retval) {
484         *msgp = NULL;
485     }
486     return retval;
487 }
488
489 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
490  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
491  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
492  * ever will be delivered to the peer, only that it has been queued for
493  * transmission.
494  *
495  * Returns a positive errno value on failure, in which case the caller
496  * retains ownership of 'msg'.
497  *
498  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
499  * transmission, it returns EAGAIN immediately. */
500 int
501 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
502 {
503     int retval = vconn_connect(vconn);
504     if (!retval) {
505         retval = do_send(vconn, msg);
506     }
507     return retval;
508 }
509
510 static int
511 do_send(struct vconn *vconn, struct ofpbuf *msg)
512 {
513     int retval;
514
515     assert(msg->size >= sizeof(struct ofp_header));
516     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
517     if (!VLOG_IS_DBG_ENABLED()) {
518         retval = (vconn->class->send)(vconn, msg);
519     } else {
520         char *s = ofp_to_string(msg->data, msg->size, 1);
521         retval = (vconn->class->send)(vconn, msg);
522         if (retval != EAGAIN) {
523             VLOG_DBG_RL(&rl, "%s: sent (%s): %s",
524                         vconn->name, strerror(retval), s);
525         }
526         free(s);
527     }
528     return retval;
529 }
530
531 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
532 int
533 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
534 {
535     int retval;
536     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
537         vconn_send_wait(vconn);
538         poll_block();
539     }
540     return retval;
541 }
542
543 /* Same as vconn_recv, except that it waits until a message is received. */
544 int
545 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
546 {
547     int retval;
548     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
549         vconn_recv_wait(vconn);
550         poll_block();
551     }
552     return retval;
553 }
554
555 /* Waits until a message with a transaction ID matching 'xid' is recived on
556  * 'vconn'.  Returns 0 if successful, in which case the reply is stored in
557  * '*replyp' for the caller to examine and free.  Otherwise returns a positive
558  * errno value, or EOF, and sets '*replyp' to null.
559  *
560  * 'request' is always destroyed, regardless of the return value. */
561 int
562 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
563 {
564     for (;;) {
565         uint32_t recv_xid;
566         struct ofpbuf *reply;
567         int error;
568
569         error = vconn_recv_block(vconn, &reply);
570         if (error) {
571             *replyp = NULL;
572             return error;
573         }
574         recv_xid = ((struct ofp_header *) reply->data)->xid;
575         if (xid == recv_xid) {
576             *replyp = reply;
577             return 0;
578         }
579
580         VLOG_DBG_RL(&rl, "%s: received reply with xid %08"PRIx32" != expected "
581                     "%08"PRIx32, vconn->name, recv_xid, xid);
582         ofpbuf_delete(reply);
583     }
584 }
585
586 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
587  * matching transaction ID.  Returns 0 if successful, in which case the reply
588  * is stored in '*replyp' for the caller to examine and free.  Otherwise
589  * returns a positive errno value, or EOF, and sets '*replyp' to null.
590  *
591  * 'request' is always destroyed, regardless of the return value. */
592 int
593 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
594                struct ofpbuf **replyp)
595 {
596     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
597     int error;
598
599     *replyp = NULL;
600     error = vconn_send_block(vconn, request);
601     if (error) {
602         ofpbuf_delete(request);
603     }
604     return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
605 }
606
607 void
608 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
609 {
610     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
611
612     switch (vconn->state) {
613     case VCS_CONNECTING:
614         wait = WAIT_CONNECT;
615         break;
616
617     case VCS_SEND_HELLO:
618     case VCS_SEND_ERROR:
619         wait = WAIT_SEND;
620         break;
621
622     case VCS_RECV_HELLO:
623         wait = WAIT_RECV;
624         break;
625
626     case VCS_CONNECTED:
627         break;
628
629     case VCS_DISCONNECTED:
630         poll_immediate_wake();
631         return;
632     }
633     (vconn->class->wait)(vconn, wait);
634 }
635
636 void
637 vconn_connect_wait(struct vconn *vconn)
638 {
639     vconn_wait(vconn, WAIT_CONNECT);
640 }
641
642 void
643 vconn_recv_wait(struct vconn *vconn)
644 {
645     vconn_wait(vconn, WAIT_RECV);
646 }
647
648 void
649 vconn_send_wait(struct vconn *vconn)
650 {
651     vconn_wait(vconn, WAIT_SEND);
652 }
653
654 /* Attempts to start listening for OpenFlow connections.  'name' is a
655  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
656  * class's name and ARGS are vconn class-specific.
657  *
658  * Returns 0 if successful, otherwise a positive errno value.  If successful,
659  * stores a pointer to the new connection in '*pvconnp', otherwise a null
660  * pointer.  */
661 int
662 pvconn_open(const char *name, struct pvconn **pvconnp)
663 {
664     size_t prefix_len;
665     size_t i;
666
667     check_vconn_classes();
668
669     *pvconnp = NULL;
670     prefix_len = strcspn(name, ":");
671     if (prefix_len == strlen(name)) {
672         return EAFNOSUPPORT;
673     }
674     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
675         struct pvconn_class *class = pvconn_classes[i];
676         if (strlen(class->name) == prefix_len
677             && !memcmp(class->name, name, prefix_len)) {
678             char *suffix_copy = xstrdup(name + prefix_len + 1);
679             int retval = class->listen(name, suffix_copy, pvconnp);
680             free(suffix_copy);
681             if (retval) {
682                 *pvconnp = NULL;
683             }
684             return retval;
685         }
686     }
687     return EAFNOSUPPORT;
688 }
689
690 /* Closes 'pvconn'. */
691 void
692 pvconn_close(struct pvconn *pvconn)
693 {
694     if (pvconn != NULL) {
695         char *name = pvconn->name;
696         (pvconn->class->close)(pvconn);
697         free(name);
698     }
699 }
700
701 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
702  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
703  * errno value.
704  *
705  * The new vconn will automatically negotiate an OpenFlow protocol version
706  * acceptable to both peers on the connection.  The version negotiated will be
707  * no lower than 'min_version' and no higher than OFP_VERSION.
708  *
709  * pvconn_accept() will not block waiting for a connection.  If no connection
710  * is ready to be accepted, it returns EAGAIN immediately. */
711 int
712 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
713 {
714     int retval = (pvconn->class->accept)(pvconn, new_vconn);
715     if (retval) {
716         *new_vconn = NULL;
717     } else {
718         assert((*new_vconn)->state != VCS_CONNECTING
719                || (*new_vconn)->class->connect);
720         (*new_vconn)->min_version = min_version;
721     }
722     return retval;
723 }
724
725 void
726 pvconn_wait(struct pvconn *pvconn)
727 {
728     (pvconn->class->wait)(pvconn);
729 }
730
731 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
732  * containing an OpenFlow header with the given 'type' and a random transaction
733  * id.  Stores the new buffer in '*bufferp'.  The caller must free the buffer
734  * when it is no longer needed. */
735 void *
736 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp) 
737 {
738     return make_openflow_xid(openflow_len, type, random_uint32(), bufferp);
739 }
740
741 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
742  * containing an OpenFlow header with the given 'type' and transaction id
743  * 'xid'.  Stores the new buffer in '*bufferp'.  The caller must free the
744  * buffer when it is no longer needed. */
745 void *
746 make_openflow_xid(size_t openflow_len, uint8_t type, uint32_t xid,
747                   struct ofpbuf **bufferp)
748 {
749     struct ofpbuf *buffer;
750     struct ofp_header *oh;
751
752     assert(openflow_len >= sizeof *oh);
753     assert(openflow_len <= UINT16_MAX);
754     buffer = *bufferp = ofpbuf_new(openflow_len);
755     oh = ofpbuf_put_zeros(buffer, openflow_len);
756     oh->version = OFP_VERSION;
757     oh->type = type;
758     oh->length = htons(openflow_len);
759     oh->xid = xid;
760     return oh;
761 }
762
763 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
764  * 'buffer->size'. */
765 void
766 update_openflow_length(struct ofpbuf *buffer) 
767 {
768     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
769     oh->length = htons(buffer->size); 
770 }
771
772 struct ofpbuf *
773 make_add_flow(const struct flow *flow, uint32_t buffer_id,
774               uint16_t idle_timeout, size_t actions_len)
775 {
776     struct ofp_flow_mod *ofm;
777     size_t size = sizeof *ofm + actions_len;
778     struct ofpbuf *out = ofpbuf_new(size);
779     ofm = ofpbuf_put_zeros(out, size);
780     ofm->header.version = OFP_VERSION;
781     ofm->header.type = OFPT_FLOW_MOD;
782     ofm->header.length = htons(size);
783     ofm->match.wildcards = htonl(0);
784     ofm->match.in_port = flow->in_port;
785     memcpy(ofm->match.dl_src, flow->dl_src, sizeof ofm->match.dl_src);
786     memcpy(ofm->match.dl_dst, flow->dl_dst, sizeof ofm->match.dl_dst);
787     ofm->match.dl_vlan = flow->dl_vlan;
788     ofm->match.dl_type = flow->dl_type;
789     ofm->match.nw_src = flow->nw_src;
790     ofm->match.nw_dst = flow->nw_dst;
791     ofm->match.nw_proto = flow->nw_proto;
792     ofm->match.tp_src = flow->tp_src;
793     ofm->match.tp_dst = flow->tp_dst;
794     ofm->command = htons(OFPFC_ADD);
795     ofm->idle_timeout = htons(idle_timeout);
796     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
797     ofm->buffer_id = htonl(buffer_id);
798     return out;
799 }
800
801 struct ofpbuf *
802 make_add_simple_flow(const struct flow *flow,
803                      uint32_t buffer_id, uint16_t out_port,
804                      uint16_t idle_timeout)
805 {
806     struct ofp_action_output *oao;
807     struct ofpbuf *buffer = make_add_flow(flow, buffer_id, idle_timeout, 
808             sizeof *oao);
809     struct ofp_flow_mod *ofm = buffer->data;
810     oao = (struct ofp_action_output *)&ofm->actions[0];
811     oao->type = htons(OFPAT_OUTPUT);
812     oao->len = htons(sizeof *oao);
813     oao->port = htons(out_port);
814     return buffer;
815 }
816
817 struct ofpbuf *
818 make_unbuffered_packet_out(const struct ofpbuf *packet,
819                            uint16_t in_port, uint16_t out_port)
820 {
821     struct ofp_packet_out *opo;
822     struct ofp_action_output *oao;
823     size_t size = sizeof *opo + sizeof *oao;
824     struct ofpbuf *out = ofpbuf_new(size + packet->size);
825
826     opo = ofpbuf_put_zeros(out, size);
827     opo->header.version = OFP_VERSION;
828     opo->header.type = OFPT_PACKET_OUT;
829     opo->buffer_id = htonl(UINT32_MAX);
830     opo->in_port = htons(in_port);
831
832     oao = (struct ofp_action_output *)&opo->actions[0];
833     oao->type = htons(OFPAT_OUTPUT);
834     oao->len = htons(sizeof *oao);
835     oao->port = htons(out_port);
836
837     opo->actions_len = htons(sizeof *oao);
838
839     ofpbuf_put(out, packet->data, packet->size);
840     update_openflow_length(out);
841     return out;
842 }
843
844 struct ofpbuf *
845 make_buffered_packet_out(uint32_t buffer_id,
846                          uint16_t in_port, uint16_t out_port)
847 {
848     struct ofp_packet_out *opo;
849     struct ofp_action_output *oao;
850     size_t size = sizeof *opo + sizeof *oao;
851     struct ofpbuf *out = ofpbuf_new(size);
852     opo = ofpbuf_put_zeros(out, size);
853     opo->header.version = OFP_VERSION;
854     opo->header.type = OFPT_PACKET_OUT;
855     opo->header.length = htons(size);
856     opo->buffer_id = htonl(buffer_id);
857     opo->in_port = htons(in_port);
858
859     oao = (struct ofp_action_output *)&opo->actions[0];
860     oao->type = htons(OFPAT_OUTPUT);
861     oao->len = htons(sizeof *oao);
862     oao->port = htons(out_port);
863
864     opo->actions_len = htons(sizeof *oao);
865     return out;
866 }
867
868 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
869 struct ofpbuf *
870 make_echo_request(void)
871 {
872     struct ofp_header *rq;
873     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
874     rq = ofpbuf_put_uninit(out, sizeof *rq);
875     rq->version = OFP_VERSION;
876     rq->type = OFPT_ECHO_REQUEST;
877     rq->length = htons(sizeof *rq);
878     rq->xid = 0;
879     return out;
880 }
881
882 /* Creates and returns an OFPT_ECHO_REPLY message matching the
883  * OFPT_ECHO_REQUEST message in 'rq'. */
884 struct ofpbuf *
885 make_echo_reply(const struct ofp_header *rq)
886 {
887     size_t size = ntohs(rq->length);
888     struct ofpbuf *out = ofpbuf_new(size);
889     struct ofp_header *reply = ofpbuf_put(out, rq, size);
890     reply->type = OFPT_ECHO_REPLY;
891     return out;
892 }
893
894 void
895 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
896            uint32_t ip, const char *name)
897 {
898     vconn->class = class;
899     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
900                     : !connect_status ? VCS_SEND_HELLO
901                     : VCS_DISCONNECTED);
902     vconn->error = connect_status;
903     vconn->version = -1;
904     vconn->min_version = -1;
905     vconn->ip = ip;
906     vconn->name = xstrdup(name);
907 }
908
909 void
910 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
911             const char *name)
912 {
913     pvconn->class = class;
914     pvconn->name = xstrdup(name);
915 }