Merge "master" into "next".
[sliver-openvswitch.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 /* Attempts to connect a stream to a remote peer.  'name' is a connection name
149  * in the form "TYPE:ARGS", where TYPE is an active stream class's name and
150  * ARGS are stream class-specific.
151  *
152  * Returns 0 if successful, otherwise a positive errno value.  If successful,
153  * stores a pointer to the new connection in '*streamp', otherwise a null
154  * pointer.  */
155 int
156 stream_open(const char *name, struct stream **streamp)
157 {
158     size_t prefix_len;
159     size_t i;
160
161     COVERAGE_INC(stream_open);
162     check_stream_classes();
163
164     *streamp = NULL;
165     prefix_len = strcspn(name, ":");
166     if (prefix_len == strlen(name)) {
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             struct stream *stream;
174             char *suffix_copy = xstrdup(name + prefix_len + 1);
175             int retval = class->open(name, suffix_copy, &stream);
176             free(suffix_copy);
177             if (!retval) {
178                 assert(stream->state != SCS_CONNECTING
179                        || stream->class->connect);
180                 *streamp = stream;
181             }
182             return retval;
183         }
184     }
185     return EAFNOSUPPORT;
186 }
187
188 int
189 stream_open_block(const char *name, struct stream **streamp)
190 {
191     struct stream *stream;
192     int error;
193
194     error = stream_open(name, &stream);
195     while (error == EAGAIN) {
196         stream_run(stream);
197         stream_run_wait(stream);
198         stream_connect_wait(stream);
199         poll_block();
200         error = stream_connect(stream);
201         assert(error != EINPROGRESS);
202     }
203     if (error) {
204         stream_close(stream);
205         *streamp = NULL;
206     } else {
207         *streamp = stream;
208     }
209     return error;
210 }
211
212 /* Closes 'stream'. */
213 void
214 stream_close(struct stream *stream)
215 {
216     if (stream != NULL) {
217         char *name = stream->name;
218         (stream->class->close)(stream);
219         free(name);
220     }
221 }
222
223 /* Returns the name of 'stream', that is, the string passed to
224  * stream_open(). */
225 const char *
226 stream_get_name(const struct stream *stream)
227 {
228     return stream ? stream->name : "(null)";
229 }
230
231 /* Returns the IP address of the peer, or 0 if the peer is not connected over
232  * an IP-based protocol or if its IP address is not yet known. */
233 uint32_t
234 stream_get_remote_ip(const struct stream *stream)
235 {
236     return stream->remote_ip;
237 }
238
239 /* Returns the transport port of the peer, or 0 if the connection does not
240  * contain a port or if the port is not yet known. */
241 uint16_t
242 stream_get_remote_port(const struct stream *stream)
243 {
244     return stream->remote_port;
245 }
246
247 /* Returns the IP address used to connect to the peer, or 0 if the connection
248  * is not an IP-based protocol or if its IP address is not yet known. */
249 uint32_t
250 stream_get_local_ip(const struct stream *stream)
251 {
252     return stream->local_ip;
253 }
254
255 /* Returns the transport port used to connect to the peer, or 0 if the
256  * connection does not contain a port or if the port is not yet known. */
257 uint16_t
258 stream_get_local_port(const struct stream *stream)
259 {
260     return stream->local_port;
261 }
262
263 static void
264 scs_connecting(struct stream *stream)
265 {
266     int retval = (stream->class->connect)(stream);
267     assert(retval != EINPROGRESS);
268     if (!retval) {
269         stream->state = SCS_CONNECTED;
270     } else if (retval != EAGAIN) {
271         stream->state = SCS_DISCONNECTED;
272         stream->error = retval;
273     }
274 }
275
276 /* Tries to complete the connection on 'stream', which must be an active
277  * stream.  If 'stream''s connection is complete, returns 0 if the connection
278  * was successful or a positive errno value if it failed.  If the
279  * connection is still in progress, returns EAGAIN. */
280 int
281 stream_connect(struct stream *stream)
282 {
283     enum stream_state last_state;
284
285     do {
286         last_state = stream->state;
287         switch (stream->state) {
288         case SCS_CONNECTING:
289             scs_connecting(stream);
290             break;
291
292         case SCS_CONNECTED:
293             return 0;
294
295         case SCS_DISCONNECTED:
296             return stream->error;
297
298         default:
299             NOT_REACHED();
300         }
301     } while (stream->state != last_state);
302
303     return EAGAIN;
304 }
305
306 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
307  *
308  *     - If successful, the number of bytes received (between 1 and 'n').
309  *
310  *     - On error, a negative errno value.
311  *
312  *     - 0, if the connection has been closed in the normal fashion, or if 'n'
313  *       is zero.
314  *
315  * The recv function will not block waiting for a packet to arrive.  If no
316  * data have been received, it returns -EAGAIN immediately. */
317 int
318 stream_recv(struct stream *stream, void *buffer, size_t n)
319 {
320     int retval = stream_connect(stream);
321     return (retval ? -retval
322             : n == 0 ? 0
323             : (stream->class->recv)(stream, buffer, n));
324 }
325
326 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
327  *
328  *     - If successful, the number of bytes sent (between 1 and 'n').  0 is
329  *       only a valid return value if 'n' is 0.
330  *
331  *     - On error, a negative errno value.
332  *
333  * The send function will not block.  If no bytes can be immediately accepted
334  * for transmission, it returns -EAGAIN immediately. */
335 int
336 stream_send(struct stream *stream, const void *buffer, size_t n)
337 {
338     int retval = stream_connect(stream);
339     return (retval ? -retval
340             : n == 0 ? 0
341             : (stream->class->send)(stream, buffer, n));
342 }
343
344 /* Allows 'stream' to perform maintenance activities, such as flushing
345  * output buffers. */
346 void
347 stream_run(struct stream *stream)
348 {
349     if (stream->class->run) {
350         (stream->class->run)(stream);
351     }
352 }
353
354 /* Arranges for the poll loop to wake up when 'stream' needs to perform
355  * maintenance activities. */
356 void
357 stream_run_wait(struct stream *stream)
358 {
359     if (stream->class->run_wait) {
360         (stream->class->run_wait)(stream);
361     }
362 }
363
364 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
365  * action of the given 'type'. */
366 void
367 stream_wait(struct stream *stream, enum stream_wait_type wait)
368 {
369     assert(wait == STREAM_CONNECT || wait == STREAM_RECV
370            || wait == STREAM_SEND);
371
372     switch (stream->state) {
373     case SCS_CONNECTING:
374         wait = STREAM_CONNECT;
375         break;
376
377     case SCS_DISCONNECTED:
378         poll_immediate_wake();
379         return;
380     }
381     (stream->class->wait)(stream, wait);
382 }
383
384 void
385 stream_connect_wait(struct stream *stream)
386 {
387     stream_wait(stream, STREAM_CONNECT);
388 }
389
390 void
391 stream_recv_wait(struct stream *stream)
392 {
393     stream_wait(stream, STREAM_RECV);
394 }
395
396 void
397 stream_send_wait(struct stream *stream)
398 {
399     stream_wait(stream, STREAM_SEND);
400 }
401
402 /* Attempts to start listening for remote stream connections.  'name' is a
403  * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
404  * class's name and ARGS are stream class-specific.
405  *
406  * Returns 0 if successful, otherwise a positive errno value.  If successful,
407  * stores a pointer to the new connection in '*pstreamp', otherwise a null
408  * pointer.  */
409 int
410 pstream_open(const char *name, struct pstream **pstreamp)
411 {
412     size_t prefix_len;
413     size_t i;
414
415     check_stream_classes();
416
417     *pstreamp = NULL;
418     prefix_len = strcspn(name, ":");
419     if (prefix_len == strlen(name)) {
420         return EAFNOSUPPORT;
421     }
422     for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
423         struct pstream_class *class = pstream_classes[i];
424         if (strlen(class->name) == prefix_len
425             && !memcmp(class->name, name, prefix_len)) {
426             char *suffix_copy = xstrdup(name + prefix_len + 1);
427             int retval = class->listen(name, suffix_copy, pstreamp);
428             free(suffix_copy);
429             if (retval) {
430                 *pstreamp = NULL;
431             }
432             return retval;
433         }
434     }
435     return EAFNOSUPPORT;
436 }
437
438 /* Returns the name that was used to open 'pstream'.  The caller must not
439  * modify or free the name. */
440 const char *
441 pstream_get_name(const struct pstream *pstream)
442 {
443     return pstream->name;
444 }
445
446 /* Closes 'pstream'. */
447 void
448 pstream_close(struct pstream *pstream)
449 {
450     if (pstream != NULL) {
451         char *name = pstream->name;
452         (pstream->class->close)(pstream);
453         free(name);
454     }
455 }
456
457 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
458  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
459  * positive errno value.
460  *
461  * pstream_accept() will not block waiting for a connection.  If no connection
462  * is ready to be accepted, it returns EAGAIN immediately. */
463 int
464 pstream_accept(struct pstream *pstream, struct stream **new_stream)
465 {
466     int retval = (pstream->class->accept)(pstream, new_stream);
467     if (retval) {
468         *new_stream = NULL;
469     } else {
470         assert((*new_stream)->state != SCS_CONNECTING
471                || (*new_stream)->class->connect);
472     }
473     return retval;
474 }
475
476 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
477  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
478  * positive errno value.
479  *
480  * pstream_accept_block() blocks until a connection is ready or until an error
481  * occurs.  It will not return EAGAIN. */
482 int
483 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
484 {
485     int error;
486
487     while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
488         pstream_wait(pstream);
489         poll_block();
490     }
491     if (error) {
492         *new_stream = NULL;
493     }
494     return error;
495 }
496
497 void
498 pstream_wait(struct pstream *pstream)
499 {
500     (pstream->class->wait)(pstream);
501 }
502 \f
503 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
504  * The initial connection status, supplied as 'connect_status', is interpreted
505  * as follows:
506  *
507  *      - 0: 'stream' is connected.  Its 'send' and 'recv' functions may be
508  *        called in the normal fashion.
509  *
510  *      - EAGAIN: 'stream' is trying to complete a connection.  Its 'connect'
511  *        function should be called to complete the connection.
512  *
513  *      - Other positive errno values indicate that the connection failed with
514  *        the specified error.
515  *
516  * After calling this function, stream_close() must be used to destroy
517  * 'stream', otherwise resources will be leaked.
518  *
519  * The caller retains ownership of 'name'. */
520 void
521 stream_init(struct stream *stream, struct stream_class *class,
522             int connect_status, const char *name)
523 {
524     stream->class = class;
525     stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
526                     : !connect_status ? SCS_CONNECTED
527                     : SCS_DISCONNECTED);
528     stream->error = connect_status;
529     stream->name = xstrdup(name);
530     assert(stream->state != SCS_CONNECTING || class->connect);
531 }
532
533 void
534 stream_set_remote_ip(struct stream *stream, uint32_t ip)
535 {
536     stream->remote_ip = ip;
537 }
538
539 void
540 stream_set_remote_port(struct stream *stream, uint16_t port)
541 {
542     stream->remote_port = port;
543 }
544
545 void
546 stream_set_local_ip(struct stream *stream, uint32_t ip)
547 {
548     stream->local_ip = ip;
549 }
550
551 void
552 stream_set_local_port(struct stream *stream, uint16_t port)
553 {
554     stream->local_port = port;
555 }
556
557 void
558 pstream_init(struct pstream *pstream, struct pstream_class *class,
559             const char *name)
560 {
561     pstream->class = class;
562     pstream->name = xstrdup(name);
563 }