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