Coverage Report

Created: 2026-06-07 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fluent-bit/plugins/out_websocket/websocket.c
Line
Count
Source
1
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3
/*  Fluent Bit
4
 *  ==========
5
 *  Copyright (C) 2015-2026 The Fluent Bit Authors
6
 *
7
 *  Licensed under the Apache License, Version 2.0 (the "License");
8
 *  you may not use this file except in compliance with the License.
9
 *  You may obtain a copy of the License at
10
 *
11
 *      http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 *  Unless required by applicable law or agreed to in writing, software
14
 *  distributed under the License is distributed on an "AS IS" BASIS,
15
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 *  See the License for the specific language governing permissions and
17
 *  limitations under the License.
18
 */
19
20
#include <fluent-bit/flb_info.h>
21
#include <fluent-bit/flb_output.h>
22
#include <fluent-bit/flb_utils.h>
23
#include <fluent-bit/flb_network.h>
24
#include <fluent-bit/flb_time.h>
25
#include <fluent-bit/flb_upstream.h>
26
#include <fluent-bit/flb_crypto.h>
27
#include <fluent-bit/flb_pack.h>
28
#include <fluent-bit/flb_sds.h>
29
#include <fluent-bit/flb_http_client.h>
30
#include <fluent-bit/flb_config_map.h>
31
#include <msgpack.h>
32
33
#include "websocket.h"
34
#include "websocket_conf.h"
35
struct flb_output_plugin out_websocket_plugin;
36
37
#define SECURED_BY "Fluent Bit"
38
39
40
static int flb_ws_handshake(struct flb_connection *u_conn,
41
                                    struct flb_out_ws *ctx)
42
0
{
43
0
    int ret;
44
0
    size_t bytes_sent;
45
0
    struct flb_http_client *c;
46
0
    struct mk_list *head;
47
0
    struct flb_config_map_val *mv;
48
0
    struct flb_slist_entry *key = NULL;
49
0
    struct flb_slist_entry *val = NULL;
50
51
0
    if (!u_conn) {
52
0
        flb_error("[output_ws] upstream connection error");
53
0
        return -1;
54
0
    }
55
56
    /* Compose HTTP Client request */
57
0
    c = flb_http_client(u_conn, FLB_HTTP_GET, ctx->uri,
58
0
                        NULL, 0, NULL, 0, NULL, 0);
59
0
    if (!c) {
60
0
       flb_upstream_conn_release(u_conn);
61
0
       return -1;
62
0
    }
63
64
0
    flb_http_buffer_size(c, ctx->buffer_size);
65
0
    flb_http_add_header(c, "Upgrade", 7, "websocket", 9);
66
0
    flb_http_add_header(c, "Connection", 10, "Upgrade", 7);
67
0
    flb_http_add_header(c, "Sec-WebSocket-Key", 17, "dGhlIHNhbXBsZSBub25jZQ==", 24);
68
0
    flb_http_add_header(c, "Sec-WebSocket-Version", 21, "13", 2);
69
70
    /* Append additional headers from configuration */
71
0
    flb_config_map_foreach(head, mv, ctx->headers) {
72
0
        key = mk_list_entry_first(mv->val.list, struct flb_slist_entry, _head);
73
0
        val = mk_list_entry_last(mv->val.list, struct flb_slist_entry, _head);
74
75
0
        flb_http_add_header(c,
76
0
                            key->str, flb_sds_len(key->str),
77
0
                            val->str, flb_sds_len(val->str));
78
0
    }
79
80
    /* Perform request*/
81
0
    ret = flb_http_do(c, &bytes_sent);
82
83
0
    if (ret != 0 || c->resp.status != 101) {
84
0
        if (c->resp.payload_size > 0) {
85
0
            flb_debug("[output_ws] Websocket Server Response\n%s",
86
0
                c->resp.payload);
87
0
        }
88
0
        flb_debug("[out_ws] Http Get Operation ret = %i, http resp = %i",
89
0
                  ret, c->resp.status);
90
0
        flb_http_client_destroy(c);
91
0
        flb_upstream_conn_release(u_conn);
92
0
        return -1;
93
0
    }
94
0
    flb_http_client_destroy(c);
95
0
    return 0;
96
0
}
97
98
static void flb_ws_mask(char *data, int len, char *mask)
99
0
{
100
0
    int i;
101
0
    for (i=0;i<len;++i) {
102
0
        *(data+i) ^= *(mask+(i%4));
103
0
    }
104
0
}
105
106
static int flb_ws_sendDataFrameHeader(struct flb_connection *u_conn,
107
                                      struct flb_out_ws *ctx, const void *data, size_t bytes)
