stream: Generalize stream_open_block().
[cascardo/ovs.git] / lib / stream.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 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 "flow.h"
29 #include "ofp-print.h"
30 #include "ofpbuf.h"
31 #include "openflow/nicira-ext.h"
32 #include "openflow/openflow.h"
33 #include "packets.h"
34 #include "poll-loop.h"
35 #include "random.h"
36 #include "util.h"
37
38 #define THIS_MODULE VLM_stream
39 #include "vlog.h"
40
41 /* State of an active stream.*/
42 enum stream_state {
43     SCS_CONNECTING,             /* Underlying stream is not connected. */
44     SCS_CONNECTED,              /* Connection established. */
45     SCS_DISCONNECTED            /* Connection failed or connection closed. */
46 };
47
48 static struct stream_class *stream_classes[] = {
49     &tcp_stream_class,
50     &unix_stream_class,
51 #ifdef HAVE_OPENSSL
52     &ssl_stream_class,
53 #endif
54 };
55
56 static struct pstream_class *pstream_classes[] = {
57     &ptcp_pstream_class,
58     &punix_pstream_class,
59 #ifdef HAVE_OPENSSL
60     &pssl_pstream_class,
61 #endif
62 };
63
64 /* Check the validity of the stream class structures. */
65 static void
66 check_stream_classes(void)
67 {
68 #ifndef NDEBUG
69     size_t i;
70
71     for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
72         struct stream_class *class = stream_classes[i];
73         assert(class->name != NULL);
74         assert(class->open != NULL);
75         if (class->close || class->recv || class->send || class->run
76             || class->run_wait || class->wait) {
77             assert(class->close != NULL);
78             assert(class->recv != NULL);
79             assert(class->send != NULL);
80             assert(class->wait != NULL);
81         } else {
82             /* This class delegates to another one. */
83         }
84     }
85
86     for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
87         struct pstream_class *class = pstream_classes[i];
88         assert(class->name != NULL);
89         assert(class->listen != NULL);
90         if (class->close || class->accept || class->wait) {
91             assert(class->close != NULL);
92             assert(class->accept != NULL);
93             assert(class->wait != NULL);
94         } else {
95             /* This class delegates to another one. */
96         }
97     }
98 #endif
99 }
100
101 /* Prints information on active (if 'active') and passive (if 'passive')
102  * connection methods supported by the stream. */
103 void
104 stream_usage(const char *name, bool active, bool passive,
105              bool bootstrap OVS_UNUSED)
106 {
107     /* Really this should be implemented via callbacks into the stream
108      * providers, but that seems too heavy-weight to bother with at the
109      * moment. */
110
111     printf("\n");
112     if (active) {
113         printf("Active %s connection methods:\n", name);
114         printf("  tcp:IP:PORT             "
115                "PORT at remote IP\n");
116 #ifdef HAVE_OPENSSL
117         printf("  ssl:IP:PORT             "
118                "SSL PORT at remote IP\n");
119 #endif
120         printf("  unix:FILE               "
121                "Unix domain socket named FILE\n");
122     }
123
124     if (passive) {
125         printf("Passive %s connection methods:\n", name);
126         printf("  ptcp:PORT[:IP]          "
127                "listen to TCP PORT on IP\n");
128 #ifdef HAVE_OPENSSL
129         printf("  pssl:PORT[:IP]          "
130                "listen for SSL on PORT on IP\n");
131 #endif
132         printf("  punix:FILE              "
133                "listen on Unix domain socket FILE\n");
134     }
135
136 #ifdef HAVE_OPENSSL
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");
141     if (bootstrap) {
142         printf("  --bootstrap-ca-cert=FILE  file with peer CA certificate "
143                "to read or create\n");
144     }
145 #endif
146 }
147
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
151  * class exists. */
152 static int
153 stream_lookup_class(const char *name, struct stream_class **classp)
154 {
155     size_t prefix_len;
156     size_t i;
157
158     check_stream_classes();
159
160     *classp = NULL;
161     prefix_len = strcspn(name, ":");
162     if (name[prefix_len] == '\0') {
163         return EAFNOSUPPORT;
164     }
165     for (i = 0; i < ARRAY_SIZE(stream_classes); i++) {
166         struct stream_class *class = stream_classes[i];
167         if (strlen(class->name) == prefix_len
168             && !memcmp(class->name, name, prefix_len)) {
169             *classp = class;
170             return 0;
171         }
172     }
173     return EAFNOSUPPORT;
174 }
175
176 /* Returns 0 if 'name' is a stream name in the form "TYPE:ARGS" and TYPE is
177  * a supported stream type, otherwise EAFNOSUPPORT.  */
178 int
179 stream_verify_name(const char *name)
180 {
181     struct stream_class *class;
182     return stream_lookup_class(name, &class);
183 }
184
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.
188  *
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
191  * pointer.  */
192 int
193 stream_open(const char *name, struct stream **streamp)
194 {
195     struct stream_class *class;
196     struct stream *stream;
197     char *suffix_copy;
198     int error;
199
200     COVERAGE_INC(stream_open);
201
202     /* Look up the class. */
203     error = stream_lookup_class(name, &class);
204     if (!class) {
205         goto error;
206     }
207
208     /* Call class's "open" function. */
209     suffix_copy = xstrdup(strchr(name, ':') + 1);
210     error = class->open(name, suffix_copy, &stream);
211     free(suffix_copy);
212     if (error) {
213         goto error;
214     }
215
216     /* Success. */
217     *streamp = stream;
218     return 0;
219
220 error:
221     *streamp = NULL;
222     return error;
223 }
224
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.
231  *
232  * Typical usage:
233  *   error = stream_open_block(stream_open("tcp:1.2.3.4:5", &stream), &stream);
234  */
235 int
236 stream_open_block(int error, struct stream **streamp)
237 {
238     struct stream *stream = *streamp;
239
240     while (error == EAGAIN) {
241         stream_run(stream);
242         stream_run_wait(stream);
243         stream_connect_wait(stream);
244         poll_block();
245         error = stream_connect(stream);
246         assert(error != EINPROGRESS);
247     }
248     if (error) {
249         stream_close(stream);
250         *streamp = NULL;
251     } else {
252         *streamp = stream;
253     }
254     return error;
255 }
256
257 /* Closes 'stream'. */
258 void
259 stream_close(struct stream *stream)
260 {
261     if (stream != NULL) {
262         char *name = stream->name;
263         (stream->class->close)(stream);
264         free(name);
265     }
266 }
267
268 /* Returns the name of 'stream', that is, the string passed to
269  * stream_open(). */
270 const char *
271 stream_get_name(const struct stream *stream)
272 {
273     return stream ? stream->name : "(null)";
274 }
275
276 /* Returns the IP address of the peer, or 0 if the peer is not connected over
277  * an IP-based protocol or if its IP address is not yet known. */
278 uint32_t
279 stream_get_remote_ip(const struct stream *stream)
280 {
281     return stream->remote_ip;
282 }
283
284 /* Returns the transport port of the peer, or 0 if the connection does not
285  * contain a port or if the port is not yet known. */
286 uint16_t
287 stream_get_remote_port(const struct stream *stream)
288 {
289     return stream->remote_port;
290 }
291
292 /* Returns the IP address used to connect to the peer, or 0 if the connection
293  * is not an IP-based protocol or if its IP address is not yet known. */
294 uint32_t
295 stream_get_local_ip(const struct stream *stream)
296 {
297     return stream->local_ip;
298 }
299
300 /* Returns the transport port used to connect to the peer, or 0 if the
301  * connection does not contain a port or if the port is not yet known. */
302 uint16_t
303 stream_get_local_port(const struct stream *stream)
304 {
305     return stream->local_port;
306 }
307
308 static void
309 scs_connecting(struct stream *stream)
310 {
311     int retval = (stream->class->connect)(stream);
312     assert(retval != EINPROGRESS);
313     if (!retval) {
314         stream->state = SCS_CONNECTED;
315     } else if (retval != EAGAIN) {
316         stream->state = SCS_DISCONNECTED;
317         stream->error = retval;
318     }
319 }
320
321 /* Tries to complete the connection on 'stream', which must be an active
322  * stream.  If 'stream''s connection is complete, returns 0 if the connection
323  * was successful or a positive errno value if it failed.  If the
324  * connection is still in progress, returns EAGAIN. */
325 int
326 stream_connect(struct stream *stream)
327 {
328     enum stream_state last_state;
329
330     do {
331         last_state = stream->state;
332         switch (stream->state) {
333         case SCS_CONNECTING:
334             scs_connecting(stream);
335             break;
336
337         case SCS_CONNECTED:
338             return 0;
339
340         case SCS_DISCONNECTED:
341             return stream->error;
342
343         default:
344             NOT_REACHED();
345         }
346     } while (stream->state != last_state);
347
348     return EAGAIN;
349 }
350
351 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
352  *
353  *     - If successful, the number of bytes received (between 1 and 'n').
354  *
355  *     - On error, a negative errno value.
356  *
357  *     - 0, if the connection has been closed in the normal fashion, or if 'n'
358  *       is zero.
359  *
360  * The recv function will not block waiting for a packet to arrive.  If no
361  * data have been received, it returns -EAGAIN immediately. */
362 int
363 stream_recv(struct stream *stream, void *buffer, size_t n)
364 {
365     int retval = stream_connect(stream);
366     return (retval ? -retval
367             : n == 0 ? 0
368             : (stream->class->recv)(stream, buffer, n));
369 }
370
371 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
372  *
373  *     - If successful, the number of bytes sent (between 1 and 'n').  0 is
374  *       only a valid return value if 'n' is 0.
375  *
376  *     - On error, a negative errno value.
377  *
378  * The send function will not block.  If no bytes can be immediately accepted
379  * for transmission, it returns -EAGAIN immediately. */
380 int
381 stream_send(struct stream *stream, const void *buffer, size_t n)
382 {
383     int retval = stream_connect(stream);
384     return (retval ? -retval
385             : n == 0 ? 0
386             : (stream->class->send)(stream, buffer, n));
387 }
388
389 /* Allows 'stream' to perform maintenance activities, such as flushing
390  * output buffers. */
391 void
392 stream_run(struct stream *stream)
393 {
394     if (stream->class->run) {
395         (stream->class->run)(stream);
396     }
397 }
398
399 /* Arranges for the poll loop to wake up when 'stream' needs to perform
400  * maintenance activities. */
401 void
402 stream_run_wait(struct stream *stream)
403 {
404     if (stream->class->run_wait) {
405         (stream->class->run_wait)(stream);
406     }
407 }
408
409 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
410  * action of the given 'type'. */
411 void
412 stream_wait(struct stream *stream, enum stream_wait_type wait)
413 {
414     assert(wait == STREAM_CONNECT || wait == STREAM_RECV
415            || wait == STREAM_SEND);
416
417     switch (stream->state) {
418     case SCS_CONNECTING:
419         wait = STREAM_CONNECT;
420         break;
421
422     case SCS_DISCONNECTED:
423         poll_immediate_wake();
424         return;
425     }
426     (stream->class->wait)(stream, wait);
427 }
428
429 void
430 stream_connect_wait(struct stream *stream)
431 {
432     stream_wait(stream, STREAM_CONNECT);
433 }
434
435 void
436 stream_recv_wait(struct stream *stream)
437 {
438     stream_wait(stream, STREAM_RECV);
439 }
440
441 void
442 stream_send_wait(struct stream *stream)
443 {
444     stream_wait(stream, STREAM_SEND);
445 }
446
447 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
448  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
449  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
450  * class exists. */
451 static int
452 pstream_lookup_class(const char *name, struct pstream_class **classp)
453 {
454     size_t prefix_len;
455     size_t i;
456
457     check_stream_classes();
458
459     *classp = NULL;
460     prefix_len = strcspn(name, ":");
461     if (name[prefix_len] == '\0') {
462         return EAFNOSUPPORT;
463     }
464     for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
465         struct pstream_class *class = pstream_classes[i];
466         if (strlen(class->name) == prefix_len
467             && !memcmp(class->name, name, prefix_len)) {
468             *classp = class;
469             return 0;
470         }
471     }
472     return EAFNOSUPPORT;
473 }
474
475 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
476  * a supported pstream type, otherwise EAFNOSUPPORT.  */
477 int
478 pstream_verify_name(const char *name)
479 {
480     struct pstream_class *class;
481     return pstream_lookup_class(name, &class);
482 }
483
484 /* Attempts to start listening for remote stream connections.  'name' is a
485  * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
486  * class's name and ARGS are stream class-specific.
487  *
488  * Returns 0 if successful, otherwise a positive errno value.  If successful,
489  * stores a pointer to the new connection in '*pstreamp', otherwise a null
490  * pointer.  */
491 int
492 pstream_open(const char *name, struct pstream **pstreamp)
493 {
494     struct pstream_class *class;
495     struct pstream *pstream;
496     char *suffix_copy;
497     int error;
498
499     COVERAGE_INC(pstream_open);
500
501     /* Look up the class. */
502     error = pstream_lookup_class(name, &class);
503     if (!class) {
504         goto error;
505     }
506
507     /* Call class's "open" function. */
508     suffix_copy = xstrdup(strchr(name, ':') + 1);
509     error = class->listen(name, suffix_copy, &pstream);
510     free(suffix_copy);
511     if (error) {
512         goto error;
513     }
514
515     /* Success. */
516     *pstreamp = pstream;
517     return 0;
518
519 error:
520     *pstreamp = NULL;
521     return error;
522 }
523
524 /* Returns the name that was used to open 'pstream'.  The caller must not
525  * modify or free the name. */
526 const char *
527 pstream_get_name(const struct pstream *pstream)
528 {
529     return pstream->name;
530 }
531
532 /* Closes 'pstream'. */
533 void
534 pstream_close(struct pstream *pstream)
535 {
536     if (pstream != NULL) {
537         char *name = pstream->name;
538         (pstream->class->close)(pstream);
539         free(name);
540     }
541 }
542
543 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
544  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
545  * positive errno value.
546  *
547  * pstream_accept() will not block waiting for a connection.  If no connection
548  * is ready to be accepted, it returns EAGAIN immediately. */
549 int
550 pstream_accept(struct pstream *pstream, struct stream **new_stream)
551 {
552     int retval = (pstream->class->accept)(pstream, new_stream);
553     if (retval) {
554         *new_stream = NULL;
555     } else {
556         assert((*new_stream)->state != SCS_CONNECTING
557                || (*new_stream)->class->connect);
558     }
559     return retval;
560 }
561
562 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
563  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
564  * positive errno value.
565  *
566  * pstream_accept_block() blocks until a connection is ready or until an error
567  * occurs.  It will not return EAGAIN. */
568 int
569 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
570 {
571     int error;
572
573     while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
574         pstream_wait(pstream);
575         poll_block();
576     }
577     if (error) {
578         *new_stream = NULL;
579     }
580     return error;
581 }
582
583 void
584 pstream_wait(struct pstream *pstream)
585 {
586     (pstream->class->wait)(pstream);
587 }
588 \f
589 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
590  * The initial connection status, supplied as 'connect_status', is interpreted
591  * as follows:
592  *
593  *      - 0: 'stream' is connected.  Its 'send' and 'recv' functions may be
594  *        called in the normal fashion.
595  *
596  *      - EAGAIN: 'stream' is trying to complete a connection.  Its 'connect'
597  *        function should be called to complete the connection.
598  *
599  *      - Other positive errno values indicate that the connection failed with
600  *        the specified error.
601  *
602  * After calling this function, stream_close() must be used to destroy
603  * 'stream', otherwise resources will be leaked.
604  *
605  * The caller retains ownership of 'name'. */
606 void
607 stream_init(struct stream *stream, struct stream_class *class,
608             int connect_status, const char *name)
609 {
610     stream->class = class;
611     stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
612                     : !connect_status ? SCS_CONNECTED
613                     : SCS_DISCONNECTED);
614     stream->error = connect_status;
615     stream->name = xstrdup(name);
616     assert(stream->state != SCS_CONNECTING || class->connect);
617 }
618
619 void
620 stream_set_remote_ip(struct stream *stream, uint32_t ip)
621 {
622     stream->remote_ip = ip;
623 }
624
625 void
626 stream_set_remote_port(struct stream *stream, uint16_t port)
627 {
628     stream->remote_port = port;
629 }
630
631 void
632 stream_set_local_ip(struct stream *stream, uint32_t ip)
633 {
634     stream->local_ip = ip;
635 }
636
637 void
638 stream_set_local_port(struct stream *stream, uint16_t port)
639 {
640     stream->local_port = port;
641 }
642
643 void
644 pstream_init(struct pstream *pstream, struct pstream_class *class,
645             const char *name)
646 {
647     pstream->class = class;
648     pstream->name = xstrdup(name);
649 }