2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "stream-provider.h"
21 #include <netinet/in.h>
26 #include "dynamic-string.h"
27 #include "fatal-signal.h"
30 #include "ofp-print.h"
32 #include "openflow/nicira-ext.h"
33 #include "openflow/openflow.h"
34 #include "ovs-thread.h"
36 #include "poll-loop.h"
38 #include "socket-util.h"
42 VLOG_DEFINE_THIS_MODULE(stream);
44 COVERAGE_DEFINE(pstream_open);
45 COVERAGE_DEFINE(stream_open);
47 /* State of an active stream.*/
49 SCS_CONNECTING, /* Underlying stream is not connected. */
50 SCS_CONNECTED, /* Connection established. */
51 SCS_DISCONNECTED /* Connection failed or connection closed. */
54 static const struct stream_class *stream_classes[] = {
64 static const struct pstream_class *pstream_classes[] = {
76 do_winsock_start(void)
81 error = WSAStartup(MAKEWORD(2, 2), &wsaData);
83 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
90 static pthread_once_t once = PTHREAD_ONCE_INIT;
91 pthread_once(&once, do_winsock_start);
95 /* Check the validity of the stream class structures. */
97 check_stream_classes(void)
102 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
103 const struct stream_class *class = stream_classes[i];
104 ovs_assert(class->name != NULL);
105 ovs_assert(class->open != NULL);
106 if (class->close || class->recv || class->send || class->run
107 || class->run_wait || class->wait) {
108 ovs_assert(class->close != NULL);
109 ovs_assert(class->recv != NULL);
110 ovs_assert(class->send != NULL);
111 ovs_assert(class->wait != NULL);
113 /* This class delegates to another one. */
117 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
118 const struct pstream_class *class = pstream_classes[i];
119 ovs_assert(class->name != NULL);
120 ovs_assert(class->listen != NULL);
121 if (class->close || class->accept || class->wait) {
122 ovs_assert(class->close != NULL);
123 ovs_assert(class->accept != NULL);
124 ovs_assert(class->wait != NULL);
126 /* This class delegates to another one. */
132 /* Prints information on active (if 'active') and passive (if 'passive')
133 * connection methods supported by the stream. */
135 stream_usage(const char *name, bool active, bool passive,
136 bool bootstrap OVS_UNUSED)
138 /* Really this should be implemented via callbacks into the stream
139 * providers, but that seems too heavy-weight to bother with at the
144 printf("Active %s connection methods:\n", name);
145 printf(" tcp:IP:PORT "
146 "PORT at remote IP\n");
148 printf(" ssl:IP:PORT "
149 "SSL PORT at remote IP\n");
152 "Unix domain socket named FILE\n");
156 printf("Passive %s connection methods:\n", name);
157 printf(" ptcp:PORT[:IP] "
158 "listen to TCP PORT on IP\n");
160 printf(" pssl:PORT[:IP] "
161 "listen for SSL on PORT on IP\n");
163 printf(" punix:FILE "
164 "listen on Unix domain socket FILE\n");
168 printf("PKI configuration (required to use SSL):\n"
169 " -p, --private-key=FILE file with private key\n"
170 " -c, --certificate=FILE file with certificate for private key\n"
171 " -C, --ca-cert=FILE file with peer CA certificate\n");
173 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
174 "to read or create\n");
179 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
180 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
181 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
184 stream_lookup_class(const char *name, const struct stream_class **classp)
189 check_stream_classes();
192 prefix_len = strcspn(name, ":");
193 if (name[prefix_len] == '\0') {
196 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
197 const struct stream_class *class = stream_classes[i];
198 if (strlen(class->name) == prefix_len
199 && !memcmp(class->name, name, prefix_len)) {
207 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
208 * a supported stream type, otherwise EAFNOSUPPORT. */
210 stream_verify_name(const char *name)
212 const struct stream_class *class;
213 return stream_lookup_class(name, &class);
216 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
217 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
218 * ARGS are stream class-specific.
220 * Returns 0 if successful, otherwise a positive errno value. If successful,
221 * stores a pointer to the new connection in '*streamp', otherwise a null
224 stream_open(const char *name, struct stream **streamp, uint8_t dscp)
226 const struct stream_class *class;
227 struct stream *stream;
231 COVERAGE_INC(stream_open);
237 /* Look up the class. */
238 error = stream_lookup_class(name, &class);
243 /* Call class's "open" function. */
244 suffix_copy = xstrdup(strchr(name, ':') + 1);
245 error = class->open(name, suffix_copy, &stream, dscp);
260 /* Blocks until a previously started stream connection attempt succeeds or
261 * fails. 'error' should be the value returned by stream_open() and 'streamp'
262 * should point to the stream pointer set by stream_open(). Returns 0 if
263 * successful, otherwise a positive errno value other than EAGAIN or
264 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
265 * '*streamp' and sets '*streamp' to null.
268 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
271 stream_open_block(int error, struct stream **streamp)
273 struct stream *stream = *streamp;
278 while ((error = stream_connect(stream)) == EAGAIN) {
280 stream_run_wait(stream);
281 stream_connect_wait(stream);
284 ovs_assert(error != EINPROGRESS);
288 stream_close(stream);
296 /* Closes 'stream'. */
298 stream_close(struct stream *stream)
300 if (stream != NULL) {
301 char *name = stream->name;
302 (stream->class->close)(stream);
307 /* Returns the name of 'stream', that is, the string passed to
310 stream_get_name(const struct stream *stream)
312 return stream ? stream->name : "(null)";
316 scs_connecting(struct stream *stream)
318 int retval = (stream->class->connect)(stream);
319 ovs_assert(retval != EINPROGRESS);
321 stream->state = SCS_CONNECTED;
322 } else if (retval != EAGAIN) {
323 stream->state = SCS_DISCONNECTED;
324 stream->error = retval;
328 /* Tries to complete the connection on 'stream'. If 'stream''s connection is
329 * complete, returns 0 if the connection was successful or a positive errno
330 * value if it failed. If the connection is still in progress, returns
333 stream_connect(struct stream *stream)
335 enum stream_state last_state;
338 last_state = stream->state;
339 switch (stream->state) {
341 scs_connecting(stream);
347 case SCS_DISCONNECTED:
348 return stream->error;
353 } while (stream->state != last_state);
358 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
360 * - If successful, the number of bytes received (between 1 and 'n').
362 * - On error, a negative errno value.
364 * - 0, if the connection has been closed in the normal fashion, or if 'n'
367 * The recv function will not block waiting for a packet to arrive. If no
368 * data have been received, it returns -EAGAIN immediately. */
370 stream_recv(struct stream *stream, void *buffer, size_t n)
372 int retval = stream_connect(stream);
373 return (retval ? -retval
375 : (stream->class->recv)(stream, buffer, n));
378 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
380 * - If successful, the number of bytes sent (between 1 and 'n'). 0 is
381 * only a valid return value if 'n' is 0.
383 * - On error, a negative errno value.
385 * The send function will not block. If no bytes can be immediately accepted
386 * for transmission, it returns -EAGAIN immediately. */
388 stream_send(struct stream *stream, const void *buffer, size_t n)
390 int retval = stream_connect(stream);
391 return (retval ? -retval
393 : (stream->class->send)(stream, buffer, n));
396 /* Allows 'stream' to perform maintenance activities, such as flushing
399 stream_run(struct stream *stream)
401 if (stream->class->run) {
402 (stream->class->run)(stream);
406 /* Arranges for the poll loop to wake up when 'stream' needs to perform
407 * maintenance activities. */
409 stream_run_wait(struct stream *stream)
411 if (stream->class->run_wait) {
412 (stream->class->run_wait)(stream);
416 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
417 * action of the given 'type'. */
419 stream_wait(struct stream *stream, enum stream_wait_type wait)
421 ovs_assert(wait == STREAM_CONNECT || wait == STREAM_RECV
422 || wait == STREAM_SEND);
424 switch (stream->state) {
426 wait = STREAM_CONNECT;
429 case SCS_DISCONNECTED:
430 poll_immediate_wake();
433 (stream->class->wait)(stream, wait);
437 stream_connect_wait(struct stream *stream)
439 stream_wait(stream, STREAM_CONNECT);
443 stream_recv_wait(struct stream *stream)
445 stream_wait(stream, STREAM_RECV);
449 stream_send_wait(struct stream *stream)
451 stream_wait(stream, STREAM_SEND);
454 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
455 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
456 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
459 pstream_lookup_class(const char *name, const struct pstream_class **classp)
464 check_stream_classes();
467 prefix_len = strcspn(name, ":");
468 if (name[prefix_len] == '\0') {
471 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
472 const struct pstream_class *class = pstream_classes[i];
473 if (strlen(class->name) == prefix_len
474 && !memcmp(class->name, name, prefix_len)) {
482 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
483 * a supported pstream type, otherwise EAFNOSUPPORT. */
485 pstream_verify_name(const char *name)
487 const struct pstream_class *class;
488 return pstream_lookup_class(name, &class);
491 /* Returns 1 if the stream or pstream specified by 'name' needs periodic probes
492 * to verify connectivity. For [p]streams which need probes, it can take a
493 * long time to notice the connection has been dropped. Returns 0 if the
494 * stream or pstream does not need probes, and -1 if 'name' is not valid. */
496 stream_or_pstream_needs_probes(const char *name)
498 const struct pstream_class *pclass;
499 const struct stream_class *class;
501 if (!stream_lookup_class(name, &class)) {
502 return class->needs_probes;
503 } else if (!pstream_lookup_class(name, &pclass)) {
504 return pclass->needs_probes;
510 /* Attempts to start listening for remote stream connections. 'name' is a
511 * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
512 * class's name and ARGS are stream class-specific.
514 * Returns 0 if successful, otherwise a positive errno value. If successful,
515 * stores a pointer to the new connection in '*pstreamp', otherwise a null
518 pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
520 const struct pstream_class *class;
521 struct pstream *pstream;
525 COVERAGE_INC(pstream_open);
531 /* Look up the class. */
532 error = pstream_lookup_class(name, &class);
537 /* Call class's "open" function. */
538 suffix_copy = xstrdup(strchr(name, ':') + 1);
539 error = class->listen(name, suffix_copy, &pstream, dscp);
554 /* Returns the name that was used to open 'pstream'. The caller must not
555 * modify or free the name. */
557 pstream_get_name(const struct pstream *pstream)
559 return pstream->name;
562 /* Closes 'pstream'. */
564 pstream_close(struct pstream *pstream)
566 if (pstream != NULL) {
567 char *name = pstream->name;
568 (pstream->class->close)(pstream);
573 /* Tries to accept a new connection on 'pstream'. If successful, stores the
574 * new connection in '*new_stream' and returns 0. Otherwise, returns a
575 * positive errno value.
577 * pstream_accept() will not block waiting for a connection. If no connection
578 * is ready to be accepted, it returns EAGAIN immediately. */
580 pstream_accept(struct pstream *pstream, struct stream **new_stream)
582 int retval = (pstream->class->accept)(pstream, new_stream);
586 ovs_assert((*new_stream)->state != SCS_CONNECTING
587 || (*new_stream)->class->connect);
592 /* Tries to accept a new connection on 'pstream'. If successful, stores the
593 * new connection in '*new_stream' and returns 0. Otherwise, returns a
594 * positive errno value.
596 * pstream_accept_block() blocks until a connection is ready or until an error
597 * occurs. It will not return EAGAIN. */
599 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
604 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
605 pstream_wait(pstream);
615 pstream_wait(struct pstream *pstream)
617 (pstream->class->wait)(pstream);
621 pstream_set_dscp(struct pstream *pstream, uint8_t dscp)
623 if (pstream->class->set_dscp) {
624 return pstream->class->set_dscp(pstream, dscp);
629 /* Returns the transport port on which 'pstream' is listening, or 0 if the
630 * concept doesn't apply. */
632 pstream_get_bound_port(const struct pstream *pstream)
634 return pstream->bound_port;
637 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
638 * The initial connection status, supplied as 'connect_status', is interpreted
641 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
642 * called in the normal fashion.
644 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
645 * function should be called to complete the connection.
647 * - Other positive errno values indicate that the connection failed with
648 * the specified error.
650 * After calling this function, stream_close() must be used to destroy
651 * 'stream', otherwise resources will be leaked.
653 * The caller retains ownership of 'name'. */
655 stream_init(struct stream *stream, const struct stream_class *class,
656 int connect_status, const char *name)
658 memset(stream, 0, sizeof *stream);
659 stream->class = class;
660 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
661 : !connect_status ? SCS_CONNECTED
663 stream->error = connect_status;
664 stream->name = xstrdup(name);
665 ovs_assert(stream->state != SCS_CONNECTING || class->connect);
669 pstream_init(struct pstream *pstream, const struct pstream_class *class,
672 memset(pstream, 0, sizeof *pstream);
673 pstream->class = class;
674 pstream->name = xstrdup(name);
678 pstream_set_bound_port(struct pstream *pstream, ovs_be16 port)
680 pstream->bound_port = port;
684 count_fields(const char *s_)
686 char *s, *field, *save_ptr;
691 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
692 field = strtok_r(NULL, ":", &save_ptr)) {
700 /* Like stream_open(), but the port defaults to 'default_port' if no port
701 * number is given. */
703 stream_open_with_default_port(const char *name_,
704 uint16_t default_port,
705 struct stream **streamp,
711 if ((!strncmp(name_, "tcp:", 4) || !strncmp(name_, "ssl:", 4))
712 && count_fields(name_) < 3) {
713 if (default_port == OFP_OLD_PORT) {
714 VLOG_WARN_ONCE("The default OpenFlow port number will change "
715 "from %d to %d in a future release",
716 OFP_OLD_PORT, OFP_PORT);
717 } else if (default_port == OVSDB_OLD_PORT) {
718 VLOG_WARN_ONCE("The default OVSDB port number will change "
719 "from %d to %d in a future release",
720 OVSDB_OLD_PORT, OVSDB_PORT);
722 name = xasprintf("%s:%d", name_, default_port);
724 name = xstrdup(name_);
726 error = stream_open(name, streamp, dscp);
732 /* Like pstream_open(), but port defaults to 'default_port' if no port
733 * number is given. */
735 pstream_open_with_default_port(const char *name_,
736 uint16_t default_port,
737 struct pstream **pstreamp,
743 if ((!strncmp(name_, "ptcp:", 5) || !strncmp(name_, "pssl:", 5))
744 && count_fields(name_) < 2) {
745 name = xasprintf("%s%d", name_, default_port);
747 name = xstrdup(name_);
749 error = pstream_open(name, pstreamp, dscp);
756 * This function extracts IP address and port from the target string.
758 * - On success, function returns true and fills *ss structure with port
759 * and IP address. If port was absent in target string then it will use
760 * corresponding default port value.
761 * - On error, function returns false and *ss contains garbage.
764 stream_parse_target_with_default_port(const char *target,
765 uint16_t default_port,
766 struct sockaddr_storage *ss)
768 return ((!strncmp(target, "tcp:", 4) || !strncmp(target, "ssl:", 4))
769 && inet_parse_active(target + 4, default_port, ss));
772 /* Attempts to guess the content type of a stream whose first few bytes were
773 * the 'size' bytes of 'data'. */
774 static enum stream_content_type
775 stream_guess_content(const uint8_t *data, ssize_t size)
778 #define PAIR(A, B) (((A) << 8) | (B))
779 switch (PAIR(data[0], data[1])) {
780 case PAIR(0x16, 0x03): /* Handshake, version 3. */
783 return STREAM_JSONRPC;
784 case PAIR(OFP10_VERSION, 0 /* OFPT_HELLO */):
785 return STREAM_OPENFLOW;
789 return STREAM_UNKNOWN;
792 /* Returns a string represenation of 'type'. */
794 stream_content_type_to_string(enum stream_content_type type)
804 case STREAM_OPENFLOW:
812 /* Attempts to guess the content type of a stream whose first few bytes were
813 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
814 * content type is other than 'expected_type', then log a message in vlog
815 * module 'module', naming 'stream_name' as the source, explaining what
816 * content was expected and what was actually received. */
818 stream_report_content(const void *data, ssize_t size,
819 enum stream_content_type expected_type,
820 struct vlog_module *module, const char *stream_name)
822 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
823 enum stream_content_type actual_type;
825 actual_type = stream_guess_content(data, size);
826 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
827 vlog_rate_limit(module, VLL_WARN, &rl,
828 "%s: received %s data on %s channel",
830 stream_content_type_to_string(actual_type),
831 stream_content_type_to_string(expected_type));