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