Coverage Report

Created: 2023-03-26 07:41

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