108
0
{
109
0
    int ret = -1;
110
0
    char* data_frame_head;
111
0
    size_t bytes_sent;
112
0
    int data_frame_head_len = 0;
113
    //TODO use random function to generate masking_key
114
0
    char masking_key[4] = {0x12, 0x34, 0x56, 0x78};
115
0
    unsigned long long payloadSize = bytes;
116
117
0
    flb_ws_mask((char *)data, payloadSize, masking_key);
118
0
    if (payloadSize < 126) {
119
0
        data_frame_head = (char *)flb_malloc(6);
120
0
        if (!data_frame_head) {
121
0
            flb_errno();
122
0
            return -1;
123
0
        }
124
0
        data_frame_head[0] = 0x81;
125
0
        data_frame_head[1] = (payloadSize & 0xff) | 0x80;
126
0
        data_frame_head[2] = masking_key[0];
127
0
        data_frame_head[3] = masking_key[1];
128
0
        data_frame_head[4] = masking_key[2];
129
0
        data_frame_head[5] = masking_key[3];
130
0
        data_frame_head_len = 6;
131
0
    }
132
0
    else if (payloadSize < 65536) {
133
0
        data_frame_head = (char *)flb_malloc(8);
134
0
        if (!data_frame_head) {
135
0
            flb_errno();
136
0
            return -1;
137
0
        }
138
0
        data_frame_head[0] = 0x81;
139
0
        data_frame_head[1] = (unsigned char) (126 | 0x80);
140
0
        data_frame_head[2] = (payloadSize >> 8) & 0xff;
141
0
        data_frame_head[3] = (payloadSize >> 0) & 0xff;
142
0
        data_frame_head[4] = masking_key[0];
143
0
        data_frame_head[5] = masking_key[1];
144
0
        data_frame_head[6] = masking_key[2];
145
0
        data_frame_head[7] = masking_key[3];
146
0
        data_frame_head_len = 8;
147
0
    }
148
0
    else {
149
0
        data_frame_head = (char *)flb_malloc(14);
150
0
        if (!data_frame_head) {
151
0
            flb_errno();
152
0
            return -1;
153
0
        }
154
0
        data_frame_head[0] = 0x81;
155
0
        data_frame_head[1] = (unsigned char) (127 | 0x80);
156
0
        data_frame_head[2] = (payloadSize >> 56) & 0xff;
157
0
        data_frame_head[3] = (payloadSize >> 48) & 0xff;
158
0
        data_frame_head[4] = (payloadSize >> 40) & 0xff;
159
0
        data_frame_head[5] = (payloadSize >> 32) & 0xff;
160
0
        data_frame_head[6] = (payloadSize >> 24) & 0xff;
161
0
        data_frame_head[7] = (payloadSize >> 16) & 0xff;
162
0
        data_frame_head[8] = (payloadSize >>  8) & 0xff;
163
0
        data_frame_head[9] = (payloadSize >>  0) & 0xff;
164
0
        data_frame_head[10] = masking_key[0];
165
0
        data_frame_head[11] = masking_key[1];
166
0
        data_frame_head[12] = masking_key[2];
167
0
        data_frame_head[13] = masking_key[3];
168
0
        data_frame_head_len = 14;
169
0
    }
170
0
    ret = flb_io_net_write(u_conn, data_frame_head, data_frame_head_len, &bytes_sent);
171
0
    if (ret == -1) {
172
0
        flb_error("[out_ws] could not write dataframe header");
173
0
        goto error;
174
0
    }
175
0
    flb_free(data_frame_head);
176
0
    return 0;
177
178
0
error:
179
0
    flb_free(data_frame_head);
180
0
    return -1;
181
0
}
182
183
static int cb_ws_init(struct flb_output_instance *ins,
184
                      struct flb_config *config, void *data)
