ofp-util: Make ofperr_encode_msg__() use correct Open Flow 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         error = vconn_connect_block(vconn);
292     }
293
294     if (error) {
295         vconn_close(vconn);
296         *vconnp = NULL;
297     } else {
298         *vconnp = vconn;
299     }
300     return error;
301 }
302
303 /* Closes 'vconn'. */
304 void
305 vconn_close(struct vconn *vconn)
306 {
307     if (vconn != NULL) {
308         char *name = vconn->name;
309         (vconn->class->close)(vconn);
310         free(name);
311     }
312 }
313
314 /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
315 const char *
316 vconn_get_name(const struct vconn *vconn)
317 {
318     return vconn->name;
319 }
320
321 /* Returns the IP address of the peer, or 0 if the peer is not connected over
322  * an IP-based protocol or if its IP address is not yet known. */
323 ovs_be32
324 vconn_get_remote_ip(const struct vconn *vconn)
325 {
326     return vconn->remote_ip;
327 }
328
329 /* Returns the transport port of the peer, or 0 if the connection does not
330  * contain a port or if the port is not yet known. */
331 ovs_be16
332 vconn_get_remote_port(const struct vconn *vconn)
333 {
334     return vconn->remote_port;
335 }
336
337 /* Returns the IP address used to connect to the peer, or 0 if the
338  * connection is not an IP-based protocol or if its IP address is not
339  * yet known. */
340 ovs_be32
341 vconn_get_local_ip(const struct vconn *vconn)
342 {
343     return vconn->local_ip;
344 }
345
346 /* Returns the transport port used to connect to the peer, or 0 if the
347  * connection does not contain a port or if the port is not yet known. */
348 ovs_be16
349 vconn_get_local_port(const struct vconn *vconn)
350 {
351     return vconn->local_port;
352 }
353
354 /* Returns the OpenFlow version negotiated with the peer, or -1 if version
355  * negotiation is not yet complete.
356  *
357  * A vconn that has successfully connected (that is, vconn_connect() or
358  * vconn_send() or vconn_recv() has returned 0) always negotiated a version. */
359 enum ofp_version
360 vconn_get_version(const struct vconn *vconn)
361 {
362     return vconn->version;
363 }
364
365 static void
366 vcs_connecting(struct vconn *vconn)
367 {
368     int retval = (vconn->class->connect)(vconn);
369     assert(retval != EINPROGRESS);
370     if (!retval) {
371         vconn->state = VCS_SEND_HELLO;
372     } else if (retval != EAGAIN) {
373         vconn->state = VCS_DISCONNECTED;
374         vconn->error = retval;
375     }
376 }
377
378 static void
379 vcs_send_hello(struct vconn *vconn)
380 {
381     struct ofpbuf *b;
382     int retval;
383
384     b = ofpraw_alloc(OFPRAW_OFPT_HELLO, OFP10_VERSION, 0);
385     retval = do_send(vconn, b);
386     if (!retval) {
387         vconn->state = VCS_RECV_HELLO;
388     } else {
389         ofpbuf_delete(b);
390         if (retval != EAGAIN) {
391             vconn->state = VCS_DISCONNECTED;
392             vconn->error = retval;
393         }
394     }
395 }
396
397 static void
398 vcs_recv_hello(struct vconn *vconn)
399 {
400     struct ofpbuf *b;
401     int retval;
402
403     retval = do_recv(vconn, &b);
404     if (!retval) {
405         const struct ofp_header *oh = b->data;
406         enum ofptype type;
407         enum ofperr error;
408
409         error = ofptype_decode(&type, b->data);
410         if (!error && type == OFPTYPE_HELLO) {
411             if (b->size > sizeof *oh) {
412                 struct ds msg = DS_EMPTY_INITIALIZER;
413                 ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
414                 ds_put_hex_dump(&msg, b->data, b->size, 0, true);
415                 VLOG_WARN_RL(&bad_ofmsg_rl, "%s", ds_cstr(&msg));
416                 ds_destroy(&msg);
417             }
418
419             vconn->version = MIN(OFP10_VERSION, oh->version);
420             if (vconn->version < vconn->min_version) {
421                 VLOG_WARN_RL(&bad_ofmsg_rl,
422                              "%s: version negotiation failed: we support "
423                              "versions 0x%02x to 0x%02x inclusive but peer "
424                              "supports no later than version 0x%02"PRIx8,
425                              vconn->name, vconn->min_version, OFP10_VERSION,
426                              oh->version);
427                 vconn->state = VCS_SEND_ERROR;
428             } else {
429                 VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
430                          "(we support versions 0x%02x to 0x%02x inclusive, "
431                          "peer no later than version 0x%02"PRIx8")",
432                          vconn->name, vconn->version, vconn->min_version,
433                          OFP10_VERSION, oh->version);
434                 vconn->state = VCS_CONNECTED;
435             }
436             ofpbuf_delete(b);
437             return;
438         } else {
439             char *s = ofp_to_string(b->data, b->size, 1);
440             VLOG_WARN_RL(&bad_ofmsg_rl,
441                          "%s: received message while expecting hello: %s",
442                          vconn->name, s);
443             free(s);
444             retval = EPROTO;
445             ofpbuf_delete(b);
446         }
447     }
448
449     if (retval != EAGAIN) {
450         vconn->state = VCS_DISCONNECTED;
451         vconn->error = retval == EOF ? ECONNRESET : retval;
452     }
453 }
454
455 static void
456 vcs_send_error(struct vconn *vconn)
457 {
458     struct ofpbuf *b;
459     char s[128];
460     int retval;
461
462     snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
463              "you support no later than version 0x%02"PRIx8".",
464              vconn->min_version, OFP12_VERSION, vconn->version);
465     b = ofperr_encode_hello(OFPERR_OFPHFC_INCOMPATIBLE, vconn->version, s);
466     retval = do_send(vconn, b);
467     if (retval) {
468         ofpbuf_delete(b);
469     }
470     if (retval != EAGAIN) {
471         vconn->state = VCS_DISCONNECTED;
472         vconn->error = retval ? retval : EPROTO;
473     }
474 }
475
476 /* Tries to complete the connection on 'vconn'. If 'vconn''s connection is
477  * complete, returns 0 if the connection was successful or a positive errno
478  * value if it failed.  If the connection is still in progress, returns
479  * EAGAIN. */
480 int
481 vconn_connect(struct vconn *vconn)
482 {
483     enum vconn_state last_state;
484
485     assert(vconn->min_version > 0);
486     do {
487         last_state = vconn->state;
488         switch (vconn->state) {
489         case VCS_CONNECTING:
490             vcs_connecting(vconn);
491             break;
492
493         case VCS_SEND_HELLO:
494             vcs_send_hello(vconn);
495             break;
496
497         case VCS_RECV_HELLO:
498             vcs_recv_hello(vconn);
499             break;
500
501         case VCS_CONNECTED:
502             return 0;
503
504         case VCS_SEND_ERROR:
505             vcs_send_error(vconn);
506             break;
507
508         case VCS_DISCONNECTED:
509             return vconn->error;
510
511         default:
512             NOT_REACHED();
513         }
514     } while (vconn->state != last_state);
515
516     return EAGAIN;
517 }
518
519 /* Tries to receive an OpenFlow message from 'vconn'.  If successful, stores
520  * the received message into '*msgp' and returns 0.  The caller is responsible
521  * for destroying the message with ofpbuf_delete().  On failure, returns a
522  * positive errno value and stores a null pointer into '*msgp'.  On normal
523  * connection close, returns EOF.
524  *
525  * vconn_recv will not block waiting for a packet to arrive.  If no packets
526  * have been received, it returns EAGAIN immediately. */
527 int
528 vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
529 {
530     struct ofpbuf *msg;
531     int retval;
532
533     retval = vconn_connect(vconn);
534     if (!retval) {
535         retval = do_recv(vconn, &msg);
536     }
537     if (!retval) {
538         const struct ofp_header *oh = msg->data;
539         if (oh->version != vconn->version) {
540             enum ofptype type;
541
542             if (ofptype_decode(&type, msg->data)
543                 || (type != OFPTYPE_HELLO &&
544                     type != OFPTYPE_ERROR &&
545                     type != OFPTYPE_ECHO_REQUEST &&
546                     type != OFPTYPE_ECHO_REPLY)) {
547                 VLOG_ERR_RL(&bad_ofmsg_rl, "%s: received OpenFlow version "
548                             "0x%02"PRIx8" != expected %02x",
549                             vconn->name, oh->version, vconn->version);
550                 ofpbuf_delete(msg);
551                 retval = EPROTO;
552             }
553         }
554     }
555
556     *msgp = retval ? NULL : msg;
557     return retval;
558 }
559
560 static int
561 do_recv(struct vconn *vconn, struct ofpbuf **msgp)
562 {
563     int retval = (vconn->class->recv)(vconn, msgp);
564     if (!retval) {
565         COVERAGE_INC(vconn_received);
566         if (VLOG_IS_DBG_ENABLED()) {
567             char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
568             VLOG_DBG_RL(&ofmsg_rl, "%s: received: %s", vconn->name, s);
569             free(s);
570         }
571     }
572     return retval;
573 }
574
575 /* Tries to queue 'msg' for transmission on 'vconn'.  If successful, returns 0,
576  * in which case ownership of 'msg' is transferred to the vconn.  Success does
577  * not guarantee that 'msg' has been or ever will be delivered to the peer,
578  * only that it has been queued for transmission.
579  *
580  * Returns a positive errno value on failure, in which case the caller
581  * retains ownership of 'msg'.
582  *
583  * vconn_send will not block.  If 'msg' cannot be immediately accepted for
584  * transmission, it returns EAGAIN immediately. */
585 int
586 vconn_send(struct vconn *vconn, struct ofpbuf *msg)
587 {
588     int retval = vconn_connect(vconn);
589     if (!retval) {
590         retval = do_send(vconn, msg);
591     }
592     return retval;
593 }
594
595 static int
596 do_send(struct vconn *vconn, struct ofpbuf *msg)
597 {
598     int retval;
599
600     assert(msg->size >= sizeof(struct ofp_header));
601
602     ofpmsg_update_length(msg);
603     if (!VLOG_IS_DBG_ENABLED()) {
604         COVERAGE_INC(vconn_sent);
605         retval = (vconn->class->send)(vconn, msg);
606     } else {
607         char *s = ofp_to_string(msg->data, msg->size, 1);
608         retval = (vconn->class->send)(vconn, msg);
609         if (retval != EAGAIN) {
610             VLOG_DBG_RL(&ofmsg_rl, "%s: sent (%s): %s",
611                         vconn->name, strerror(retval), s);
612         }
613         free(s);
614     }
615     return retval;
616 }
617
618 /* Same as vconn_connect(), except that it waits until the connection on
619  * 'vconn' completes or fails.  Thus, it will never return EAGAIN. */
620 int
621 vconn_connect_block(struct vconn *vconn)
622 {
623     int error;
624
625     while ((error = vconn_connect(vconn)) == EAGAIN) {
626         vconn_run(vconn);
627         vconn_run_wait(vconn);
628         vconn_connect_wait(vconn);
629         poll_block();
630     }
631     assert(error != EINPROGRESS);
632
633     return error;
634 }
635
636 /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */
637 int
638 vconn_send_block(struct vconn *vconn, struct ofpbuf *msg)
639 {
640     int retval;
641
642     fatal_signal_run();
643
644     while ((retval = vconn_send(vconn, msg)) == EAGAIN) {
645         vconn_run(vconn);
646         vconn_run_wait(vconn);
647         vconn_send_wait(vconn);
648         poll_block();
649     }
650     return retval;
651 }
652
653 /* Same as vconn_recv, except that it waits until a message is received. */
654 int
655 vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp)
656 {
657     int retval;
658
659     fatal_signal_run();
660
661     while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) {
662         vconn_run(vconn);
663         vconn_run_wait(vconn);
664         vconn_recv_wait(vconn);
665         poll_block();
666     }
667     return retval;
668 }
669
670 /* Waits until a message with a transaction ID matching 'xid' is recived on
671  * 'vconn'.  Returns 0 if successful, in which case the reply is stored in
672  * '*replyp' for the caller to examine and free.  Otherwise returns a positive
673  * errno value, or EOF, and sets '*replyp' to null.
674  *
675  * 'request' is always destroyed, regardless of the return value. */
676 int
677 vconn_recv_xid(struct vconn *vconn, ovs_be32 xid, struct ofpbuf **replyp)
678 {
679     for (;;) {
680         ovs_be32 recv_xid;
681         struct ofpbuf *reply;
682         int error;
683
684         error = vconn_recv_block(vconn, &reply);
685         if (error) {
686             *replyp = NULL;
687             return error;
688         }
689         recv_xid = ((struct ofp_header *) reply->data)->xid;
690         if (xid == recv_xid) {
691             *replyp = reply;
692             return 0;
693         }
694
695         VLOG_DBG_RL(&bad_ofmsg_rl, "%s: received reply with xid %08"PRIx32
696                     " != expected %08"PRIx32,
697                     vconn->name, ntohl(recv_xid), ntohl(xid));
698         ofpbuf_delete(reply);
699     }
700 }
701
702 /* Sends 'request' to 'vconn' and blocks until it receives a reply with a
703  * matching transaction ID.  Returns 0 if successful, in which case the reply
704  * is stored in '*replyp' for the caller to examine and free.  Otherwise
705  * returns a positive errno value, or EOF, and sets '*replyp' to null.
706  *
707  * 'request' should be an OpenFlow request that requires a reply.  Otherwise,
708  * if there is no reply, this function can end up blocking forever (or until
709  * the peer drops the connection).
710  *
711  * 'request' is always destroyed, regardless of the return value. */
712 int
713 vconn_transact(struct vconn *vconn, struct ofpbuf *request,
714                struct ofpbuf **replyp)
715 {
716     ovs_be32 send_xid = ((struct ofp_header *) request->data)->xid;
717     int error;
718
719     *replyp = NULL;
720     error = vconn_send_block(vconn, request);
721     if (error) {
722         ofpbuf_delete(request);
723     }
724     return error ? error : vconn_recv_xid(vconn, send_xid, replyp);
725 }
726
727 /* Sends 'request' followed by a barrier request to 'vconn', then blocks until
728  * it receives a reply to the barrier.  If successful, stores the reply to
729  * 'request' in '*replyp', if one was received, and otherwise NULL, then
730  * returns 0.  Otherwise returns a positive errno value, or EOF, and sets
731  * '*replyp' to null.
732  *
733  * This function is useful for sending an OpenFlow request that doesn't
734  * ordinarily include a reply but might report an error in special
735  * circumstances.
736  *
737  * 'request' is always destroyed, regardless of the return value. */
738 int
739 vconn_transact_noreply(struct vconn *vconn, struct ofpbuf *request,
740                        struct ofpbuf **replyp)
741 {
742     ovs_be32 request_xid;
743     ovs_be32 barrier_xid;
744     struct ofpbuf *barrier;
745     int error;
746
747     *replyp = NULL;
748
749     /* Send request. */
750     request_xid = ((struct ofp_header *) request->data)->xid;
751     error = vconn_send_block(vconn, request);
752     if (error) {
753         ofpbuf_delete(request);
754         return error;
755     }
756
757     /* Send barrier. */
758     barrier = ofputil_encode_barrier_request(vconn_get_version(vconn));
759     barrier_xid = ((struct ofp_header *) barrier->data)->xid;
760     error = vconn_send_block(vconn, barrier);
761     if (error) {
762         ofpbuf_delete(barrier);
763         return error;
764     }
765
766     for (;;) {
767         struct ofpbuf *msg;
768         ovs_be32 msg_xid;
769         int error;
770
771         error = vconn_recv_block(vconn, &msg);
772         if (error) {
773             ofpbuf_delete(*replyp);
774             *replyp = NULL;
775             return error;
776         }
777
778         msg_xid = ((struct ofp_header *) msg->data)->xid;
779         if (msg_xid == request_xid) {
780             if (*replyp) {
781                 VLOG_WARN_RL(&bad_ofmsg_rl, "%s: duplicate replies with "
782                              "xid %08"PRIx32, vconn->name, ntohl(msg_xid));
783                 ofpbuf_delete(*replyp);
784             }
785             *replyp = msg;
786         } else {
787             ofpbuf_delete(msg);
788             if (msg_xid == barrier_xid) {
789                 return 0;
790             } else {
791                 VLOG_DBG_RL(&bad_ofmsg_rl, "%s: reply with xid %08"PRIx32
792                             " != expected %08"PRIx32" or %08"PRIx32,
793                             vconn->name, ntohl(msg_xid),
794                             ntohl(request_xid), ntohl(barrier_xid));
795             }
796         }
797     }
798 }
799
800 /* vconn_transact_noreply() for a list of "struct ofpbuf"s, sent one by one.
801  * All of the requests on 'requests' are always destroyed, regardless of the
802  * return value. */
803 int
804 vconn_transact_multiple_noreply(struct vconn *vconn, struct list *requests,
805                                 struct ofpbuf **replyp)
806 {
807     struct ofpbuf *request, *next;
808
809     LIST_FOR_EACH_SAFE (request, next, list_node, requests) {
810         int error;
811
812         list_remove(&request->list_node);
813
814         error = vconn_transact_noreply(vconn, request, replyp);
815         if (error || *replyp) {
816             ofpbuf_list_delete(requests);
817             return error;
818         }
819     }
820
821     *replyp = NULL;
822     return 0;
823 }
824
825 void
826 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
827 {
828     assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
829
830     switch (vconn->state) {
831     case VCS_CONNECTING:
832         wait = WAIT_CONNECT;
833         break;
834
835     case VCS_SEND_HELLO:
836     case VCS_SEND_ERROR:
837         wait = WAIT_SEND;
838         break;
839
840     case VCS_RECV_HELLO:
841         wait = WAIT_RECV;
842         break;
843
844     case VCS_CONNECTED:
845         break;
846
847     case VCS_DISCONNECTED:
848         poll_immediate_wake();
849         return;
850     }
851     (vconn->class->wait)(vconn, wait);
852 }
853
854 void
855 vconn_connect_wait(struct vconn *vconn)
856 {
857     vconn_wait(vconn, WAIT_CONNECT);
858 }
859
860 void
861 vconn_recv_wait(struct vconn *vconn)
862 {
863     vconn_wait(vconn, WAIT_RECV);
864 }
865
866 void
867 vconn_send_wait(struct vconn *vconn)
868 {
869     vconn_wait(vconn, WAIT_SEND);
870 }
871
872 /* Given 'name', a connection name in the form "TYPE:ARGS", stores the class
873  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
874  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
875  * class exists. */
876 static int
877 pvconn_lookup_class(const char *name, struct pvconn_class **classp)
878 {
879     size_t prefix_len;
880
881     prefix_len = strcspn(name, ":");
882     if (name[prefix_len] != '\0') {
883         size_t i;
884
885         for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
886             struct pvconn_class *class = pvconn_classes[i];
887             if (strlen(class->name) == prefix_len
888                 && !memcmp(class->name, name, prefix_len)) {
889                 *classp = class;
890                 return 0;
891             }
892         }
893     }
894
895     *classp = NULL;
896     return EAFNOSUPPORT;
897 }
898
899 /* Returns 0 if 'name' is a connection name in the form "TYPE:ARGS" and TYPE is
900  * a supported connection type, otherwise EAFNOSUPPORT.  */
901 int
902 pvconn_verify_name(const char *name)
903 {
904     struct pvconn_class *class;
905     return pvconn_lookup_class(name, &class);
906 }
907
908 /* Attempts to start listening for OpenFlow connections.  'name' is a
909  * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
910  * class's name and ARGS are vconn class-specific.
911  *
912  * Returns 0 if successful, otherwise a positive errno value.  If successful,
913  * stores a pointer to the new connection in '*pvconnp', otherwise a null
914  * pointer.  */
915 int
916 pvconn_open(const char *name, struct pvconn **pvconnp, uint8_t dscp)
917 {
918     struct pvconn_class *class;
919     struct pvconn *pvconn;
920     char *suffix_copy;
921     int error;
922
923     check_vconn_classes();
924
925     /* Look up the class. */
926     error = pvconn_lookup_class(name, &class);
927     if (!class) {
928         goto error;
929     }
930
931     /* Call class's "open" function. */
932     suffix_copy = xstrdup(strchr(name, ':') + 1);
933     error = class->listen(name, suffix_copy, &pvconn, dscp);
934     free(suffix_copy);
935     if (error) {
936         goto error;
937     }
938
939     /* Success. */
940     *pvconnp = pvconn;
941     return 0;
942
943 error:
944     *pvconnp = NULL;
945     return error;
946 }
947
948 /* Returns the name that was used to open 'pvconn'.  The caller must not
949  * modify or free the name. */
950 const char *
951 pvconn_get_name(const struct pvconn *pvconn)
952 {
953     return pvconn->name;
954 }
955
956 /* Closes 'pvconn'. */
957 void
958 pvconn_close(struct pvconn *pvconn)
959 {
960     if (pvconn != NULL) {
961         char *name = pvconn->name;
962         (pvconn->class->close)(pvconn);
963         free(name);
964     }
965 }
966
967 /* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
968  * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
969  * errno value.
970  *
971  * The new vconn will automatically negotiate an OpenFlow protocol version
972  * acceptable to both peers on the connection.  The version negotiated will be
973  * no lower than 'min_version' and no higher than OFP10_VERSION.
974  *
975  * pvconn_accept() will not block waiting for a connection.  If no connection
976  * is ready to be accepted, it returns EAGAIN immediately. */
977 int
978 pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
979 {
980     int retval = (pvconn->class->accept)(pvconn, new_vconn);
981     if (retval) {
982         *new_vconn = NULL;
983     } else {
984         assert((*new_vconn)->state != VCS_CONNECTING
985                || (*new_vconn)->class->connect);
986         (*new_vconn)->min_version = min_version;
987     }
988     return retval;
989 }
990
991 void
992 pvconn_wait(struct pvconn *pvconn)
993 {
994     (pvconn->class->wait)(pvconn);
995 }
996
997 /* Initializes 'vconn' as a new vconn named 'name', implemented via 'class'.
998  * The initial connection status, supplied as 'connect_status', is interpreted
999  * as follows:
1000  *
1001  *      - 0: 'vconn' is connected.  Its 'send' and 'recv' functions may be
1002  *        called in the normal fashion.
1003  *
1004  *      - EAGAIN: 'vconn' is trying to complete a connection.  Its 'connect'
1005  *        function should be called to complete the connection.
1006  *
1007  *      - Other positive errno values indicate that the connection failed with
1008  *        the specified error.
1009  *
1010  * After calling this function, vconn_close() must be used to destroy 'vconn',
1011  * otherwise resources will be leaked.
1012  *
1013  * The caller retains ownership of 'name'. */
1014 void
1015 vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
1016            const char *name)
1017 {
1018     vconn->class = class;
1019     vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
1020                     : !connect_status ? VCS_SEND_HELLO
1021                     : VCS_DISCONNECTED);
1022     vconn->error = connect_status;
1023     vconn->version = 0;
1024     vconn->min_version = 0;
1025     vconn->remote_ip = 0;
1026     vconn->remote_port = 0;
1027     vconn->local_ip = 0;
1028     vconn->local_port = 0;
1029     vconn->name = xstrdup(name);
1030     assert(vconn->state != VCS_CONNECTING || class->connect);
1031 }
1032
1033 void
1034 vconn_set_remote_ip(struct vconn *vconn, ovs_be32 ip)
1035 {
1036     vconn->remote_ip = ip;
1037 }
1038
1039 void
1040 vconn_set_remote_port(struct vconn *vconn, ovs_be16 port)
1041 {
1042     vconn->remote_port = port;
1043 }
1044
1045 void
1046 vconn_set_local_ip(struct vconn *vconn, ovs_be32 ip)
1047 {
1048     vconn->local_ip = ip;
1049 }
1050
1051 void
1052 vconn_set_local_port(struct vconn *vconn, ovs_be16 port)
1053 {
1054     vconn->local_port = port;
1055 }
1056
1057 void
1058 pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
1059             const char *name)
1060 {
1061     pvconn->class = class;
1062     pvconn->name = xstrdup(name);
1063 }