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"
29 #include "ofp-print.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
34 #include "poll-loop.h"
38 COVERAGE_DEFINE(pstream_open);
39 COVERAGE_DEFINE(stream_open);
41 /* State of an active stream.*/
43 SCS_CONNECTING, /* Underlying stream is not connected. */
44 SCS_CONNECTED, /* Connection established. */
45 SCS_DISCONNECTED /* Connection failed or connection closed. */
48 static const struct stream_class *stream_classes[] = {
56 static const struct pstream_class *pstream_classes[] = {
64 /* Check the validity of the stream class structures. */
66 check_stream_classes(void)
71 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
72 const struct stream_class *class = stream_classes[i];
73 ovs_assert(class->name != NULL);
74 ovs_assert(class->open != NULL);
75 if (class->close || class->recv || class->send || class->run
76 || class->run_wait || class->wait) {
77 ovs_assert(class->close != NULL);
78 ovs_assert(class->recv != NULL);
79 ovs_assert(class->send != NULL);
80 ovs_assert(class->wait != NULL);
82 /* This class delegates to another one. */
86 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
87 const struct pstream_class *class = pstream_classes[i];
88 ovs_assert(class->name != NULL);
89 ovs_assert(class->listen != NULL);
90 if (class->close || class->accept || class->wait) {
91 ovs_assert(class->close != NULL);
92 ovs_assert(class->accept != NULL);
93 ovs_assert(class->wait != NULL);
95 /* This class delegates to another one. */
101 /* Prints information on active (if 'active') and passive (if 'passive')
102 * connection methods supported by the stream. */
104 stream_usage(const char *name, bool active, bool passive,
105 bool bootstrap OVS_UNUSED)
107 /* Really this should be implemented via callbacks into the stream
108 * providers, but that seems too heavy-weight to bother with at the
113 printf("Active %s connection methods:\n", name);
114 printf(" tcp:IP:PORT "
115 "PORT at remote IP\n");
117 printf(" ssl:IP:PORT "
118 "SSL PORT at remote IP\n");
121 "Unix domain socket named FILE\n");
125 printf("Passive %s connection methods:\n", name);
126 printf(" ptcp:PORT[:IP] "
127 "listen to TCP PORT on IP\n");
129 printf(" pssl:PORT[:IP] "
130 "listen for SSL on PORT on IP\n");
132 printf(" punix:FILE "
133 "listen on Unix domain socket FILE\n");
137 printf("PKI configuration (required to use SSL):\n"
138 " -p, --private-key=FILE file with private key\n"
139 " -c, --certificate=FILE file with certificate for private key\n"
140 " -C, --ca-cert=FILE file with peer CA certificate\n");
142 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
143 "to read or create\n");
148 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
149 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
150 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
153 stream_lookup_class(const char *name, const struct stream_class **classp)
158 check_stream_classes();
161 prefix_len = strcspn(name, ":");
162 if (name[prefix_len] == '\0') {
165 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
166 const struct stream_class *class = stream_classes[i];
167 if (strlen(class->name) == prefix_len
168 && !memcmp(class->name, name, prefix_len)) {
176 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
177 * a supported stream type, otherwise EAFNOSUPPORT. */
179 stream_verify_name(const char *name)
181 const struct stream_class *class;
182 return stream_lookup_class(name, &class);
185 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
186 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
187 * ARGS are stream class-specific.
189 * Returns 0 if successful, otherwise a positive errno value. If successful,
190 * stores a pointer to the new connection in '*streamp', otherwise a null
193 stream_open(const char *name, struct stream **streamp, uint8_t dscp)
195 const struct stream_class *class;
196 struct stream *stream;
200 COVERAGE_INC(stream_open);
202 /* Look up the class. */
203 error = stream_lookup_class(name, &class);
208 /* Call class's "open" function. */
209 suffix_copy = xstrdup(strchr(name, ':') + 1);
210 error = class->open(name, suffix_copy, &stream, dscp);
225 /* Blocks until a previously started stream connection attempt succeeds or
226 * fails. 'error' should be the value returned by stream_open() and 'streamp'
227 * should point to the stream pointer set by stream_open(). Returns 0 if
228 * successful, otherwise a positive errno value other than EAGAIN or
229 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
230 * '*streamp' and sets '*streamp' to null.
233 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
236 stream_open_block(int error, struct stream **streamp)
238 struct stream *stream = *streamp;
243 while ((error = stream_connect(stream)) == EAGAIN) {
245 stream_run_wait(stream);
246 stream_connect_wait(stream);
249 ovs_assert(error != EINPROGRESS);
253 stream_close(stream);
261 /* Closes 'stream'. */
263 stream_close(struct stream *stream)
265 if (stream != NULL) {
266 char *name = stream->name;
267 (stream->class->close)(stream);
272 /* Returns the name of 'stream', that is, the string passed to
275 stream_get_name(const struct stream *stream)
277 return stream ? stream->name : "(null)";
280 /* Returns the IP address of the peer, or 0 if the peer is not connected over
281 * an IP-based protocol or if its IP address is not yet known. */
283 stream_get_remote_ip(const struct stream *stream)
285 return stream->remote_ip;
288 /* Returns the transport port of the peer, or 0 if the connection does not
289 * contain a port or if the port is not yet known. */
291 stream_get_remote_port(const struct stream *stream)
293 return stream->remote_port;
296 /* Returns the IP address used to connect to the peer, or 0 if the connection
297 * is not an IP-based protocol or if its IP address is not yet known. */
299 stream_get_local_ip(const struct stream *stream)
301 return stream->local_ip;
304 /* Returns the transport port used to connect to the peer, or 0 if the
305 * connection does not contain a port or if the port is not yet known. */
307 stream_get_local_port(const struct stream *stream)
309 return stream->local_port;
313 scs_connecting(struct stream *stream)
315 int retval = (stream->class->connect)(stream);
316 ovs_assert(retval != EINPROGRESS);
318 stream->state = SCS_CONNECTED;
319 } else if (retval != EAGAIN) {
320 stream->state = SCS_DISCONNECTED;
321 stream->error = retval;
325 /* Tries to complete the connection on 'stream'. If 'stream''s connection is
326 * complete, returns 0 if the connection was successful or a positive errno
327 * value if it failed. If the connection is still in progress, returns
330 stream_connect(struct stream *stream)
332 enum stream_state last_state;
335 last_state = stream->state;
336 switch (stream->state) {
338 scs_connecting(stream);
344 case SCS_DISCONNECTED:
345 return stream->error;
350 } while (stream->state != last_state);
355 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
357 * - If successful, the number of bytes received (between 1 and 'n').
359 * - On error, a negative errno value.
361 * - 0, if the connection has been closed in the normal fashion, or if 'n'
364 * The recv function will not block waiting for a packet to arrive. If no
365 * data have been received, it returns -EAGAIN immediately. */
367 stream_recv(struct stream *stream, void *buffer, size_t n)
369 int retval = stream_connect(stream);
370 return (retval ? -retval
372 : (stream->class->recv)(stream, buffer, n));
375 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
377 * - If successful, the number of bytes sent (between 1 and 'n'). 0 is
378 * only a valid return value if 'n' is 0.
380 * - On error, a negative errno value.
382 * The send function will not block. If no bytes can be immediately accepted
383 * for transmission, it returns -EAGAIN immediately. */
385 stream_send(struct stream *stream, const void *buffer, size_t n)
387 int retval = stream_connect(stream);
388 return (retval ? -retval
390 : (stream->class->send)(stream, buffer, n));
393 /* Allows 'stream' to perform maintenance activities, such as flushing
396 stream_run(struct stream *stream)
398 if (stream->class->run) {
399 (stream->class->run)(stream);
403 /* Arranges for the poll loop to wake up when 'stream' needs to perform
404 * maintenance activities. */
406 stream_run_wait(struct stream *stream)
408 if (stream->class->run_wait) {
409 (stream->class->run_wait)(stream);
413 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
414 * action of the given 'type'. */
416 stream_wait(struct stream *stream, enum stream_wait_type wait)
418 ovs_assert(wait == STREAM_CONNECT || wait == STREAM_RECV
419 || wait == STREAM_SEND);
421 switch (stream->state) {
423 wait = STREAM_CONNECT;
426 case SCS_DISCONNECTED:
427 poll_immediate_wake();
430 (stream->class->wait)(stream, wait);
434 stream_connect_wait(struct stream *stream)
436 stream_wait(stream, STREAM_CONNECT);
440 stream_recv_wait(struct stream *stream)
442 stream_wait(stream, STREAM_RECV);
446 stream_send_wait(struct stream *stream)
448 stream_wait(stream, STREAM_SEND);
451 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
452 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
453 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
456 pstream_lookup_class(const char *name, const struct pstream_class **classp)
461 check_stream_classes();
464 prefix_len = strcspn(name, ":");
465 if (name[prefix_len] == '\0') {
468 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
469 const struct pstream_class *class = pstream_classes[i];
470 if (strlen(class->name) == prefix_len
471 && !memcmp(class->name, name, prefix_len)) {
479 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
480 * a supported pstream type, otherwise EAFNOSUPPORT. */
482 pstream_verify_name(const char *name)
484 const struct pstream_class *class;
485 return pstream_lookup_class(name, &class);
488 /* Returns 1 if the stream or pstream specified by 'name' needs periodic probes
489 * to verify connectivity. For [p]streams which need probes, it can take a
490 * long time to notice the connection has been dropped. Returns 0 if the
491 * stream or pstream does not need probes, and -1 if 'name' is not valid. */
493 stream_or_pstream_needs_probes(const char *name)
495 const struct pstream_class *pclass;
496 const struct stream_class *class;
498 if (!stream_lookup_class(name, &class)) {
499 return class->needs_probes;
500 } else if (!pstream_lookup_class(name, &pclass)) {
501 return pclass->needs_probes;
507 /* Attempts to start listening for remote stream connections. 'name' is a
508 * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
509 * class's name and ARGS are stream class-specific.
511 * Returns 0 if successful, otherwise a positive errno value. If successful,
512 * stores a pointer to the new connection in '*pstreamp', otherwise a null
515 pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
517 const struct pstream_class *class;
518 struct pstream *pstream;
522 COVERAGE_INC(pstream_open);
524 /* Look up the class. */
525 error = pstream_lookup_class(name, &class);
530 /* Call class's "open" function. */
531 suffix_copy = xstrdup(strchr(name, ':') + 1);
532 error = class->listen(name, suffix_copy, &pstream, dscp);
547 /* Returns the name that was used to open 'pstream'. The caller must not
548 * modify or free the name. */
550 pstream_get_name(const struct pstream *pstream)
552 return pstream->name;
555 /* Closes 'pstream'. */
557 pstream_close(struct pstream *pstream)
559 if (pstream != NULL) {
560 char *name = pstream->name;
561 (pstream->class->close)(pstream);
566 /* Tries to accept a new connection on 'pstream'. If successful, stores the
567 * new connection in '*new_stream' and returns 0. Otherwise, returns a
568 * positive errno value.
570 * pstream_accept() will not block waiting for a connection. If no connection
571 * is ready to be accepted, it returns EAGAIN immediately. */
573 pstream_accept(struct pstream *pstream, struct stream **new_stream)
575 int retval = (pstream->class->accept)(pstream, new_stream);
579 ovs_assert((*new_stream)->state != SCS_CONNECTING
580 || (*new_stream)->class->connect);
585 /* Tries to accept a new connection on 'pstream'. If successful, stores the
586 * new connection in '*new_stream' and returns 0. Otherwise, returns a
587 * positive errno value.
589 * pstream_accept_block() blocks until a connection is ready or until an error
590 * occurs. It will not return EAGAIN. */
592 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
597 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
598 pstream_wait(pstream);
608 pstream_wait(struct pstream *pstream)
610 (pstream->class->wait)(pstream);
614 pstream_set_dscp(struct pstream *pstream, uint8_t dscp)
616 if (pstream->class->set_dscp) {
617 return pstream->class->set_dscp(pstream, dscp);
622 /* Returns the transport port on which 'pstream' is listening, or 0 if the
623 * concept doesn't apply. */
625 pstream_get_bound_port(const struct pstream *pstream)
627 return pstream->bound_port;
630 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
631 * The initial connection status, supplied as 'connect_status', is interpreted
634 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
635 * called in the normal fashion.
637 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
638 * function should be called to complete the connection.
640 * - Other positive errno values indicate that the connection failed with
641 * the specified error.
643 * After calling this function, stream_close() must be used to destroy
644 * 'stream', otherwise resources will be leaked.
646 * The caller retains ownership of 'name'. */
648 stream_init(struct stream *stream, const struct stream_class *class,
649 int connect_status, const char *name)
651 memset(stream, 0, sizeof *stream);
652 stream->class = class;
653 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
654 : !connect_status ? SCS_CONNECTED
656 stream->error = connect_status;
657 stream->name = xstrdup(name);
658 ovs_assert(stream->state != SCS_CONNECTING || class->connect);
662 stream_set_remote_ip(struct stream *stream, ovs_be32 ip)
664 stream->remote_ip = ip;
668 stream_set_remote_port(struct stream *stream, ovs_be16 port)
670 stream->remote_port = port;
674 stream_set_local_ip(struct stream *stream, ovs_be32 ip)
676 stream->local_ip = ip;
680 stream_set_local_port(struct stream *stream, ovs_be16 port)
682 stream->local_port = port;
686 pstream_init(struct pstream *pstream, const struct pstream_class *class,
689 memset(pstream, 0, sizeof *pstream);
690 pstream->class = class;
691 pstream->name = xstrdup(name);
695 pstream_set_bound_port(struct pstream *pstream, ovs_be16 port)
697 pstream->bound_port = port;
701 count_fields(const char *s_)
703 char *s, *field, *save_ptr;
708 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
709 field = strtok_r(NULL, ":", &save_ptr)) {
717 /* Like stream_open(), but the port defaults to 'default_port' if no port
718 * number is given. */
720 stream_open_with_default_port(const char *name_,
721 uint16_t default_port,
722 struct stream **streamp,
728 if ((!strncmp(name_, "tcp:", 4) || !strncmp(name_, "ssl:", 4))
729 && count_fields(name_) < 3) {
730 name = xasprintf("%s:%d", name_, default_port);
732 name = xstrdup(name_);
734 error = stream_open(name, streamp, dscp);
740 /* Like pstream_open(), but port defaults to 'default_port' if no port
741 * number is given. */
743 pstream_open_with_default_port(const char *name_,
744 uint16_t default_port,
745 struct pstream **pstreamp,
751 if ((!strncmp(name_, "ptcp:", 5) || !strncmp(name_, "pssl:", 5))
752 && count_fields(name_) < 2) {
753 name = xasprintf("%s%d", name_, default_port);
755 name = xstrdup(name_);
757 error = pstream_open(name, pstreamp, dscp);
764 * This function extracts IP address and port from the target string.
766 * - On success, function returns true and fills *sin structure with port
767 * and IP address. If port was absent in target string then it will use
768 * corresponding default port value.
769 * - On error, function returns false and *sin contains garbage.
772 stream_parse_target_with_default_port(const char *target,
773 uint16_t default_port,
774 struct sockaddr_in *sin)
776 return ((!strncmp(target, "tcp:", 4) || !strncmp(target, "ssl:", 4))
777 && inet_parse_active(target + 4, default_port, sin));
780 /* Attempts to guess the content type of a stream whose first few bytes were
781 * the 'size' bytes of 'data'. */
782 static enum stream_content_type
783 stream_guess_content(const uint8_t *data, ssize_t size)
786 #define PAIR(A, B) (((A) << 8) | (B))
787 switch (PAIR(data[0], data[1])) {
788 case PAIR(0x16, 0x03): /* Handshake, version 3. */
791 return STREAM_JSONRPC;
792 case PAIR(OFP10_VERSION, 0 /* OFPT_HELLO */):
793 return STREAM_OPENFLOW;
797 return STREAM_UNKNOWN;
800 /* Returns a string represenation of 'type'. */
802 stream_content_type_to_string(enum stream_content_type type)
812 case STREAM_OPENFLOW:
820 /* Attempts to guess the content type of a stream whose first few bytes were
821 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
822 * content type is other than 'expected_type', then log a message in vlog
823 * module 'module', naming 'stream_name' as the source, explaining what
824 * content was expected and what was actually received. */
826 stream_report_content(const void *data, ssize_t size,
827 enum stream_content_type expected_type,
828 struct vlog_module *module, const char *stream_name)
830 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
831 enum stream_content_type actual_type;
833 actual_type = stream_guess_content(data, size);
834 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
835 vlog_rate_limit(module, VLL_WARN, &rl,
836 "%s: received %s data on %s channel",
838 stream_content_type_to_string(actual_type),
839 stream_content_type_to_string(expected_type));