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