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"
35 #include "poll-loop.h"
40 VLOG_DEFINE_THIS_MODULE(stream);
42 COVERAGE_DEFINE(pstream_open);
43 COVERAGE_DEFINE(stream_open);
45 /* State of an active stream.*/
47 SCS_CONNECTING, /* Underlying stream is not connected. */
48 SCS_CONNECTED, /* Connection established. */
49 SCS_DISCONNECTED /* Connection failed or connection closed. */
52 static const struct stream_class *stream_classes[] = {
62 static const struct pstream_class *pstream_classes[] = {
72 /* Check the validity of the stream class structures. */
74 check_stream_classes(void)
79 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
80 const struct stream_class *class = stream_classes[i];
81 ovs_assert(class->name != NULL);
82 ovs_assert(class->open != NULL);
83 if (class->close || class->recv || class->send || class->run
84 || class->run_wait || class->wait) {
85 ovs_assert(class->close != NULL);
86 ovs_assert(class->recv != NULL);
87 ovs_assert(class->send != NULL);
88 ovs_assert(class->wait != NULL);
90 /* This class delegates to another one. */
94 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
95 const struct pstream_class *class = pstream_classes[i];
96 ovs_assert(class->name != NULL);
97 ovs_assert(class->listen != NULL);
98 if (class->close || class->accept || class->wait) {
99 ovs_assert(class->close != NULL);
100 ovs_assert(class->accept != NULL);
101 ovs_assert(class->wait != NULL);
103 /* This class delegates to another one. */
109 /* Prints information on active (if 'active') and passive (if 'passive')
110 * connection methods supported by the stream. */
112 stream_usage(const char *name, bool active, bool passive,
113 bool bootstrap OVS_UNUSED)
115 /* Really this should be implemented via callbacks into the stream
116 * providers, but that seems too heavy-weight to bother with at the
121 printf("Active %s connection methods:\n", name);
122 printf(" tcp:IP:PORT "
123 "PORT at remote IP\n");
125 printf(" ssl:IP:PORT "
126 "SSL PORT at remote IP\n");
129 "Unix domain socket named FILE\n");
133 printf("Passive %s connection methods:\n", name);
134 printf(" ptcp:PORT[:IP] "
135 "listen to TCP PORT on IP\n");
137 printf(" pssl:PORT[:IP] "
138 "listen for SSL on PORT on IP\n");
140 printf(" punix:FILE "
141 "listen on Unix domain socket FILE\n");
145 printf("PKI configuration (required to use SSL):\n"
146 " -p, --private-key=FILE file with private key\n"
147 " -c, --certificate=FILE file with certificate for private key\n"
148 " -C, --ca-cert=FILE file with peer CA certificate\n");
150 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
151 "to read or create\n");
156 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
157 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
158 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
161 stream_lookup_class(const char *name, const struct stream_class **classp)
166 check_stream_classes();
169 prefix_len = strcspn(name, ":");
170 if (name[prefix_len] == '\0') {
173 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
174 const struct stream_class *class = stream_classes[i];
175 if (strlen(class->name) == prefix_len
176 && !memcmp(class->name, name, prefix_len)) {
184 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
185 * a supported stream type, otherwise EAFNOSUPPORT. */
187 stream_verify_name(const char *name)
189 const struct stream_class *class;
190 return stream_lookup_class(name, &class);
193 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
194 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
195 * ARGS are stream class-specific.
197 * Returns 0 if successful, otherwise a positive errno value. If successful,
198 * stores a pointer to the new connection in '*streamp', otherwise a null
201 stream_open(const char *name, struct stream **streamp, uint8_t dscp)
203 const struct stream_class *class;
204 struct stream *stream;
208 COVERAGE_INC(stream_open);
210 /* Look up the class. */
211 error = stream_lookup_class(name, &class);
216 /* Call class's "open" function. */
217 suffix_copy = xstrdup(strchr(name, ':') + 1);
218 error = class->open(name, suffix_copy, &stream, dscp);
233 /* Blocks until a previously started stream connection attempt succeeds or
234 * fails. 'error' should be the value returned by stream_open() and 'streamp'
235 * should point to the stream pointer set by stream_open(). Returns 0 if
236 * successful, otherwise a positive errno value other than EAGAIN or
237 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
238 * '*streamp' and sets '*streamp' to null.
241 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
244 stream_open_block(int error, struct stream **streamp)
246 struct stream *stream = *streamp;
251 while ((error = stream_connect(stream)) == EAGAIN) {
253 stream_run_wait(stream);
254 stream_connect_wait(stream);
257 ovs_assert(error != EINPROGRESS);
261 stream_close(stream);
269 /* Closes 'stream'. */
271 stream_close(struct stream *stream)
273 if (stream != NULL) {
274 char *name = stream->name;
275 (stream->class->close)(stream);
280 /* Returns the name of 'stream', that is, the string passed to
283 stream_get_name(const struct stream *stream)
285 return stream ? stream->name : "(null)";
289 scs_connecting(struct stream *stream)
291 int retval = (stream->class->connect)(stream);
292 ovs_assert(retval != EINPROGRESS);
294 stream->state = SCS_CONNECTED;
295 } else if (retval != EAGAIN) {
296 stream->state = SCS_DISCONNECTED;
297 stream->error = retval;
301 /* Tries to complete the connection on 'stream'. If 'stream''s connection is
302 * complete, returns 0 if the connection was successful or a positive errno
303 * value if it failed. If the connection is still in progress, returns
306 stream_connect(struct stream *stream)
308 enum stream_state last_state;
311 last_state = stream->state;
312 switch (stream->state) {
314 scs_connecting(stream);
320 case SCS_DISCONNECTED:
321 return stream->error;
326 } while (stream->state != last_state);
331 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
333 * - If successful, the number of bytes received (between 1 and 'n').
335 * - On error, a negative errno value.
337 * - 0, if the connection has been closed in the normal fashion, or if 'n'
340 * The recv function will not block waiting for a packet to arrive. If no
341 * data have been received, it returns -EAGAIN immediately. */
343 stream_recv(struct stream *stream, void *buffer, size_t n)
345 int retval = stream_connect(stream);
346 return (retval ? -retval
348 : (stream->class->recv)(stream, buffer, n));
351 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
353 * - If successful, the number of bytes sent (between 1 and 'n'). 0 is
354 * only a valid return value if 'n' is 0.
356 * - On error, a negative errno value.
358 * The send function will not block. If no bytes can be immediately accepted
359 * for transmission, it returns -EAGAIN immediately. */
361 stream_send(struct stream *stream, const void *buffer, size_t n)
363 int retval = stream_connect(stream);
364 return (retval ? -retval
366 : (stream->class->send)(stream, buffer, n));
369 /* Allows 'stream' to perform maintenance activities, such as flushing
372 stream_run(struct stream *stream)
374 if (stream->class->run) {
375 (stream->class->run)(stream);
379 /* Arranges for the poll loop to wake up when 'stream' needs to perform
380 * maintenance activities. */
382 stream_run_wait(struct stream *stream)
384 if (stream->class->run_wait) {
385 (stream->class->run_wait)(stream);
389 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
390 * action of the given 'type'. */
392 stream_wait(struct stream *stream, enum stream_wait_type wait)
394 ovs_assert(wait == STREAM_CONNECT || wait == STREAM_RECV
395 || wait == STREAM_SEND);
397 switch (stream->state) {
399 wait = STREAM_CONNECT;
402 case SCS_DISCONNECTED:
403 poll_immediate_wake();
406 (stream->class->wait)(stream, wait);
410 stream_connect_wait(struct stream *stream)
412 stream_wait(stream, STREAM_CONNECT);
416 stream_recv_wait(struct stream *stream)
418 stream_wait(stream, STREAM_RECV);
422 stream_send_wait(struct stream *stream)
424 stream_wait(stream, STREAM_SEND);
427 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
428 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
429 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
432 pstream_lookup_class(const char *name, const struct pstream_class **classp)
437 check_stream_classes();
440 prefix_len = strcspn(name, ":");
441 if (name[prefix_len] == '\0') {
444 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
445 const struct pstream_class *class = pstream_classes[i];
446 if (strlen(class->name) == prefix_len
447 && !memcmp(class->name, name, prefix_len)) {
455 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
456 * a supported pstream type, otherwise EAFNOSUPPORT. */
458 pstream_verify_name(const char *name)
460 const struct pstream_class *class;
461 return pstream_lookup_class(name, &class);
464 /* Returns 1 if the stream or pstream specified by 'name' needs periodic probes
465 * to verify connectivity. For [p]streams which need probes, it can take a
466 * long time to notice the connection has been dropped. Returns 0 if the
467 * stream or pstream does not need probes, and -1 if 'name' is not valid. */
469 stream_or_pstream_needs_probes(const char *name)
471 const struct pstream_class *pclass;
472 const struct stream_class *class;
474 if (!stream_lookup_class(name, &class)) {
475 return class->needs_probes;
476 } else if (!pstream_lookup_class(name, &pclass)) {
477 return pclass->needs_probes;
483 /* Attempts to start listening for remote stream connections. 'name' is a
484 * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
485 * class's name and ARGS are stream class-specific.
487 * Returns 0 if successful, otherwise a positive errno value. If successful,
488 * stores a pointer to the new connection in '*pstreamp', otherwise a null
491 pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
493 const struct pstream_class *class;
494 struct pstream *pstream;
498 COVERAGE_INC(pstream_open);
500 /* Look up the class. */
501 error = pstream_lookup_class(name, &class);
506 /* Call class's "open" function. */
507 suffix_copy = xstrdup(strchr(name, ':') + 1);
508 error = class->listen(name, suffix_copy, &pstream, dscp);
523 /* Returns the name that was used to open 'pstream'. The caller must not
524 * modify or free the name. */
526 pstream_get_name(const struct pstream *pstream)
528 return pstream->name;
531 /* Closes 'pstream'. */
533 pstream_close(struct pstream *pstream)
535 if (pstream != NULL) {
536 char *name = pstream->name;
537 (pstream->class->close)(pstream);
542 /* Tries to accept a new connection on 'pstream'. If successful, stores the
543 * new connection in '*new_stream' and returns 0. Otherwise, returns a
544 * positive errno value.
546 * pstream_accept() will not block waiting for a connection. If no connection
547 * is ready to be accepted, it returns EAGAIN immediately. */
549 pstream_accept(struct pstream *pstream, struct stream **new_stream)
551 int retval = (pstream->class->accept)(pstream, new_stream);
555 ovs_assert((*new_stream)->state != SCS_CONNECTING
556 || (*new_stream)->class->connect);
561 /* Tries to accept a new connection on 'pstream'. If successful, stores the
562 * new connection in '*new_stream' and returns 0. Otherwise, returns a
563 * positive errno value.
565 * pstream_accept_block() blocks until a connection is ready or until an error
566 * occurs. It will not return EAGAIN. */
568 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
573 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
574 pstream_wait(pstream);
584 pstream_wait(struct pstream *pstream)
586 (pstream->class->wait)(pstream);
590 pstream_set_dscp(struct pstream *pstream, uint8_t dscp)
592 if (pstream->class->set_dscp) {
593 return pstream->class->set_dscp(pstream, dscp);
598 /* Returns the transport port on which 'pstream' is listening, or 0 if the
599 * concept doesn't apply. */
601 pstream_get_bound_port(const struct pstream *pstream)
603 return pstream->bound_port;
606 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
607 * The initial connection status, supplied as 'connect_status', is interpreted
610 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
611 * called in the normal fashion.
613 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
614 * function should be called to complete the connection.
616 * - Other positive errno values indicate that the connection failed with
617 * the specified error.
619 * After calling this function, stream_close() must be used to destroy
620 * 'stream', otherwise resources will be leaked.
622 * The caller retains ownership of 'name'. */
624 stream_init(struct stream *stream, const struct stream_class *class,
625 int connect_status, const char *name)
627 memset(stream, 0, sizeof *stream);
628 stream->class = class;
629 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
630 : !connect_status ? SCS_CONNECTED
632 stream->error = connect_status;
633 stream->name = xstrdup(name);
634 ovs_assert(stream->state != SCS_CONNECTING || class->connect);
638 pstream_init(struct pstream *pstream, const struct pstream_class *class,
641 memset(pstream, 0, sizeof *pstream);
642 pstream->class = class;
643 pstream->name = xstrdup(name);
647 pstream_set_bound_port(struct pstream *pstream, ovs_be16 port)
649 pstream->bound_port = port;
653 count_fields(const char *s_)
655 char *s, *field, *save_ptr;
660 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
661 field = strtok_r(NULL, ":", &save_ptr)) {
669 /* Like stream_open(), but the port defaults to 'default_port' if no port
670 * number is given. */
672 stream_open_with_default_port(const char *name_,
673 uint16_t default_port,
674 struct stream **streamp,
680 if ((!strncmp(name_, "tcp:", 4) || !strncmp(name_, "ssl:", 4))
681 && count_fields(name_) < 3) {
682 if (default_port == OFP_OLD_PORT) {
683 VLOG_WARN_ONCE("The default OpenFlow port number will change "
684 "from %d to %d in a future release",
685 OFP_OLD_PORT, OFP_PORT);
686 } else if (default_port == OVSDB_OLD_PORT) {
687 VLOG_WARN_ONCE("The default OVSDB port number will change "
688 "from %d to %d in a future release",
689 OVSDB_OLD_PORT, OVSDB_PORT);
691 name = xasprintf("%s:%d", name_, default_port);
693 name = xstrdup(name_);
695 error = stream_open(name, streamp, dscp);
701 /* Like pstream_open(), but port defaults to 'default_port' if no port
702 * number is given. */
704 pstream_open_with_default_port(const char *name_,
705 uint16_t default_port,
706 struct pstream **pstreamp,
712 if ((!strncmp(name_, "ptcp:", 5) || !strncmp(name_, "pssl:", 5))
713 && count_fields(name_) < 2) {
714 name = xasprintf("%s%d", name_, default_port);
716 name = xstrdup(name_);
718 error = pstream_open(name, pstreamp, dscp);
725 * This function extracts IP address and port from the target string.
727 * - On success, function returns true and fills *ss structure with port
728 * and IP address. If port was absent in target string then it will use
729 * corresponding default port value.
730 * - On error, function returns false and *ss contains garbage.
733 stream_parse_target_with_default_port(const char *target,
734 uint16_t default_port,
735 struct sockaddr_storage *ss)
737 return ((!strncmp(target, "tcp:", 4) || !strncmp(target, "ssl:", 4))
738 && inet_parse_active(target + 4, default_port, ss));
741 /* Attempts to guess the content type of a stream whose first few bytes were
742 * the 'size' bytes of 'data'. */
743 static enum stream_content_type
744 stream_guess_content(const uint8_t *data, ssize_t size)
747 #define PAIR(A, B) (((A) << 8) | (B))
748 switch (PAIR(data[0], data[1])) {
749 case PAIR(0x16, 0x03): /* Handshake, version 3. */
752 return STREAM_JSONRPC;
753 case PAIR(OFP10_VERSION, 0 /* OFPT_HELLO */):
754 return STREAM_OPENFLOW;
758 return STREAM_UNKNOWN;
761 /* Returns a string represenation of 'type'. */
763 stream_content_type_to_string(enum stream_content_type type)
773 case STREAM_OPENFLOW:
781 /* Attempts to guess the content type of a stream whose first few bytes were
782 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
783 * content type is other than 'expected_type', then log a message in vlog
784 * module 'module', naming 'stream_name' as the source, explaining what
785 * content was expected and what was actually received. */
787 stream_report_content(const void *data, ssize_t size,
788 enum stream_content_type expected_type,
789 struct vlog_module *module, const char *stream_name)
791 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
792 enum stream_content_type actual_type;
794 actual_type = stream_guess_content(data, size);
795 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
796 vlog_rate_limit(module, VLL_WARN, &rl,
797 "%s: received %s data on %s channel",
799 stream_content_type_to_string(actual_type),
800 stream_content_type_to_string(expected_type));