ovsdb-idl: Simplify usage of ovsdb_idl_run().
[sliver-openvswitch.git] / lib / vconn.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "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 "fatal-signal.h"
29 #include "flow.h"
30 #include "ofp-print.h"
31 #include "ofp-util.h"
32 #include "ofpbuf.h"
33 #include "openflow/nicira-ext.h"
34 #include "openflow/openflow.h"
35 #include "packets.h"
36 #include "poll-loop.h"
37 #include "random.h"
38 #include "util.h"
39
40 #define THIS_MODULE VLM_vconn
41 #include "vlog.h"
42
43 /* State of an active vconn.*/
44 enum vconn_state {
45     /* This is the ordinary progression of states. */
46     VCS_CONNECTING,             /* Underlying vconn is not connected. */
47     VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
48     VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
49     VCS_CONNECTED,              /* Connection established. */
50
51     /* These states are entered only when something goes wrong. */
52     VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
53     VCS_DISCONNECTED            /* Connection failed or connection closed. */
54 };
55
56 static struct vconn_class *vconn_classes[] = {
57     &tcp_vconn_class,
58     &unix_vconn_class,
59 #ifdef HAVE_OPENSSL
60     &ssl_vconn_class,
61 #endif
62 };
63
64 static struct pvconn_class *pvconn_classes[] = {
65     &ptcp_pvconn_class,
66     &punix_pvconn_class,
67 #ifdef HAVE_OPENSSL
68     &pssl_pvconn_class,
69 #endif
70 };
71
72 /* Rate limit for individual OpenFlow messages going over the vconn, output at
73  * DBG level.  This is very high because, if these are enabled, it is because
74  * we really need to see them. */
75 static struct vlog_rate_limit ofmsg_rl = VLOG_RATE_LIMIT_INIT(600, 600);
76
77 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
78  * in the peer and so there's not much point in showing a lot of them. */
79 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
80
81 static int do_recv(struct vconn *, struct ofpbuf **);
82 static int do_send(struct vconn *, struct ofpbuf *);
83
84 /* Check the validity of the vconn class structures. */
85 static void
86 check_vconn_classes(void)
87 {
88 #ifndef NDEBUG
89     size_t i;
90
91     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
92         struct vconn_class *class = vconn_classes[i];
93         assert(class->name != NULL);
94         assert(class->open != NULL);
95         if (class->close || class->recv || class->send
96             || class->run || class->run_wait || class->wait) {
97             assert(class->close != NULL);
98             assert(class->recv != NULL);
99             assert(class->send != NULL);
100             assert(class->wait != NULL);
101         } else {
102             /* This class delegates to another one. */
103         }
104     }
105
106     for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
107         struct pvconn_class *class = pvconn_classes[i];
108         assert(class->name != NULL);
109         assert(class->listen != NULL);
110         if (class->close || class->accept || class->wait) {
111             assert(class->close != NULL);
112             assert(class->accept != NULL);
113             assert(class->wait != NULL);
114         } else {
115             /* This class delegates to another one. */
116         }
117     }
118 #endif
119 }
120
121 /* Prints information on active (if 'active') and passive (if 'passive')
122  * connection methods supported by the vconn.  If 'bootstrap' is true, also
123  * advertises options to bootstrap the CA certificate. */
124 void
125 vconn_usage(bool active, bool passive, bool bootstrap OVS_UNUSED)
126 {
127     /* Really this should be implemented via callbacks into the vconn
128      * providers, but that seems too heavy-weight to bother with at the
129      * moment. */
130     
131     printf("\n");
132     if (active) {
133         printf("Active OpenFlow connection methods:\n");
134         printf("  tcp:IP[:PORT]         "
135                "PORT (default: %d) at remote IP\n", OFP_TCP_PORT);
136 #ifdef HAVE_OPENSSL
137         printf("  ssl:IP[:PORT]         "
138                "SSL PORT (default: %d) at remote IP\n", OFP_SSL_PORT);
139 #endif
140         printf("  unix:FILE               Unix domain socket named FILE\n");
141     }
142
143     if (passive) {
144         printf("Passive OpenFlow connection methods:\n");
145         printf("  ptcp:[PORT][:IP]        "
146                "listen to TCP PORT (default: %d) on IP\n",
147                OFP_TCP_PORT);
148 #ifdef HAVE_OPENSSL
149         printf("  pssl:[PORT][:IP]        "
150                "listen for SSL on PORT (default: %d) on IP\n",
151                OFP_SSL_PORT);
152 #endif
153         printf("  punix:FILE              "
154                "listen on Unix domain socket FILE\n");
155     }
156
157 #ifdef HAVE_OPENSSL
158     printf("PKI configuration (required to use SSL):\n"
159            "  -p, --private-key=FILE  file with private key\n"
160            "  -c, --certificate=FILE  file with certificate for private key\n"
161            "  -C, --ca-cert=FILE      file with peer CA certificate\n");
162     if (bootstrap) {
163         printf("  --bootstrap-ca-cert=FILE  file with peer CA certificate "
164                "to read or create\n");
165     }
166 #endif
167 }
168
169 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
170  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
171  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
172  * class exists. */
173 static int
174 vconn_lookup_class(const char *name, struct vconn_class **classp)
175 {
176     size_t prefix_len;
177
178     prefix_len = strcspn(name, ":");
179     if (name[prefix_len] != '\0') {
180         size_t i;
181
182         for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
183             struct vconn_class *class = vconn_classes[i];
184             if (strlen(class->name) == prefix_len
185                 && !memcmp(class->name, name, prefix_len)) {
186                 *classp = class;
187                 return 0;
188             }
189         }
190     }
191
192     *classp = NULL;
193     return EAFNOSUPPORT;
194 }
195
196 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
197  * a supported connection type, otherwise EAFNOSUPPORT.  */
198 int
199 vconn_verify_name(const char *name)
200 {
201     struct vconn_class *class;
202     return vconn_lookup_class(name, &class);
203 }
204
205 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
206  * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
207  * are vconn class-specific.
208  *
209  * The vconn will automatically negotiate an OpenFlow protocol version
210  * acceptable to both peers on the connection.  The version negotiated will be
211  * no lower than 'min_version' and no higher than OFP_VERSION.
212  *
213  * Returns 0 if successful, otherwise a positive errno value.  If successful,
214  * stores a pointer to the new connection in '*vconnp', otherwise a null
215  * pointer.  */
216 int
217 vconn_open(const char *name, int min_version, struct vconn **vconnp)
218 {
219     struct vconn_class *class;
220     struct vconn *vconn;
221     char *suffix_copy;
222     int error;
223
224     COVERAGE_INC(vconn_open);
225     check_vconn_classes();
226
227     /* Look up the class. */
228     error = vconn_lookup_class(name, &class);
229     if (!class) {
230         goto error;
231     }
232
233     /* Call class's "open" function. */
234     suffix_copy = xstrdup(strchr(name, ':') + 1);
235     error = class->open(name, suffix_copy, &vconn);
236     free(suffix_copy);
237     if (error) {
238         goto error;
239     }
240
241     /* Success. */
242     assert(vconn->state != VCS_CONNECTING || vconn->class->connect);
243     vconn->min_version = min_version;
244     *vconnp = vconn;
245     return 0;
246
247 error:
248     *vconnp = NULL;
249     return error;
250 }
251
252 /* Allows 'vconn' to perform maintenance activities, such as flushing output
253  * buffers. */
254 void
255 vconn_run(struct vconn *vconn)
256 {
257     if (vconn->class->run) {
258         (vconn->class->run)(vconn);
259     }
260 }
261
262 /* Arranges for the poll loop to wake up when 'vconn' needs to perform
263  * maintenance activities. */
264 void
265 vconn_run_wait(struct vconn *vconn)
266 {
267     if (vconn->class->run_wait) {
268         (vconn->class->run_wait)(vconn);
269     }
270 }
271
272 int
273 vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
274 {
275     struct vconn *vconn;
276     int error;
277
278     fatal_signal_run();
279
280     error = vconn_open(name, min_version, &vconn);
281     while (error == EAGAIN) {
282         vconn_run(vconn);
283         vconn_run_wait(vconn);
284         vconn_connect_wait(vconn);
285         poll_block();
286         error = vconn_connect(vconn);
287         assert(error != EINPROGRESS);
288     }
289     if (error) {
290         vconn_close(vconn);
291         *vconnp = NULL;
292     } else {
293         *vconnp = vconn;
294     }
295     return error;
296 }
297
298 /* Closes 'vconn'. */
299 void
300 vconn_close(struct vconn *vconn)
301 {
302     if (vconn != NULL) {
303         char *name = vconn->name;
304         (vconn->class->close)(vconn);
305         free(name);
306     }
307 }
308
309 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
310 const char *
311 vconn_get_name(const struct vconn *vconn)
312 {
313     return vconn->name;
314 }
315
316 /* Returns the IP address of the peer, or 0 if the peer is not connected over
317  * an IP-based protocol or if its IP address is not yet known. */
318 uint32_t
319 vconn_get_remote_ip(const struct vconn *vconn) 
320 {
321     return vconn->remote_ip;
322 }
323
324 /* Returns the transport port of the peer, or 0 if the connection does not 
325  * contain a port or if the port is not yet known. */
326 uint16_t
327 vconn_get_remote_port(const struct vconn *vconn) 
328 {
329     return vconn->remote_port;
330 }
331
332 /* Returns the IP address used to connect to the peer, or 0 if the 
333  * connection is not an IP-based protocol or if its IP address is not 
334  * yet known. */
335 uint32_t
336 vconn_get_local_ip(const struct vconn *vconn) 
337 {
338     return vconn->local_ip;
339 }
340
341 /* Returns the transport port used to connect to the peer, or 0 if the 
342  * connection does not contain a port or if the port is not yet known. */
343 uint16_t
344 vconn_get_local_port(const struct vconn *vconn) 
345 {
346     return vconn->local_port;
347 }
348
349 static void
350 vcs_connecting(struct vconn *vconn) 
351 {
352     int retval = (vconn->class->connect)(vconn);
353     assert(retval != EINPROGRESS);
354     if (!retval) {
355         vconn->state = VCS_SEND_HELLO;
356     } else if (retval != EAGAIN) {
357         vconn->state = VCS_DISCONNECTED;
358         vconn->error = retval;
359     }
360 }
361
362 static void
363 vcs_send_hello(struct vconn *vconn)
364 {
365     struct ofpbuf *b;
366     int retval;
367
368     make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
369     retval = do_send(vconn, b);
370     if (!retval) {
371         vconn->state = VCS_RECV_HELLO;
372     } else {
373         ofpbuf_delete(b);
374         if (retval != EAGAIN) {
375             vconn->state = VCS_DISCONNECTED;
376             vconn->error = retval;
377         }
378     }
379 }
380
381 static void
382 vcs_recv_hello(struct vconn *vconn)
383 {
384     struct ofpbuf *b;
385     int retval;
386
387     retval = do_recv(vconn, &b);
388     if (!retval) {
389         struct ofp_header *oh = b->data;
390
391         if (oh->type == OFPT_HELLO) {
392             if (b->size > sizeof *oh) {
393                 struct ds msg = DS_EMPTY_INITIALIZER;
394                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
395                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
396                 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
397                 ds_destroy(&msg);
398             }
399
400             vconn->version = MIN(OFP_VERSION, oh->version);
401             if (vconn->version < vconn->min_version) {
402                 VLOG_WARN_RL(&bad_ofmsg_rl,
403                              "%s: version negotiation failed: we support "
404                              "versions 0x%02x to 0x%02x inclusive but peer "
405                              "supports no later than version 0x%02"PRIx8,
406                              vconn->name, vconn->min_version, OFP_VERSION,
407                              oh->version);
408                 vconn->state = VCS_SEND_ERROR;
409             } else {
410                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
411                          "(we support versions 0x%02x to 0x%02x inclusive, "
412                          "peer no later than version 0x%02"PRIx8")",
413                          vconn->name, vconn->version, vconn->min_version,
414                          OFP_VERSION, oh->version);
415                 vconn->state = VCS_CONNECTED;
416             }
417             ofpbuf_delete(b);
418             return;
419         } else {
420             char *s = ofp_to_string(b->data, b->size, 1);
421             VLOG_WARN_RL(&bad_ofmsg_rl,
422                          "%s: received message while expecting hello: %s",
423                          vconn->name, s);
424             free(s);
425             retval = EPROTO;
426             ofpbuf_delete(b);
427         }
428     }
429
430     if (retval != EAGAIN) {
431         vconn->state = VCS_DISCONNECTED;
432         vconn->error = retval == EOF ? ECONNRESET : retval;
433     }
434 }
435
436 static void
437 vcs_send_error(struct vconn *vconn)
438 {
439     struct ofp_error_msg *error;
440     struct ofpbuf *b;
441     char s[128];
442     int retval;
443
444     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
445              "you support no later than version 0x%02"PRIx8".",
446              vconn->min_version, OFP_VERSION, vconn->version);
447     error = make_openflow(sizeof *error, OFPT_ERROR, &b);
448     error->type = htons(OFPET_HELLO_FAILED);
449     error->code = htons(OFPHFC_INCOMPATIBLE);
450     ofpbuf_put(b, s, strlen(s));
451     update_openflow_length(b);
452     retval = do_send(vconn, b);
453     if (retval) {
454         ofpbuf_delete(b);
455     }
456     if (retval != EAGAIN) {
457         vconn->state = VCS_DISCONNECTED;
458         vconn->error = retval ? retval : EPROTO;
459     }
460 }
461
462 /* Tries to complete the connection on 'vconn', which must be an active
463  * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
464  * was successful or a positive errno value if it failed.  If the
465  * connection is still in progress, returns EAGAIN. */
466 int
467 vconn_connect(struct vconn *vconn)
468 {
469     enum vconn_state last_state;
470
471     assert(vconn->min_version >= 0);
472     do {
473         last_state = vconn->state;
474         switch (vconn->state) {
475         case VCS_CONNECTING:
476             vcs_connecting(vconn);
477             break;
478
479         case VCS_SEND_HELLO:
480             vcs_send_hello(vconn);
481             break;
482
483         case VCS_RECV_HELLO:
484             vcs_recv_hello(vconn);
485             break;
486
487         case VCS_CONNECTED:
488             return 0;
489
490         case VCS_SEND_ERROR:
491             vcs_send_error(vconn);
492             break;
493
494         case VCS_DISCONNECTED:
495             return vconn->error;
496
497         default:
498             NOT_REACHED();
499         }
500     } while (vconn->state != last_state);
501
502     return EAGAIN;
503 }
504
505 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
506  * vconn.  If successful, stores the received message into '*msgp' and returns
507  * 0.  The caller is responsible for destroying the message with
508  * ofpbuf_delete().  On failure, returns a positive errno value and stores a
509  * null pointer into '*msgp'.  On normal connection close, returns EOF.
510  *
511  * vconn_recv will not block waiting for a packet to arrive.  If no packets
512  * have been received, it returns EAGAIN immediately. */
513 int
514 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
515 {
516     int retval = vconn_connect(vconn);
517     if (!retval) {
518         retval = do_recv(vconn, msgp);
519     }
520     return retval;
521 }
522
523 static int
524 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
525 {
526     int retval = (vconn->class->recv)(vconn, msgp);
527     if (!retval) {
528         struct ofp_header *oh;
529
530         COVERAGE_INC(vconn_received);
531         if (VLOG_IS_DBG_ENABLED()) {
532             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
533             VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
534             free(s);
535         }
536
537         oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
538         if (oh->version != vconn->version
539             && oh->type != OFPT_HELLO
540             && oh->type != OFPT_ERROR
541             && oh->type != OFPT_ECHO_REQUEST
542             && oh->type != OFPT_ECHO_REPLY
543             && oh->type != OFPT_VENDOR)
544         {
545             if (vconn->version < 0) {
546                 VLOG_ERR_RL(&bad_ofmsg_rl,
547                             "%s: received OpenFlow message type %"PRIu8" "
548                             "before version negotiation complete",
549                             vconn->name, oh->type);
550             } else {
551                 VLOG_ERR_RL(&bad_ofmsg_rl,
552                             "%s: received OpenFlow version 0x%02"PRIx8" "
553                             "!= expected %02x",
554                             vconn->name, oh->version, vconn->version);
555             }
556             ofpbuf_delete(*msgp);
557             retval = EPROTO;
558         }
559     }
560     if (retval) {
561         *msgp = NULL;
562     }
563     return retval;
564 }
565
566 /* Tries to queue 'msg' for transmission on 'vconn', which must be an active
567  * vconn.  If successful, returns 0, in which case ownership of 'msg' is
568  * transferred to the vconn.  Success does not guarantee that 'msg' has been or
569  * ever will be delivered to the peer, only that it has been queued for
570  * transmission.
571  *
572  * Returns a positive errno value on failure, in which case the caller
573  * retains ownership of 'msg'.
574  *
575  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
576  * transmission, it returns EAGAIN immediately. */
577 int
578 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
579 {
580     int retval = vconn_connect(vconn);
581     if (!retval) {
582         retval = do_send(vconn, msg);
583     }
584     return retval;
585 }
586
587 static int
588 do_send(struct vconn *vconn, struct ofpbuf *msg)
589 {
590     int retval;
591
592     assert(msg->size >= sizeof(struct ofp_header));
593     assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
594     if (!VLOG_IS_DBG_ENABLED()) {
595         COVERAGE_INC(vconn_sent);
596         retval = (vconn->class->send)(vconn, msg);
597     } else {
598         char *s = ofp_to_string(msg->data, msg->size, 1);
599         retval = (vconn->class->send)(vconn, msg);
600         if (retval != EAGAIN) {
601             VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
602                         vconn->name, strerror(retval), s);
603         }
604         free(s);
605     }
606     return retval;
607 }
608
609 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
610 int
611 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
612 {
613     int retval;
614
615     fatal_signal_run();
616
617     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
618         vconn_run(vconn);
619         vconn_run_wait(vconn);
620         vconn_send_wait(vconn);
621         poll_block();
622     }
623     return retval;
624 }
625
626 /* Same as vconn_recv, except that it waits until a message is received. */
627 int
628 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
629 {
630     int retval;
631
632     fatal_signal_run();
633
634     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
635         vconn_run(vconn);
636         vconn_run_wait(vconn);
637         vconn_recv_wait(vconn);
638         poll_block();
639     }
640     return retval;
641 }
642
643 /* Waits until a message with a transaction ID matching 'xid' is recived on
644  * 'vconn'.  Returns 0 if successful, in which case the reply is stored in
645  * '*replyp' for the caller to examine and free.  Otherwise returns a positive
646  * errno value, or EOF, and sets '*replyp' to null.
647  *
648  * 'request' is always destroyed, regardless of the return value. */
649 int
650 vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp)
651 {
652     for (;;) {
653         uint32_t recv_xid;
654         struct ofpbuf *reply;
655         int error;
656
657         error = vconn_recv_block(vconn, &reply);
658         if (error) {
659             *replyp = NULL;
660             return error;
661         }
662         recv_xid = ((struct ofp_header *) reply->data)->xid;
663         if (xid == recv_xid) {
664             *replyp = reply;
665             return 0;
666         }
667
668         VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
669                     " != expected %08"PRIx32, vconn->name, recv_xid, xid);
670         ofpbuf_delete(reply);
671     }
672 }
673
674 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
675  * matching transaction ID.  Returns 0 if successful, in which case the reply
676  * is stored in '*replyp' for the caller to examine and free.  Otherwise
677  * returns a positive errno value, or EOF, and sets '*replyp' to null.
678  *
679  * 'request' is always destroyed, regardless of the return value. */
680 int
681 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
682                struct ofpbuf **replyp)
683 {
684     uint32_t send_xid = ((struct ofp_header *) request->data)->xid;
685     int error;
686
687     *replyp = NULL;
688     error = vconn_send_block(vconn, request);
689     if (error) {
690         ofpbuf_delete(request);
691     }
692     return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
693 }
694
695 void
696 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
697 {
698     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
699
700     switch (vconn->state) {
701     case VCS_CONNECTING:
702         wait = WAIT_CONNECT;
703         break;
704
705     case VCS_SEND_HELLO:
706     case VCS_SEND_ERROR:
707         wait = WAIT_SEND;
708         break;
709
710     case VCS_RECV_HELLO:
711         wait = WAIT_RECV;
712         break;
713
714     case VCS_CONNECTED:
715         break;
716
717     case VCS_DISCONNECTED:
718         poll_immediate_wake();
719         return;
720     }
721     (vconn->class->wait)(vconn, wait);
722 }
723
724 void
725 vconn_connect_wait(struct vconn *vconn)
726 {
727     vconn_wait(vconn, WAIT_CONNECT);
728 }
729
730 void
731 vconn_recv_wait(struct vconn *vconn)
732 {
733     vconn_wait(vconn, WAIT_RECV);
734 }
735
736 void
737 vconn_send_wait(struct vconn *vconn)
738 {
739     vconn_wait(vconn, WAIT_SEND);
740 }
741
742 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
743  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
744  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
745  * class exists. */
746 static int
747 pvconn_lookup_class(const char *name, struct pvconn_class **classp)
748 {
749     size_t prefix_len;
750
751     prefix_len = strcspn(name, ":");
752     if (name[prefix_len] != '\0') {
753         size_t i;
754
755         for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
756             struct pvconn_class *class = pvconn_classes[i];
757             if (strlen(class->name) == prefix_len
758                 && !memcmp(class->name, name, prefix_len)) {
759                 *classp = class;
760                 return 0;
761             }
762         }
763     }
764
765     *classp = NULL;
766     return EAFNOSUPPORT;
767 }
768
769 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
770  * a supported connection type, otherwise EAFNOSUPPORT.  */
771 int
772 pvconn_verify_name(const char *name)
773 {
774     struct pvconn_class *class;
775     return pvconn_lookup_class(name, &class);
776 }
777
778 /* Attempts to start listening for OpenFlow connections.  'name' is a
779  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
780  * class's name and ARGS are vconn class-specific.
781  *
782  * Returns 0 if successful, otherwise a positive errno value.  If successful,
783  * stores a pointer to the new connection in '*pvconnp', otherwise a null
784  * pointer.  */
785 int
786 pvconn_open(const char *name, struct pvconn **pvconnp)
787 {
788     struct pvconn_class *class;
789     struct pvconn *pvconn;
790     char *suffix_copy;
791     int error;
792
793     check_vconn_classes();
794
795     /* Look up the class. */
796     error = pvconn_lookup_class(name, &class);
797     if (!class) {
798         goto error;
799     }
800
801     /* Call class's "open" function. */
802     suffix_copy = xstrdup(strchr(name, ':') + 1);
803     error = class->listen(name, suffix_copy, &pvconn);
804     free(suffix_copy);
805     if (error) {
806         goto error;
807     }
808
809     /* Success. */
810     *pvconnp = pvconn;
811     return 0;
812
813 error:
814     *pvconnp = NULL;
815     return error;
816 }
817
818 /* Returns the name that was used to open 'pvconn'.  The caller must not
819  * modify or free the name. */
820 const char *
821 pvconn_get_name(const struct pvconn *pvconn)
822 {
823     return pvconn->name;
824 }
825
826 /* Closes 'pvconn'. */
827 void
828 pvconn_close(struct pvconn *pvconn)
829 {
830     if (pvconn != NULL) {
831         char *name = pvconn->name;
832         (pvconn->class->close)(pvconn);
833         free(name);
834     }
835 }
836
837 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
838  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
839  * errno value.
840  *
841  * The new vconn will automatically negotiate an OpenFlow protocol version
842  * acceptable to both peers on the connection.  The version negotiated will be
843  * no lower than 'min_version' and no higher than OFP_VERSION.
844  *
845  * pvconn_accept() will not block waiting for a connection.  If no connection
846  * is ready to be accepted, it returns EAGAIN immediately. */
847 int
848 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
849 {
850     int retval = (pvconn->class->accept)(pvconn, new_vconn);
851     if (retval) {
852         *new_vconn = NULL;
853     } else {
854         assert((*new_vconn)->state != VCS_CONNECTING
855                || (*new_vconn)->class->connect);
856         (*new_vconn)->min_version = min_version;
857     }
858     return retval;
859 }
860
861 void
862 pvconn_wait(struct pvconn *pvconn)
863 {
864     (pvconn->class->wait)(pvconn);
865 }
866
867 /* Initializes 'vconn' as a new vconn named 'name', implemented via 'class'.
868  * The initial connection status, supplied as 'connect_status', is interpreted
869  * as follows:
870  *
871  *      - 0: 'vconn' is connected.  Its 'send' and 'recv' functions may be
872  *        called in the normal fashion.
873  *
874  *      - EAGAIN: 'vconn' is trying to complete a connection.  Its 'connect'
875  *        function should be called to complete the connection.
876  *
877  *      - Other positive errno values indicate that the connection failed with
878  *        the specified error.
879  *
880  * After calling this function, vconn_close() must be used to destroy 'vconn',
881  * otherwise resources will be leaked.
882  *
883  * The caller retains ownership of 'name'. */
884 void
885 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
886            const char *name)
887 {
888     vconn->class = class;
889     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
890                     : !connect_status ? VCS_SEND_HELLO
891                     : VCS_DISCONNECTED);
892     vconn->error = connect_status;
893     vconn->version = -1;
894     vconn->min_version = -1;
895     vconn->remote_ip = 0;
896     vconn->remote_port = 0;
897     vconn->local_ip = 0;
898     vconn->local_port = 0;
899     vconn->name = xstrdup(name);
900     assert(vconn->state != VCS_CONNECTING || class->connect);
901 }
902
903 void
904 vconn_set_remote_ip(struct vconn *vconn, uint32_t ip)
905 {
906     vconn->remote_ip = ip;
907 }
908
909 void
910 vconn_set_remote_port(struct vconn *vconn, uint16_t port)
911 {
912     vconn->remote_port = port;
913 }
914
915 void 
916 vconn_set_local_ip(struct vconn *vconn, uint32_t ip)
917 {
918     vconn->local_ip = ip;
919 }
920
921 void 
922 vconn_set_local_port(struct vconn *vconn, uint16_t port)
923 {
924     vconn->local_port = port;
925 }
926
927 void
928 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
929             const char *name)
930 {
931     pvconn->class = class;
932     pvconn->name = xstrdup(name);
933 }