2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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"
29 #include "ofp-print.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
34 #include "poll-loop.h"
39 VLOG_DEFINE_THIS_MODULE(stream);
41 COVERAGE_DEFINE(pstream_open);
42 COVERAGE_DEFINE(stream_open);
44 /* State of an active stream.*/
46 SCS_CONNECTING, /* Underlying stream is not connected. */
47 SCS_CONNECTED, /* Connection established. */
48 SCS_DISCONNECTED /* Connection failed or connection closed. */
51 static const struct stream_class *stream_classes[] = {
59 static const struct pstream_class *pstream_classes[] = {
67 /* Check the validity of the stream class structures. */
69 check_stream_classes(void)
74 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
75 const struct stream_class *class = stream_classes[i];
76 ovs_assert(class->name != NULL);
77 ovs_assert(class->open != NULL);
78 if (class->close || class->recv || class->send || class->run
79 || class->run_wait || class->wait) {
80 ovs_assert(class->close != NULL);
81 ovs_assert(class->recv != NULL);
82 ovs_assert(class->send != NULL);
83 ovs_assert(class->wait != NULL);
85 /* This class delegates to another one. */
89 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
90 const struct pstream_class *class = pstream_classes[i];
91 ovs_assert(class->name != NULL);
92 ovs_assert(class->listen != NULL);
93 if (class->close || class->accept || class->wait) {
94 ovs_assert(class->close != NULL);
95 ovs_assert(class->accept != NULL);
96 ovs_assert(class->wait != NULL);
98 /* This class delegates to another one. */
104 /* Prints information on active (if 'active') and passive (if 'passive')
105 * connection methods supported by the stream. */
107 stream_usage(const char *name, bool active, bool passive,
108 bool bootstrap OVS_UNUSED)
110 /* Really this should be implemented via callbacks into the stream
111 * providers, but that seems too heavy-weight to bother with at the
116 printf("Active %s connection methods:\n", name);
117 printf(" tcp:IP:PORT "
118 "PORT at remote IP\n");
120 printf(" ssl:IP:PORT "
121 "SSL PORT at remote IP\n");
124 "Unix domain socket named FILE\n");
128 printf("Passive %s connection methods:\n", name);
129 printf(" ptcp:PORT[:IP] "
130 "listen to TCP PORT on IP\n");
132 printf(" pssl:PORT[:IP] "
133 "listen for SSL on PORT on IP\n");
135 printf(" punix:FILE "
136 "listen on Unix domain socket FILE\n");
140 printf("PKI configuration (required to use SSL):\n"
141 " -p, --private-key=FILE file with private key\n"
142 " -c, --certificate=FILE file with certificate for private key\n"
143 " -C, --ca-cert=FILE file with peer CA certificate\n");
145 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
146 "to read or create\n");
151 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
152 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
153 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
156 stream_lookup_class(const char *name, const struct stream_class **classp)
161 check_stream_classes();
164 prefix_len = strcspn(name, ":");
165 if (name[prefix_len] == '\0') {
168 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
169 const struct stream_class *class = stream_classes[i];
170 if (strlen(class->name) == prefix_len
171 && !memcmp(class->name, name, prefix_len)) {
179 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
180 * a supported stream type, otherwise EAFNOSUPPORT. */
182 stream_verify_name(const char *name)
184 const struct stream_class *class;
185 return stream_lookup_class(name, &class);
188 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
189 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
190 * ARGS are stream class-specific.
192 * Returns 0 if successful, otherwise a positive errno value. If successful,
193 * stores a pointer to the new connection in '*streamp', otherwise a null
196 stream_open(const char *name, struct stream **streamp, uint8_t dscp)
198 const struct stream_class *class;
199 struct stream *stream;
203 COVERAGE_INC(stream_open);
205 /* Look up the class. */
206 error = stream_lookup_class(name, &class);
211 /* Call class's "open" function. */
212 suffix_copy = xstrdup(strchr(name, ':') + 1);
213 error = class->open(name, suffix_copy, &stream, dscp);
228 /* Blocks until a previously started stream connection attempt succeeds or
229 * fails. 'error' should be the value returned by stream_open() and 'streamp'
230 * should point to the stream pointer set by stream_open(). Returns 0 if
231 * successful, otherwise a positive errno value other than EAGAIN or
232 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
233 * '*streamp' and sets '*streamp' to null.
236 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
239 stream_open_block(int error, struct stream **streamp)
241 struct stream *stream = *streamp;
246 while ((error = stream_connect(stream)) == EAGAIN) {
248 stream_run_wait(stream);
249 stream_connect_wait(stream);
252 ovs_assert(error != EINPROGRESS);
256 stream_close(stream);
264 /* Closes 'stream'. */
266 stream_close(struct stream *stream)
268 if (stream != NULL) {
269 char *name = stream->name;
270 (stream->class->close)(stream);
275 /* Returns the name of 'stream', that is, the string passed to
278 stream_get_name(const struct stream *stream)
280 return stream ? stream->name : "(null)";
283 /* Returns the IP address of the peer, or 0 if the peer is not connected over
284 * an IP-based protocol or if its IP address is not yet known. */
286 stream_get_remote_ip(const struct stream *stream)
288 return stream->remote_ip;
291 /* Returns the transport port of the peer, or 0 if the connection does not
292 * contain a port or if the port is not yet known. */
294 stream_get_remote_port(const struct stream *stream)
296 return stream->remote_port;
299 /* Returns the IP address used to connect to the peer, or 0 if the connection
300 * is not an IP-based protocol or if its IP address is not yet known. */
302 stream_get_local_ip(const struct stream *stream)
304 return stream->local_ip;
307 /* Returns the transport port used to connect to the peer, or 0 if the
308 * connection does not contain a port or if the port is not yet known. */
310 stream_get_local_port(const struct stream *stream)
312 return stream->local_port;
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);
527 /* Look up the class. */
528 error = pstream_lookup_class(name, &class);
533 /* Call class's "open" function. */
534 suffix_copy = xstrdup(strchr(name, ':') + 1);
535 error = class->listen(name, suffix_copy, &pstream, dscp);
550 /* Returns the name that was used to open 'pstream'. The caller must not
551 * modify or free the name. */
553 pstream_get_name(const struct pstream *pstream)
555 return pstream->name;
558 /* Closes 'pstream'. */
560 pstream_close(struct pstream *pstream)
562 if (pstream != NULL) {
563 char *name = pstream->name;
564 (pstream->class->close)(pstream);
569 /* Tries to accept a new connection on 'pstream'. If successful, stores the
570 * new connection in '*new_stream' and returns 0. Otherwise, returns a
571 * positive errno value.
573 * pstream_accept() will not block waiting for a connection. If no connection
574 * is ready to be accepted, it returns EAGAIN immediately. */
576 pstream_accept(struct pstream *pstream, struct stream **new_stream)
578 int retval = (pstream->class->accept)(pstream, new_stream);
582 ovs_assert((*new_stream)->state != SCS_CONNECTING
583 || (*new_stream)->class->connect);
588 /* Tries to accept a new connection on 'pstream'. If successful, stores the
589 * new connection in '*new_stream' and returns 0. Otherwise, returns a
590 * positive errno value.
592 * pstream_accept_block() blocks until a connection is ready or until an error
593 * occurs. It will not return EAGAIN. */
595 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
600 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
601 pstream_wait(pstream);
611 pstream_wait(struct pstream *pstream)
613 (pstream->class->wait)(pstream);
617 pstream_set_dscp(struct pstream *pstream, uint8_t dscp)
619 if (pstream->class->set_dscp) {
620 return pstream->class->set_dscp(pstream, dscp);
625 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
626 * The initial connection status, supplied as 'connect_status', is interpreted
629 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
630 * called in the normal fashion.
632 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
633 * function should be called to complete the connection.
635 * - Other positive errno values indicate that the connection failed with
636 * the specified error.
638 * After calling this function, stream_close() must be used to destroy
639 * 'stream', otherwise resources will be leaked.
641 * The caller retains ownership of 'name'. */
643 stream_init(struct stream *stream, const struct stream_class *class,
644 int connect_status, const char *name)
646 memset(stream, 0, sizeof *stream);
647 stream->class = class;
648 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
649 : !connect_status ? SCS_CONNECTED
651 stream->error = connect_status;
652 stream->name = xstrdup(name);
653 ovs_assert(stream->state != SCS_CONNECTING || class->connect);
657 stream_set_remote_ip(struct stream *stream, ovs_be32 ip)
659 stream->remote_ip = ip;
663 stream_set_remote_port(struct stream *stream, ovs_be16 port)
665 stream->remote_port = port;
669 stream_set_local_ip(struct stream *stream, ovs_be32 ip)
671 stream->local_ip = ip;
675 stream_set_local_port(struct stream *stream, ovs_be16 port)
677 stream->local_port = port;
681 pstream_init(struct pstream *pstream, const struct pstream_class *class,
684 pstream->class = class;
685 pstream->name = xstrdup(name);
689 count_fields(const char *s_)
691 char *s, *field, *save_ptr;
696 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
697 field = strtok_r(NULL, ":", &save_ptr)) {
705 /* Like stream_open(), but for tcp streams the port defaults to
706 * 'default_tcp_port' if no port number is given and for SSL streams the port
707 * defaults to 'default_ssl_port' if no port number is given. */
709 stream_open_with_default_ports(const char *name_,
710 uint16_t default_tcp_port,
711 uint16_t default_ssl_port,
712 struct stream **streamp,
718 if (!strncmp(name_, "tcp:", 4) && count_fields(name_) < 3) {
719 name = xasprintf("%s:%d", name_, default_tcp_port);
720 } else if (!strncmp(name_, "ssl:", 4) && count_fields(name_) < 3) {
721 name = xasprintf("%s:%d", name_, default_ssl_port);
723 name = xstrdup(name_);
725 error = stream_open(name, streamp, dscp);
731 /* Like pstream_open(), but for ptcp streams the port defaults to
732 * 'default_ptcp_port' if no port number is given and for passive SSL streams
733 * the port defaults to 'default_pssl_port' if no port number is given. */
735 pstream_open_with_default_ports(const char *name_,
736 uint16_t default_ptcp_port,
737 uint16_t default_pssl_port,
738 struct pstream **pstreamp,
744 if (!strncmp(name_, "ptcp:", 5) && count_fields(name_) < 2) {
745 name = xasprintf("%s%d", name_, default_ptcp_port);
746 } else if (!strncmp(name_, "pssl:", 5) && count_fields(name_) < 2) {
747 name = xasprintf("%s%d", name_, default_pssl_port);
749 name = xstrdup(name_);
751 error = pstream_open(name, pstreamp, dscp);
758 * This function extracts IP address and port from the target string.
760 * - On success, function returns true and fills *sin structure with port
761 * and IP address. If port was absent in target string then it will use
762 * corresponding default port value.
763 * - On error, function returns false and *sin contains garbage.
766 stream_parse_target_with_default_ports(const char *target,
767 uint16_t default_tcp_port,
768 uint16_t default_ssl_port,
769 struct sockaddr_in *sin)
771 return (!strncmp(target, "tcp:", 4)
772 && inet_parse_active(target + 4, default_tcp_port, sin)) ||
773 (!strncmp(target, "ssl:", 4)
774 && inet_parse_active(target + 4, default_ssl_port, sin));
777 /* Attempts to guess the content type of a stream whose first few bytes were
778 * the 'size' bytes of 'data'. */
779 static enum stream_content_type
780 stream_guess_content(const uint8_t *data, ssize_t size)
783 #define PAIR(A, B) (((A) << 8) | (B))
784 switch (PAIR(data[0], data[1])) {
785 case PAIR(0x16, 0x03): /* Handshake, version 3. */
788 return STREAM_JSONRPC;
789 case PAIR(OFP10_VERSION, 0 /* OFPT_HELLO */):
790 return STREAM_OPENFLOW;
794 return STREAM_UNKNOWN;
797 /* Returns a string represenation of 'type'. */
799 stream_content_type_to_string(enum stream_content_type type)
809 case STREAM_OPENFLOW:
817 /* Attempts to guess the content type of a stream whose first few bytes were
818 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
819 * content type is other than 'expected_type', then log a message in vlog
820 * module 'module', naming 'stream_name' as the source, explaining what
821 * content was expected and what was actually received. */
823 stream_report_content(const void *data, ssize_t size,
824 enum stream_content_type expected_type,
825 struct vlog_module *module, const char *stream_name)
827 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
828 enum stream_content_type actual_type;
830 actual_type = stream_guess_content(data, size);
831 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
832 vlog_rate_limit(module, VLL_WARN, &rl,
833 "%s: received %s data on %s channel",
835 stream_content_type_to_string(actual_type),
836 stream_content_type_to_string(expected_type));