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