185
0
{
186
0
    struct flb_out_ws *ctx = NULL;
187
188
0
    ctx = flb_ws_conf_create(ins, config);
189
0
    if (!ctx) {
190
0
        return -1;
191
0
    }
192
193
0
    ctx->handshake = 1;
194
0
    ctx->last_input_timestamp = time(NULL);
195
0
    flb_output_set_context(ins, ctx);
196
0
    return 0;
197
0
}
198
199
static int cb_ws_exit(void *data, struct flb_config *config)
200
0
{
201
0
    struct flb_out_ws *ctx = data;
202
0
    flb_ws_conf_destroy(ctx);
203
0
    return 0;
204
0
}
205
206
static void cb_ws_flush(struct flb_event_chunk *event_chunk,
207
                        struct flb_output_flush *out_flush,
208
                        struct flb_input_instance *i_ins,
209
                        void *out_context,
210
                        struct flb_config *config)
211
0
{
212
0
    int ret = -1;
213
0
    size_t bytes_sent;
214
0
    flb_sds_t json = NULL;
215
0
    struct flb_upstream *u;
216
0
    struct flb_connection *u_conn;
217
0
    struct flb_out_ws *ctx = out_context;
218
0
    time_t now;
219
220
    /* Get upstream context and connection */
221
0
    u = ctx->u;
222
0
    u_conn = flb_upstream_conn_get(u);
223
224
0
    if (!u_conn) {
225
0
        flb_error("[out_ws] no upstream connections available to %s:%i", u->tcp_host, u->tcp_port);
226
0
        ctx->handshake = 1;
227
0
        FLB_OUTPUT_RETURN(FLB_RETRY);
228
0
    }
229
230
0
    now = time(NULL);
231
232
    //TODO how to determine the interval? conn disconnet is about 30 sec, so we set 20 ssecnds here.
233
0
    flb_debug("[out_ws] interval is  %ld and handshake is %d", now - ctx->last_input_timestamp, ctx->handshake);
234
0
    if ((now - ctx->last_input_timestamp > ctx->idle_interval) && (ctx->handshake == 0)) {
235
0
        ctx->handshake = 1;
236
0
        flb_upstream_conn_release(u_conn);
237
0
        FLB_OUTPUT_RETURN(FLB_RETRY);
238
0
    }
239
0
    ctx->last_input_timestamp = now;
240
241
0
    if (ctx->handshake == 1) {
242
        /* Handshake with websocket server*/
243
0
        flb_info("[out_ws] handshake for ws");
244
0
        ret = flb_ws_handshake(u_conn, ctx);
245
0
        if (ret == -1) {
246
0
            flb_upstream_conn_release(u_conn);
247
0
            FLB_OUTPUT_RETURN(FLB_RETRY);
248
0
        }
249
0
        ctx->handshake = 0;
250
0
    }
251
252
    /* Data format process*/
253
0
    if (ctx->out_format != FLB_PACK_JSON_FORMAT_NONE) {
254
0
        json = flb_pack_msgpack_to_json_format(event_chunk->data,
255
0
                                               event_chunk->size,
256
0
                                               ctx->out_format,
257
0
                                               ctx->json_date_format,
258
0
                                               ctx->json_date_key,
259
0
                                               config->json_escape_unicode);
260
261
0
        if (!json) {
262
0
            flb_error("[out_ws] error formatting JSON payload");
263
0
            flb_upstream_conn_release(u_conn);
264
0
            FLB_OUTPUT_RETURN(FLB_ERROR);
265
0
        }
266
0
    }
267
268
    /* Write message header */
269
0
    if (ctx->out_format == FLB_PACK_JSON_FORMAT_NONE) {
270
0
        ret = flb_ws_sendDataFrameHeader(u_conn, ctx,
271
0
                                         event_chunk->data,
272
0
                                         event_chunk->size);
273
0
    }
274
0
    else {
275
0
        ret = flb_ws_sendDataFrameHeader(u_conn, ctx, json, flb_sds_len(json));
276
0
    }
277
278
0
    if (ret == -1) {
279
0
        flb_error("[out_ws] dataFrameHeader sent failed");
280
0
        ctx->handshake = 1;
281
0
        if (json) {
282
0
            flb_sds_destroy(json);
283
0
        }
284
0
        flb_upstream_conn_release(u_conn);
285
0
        FLB_OUTPUT_RETURN(FLB_RETRY);
286
0
    }
287
288
    /* Write message body*/
289
0
    if (ctx->out_format == FLB_PACK_JSON_FORMAT_NONE) {
290
0
        ret = flb_io_net_write(u_conn,
291
0
                               event_chunk->data,
292
0
                               event_chunk->size,
293
0
                               &bytes_sent);
294
0
    }
295
0
    else {
296
0
        ret = flb_io_net_write(u_conn, json, flb_sds_len(json), &bytes_sent);
297
0
        flb_sds_destroy(json);
298
0
    }
299
300
    //flb_info("[out_ws] sendDataFrame number of bytes sent = %i", ret);
301
0
    if (ret == -1) {
302
0
        ctx->handshake = 1;
303
0
        flb_upstream_conn_release(u_conn);
304
0
        FLB_OUTPUT_RETURN(FLB_RETRY);
305
0
    }
306
307
    /* Release the connection */
308
0
    flb_upstream_conn_release(u_conn);
309
0
    FLB_OUTPUT_RETURN(FLB_OK);
310
0
}
311
312
/* Configuration properties map */
313
static struct flb_config_map config_map[] = {
314
    {
315
     FLB_CONFIG_MAP_STR, "uri", NULL,
316
     0, FLB_TRUE, offsetof(struct flb_out_ws, uri),
317
     "Specify an optional URI for the target web socket server, e.g: /something"
318
    },
319
    {
320
     FLB_CONFIG_MAP_STR, "format", NULL,
321
     0, FLB_FALSE, 0,
322
     "Set desired payload format: json, json_stream, json_lines, gelf or msgpack"
323
    },
324
    {
325
     FLB_CONFIG_MAP_STR, "json_date_format", "double",
326
     0, FLB_FALSE, 0,
327
     "Specify the format of the date"
328
    },
329
    {
330
     FLB_CONFIG_MAP_STR, "json_date_key", "date",
331
     0, FLB_TRUE, offsetof(struct flb_out_ws, json_date_key),
332
     "Specify the name of the date field in output"
333
    },
334
    {
335
     FLB_CONFIG_MAP_SLIST_1, "header", NULL,
336
     FLB_CONFIG_MAP_MULT, FLB_TRUE, offsetof(struct flb_out_ws, headers),
337
     "Add a HTTP header key/value pair to the initial HTTP request. Multiple headers can be set"
338
    },
339
    /* EOF */
340
    {0}
341
};
342
343
/* Plugin reference */
344
struct flb_output_plugin out_websocket_plugin = {
345
    .name         = "websocket",
346
    .description  = "Websocket",
347
    .cb_init      = cb_ws_init,
348
    .cb_flush     = cb_ws_flush,
349
    .cb_exit      = cb_ws_exit,
350
    .config_map   = config_map,
351
    .flags        = FLB_OUTPUT_NET | FLB_IO_OPT_TLS,
352
};