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