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