]> git.proxmox.com Git - mirror_ovs.git/blob - lib/stream.c
stream: Fix error message.
[mirror_ovs.git] / lib / stream.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "stream-provider.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <poll.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "fatal-signal.h"
29 #include "flow.h"
30 #include "ofp-print.h"
31 #include "ofpbuf.h"
32 #include "openflow/nicira-ext.h"
33 #include "openflow/openflow.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "random.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(stream);
41
42 COVERAGE_DEFINE(pstream_open);
43 COVERAGE_DEFINE(stream_open);
44
45 /* State of an active stream.*/
46 enum stream_state {
47 SCS_CONNECTING, /* Underlying stream is not connected. */
48 SCS_CONNECTED, /* Connection established. */
49 SCS_DISCONNECTED /* Connection failed or connection closed. */
50 };
51
52 static struct stream_class *stream_classes[] = {
53 &tcp_stream_class,
54 &unix_stream_class,
55 #ifdef HAVE_OPENSSL
56 &ssl_stream_class,
57 #endif
58 };
59
60 static struct pstream_class *pstream_classes[] = {
61 &ptcp_pstream_class,
62 &punix_pstream_class,
63 #ifdef HAVE_OPENSSL
64 &pssl_pstream_class,
65 #endif
66 };
67
68 /* Check the validity of the stream class structures. */
69 static void
70 check_stream_classes(void)
71 {
72 #ifndef NDEBUG
73 size_t i;
74
75 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
76 struct stream_class *class = stream_classes[i];
77 assert(class->name != NULL);
78 assert(class->open != NULL);
79 if (class->close || class->recv || class->send || class->run
80 || class->run_wait || class->wait) {
81 assert(class->close != NULL);
82 assert(class->recv != NULL);
83 assert(class->send != NULL);
84 assert(class->wait != NULL);
85 } else {
86 /* This class delegates to another one. */
87 }
88 }
89
90 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
91 struct pstream_class *class = pstream_classes[i];
92 assert(class->name != NULL);
93 assert(class->listen != NULL);
94 if (class->close || class->accept || class->wait) {
95 assert(class->close != NULL);
96 assert(class->accept != NULL);
97 assert(class->wait != NULL);
98 } else {
99 /* This class delegates to another one. */
100 }
101 }
102 #endif
103 }
104
105 /* Prints information on active (if 'active') and passive (if 'passive')
106 * connection methods supported by the stream. */
107 void
108 stream_usage(const char *name, bool active, bool passive,
109 bool bootstrap OVS_UNUSED)
110 {
111 /* Really this should be implemented via callbacks into the stream
112 * providers, but that seems too heavy-weight to bother with at the
113 * moment. */
114
115 printf("\n");
116 if (active) {
117 printf("Active %s connection methods:\n", name);
118 printf(" tcp:IP:PORT "
119 "PORT at remote IP\n");
120 #ifdef HAVE_OPENSSL
121 printf(" ssl:IP:PORT "
122 "SSL PORT at remote IP\n");
123 #endif
124 printf(" unix:FILE "
125 "Unix domain socket named FILE\n");
126 }
127
128 if (passive) {
129 printf("Passive %s connection methods:\n", name);
130 printf(" ptcp:PORT[:IP] "
131 "listen to TCP PORT on IP\n");
132 #ifdef HAVE_OPENSSL
133 printf(" pssl:PORT[:IP] "
134 "listen for SSL on PORT on IP\n");
135 #endif
136 printf(" punix:FILE "
137 "listen on Unix domain socket FILE\n");
138 }
139
140 #ifdef HAVE_OPENSSL
141 printf("PKI configuration (required to use SSL):\n"
142 " -p, --private-key=FILE file with private key\n"
143 " -c, --certificate=FILE file with certificate for private key\n"
144 " -C, --ca-cert=FILE file with peer CA certificate\n");
145 if (bootstrap) {
146 printf(" --bootstrap-ca-cert=FILE file with peer CA certificate "
147 "to read or create\n");
148 }
149 #endif
150 }
151
152 /* Given 'name', a stream name in the form "TYPE:ARGS", stores the class
153 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
154 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
155 * class exists. */
156 static int
157 stream_lookup_class(const char *name, struct stream_class **classp)
158 {
159 size_t prefix_len;
160 size_t i;
161
162 check_stream_classes();
163
164 *classp = NULL;
165 prefix_len = strcspn(name, ":");
166 if (name[prefix_len] == '\0') {
167 return EAFNOSUPPORT;
168 }
169 for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
170 struct stream_class *class = stream_classes[i];
171 if (strlen(class->name) == prefix_len
172 && !memcmp(class->name, name, prefix_len)) {
173 *classp = class;
174 return 0;
175 }
176 }
177 return EAFNOSUPPORT;
178 }
179
180 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
181 * a supported stream type, otherwise EAFNOSUPPORT. */
182 int
183 stream_verify_name(const char *name)
184 {
185 struct stream_class *class;
186 return stream_lookup_class(name, &class);
187 }
188
189 /* Attempts to connect a stream to a remote peer. 'name' is a connection name
190 * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
191 * ARGS are stream class-specific.
192 *
193 * Returns 0 if successful, otherwise a positive errno value. If successful,
194 * stores a pointer to the new connection in '*streamp', otherwise a null
195 * pointer. */
196 int
197 stream_open(const char *name, struct stream **streamp)
198 {
199 struct stream_class *class;
200 struct stream *stream;
201 char *suffix_copy;
202 int error;
203
204 COVERAGE_INC(stream_open);
205
206 /* Look up the class. */
207 error = stream_lookup_class(name, &class);
208 if (!class) {
209 goto error;
210 }
211
212 /* Call class's "open" function. */
213 suffix_copy = xstrdup(strchr(name, ':') + 1);
214 error = class->open(name, suffix_copy, &stream);
215 free(suffix_copy);
216 if (error) {
217 goto error;
218 }
219
220 /* Success. */
221 *streamp = stream;
222 return 0;
223
224 error:
225 *streamp = NULL;
226 return error;
227 }
228
229 /* Blocks until a previously started stream connection attempt succeeds or
230 * fails. 'error' should be the value returned by stream_open() and 'streamp'
231 * should point to the stream pointer set by stream_open(). Returns 0 if
232 * successful, otherwise a positive errno value other than EAGAIN or
233 * EINPROGRESS. If successful, leaves '*streamp' untouched; on error, closes
234 * '*streamp' and sets '*streamp' to null.
235 *
236 * Typical usage:
237 * error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
238 */
239 int
240 stream_open_block(int error, struct stream **streamp)
241 {
242 struct stream *stream = *streamp;
243
244 fatal_signal_run();
245
246 if (!error) {
247 while ((error = stream_connect(stream)) == EAGAIN) {
248 stream_run(stream);
249 stream_run_wait(stream);
250 stream_connect_wait(stream);
251 poll_block();
252 }
253 assert(error != EINPROGRESS);
254 }
255
256 if (error) {
257 stream_close(stream);
258 *streamp = NULL;
259 } else {
260 *streamp = stream;
261 }
262 return error;
263 }
264
265 /* Closes 'stream'. */
266 void
267 stream_close(struct stream *stream)
268 {
269 if (stream != NULL) {
270 char *name = stream->name;
271 (stream->class->close)(stream);
272 free(name);
273 }
274 }
275
276 /* Returns the name of 'stream', that is, the string passed to
277 * stream_open(). */
278 const char *
279 stream_get_name(const struct stream *stream)
280 {
281 return stream ? stream->name : "(null)";
282 }
283
284 /* Returns the IP address of the peer, or 0 if the peer is not connected over
285 * an IP-based protocol or if its IP address is not yet known. */
286 ovs_be32
287 stream_get_remote_ip(const struct stream *stream)
288 {
289 return stream->remote_ip;
290 }
291
292 /* Returns the transport port of the peer, or 0 if the connection does not
293 * contain a port or if the port is not yet known. */
294 ovs_be16
295 stream_get_remote_port(const struct stream *stream)
296 {
297 return stream->remote_port;
298 }
299
300 /* Returns the IP address used to connect to the peer, or 0 if the connection
301 * is not an IP-based protocol or if its IP address is not yet known. */
302 ovs_be32
303 stream_get_local_ip(const struct stream *stream)
304 {
305 return stream->local_ip;
306 }
307
308 /* Returns the transport port used to connect to the peer, or 0 if the
309 * connection does not contain a port or if the port is not yet known. */
310 ovs_be16
311 stream_get_local_port(const struct stream *stream)
312 {
313 return stream->local_port;
314 }
315
316 static void
317 scs_connecting(struct stream *stream)
318 {
319 int retval = (stream->class->connect)(stream);
320 assert(retval != EINPROGRESS);
321 if (!retval) {
322 stream->state = SCS_CONNECTED;
323 } else if (retval != EAGAIN) {
324 stream->state = SCS_DISCONNECTED;
325 stream->error = retval;
326 }
327 }
328
329 /* Tries to complete the connection on 'stream'. If 'stream''s connection is
330 * complete, returns 0 if the connection was successful or a positive errno
331 * value if it failed. If the connection is still in progress, returns
332 * EAGAIN. */
333 int
334 stream_connect(struct stream *stream)
335 {
336 enum stream_state last_state;
337
338 do {
339 last_state = stream->state;
340 switch (stream->state) {
341 case SCS_CONNECTING:
342 scs_connecting(stream);
343 break;
344
345 case SCS_CONNECTED:
346 return 0;
347
348 case SCS_DISCONNECTED:
349 return stream->error;
350
351 default:
352 NOT_REACHED();
353 }
354 } while (stream->state != last_state);
355
356 return EAGAIN;
357 }
358
359 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
360 *
361 * - If successful, the number of bytes received (between 1 and 'n').
362 *
363 * - On error, a negative errno value.
364 *
365 * - 0, if the connection has been closed in the normal fashion, or if 'n'
366 * is zero.
367 *
368 * The recv function will not block waiting for a packet to arrive. If no
369 * data have been received, it returns -EAGAIN immediately. */
370 int
371 stream_recv(struct stream *stream, void *buffer, size_t n)
372 {
373 int retval = stream_connect(stream);
374 return (retval ? -retval
375 : n == 0 ? 0
376 : (stream->class->recv)(stream, buffer, n));
377 }
378
379 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
380 *
381 * - If successful, the number of bytes sent (between 1 and 'n'). 0 is
382 * only a valid return value if 'n' is 0.
383 *
384 * - On error, a negative errno value.
385 *
386 * The send function will not block. If no bytes can be immediately accepted
387 * for transmission, it returns -EAGAIN immediately. */
388 int
389 stream_send(struct stream *stream, const void *buffer, size_t n)
390 {
391 int retval = stream_connect(stream);
392 return (retval ? -retval
393 : n == 0 ? 0
394 : (stream->class->send)(stream, buffer, n));
395 }
396
397 /* Allows 'stream' to perform maintenance activities, such as flushing
398 * output buffers. */
399 void
400 stream_run(struct stream *stream)
401 {
402 if (stream->class->run) {
403 (stream->class->run)(stream);
404 }
405 }
406
407 /* Arranges for the poll loop to wake up when 'stream' needs to perform
408 * maintenance activities. */
409 void
410 stream_run_wait(struct stream *stream)
411 {
412 if (stream->class->run_wait) {
413 (stream->class->run_wait)(stream);
414 }
415 }
416
417 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
418 * action of the given 'type'. */
419 void
420 stream_wait(struct stream *stream, enum stream_wait_type wait)
421 {
422 assert(wait == STREAM_CONNECT || wait == STREAM_RECV
423 || wait == STREAM_SEND);
424
425 switch (stream->state) {
426 case SCS_CONNECTING:
427 wait = STREAM_CONNECT;
428 break;
429
430 case SCS_DISCONNECTED:
431 poll_immediate_wake();
432 return;
433 }
434 (stream->class->wait)(stream, wait);
435 }
436
437 void
438 stream_connect_wait(struct stream *stream)
439 {
440 stream_wait(stream, STREAM_CONNECT);
441 }
442
443 void
444 stream_recv_wait(struct stream *stream)
445 {
446 stream_wait(stream, STREAM_RECV);
447 }
448
449 void
450 stream_send_wait(struct stream *stream)
451 {
452 stream_wait(stream, STREAM_SEND);
453 }
454
455 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
456 * named "TYPE" into '*classp' and returns 0. Returns EAFNOSUPPORT and stores
457 * a null pointer into '*classp' if 'name' is in the wrong form or if no such
458 * class exists. */
459 static int
460 pstream_lookup_class(const char *name, struct pstream_class **classp)
461 {
462 size_t prefix_len;
463 size_t i;
464
465 check_stream_classes();
466
467 *classp = NULL;
468 prefix_len = strcspn(name, ":");
469 if (name[prefix_len] == '\0') {
470 return EAFNOSUPPORT;
471 }
472 for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
473 struct pstream_class *class = pstream_classes[i];
474 if (strlen(class->name) == prefix_len
475 && !memcmp(class->name, name, prefix_len)) {
476 *classp = class;
477 return 0;
478 }
479 }
480 return EAFNOSUPPORT;
481 }
482
483 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
484 * a supported pstream type, otherwise EAFNOSUPPORT. */
485 int
486 pstream_verify_name(const char *name)
487 {
488 struct pstream_class *class;
489 return pstream_lookup_class(name, &class);
490 }
491
492 /* Attempts to start listening for remote stream connections. 'name' is a
493 * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
494 * class's name and ARGS are stream class-specific.
495 *
496 * Returns 0 if successful, otherwise a positive errno value. If successful,
497 * stores a pointer to the new connection in '*pstreamp', otherwise a null
498 * pointer. */
499 int
500 pstream_open(const char *name, struct pstream **pstreamp)
501 {
502 struct pstream_class *class;
503 struct pstream *pstream;
504 char *suffix_copy;
505 int error;
506
507 COVERAGE_INC(pstream_open);
508
509 /* Look up the class. */
510 error = pstream_lookup_class(name, &class);
511 if (!class) {
512 goto error;
513 }
514
515 /* Call class's "open" function. */
516 suffix_copy = xstrdup(strchr(name, ':') + 1);
517 error = class->listen(name, suffix_copy, &pstream);
518 free(suffix_copy);
519 if (error) {
520 goto error;
521 }
522
523 /* Success. */
524 *pstreamp = pstream;
525 return 0;
526
527 error:
528 *pstreamp = NULL;
529 return error;
530 }
531
532 /* Returns the name that was used to open 'pstream'. The caller must not
533 * modify or free the name. */
534 const char *
535 pstream_get_name(const struct pstream *pstream)
536 {
537 return pstream->name;
538 }
539
540 /* Closes 'pstream'. */
541 void
542 pstream_close(struct pstream *pstream)
543 {
544 if (pstream != NULL) {
545 char *name = pstream->name;
546 (pstream->class->close)(pstream);
547 free(name);
548 }
549 }
550
551 /* Tries to accept a new connection on 'pstream'. If successful, stores the
552 * new connection in '*new_stream' and returns 0. Otherwise, returns a
553 * positive errno value.
554 *
555 * pstream_accept() will not block waiting for a connection. If no connection
556 * is ready to be accepted, it returns EAGAIN immediately. */
557 int
558 pstream_accept(struct pstream *pstream, struct stream **new_stream)
559 {
560 int retval = (pstream->class->accept)(pstream, new_stream);
561 if (retval) {
562 *new_stream = NULL;
563 } else {
564 assert((*new_stream)->state != SCS_CONNECTING
565 || (*new_stream)->class->connect);
566 }
567 return retval;
568 }
569
570 /* Tries to accept a new connection on 'pstream'. If successful, stores the
571 * new connection in '*new_stream' and returns 0. Otherwise, returns a
572 * positive errno value.
573 *
574 * pstream_accept_block() blocks until a connection is ready or until an error
575 * occurs. It will not return EAGAIN. */
576 int
577 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
578 {
579 int error;
580
581 fatal_signal_run();
582 while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
583 pstream_wait(pstream);
584 poll_block();
585 }
586 if (error) {
587 *new_stream = NULL;
588 }
589 return error;
590 }
591
592 void
593 pstream_wait(struct pstream *pstream)
594 {
595 (pstream->class->wait)(pstream);
596 }
597 \f
598 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
599 * The initial connection status, supplied as 'connect_status', is interpreted
600 * as follows:
601 *
602 * - 0: 'stream' is connected. Its 'send' and 'recv' functions may be
603 * called in the normal fashion.
604 *
605 * - EAGAIN: 'stream' is trying to complete a connection. Its 'connect'
606 * function should be called to complete the connection.
607 *
608 * - Other positive errno values indicate that the connection failed with
609 * the specified error.
610 *
611 * After calling this function, stream_close() must be used to destroy
612 * 'stream', otherwise resources will be leaked.
613 *
614 * The caller retains ownership of 'name'. */
615 void
616 stream_init(struct stream *stream, struct stream_class *class,
617 int connect_status, const char *name)
618 {
619 stream->class = class;
620 stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
621 : !connect_status ? SCS_CONNECTED
622 : SCS_DISCONNECTED);
623 stream->error = connect_status;
624 stream->name = xstrdup(name);
625 assert(stream->state != SCS_CONNECTING || class->connect);
626 }
627
628 void
629 stream_set_remote_ip(struct stream *stream, ovs_be32 ip)
630 {
631 stream->remote_ip = ip;
632 }
633
634 void
635 stream_set_remote_port(struct stream *stream, ovs_be16 port)
636 {
637 stream->remote_port = port;
638 }
639
640 void
641 stream_set_local_ip(struct stream *stream, ovs_be32 ip)
642 {
643 stream->local_ip = ip;
644 }
645
646 void
647 stream_set_local_port(struct stream *stream, ovs_be16 port)
648 {
649 stream->local_port = port;
650 }
651
652 void
653 pstream_init(struct pstream *pstream, struct pstream_class *class,
654 const char *name)
655 {
656 pstream->class = class;
657 pstream->name = xstrdup(name);
658 }
659 \f
660 static int
661 count_fields(const char *s_)
662 {
663 char *s, *field, *save_ptr;
664 int n = 0;
665
666 save_ptr = NULL;
667 s = xstrdup(s_);
668 for (field = strtok_r(s, ":", &save_ptr); field != NULL;
669 field = strtok_r(NULL, ":", &save_ptr)) {
670 n++;
671 }
672 free(s);
673
674 return n;
675 }
676
677 /* Like stream_open(), but for tcp streams the port defaults to
678 * 'default_tcp_port' if no port number is given and for SSL streams the port
679 * defaults to 'default_ssl_port' if no port number is given. */
680 int
681 stream_open_with_default_ports(const char *name_,
682 uint16_t default_tcp_port,
683 uint16_t default_ssl_port,
684 struct stream **streamp)
685 {
686 char *name;
687 int error;
688
689 if (!strncmp(name_, "tcp:", 4) && count_fields(name_) < 3) {
690 name = xasprintf("%s:%d", name_, default_tcp_port);
691 } else if (!strncmp(name_, "ssl:", 4) && count_fields(name_) < 3) {
692 name = xasprintf("%s:%d", name_, default_ssl_port);
693 } else {
694 name = xstrdup(name_);
695 }
696 error = stream_open(name, streamp);
697 free(name);
698
699 return error;
700 }
701
702 /* Like pstream_open(), but for ptcp streams the port defaults to
703 * 'default_ptcp_port' if no port number is given and for passive SSL streams
704 * the port defaults to 'default_pssl_port' if no port number is given. */
705 int
706 pstream_open_with_default_ports(const char *name_,
707 uint16_t default_ptcp_port,
708 uint16_t default_pssl_port,
709 struct pstream **pstreamp)
710 {
711 char *name;
712 int error;
713
714 if (!strncmp(name_, "ptcp:", 5) && count_fields(name_) < 2) {
715 name = xasprintf("%s%d", name_, default_ptcp_port);
716 } else if (!strncmp(name_, "pssl:", 5) && count_fields(name_) < 2) {
717 name = xasprintf("%s%d", name_, default_pssl_port);
718 } else {
719 name = xstrdup(name_);
720 }
721 error = pstream_open(name, pstreamp);
722 free(name);
723
724 return error;
725 }
726 \f
727 /* Attempts to guess the content type of a stream whose first few bytes were
728 * the 'size' bytes of 'data'. */
729 static enum stream_content_type
730 stream_guess_content(const uint8_t *data, size_t size)
731 {
732 if (size >= 2) {
733 #define PAIR(A, B) (((A) << 8) | (B))
734 switch (PAIR(data[0], data[1])) {
735 case PAIR(0x16, 0x03): /* Handshake, version 3. */
736 return STREAM_SSL;
737 case PAIR('{', '"'):
738 return STREAM_JSONRPC;
739 case PAIR(OFP_VERSION, OFPT_HELLO):
740 return STREAM_OPENFLOW;
741 }
742 }
743
744 return STREAM_UNKNOWN;
745 }
746
747 /* Returns a string represenation of 'type'. */
748 static const char *
749 stream_content_type_to_string(enum stream_content_type type)
750 {
751 switch (type) {
752 case STREAM_UNKNOWN:
753 default:
754 return "unknown";
755
756 case STREAM_JSONRPC:
757 return "JSON-RPC";
758
759 case STREAM_OPENFLOW:
760 return "OpenFlow";
761
762 case STREAM_SSL:
763 return "SSL";
764 }
765 }
766
767 /* Attempts to guess the content type of a stream whose first few bytes were
768 * the 'size' bytes of 'data'. If this is done successfully, and the guessed
769 * content type is other than 'expected_type', then log a message in vlog
770 * module 'module', naming 'stream_name' as the source, explaining what
771 * content was expected and what was actually received. */
772 void
773 stream_report_content(const void *data, size_t size,
774 enum stream_content_type expected_type,
775 struct vlog_module *module, const char *stream_name)
776 {
777 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
778 enum stream_content_type actual_type;
779
780 actual_type = stream_guess_content(data, size);
781 if (actual_type != expected_type && actual_type != STREAM_UNKNOWN) {
782 vlog_rate_limit(module, VLL_WARN, &rl,
783 "%s: received %s data on %s channel",
784 stream_name,
785 stream_content_type_to_string(actual_type),
786 stream_content_type_to_string(expected_type));
787 }
788 }