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