stream: New functions stream_verify_name() and pstream_verify_name().
[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 /* 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 int
226 stream_open_block(const char *name, struct stream **streamp)
227 {
228     struct stream *stream;
229     int error;
230
231     error = stream_open(name, &stream);
232     while (error == EAGAIN) {
233         stream_run(stream);
234         stream_run_wait(stream);
235         stream_connect_wait(stream);
236         poll_block();
237         error = stream_connect(stream);
238         assert(error != EINPROGRESS);
239     }
240     if (error) {
241         stream_close(stream);
242         *streamp = NULL;
243     } else {
244         *streamp = stream;
245     }
246     return error;
247 }
248
249 /* Closes 'stream'. */
250 void
251 stream_close(struct stream *stream)
252 {
253     if (stream != NULL) {
254         char *name = stream->name;
255         (stream->class->close)(stream);
256         free(name);
257     }
258 }
259
260 /* Returns the name of 'stream', that is, the string passed to
261  * stream_open(). */
262 const char *
263 stream_get_name(const struct stream *stream)
264 {
265     return stream ? stream->name : "(null)";
266 }
267
268 /* Returns the IP address of the peer, or 0 if the peer is not connected over
269  * an IP-based protocol or if its IP address is not yet known. */
270 uint32_t
271 stream_get_remote_ip(const struct stream *stream)
272 {
273     return stream->remote_ip;
274 }
275
276 /* Returns the transport port of the peer, or 0 if the connection does not
277  * contain a port or if the port is not yet known. */
278 uint16_t
279 stream_get_remote_port(const struct stream *stream)
280 {
281     return stream->remote_port;
282 }
283
284 /* Returns the IP address used to connect to the peer, or 0 if the connection
285  * is not an IP-based protocol or if its IP address is not yet known. */
286 uint32_t
287 stream_get_local_ip(const struct stream *stream)
288 {
289     return stream->local_ip;
290 }
291
292 /* Returns the transport port used to connect to the peer, or 0 if the
293  * connection does not contain a port or if the port is not yet known. */
294 uint16_t
295 stream_get_local_port(const struct stream *stream)
296 {
297     return stream->local_port;
298 }
299
300 static void
301 scs_connecting(struct stream *stream)
302 {
303     int retval = (stream->class->connect)(stream);
304     assert(retval != EINPROGRESS);
305     if (!retval) {
306         stream->state = SCS_CONNECTED;
307     } else if (retval != EAGAIN) {
308         stream->state = SCS_DISCONNECTED;
309         stream->error = retval;
310     }
311 }
312
313 /* Tries to complete the connection on 'stream', which must be an active
314  * stream.  If 'stream''s connection is complete, returns 0 if the connection
315  * was successful or a positive errno value if it failed.  If the
316  * connection is still in progress, returns EAGAIN. */
317 int
318 stream_connect(struct stream *stream)
319 {
320     enum stream_state last_state;
321
322     do {
323         last_state = stream->state;
324         switch (stream->state) {
325         case SCS_CONNECTING:
326             scs_connecting(stream);
327             break;
328
329         case SCS_CONNECTED:
330             return 0;
331
332         case SCS_DISCONNECTED:
333             return stream->error;
334
335         default:
336             NOT_REACHED();
337         }
338     } while (stream->state != last_state);
339
340     return EAGAIN;
341 }
342
343 /* Tries to receive up to 'n' bytes from 'stream' into 'buffer', and returns:
344  *
345  *     - If successful, the number of bytes received (between 1 and 'n').
346  *
347  *     - On error, a negative errno value.
348  *
349  *     - 0, if the connection has been closed in the normal fashion, or if 'n'
350  *       is zero.
351  *
352  * The recv function will not block waiting for a packet to arrive.  If no
353  * data have been received, it returns -EAGAIN immediately. */
354 int
355 stream_recv(struct stream *stream, void *buffer, size_t n)
356 {
357     int retval = stream_connect(stream);
358     return (retval ? -retval
359             : n == 0 ? 0
360             : (stream->class->recv)(stream, buffer, n));
361 }
362
363 /* Tries to send up to 'n' bytes of 'buffer' on 'stream', and returns:
364  *
365  *     - If successful, the number of bytes sent (between 1 and 'n').  0 is
366  *       only a valid return value if 'n' is 0.
367  *
368  *     - On error, a negative errno value.
369  *
370  * The send function will not block.  If no bytes can be immediately accepted
371  * for transmission, it returns -EAGAIN immediately. */
372 int
373 stream_send(struct stream *stream, const void *buffer, size_t n)
374 {
375     int retval = stream_connect(stream);
376     return (retval ? -retval
377             : n == 0 ? 0
378             : (stream->class->send)(stream, buffer, n));
379 }
380
381 /* Allows 'stream' to perform maintenance activities, such as flushing
382  * output buffers. */
383 void
384 stream_run(struct stream *stream)
385 {
386     if (stream->class->run) {
387         (stream->class->run)(stream);
388     }
389 }
390
391 /* Arranges for the poll loop to wake up when 'stream' needs to perform
392  * maintenance activities. */
393 void
394 stream_run_wait(struct stream *stream)
395 {
396     if (stream->class->run_wait) {
397         (stream->class->run_wait)(stream);
398     }
399 }
400
401 /* Arranges for the poll loop to wake up when 'stream' is ready to take an
402  * action of the given 'type'. */
403 void
404 stream_wait(struct stream *stream, enum stream_wait_type wait)
405 {
406     assert(wait == STREAM_CONNECT || wait == STREAM_RECV
407            || wait == STREAM_SEND);
408
409     switch (stream->state) {
410     case SCS_CONNECTING:
411         wait = STREAM_CONNECT;
412         break;
413
414     case SCS_DISCONNECTED:
415         poll_immediate_wake();
416         return;
417     }
418     (stream->class->wait)(stream, wait);
419 }
420
421 void
422 stream_connect_wait(struct stream *stream)
423 {
424     stream_wait(stream, STREAM_CONNECT);
425 }
426
427 void
428 stream_recv_wait(struct stream *stream)
429 {
430     stream_wait(stream, STREAM_RECV);
431 }
432
433 void
434 stream_send_wait(struct stream *stream)
435 {
436     stream_wait(stream, STREAM_SEND);
437 }
438
439 /* Given 'name', a pstream name in the form "TYPE:ARGS", stores the class
440  * named "TYPE" into '*classp' and returns 0.  Returns EAFNOSUPPORT and stores
441  * a null pointer into '*classp' if 'name' is in the wrong form or if no such
442  * class exists. */
443 static int
444 pstream_lookup_class(const char *name, struct pstream_class **classp)
445 {
446     size_t prefix_len;
447     size_t i;
448
449     check_stream_classes();
450
451     *classp = NULL;
452     prefix_len = strcspn(name, ":");
453     if (name[prefix_len] == '\0') {
454         return EAFNOSUPPORT;
455     }
456     for (i = 0; i < ARRAY_SIZE(pstream_classes); i++) {
457         struct pstream_class *class = pstream_classes[i];
458         if (strlen(class->name) == prefix_len
459             && !memcmp(class->name, name, prefix_len)) {
460             *classp = class;
461             return 0;
462         }
463     }
464     return EAFNOSUPPORT;
465 }
466
467 /* Returns 0 if 'name' is a pstream name in the form "TYPE:ARGS" and TYPE is
468  * a supported pstream type, otherwise EAFNOSUPPORT.  */
469 int
470 pstream_verify_name(const char *name)
471 {
472     struct pstream_class *class;
473     return pstream_lookup_class(name, &class);
474 }
475
476 /* Attempts to start listening for remote stream connections.  'name' is a
477  * connection name in the form "TYPE:ARGS", where TYPE is an passive stream
478  * class's name and ARGS are stream class-specific.
479  *
480  * Returns 0 if successful, otherwise a positive errno value.  If successful,
481  * stores a pointer to the new connection in '*pstreamp', otherwise a null
482  * pointer.  */
483 int
484 pstream_open(const char *name, struct pstream **pstreamp)
485 {
486     struct pstream_class *class;
487     struct pstream *pstream;
488     char *suffix_copy;
489     int error;
490
491     COVERAGE_INC(pstream_open);
492
493     /* Look up the class. */
494     error = pstream_lookup_class(name, &class);
495     if (!class) {
496         goto error;
497     }
498
499     /* Call class's "open" function. */
500     suffix_copy = xstrdup(strchr(name, ':') + 1);
501     error = class->listen(name, suffix_copy, &pstream);
502     free(suffix_copy);
503     if (error) {
504         goto error;
505     }
506
507     /* Success. */
508     *pstreamp = pstream;
509     return 0;
510
511 error:
512     *pstreamp = NULL;
513     return error;
514 }
515
516 /* Returns the name that was used to open 'pstream'.  The caller must not
517  * modify or free the name. */
518 const char *
519 pstream_get_name(const struct pstream *pstream)
520 {
521     return pstream->name;
522 }
523
524 /* Closes 'pstream'. */
525 void
526 pstream_close(struct pstream *pstream)
527 {
528     if (pstream != NULL) {
529         char *name = pstream->name;
530         (pstream->class->close)(pstream);
531         free(name);
532     }
533 }
534
535 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
536  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
537  * positive errno value.
538  *
539  * pstream_accept() will not block waiting for a connection.  If no connection
540  * is ready to be accepted, it returns EAGAIN immediately. */
541 int
542 pstream_accept(struct pstream *pstream, struct stream **new_stream)
543 {
544     int retval = (pstream->class->accept)(pstream, new_stream);
545     if (retval) {
546         *new_stream = NULL;
547     } else {
548         assert((*new_stream)->state != SCS_CONNECTING
549                || (*new_stream)->class->connect);
550     }
551     return retval;
552 }
553
554 /* Tries to accept a new connection on 'pstream'.  If successful, stores the
555  * new connection in '*new_stream' and returns 0.  Otherwise, returns a
556  * positive errno value.
557  *
558  * pstream_accept_block() blocks until a connection is ready or until an error
559  * occurs.  It will not return EAGAIN. */
560 int
561 pstream_accept_block(struct pstream *pstream, struct stream **new_stream)
562 {
563     int error;
564
565     while ((error = pstream_accept(pstream, new_stream)) == EAGAIN) {
566         pstream_wait(pstream);
567         poll_block();
568     }
569     if (error) {
570         *new_stream = NULL;
571     }
572     return error;
573 }
574
575 void
576 pstream_wait(struct pstream *pstream)
577 {
578     (pstream->class->wait)(pstream);
579 }
580 \f
581 /* Initializes 'stream' as a new stream named 'name', implemented via 'class'.
582  * The initial connection status, supplied as 'connect_status', is interpreted
583  * as follows:
584  *
585  *      - 0: 'stream' is connected.  Its 'send' and 'recv' functions may be
586  *        called in the normal fashion.
587  *
588  *      - EAGAIN: 'stream' is trying to complete a connection.  Its 'connect'
589  *        function should be called to complete the connection.
590  *
591  *      - Other positive errno values indicate that the connection failed with
592  *        the specified error.
593  *
594  * After calling this function, stream_close() must be used to destroy
595  * 'stream', otherwise resources will be leaked.
596  *
597  * The caller retains ownership of 'name'. */
598 void
599 stream_init(struct stream *stream, struct stream_class *class,
600             int connect_status, const char *name)
601 {
602     stream->class = class;
603     stream->state = (connect_status == EAGAIN ? SCS_CONNECTING
604                     : !connect_status ? SCS_CONNECTED
605                     : SCS_DISCONNECTED);
606     stream->error = connect_status;
607     stream->name = xstrdup(name);
608     assert(stream->state != SCS_CONNECTING || class->connect);
609 }
610
611 void
612 stream_set_remote_ip(struct stream *stream, uint32_t ip)
613 {
614     stream->remote_ip = ip;
615 }
616
617 void
618 stream_set_remote_port(struct stream *stream, uint16_t port)
619 {
620     stream->remote_port = port;
621 }
622
623 void
624 stream_set_local_ip(struct stream *stream, uint32_t ip)
625 {
626     stream->local_ip = ip;
627 }
628
629 void
630 stream_set_local_port(struct stream *stream, uint16_t port)
631 {
632     stream->local_port = port;
633 }
634
635 void
636 pstream_init(struct pstream *pstream, struct pstream_class *class,
637             const char *name)
638 {
639     pstream->class = class;
640     pstream->name = xstrdup(name);
641 }