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[] = {
59 &windows_stream_class,
66 static const struct pstream_class *pstream_classes[] = {
71 &pwindows_pstream_class,
80 do_winsock_start(void)
85 error = WSAStartup(MAKEWORD(2, 2), &wsaData);
87 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
94 static pthread_once_t once = PTHREAD_ONCE_INIT;
95 pthread_once(&once, do_winsock_start);
99 /* Check the validity of the stream class structures. */
101 check_stream_classes(void)
106 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
107 const struct stream_class *class = stream_classes[i];
108 ovs_assert(class->name != NULL);
109 ovs_assert(class->open != NULL);
110 if (class->close || class->recv || class->send || class->run
111 || class->run_wait || class->wait) {
112 ovs_assert(class->close != NULL);
113 ovs_assert(class->recv != NULL);
114 ovs_assert(class->send != NULL);
115 ovs_assert(class->wait != NULL);
117 /* This class delegates to another one. */
121 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
122 const struct pstream_class *class = pstream_classes[i];
123 ovs_assert(class->name != NULL);
124 ovs_assert(class->listen != NULL);
125 if (class->close || class->accept || class->wait) {
126 ovs_assert(class->close != NULL);
127 ovs_assert(class->accept != NULL);
128 ovs_assert(class->wait != NULL);
130 /* This class delegates to another one. */
136 /* Prints information on active (if 'active') and passive (if 'passive')
137 * connection methods supported by the stream. */
139 stream_usage(const char *name, bool active, bool passive,
140 bool bootstrap OVS_UNUSED)
142 /* Really this should be implemented via callbacks into the stream
143 * providers, but that seems too heavy-weight to bother with at the
148 printf("Active %s connection methods:\n", name);
149 printf(" tcp:IP:PORT "
150 "PORT at remote IP\n");
152 printf(" ssl:IP:PORT "
153 "SSL PORT at remote IP\n");
156 "Unix domain socket named FILE\n");
160 printf("Passive %s connection methods:\n", name);
161 printf(" ptcp:PORT[:IP] "
162 "listen to TCP PORT on IP\n");
164 printf(" pssl:PORT[:IP] "
165 "listen for SSL on PORT on IP\n");
167 printf(" punix:FILE "
168 "listen on Unix domain socket FILE\n");
172 printf("PKI configuration (required to use SSL):\n"
173 " -p, --private-key=FILE file with private key\n"
174 " -c, --certificate=FILE file with certificate for private key\n"
175 " -C, --ca-cert=FILE file with peer CA certificate\n");
177 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
178 "to read or create\n");
183 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
184 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
185 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
188 stream_lookup_class(const char *name, const struct stream_class **classp)
193 check_stream_classes();
196 prefix_len = strcspn(name, ":");
197 if (name[prefix_len] == '\0') {
200 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
201 const struct stream_class *class = stream_classes[i];
202 if (strlen(class->name) == prefix_len
203 && !memcmp(class->name, name, prefix_len)) {
211 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
212 * a supported stream type, otherwise EAFNOSUPPORT. */
214 stream_verify_name(const char *name)
216 const struct stream_class *class;
217 return stream_lookup_class(name, &class);
220 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
221 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
222 * ARGS are stream class-specific.
224 * Returns 0 if successful, otherwise a positive errno value. If successful,
225 * stores a pointer to the new connection in '*streamp', otherwise a null
228 stream_open(const char *name, struct stream **streamp, uint8_t dscp)
230 const struct stream_class *class;
231 struct stream *stream;
235 COVERAGE_INC(stream_open);
241 /* Look up the class. */
242 error = stream_lookup_class(name, &class);
247 /* Call class's "open" function. */
248 suffix_copy = xstrdup(strchr(name, ':') + 1);
249 error = class->open(name, suffix_copy, &stream, dscp);
264 /* Blocks until a previously started stream connection attempt succeeds or
265 * fails. 'error' should be the value returned by stream_open() and 'streamp'
266 * should point to the stream pointer set by stream_open(). Returns 0 if
267 * successful, otherwise a positive errno value other than EAGAIN or
268 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
269 * '*streamp' and sets '*streamp' to null.
272 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
275 stream_open_block(int error, struct stream **streamp)
277 struct stream *stream = *streamp;
282 while ((error = stream_connect(stream)) == EAGAIN) {
284 stream_run_wait(stream);
285 stream_connect_wait(stream);
288 ovs_assert(error != EINPROGRESS);
292 stream_close(stream);
300 /* Closes 'stream'. */
302 stream_close(struct stream *stream)
304 if (stream != NULL) {
305 char *name = stream->name;
306 (stream->class->close)(stream);
311 /* Returns the name of 'stream', that is, the string passed to
314 stream_get_name(const struct stream *stream)
316 return stream ? stream->name : "(null)";
320 scs_connecting(struct stream *stream)
322 int retval = (stream->class->connect)(stream);
323 ovs_assert(retval != EINPROGRESS);
325 stream->state = SCS_CONNECTED;
326 } else if (retval != EAGAIN) {
327 stream->state = SCS_DISCONNECTED;
328 stream->error = retval;
332 /* Tries to complete the connection on 'stream'. If 'stream''s connection is
333 * complete, returns 0 if the connection was successful or a positive errno
334 * value if it failed. If the connection is still in progress, returns
337 stream_connect(struct stream *stream)
339 enum stream_state last_state;
342 last_state = stream->state;
343 switch (stream->state) {
345 scs_connecting(stream);
351 case SCS_DISCONNECTED:
352 return stream->error;
357 } while (stream->state != last_state);
362 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
364 * - If successful, the number of bytes received (between 1 and 'n').
366 * - On error, a negative errno value.
368 * - 0, if the connection has been closed in the normal fashion, or if 'n'
371 * The recv function will not block waiting for a packet to arrive. If no
372 * data have been received, it returns -EAGAIN immediately. */
374 stream_recv(struct stream *stream, void *buffer, size_t n)
376 int retval = stream_connect(stream);
377 return (retval ? -retval
379 : (stream->class->recv)(stream, buffer, n));
382 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
384 * - If successful, the number of bytes sent (between 1 and 'n'). 0 is
385 * only a valid return value if 'n' is 0.
387 * - On error, a negative errno value.
389 * The send function will not block. If no bytes can be immediately accepted
390 * for transmission, it returns -EAGAIN immediately. */
392 stream_send(struct stream *stream, const void *buffer, size_t n)
394 int retval = stream_connect(stream);
395 return (retval ? -retval
397 : (stream->class->send)(stream, buffer, n));
400 /* Allows 'stream' to perform maintenance activities, such as flushing
403 stream_run(struct stream *stream)
405 if (stream->class->run) {
406 (stream->class->run)(stream);
410 /* Arranges for the poll loop to wake up when 'stream' needs to perform
411 * maintenance activities. */
413 stream_run_wait(struct stream *stream)
415 if (stream->class->run_wait) {
416 (stream->class->run_wait)(stream);
420 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
421 * action of the given 'type'. */
423 stream_wait(struct stream *stream, enum stream_wait_type wait)
425 ovs_assert(wait == STREAM_CONNECT || wait == STREAM_RECV
426 || wait == STREAM_SEND);
428 switch (stream->state) {
430 wait = STREAM_CONNECT;
433 case SCS_DISCONNECTED:
434 poll_immediate_wake();
437 (stream->class->wait)(stream, wait);
441 stream_connect_wait(struct stream *stream)
443 stream_wait(stream, STREAM_CONNECT);
447 stream_recv_wait(struct stream *stream)
449 stream_wait(stream, STREAM_RECV);
453 stream_send_wait(struct stream *stream)
455 stream_wait(stream, STREAM_SEND);
458 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
459 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
460 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
463 pstream_lookup_class(const char *name, const struct pstream_class **classp)
468 check_stream_classes();
471 prefix_len = strcspn(name, ":");
472 if (name[prefix_len] == '\0') {
475 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
476 const struct pstream_class *class = pstream_classes[i];
477 if (strlen(class->name) == prefix_len
478 && !memcmp(class->name, name, prefix_len)) {
486 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
487 * a supported pstream type, otherwise EAFNOSUPPORT. */
489 pstream_verify_name(const char *name)
491 const struct pstream_class *class;
492 return pstream_lookup_class(name, &class);
495 /* Returns 1 if the stream or pstream specified by 'name' needs periodic probes
496 * to verify connectivity. For [p]streams which need probes, it can take a
497 * long time to notice the connection has been dropped. Returns 0 if the
498 * stream or pstream does not need probes, and -1 if 'name' is not valid. */
500 stream_or_pstream_needs_probes(const char *name)
502 const struct pstream_class *pclass;
503 const struct stream_class *class;
505 if (!stream_lookup_class(name, &class)) {
506 return class->needs_probes;
507 } else if (!pstream_lookup_class(name, &pclass)) {
508 return pclass->needs_probes;
514 /* Attempts to start listening for remote stream connections. 'name' is a
515 * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
516 * class's name and ARGS are stream class-specific.
518 * Returns 0 if successful, otherwise a positive errno value. If successful,
519 * stores a pointer to the new connection in '*pstreamp', otherwise a null
522 pstream_open(const char *name, struct pstream **pstreamp, uint8_t dscp)
524 const struct pstream_class *class;
525 struct pstream *pstream;
529 COVERAGE_INC(pstream_open);
535 /* Look up the class. */
536 error = pstream_lookup_class(name, &class);
541 /* Call class's "open" function. */
542 suffix_copy = xstrdup(strchr(name, ':') + 1);
543 error = class->listen(name, suffix_copy, &pstream, dscp);
558 /* Returns the name that was used to open 'pstream'. The caller must not
559 * modify or free the name. */
561 pstream_get_name(const struct pstream *pstream)
563 return pstream->name;
566 /* Closes 'pstream'. */
568 pstream_close(struct pstream *pstream)
570 if (pstream != NULL) {
571 char *name = pstream->name;
572 (pstream->class->close)(pstream);
577 /* Tries to accept a new connection on 'pstream'. If successful, stores the
578 * new connection in '*new_stream' and returns 0. Otherwise, returns a
579 * positive errno value.
581 * pstream_accept() will not block waiting for a connection. If no connection
582 * is ready to be accepted, it returns EAGAIN immediately. */
584 pstream_accept(struct pstream *pstream, struct stream **new_stream)
586 int retval = (pstream->class->accept)(pstream, new_stream);
590 ovs_assert((*new_stream)->state != SCS_CONNECTING
591 || (*new_stream)->class->connect);
596 /* Tries to accept a new connection on 'pstream'. If successful, stores the
597 * new connection in '*new_stream' and returns 0. Otherwise, returns a
598 * positive errno value.
600 * pstream_accept_block() blocks until a connection is ready or until an error
601 * occurs. It will not return EAGAIN. */
603 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
608 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
609 pstream_wait(pstream);
619 pstream_wait(struct pstream *pstream)
621 (pstream->class->wait)(pstream);
625 pstream_set_dscp(struct pstream *pstream, uint8_t dscp)
627 if (pstream->class->set_dscp) {
628 return pstream->class->set_dscp(pstream, dscp);
633 /* Returns the transport port on which 'pstream' is listening, or 0 if the
634 * concept doesn't apply. */
636 pstream_get_bound_port(const struct pstream *pstream)
638 return pstream->bound_port;
641 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
642 * The initial connection status, supplied as 'connect_status', is interpreted
645 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
646 * called in the normal fashion.
648 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
649 * function should be called to complete the connection.
651 * - Other positive errno values indicate that the connection failed with
652 * the specified error.
654 * After calling this function, stream_close() must be used to destroy
655 * 'stream', otherwise resources will be leaked.
657 * The caller retains ownership of 'name'. */
659 stream_init(struct stream *stream, const struct stream_class *class,
660 int connect_status, const char *name)
662 memset(stream, 0, sizeof *stream);
663 stream->class = class;
664 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
665 : !connect_status ? SCS_CONNECTED
667 stream->error = connect_status;
668 stream->name = xstrdup(name);
669 ovs_assert(stream->state != SCS_CONNECTING || class->connect);
673 pstream_init(struct pstream *pstream, const struct pstream_class *class,
676 memset(pstream, 0, sizeof *pstream);
677 pstream->class = class;
678 pstream->name = xstrdup(name);
682 pstream_set_bound_port(struct pstream *pstream, ovs_be16 port)
684 pstream->bound_port = port;
688 count_fields(const char *s_)
690 char *s, *field, *save_ptr;
695 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
696 field = strtok_r(NULL, ":", &save_ptr)) {
704 /* Like stream_open(), but the port defaults to 'default_port' if no port
705 * number is given. */
707 stream_open_with_default_port(const char *name_,
708 uint16_t default_port,
709 struct stream **streamp,
715 if ((!strncmp(name_, "tcp:", 4) || !strncmp(name_, "ssl:", 4))
716 && count_fields(name_) < 3) {
717 if (default_port == OFP_OLD_PORT) {
718 VLOG_WARN_ONCE("The default OpenFlow port number will change "
719 "from %d to %d in a future release",
720 OFP_OLD_PORT, OFP_PORT);
721 } else if (default_port == OVSDB_OLD_PORT) {
722 VLOG_WARN_ONCE("The default OVSDB port number will change "
723 "from %d to %d in a future release",
724 OVSDB_OLD_PORT, OVSDB_PORT);
726 name = xasprintf("%s:%d", name_, default_port);
728 name = xstrdup(name_);
730 error = stream_open(name, streamp, dscp);
736 /* Like pstream_open(), but port defaults to 'default_port' if no port
737 * number is given. */
739 pstream_open_with_default_port(const char *name_,
740 uint16_t default_port,
741 struct pstream **pstreamp,
747 if ((!strncmp(name_, "ptcp:", 5) || !strncmp(name_, "pssl:", 5))
748 && count_fields(name_) < 2) {
749 name = xasprintf("%s%d", name_, default_port);
751 name = xstrdup(name_);
753 error = pstream_open(name, pstreamp, dscp);
760 * This function extracts IP address and port from the target string.
762 * - On success, function returns true and fills *ss structure with port
763 * and IP address. If port was absent in target string then it will use
764 * corresponding default port value.
765 * - On error, function returns false and *ss contains garbage.
768 stream_parse_target_with_default_port(const char *target,
769 uint16_t default_port,
770 struct sockaddr_storage *ss)
772 return ((!strncmp(target, "tcp:", 4) || !strncmp(target, "ssl:", 4))
773 && inet_parse_active(target + 4, default_port, ss));
776 /* Attempts to guess the content type of a stream whose first few bytes were
777 * the 'size' bytes of 'data'. */
778 static enum stream_content_type
779 stream_guess_content(const uint8_t *data, ssize_t size)
782 #define PAIR(A, B) (((A) << 8) | (B))
783 switch (PAIR(data[0], data[1])) {
784 case PAIR(0x16, 0x03): /* Handshake, version 3. */
787 return STREAM_JSONRPC;
788 case PAIR(OFP10_VERSION, 0 /* OFPT_HELLO */):
789 return STREAM_OPENFLOW;
793 return STREAM_UNKNOWN;
796 /* Returns a string represenation of 'type'. */
798 stream_content_type_to_string(enum stream_content_type type)
808 case STREAM_OPENFLOW:
816 /* Attempts to guess the content type of a stream whose first few bytes were
817 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
818 * content type is other than 'expected_type', then log a message in vlog
819 * module 'module', naming 'stream_name' as the source, explaining what
820 * content was expected and what was actually received. */
822 stream_report_content(const void *data, ssize_t size,
823 enum stream_content_type expected_type,
824 struct vlog_module *module, const char *stream_name)
826 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
827 enum stream_content_type actual_type;
829 actual_type = stream_guess_content(data, size);
830 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
831 vlog_rate_limit(module, VLL_WARN, &rl,
832 "%s: received %s data on %s channel",
834 stream_content_type_to_string(actual_type),
835 stream_content_type_to_string(expected_type));