Coverage Report

Created: 2026-11-13 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-oss-fuzz/harnesses/sockets.c
Line
Count
Source
1
/*
2
 * Exercise R's socket connections as a state machine: sockconn.c, Rsock.c
3
 * and sock.c in the internet module, and do_sockselect / do_socktimeout in
4
 * src/main/connections.c.
5
 *
6
 * The other targets hand one R function one hostile value.  Sockets fail
7
 * differently: the bugs are in what a connection lets you do in a state
8
 * it was not written for (never opened, open failed, peer gone, half a
9
 * line buffered).  So each input is a short program of socket calls over
10
 * four connection slots and one listening socket, all in this process and
11
 * all on the loopback interface (instrumentation/0006 binds R's server
12
 * sockets to 127.0.0.1); see `interpreter` below for the calls.
13
 *
14
 * Two things here are unlike the other harnesses.
15
 *
16
 * Nothing may wait.  R's socket code waits in select() for up to the
17
 * connection's timeout, and a wait of even a second per call would starve
18
 * the fuzzer and report as a timeout.  Every connection is therefore
19
 * created with timeout = 0, which makes each read and write a poll, and
20
 * the interpreter only connects where the answer is immediate (the
21
 * process's own listener, or port 0, which refuses) and only accepts a
22
 * connection that is already queued.  sock_open() replaces a timeout of 0
23
 * by 60 seconds for connect() and accept(), which is why those two are
24
 * guarded rather than left to time out.
25
 *
26
 * The internet module is needed.  ossfuzz.sh removes it from the bundled
27
 * R so that no other target can reach the network, and keeps a copy for
28
 * this one; see sockets_load_module().
29
 */
30
31
#include <stdint.h>
32
#include <string.h>
33
34
#include "common.h"
35
36
/* 64 three-byte operations; keep options/sockets.options in step. */
37
0
#define FUZZ_MAX_INPUT 192
38
39
1
#define N_CALLS 1
40
41
static SEXP calls[N_CALLS];
42
43
/*
44
 * Each operation is three bytes: op, a, b.  op %% 13 picks the call and
45
 * op %/% 13 %% 4 the slot it applies to; a and b are its arguments.  The
46
 * whole input doubles as the pool that written data is taken from.
47
 *
48
 * State kept between inputs is the listener's port alone: if another
49
 * fuzzing process holds it, the next free one is used from then on.
50
 * Everything else is closed when the input ends, so a connection table
51
 * of 128 entries never fills up.
52
 */
53
static const char interpreter[] = R"(
54
local({
55
    encodings <- c("native.enc", "UTF-8", "latin1", "UTF-16LE")
56
    modes <- c("r", "w", "a+", "r+", "rb", "wb", "a+b", "r+b")
57
58
    # Lengths either side of the 4096-byte input buffer of a socket.
59
    sizes <- c(1L, 100L, 4095L, 4096L, 4097L, 9000L)
60
61
    # For connections made with server = TRUE, which are never opened.
62
    passive_ports <- c(0L, 1L, 65535L, 65536L, 1000000L)
63
64
    port <- 0L
65
    listener <- NULL
66
    pending <- 0L                # connected to the listener, not yet accepted
67
    written <- 0L
68
    cons <- vector("list", 4L)
69
    dest <- integer(4L)          # port a slot connects to; 0 refuses at once
70
    passive <- logical(4L)       # opening would wait for a peer: never done
71
72
    drop <- function(k) {
73
        con <- cons[[k]]
74
        cons[k] <<- list(NULL)
75
        if (!is.null(con))
76
            close(con)
77
    }
78
79
    listen <- function() {
80
        if (!is.null(listener))
81
            return(invisible())
82
83
        for (p in port + 0:15) {
84
            s <- tryCatch(serverSocket(p), error = function(e) NULL)
85
            if (!is.null(s)) {
86
                port <<- p
87
                listener <<- s
88
                pending <<- 0L
89
                break
90
            }
91
        }
92
    }
93
94
    unlisten <- function() {
95
        s <- listener
96
        listener <<- NULL
97
        pending <<- 0L
98
        if (!is.null(s))
99
            close(s)
100
    }
101
102
    # Can slot k be opened without waiting?  Port 0 refuses at once, and
103
    # this process's listener answers at once while its queue has room.
104
    # Any other port may be closed, or another process's listener.
105
    prompt <- function(k) {
106
        if (dest[k] == 0L)
107
            return(TRUE)
108
109
        !is.null(listener) && dest[k] == port && pending < 8L
110
    }
111
112
    # Can slot k be read, written or opened?  Reads and writes open an
113
    # unopened connection, so they are held to the same rule.
114
    usable <- function(k) {
115
        con <- cons[[k]]
116
        if (is.null(con) || passive[k])
117
            return(FALSE)
118
119
        isOpen(con) || prompt(k)
120
    }
121
122
    # Count a connection that slot k has just made to the listener.
123
    note_open <- function(k, was_open) {
124
        con <- cons[[k]]
125
        if (!was_open && !is.null(con) && dest[k] != 0L && isOpen(con))
126
            pending <<- pending + 1L
127
    }
128
129
    client <- function(k, a, mode) {
130
        drop(k)
131
        dest[k] <<- if (bitwAnd(a, 2L) != 0L) port else 0L
132
        passive[k] <<- FALSE
133
        if (!prompt(k))
134
            mode <- ""
135
136
        cons[[k]] <<- socketConnection(
137
            "127.0.0.1",
138
            dest[k],
139
            server = FALSE,
140
            blocking = bitwAnd(a, 1L) != 0L,
141
            open = mode,
142
            encoding = encodings[bitwAnd(a, 12L) %/% 4L + 1L],
143
            timeout = 0L,
144
            options = if (bitwAnd(a, 16L) != 0L) "no-delay"
145
        )
146
        note_open(k, FALSE)
147
    }
148
149
    passive_connection <- function(k, a) {
150
        drop(k)
151
        dest[k] <<- 0L
152
        passive[k] <<- TRUE
153
154
        cons[[k]] <<- socketConnection(
155
            port = passive_ports[a %% 5L + 1L],
156
            server = TRUE,
157
            blocking = bitwAnd(a, 8L) != 0L,
158
            open = "",
159
            timeout = 0L
160
        )
161
    }
162
163
    open_slot <- function(k, b) {
164
        if (!usable(k))
165
            return(invisible())
166
167
        con <- cons[[k]]
168
        was_open <- isOpen(con)
169
        on.exit(note_open(k, was_open))
170
171
        open(con, modes[b %% 8L + 1L])
172
    }
173
174
    # Only a connection this input made, and only once it is queued:
175
    # socketAccept() would otherwise wait for one.
176
    accept <- function(k, a, b) {
177
        if (is.null(listener) || pending == 0L)
178
            return(invisible())
179
        if (!socketSelect(list(listener), timeout = 0))
180
            return(invisible())
181
182
        drop(k)
183
        con <- socketAccept(
184
            listener,
185
            blocking = bitwAnd(a, 1L) != 0L,
186
            open = modes[b %% 8L + 1L],
187
            encoding = encodings[bitwAnd(a, 12L) %/% 4L + 1L],
188
            timeout = 0L,
189
            options = if (bitwAnd(a, 16L) != 0L) "no-delay"
190
        )
191
192
        pending <<- pending - 1L
193
        dest[k] <<- 0L
194
        passive[k] <<- FALSE
195
        cons[[k]] <<- con
196
    }
197
198
    # Any mix of slots, open or not, the listener, the same socket twice
199
    # and something that is not a socket.
200
    select <- function(a, b) {
201
        socks <- cons[bitwAnd(a, c(1L, 2L, 4L, 8L)) != 0L]
202
        socks <- socks[!vapply(socks, is.null, NA)]
203
        if (bitwAnd(a, 16L) != 0L && !is.null(listener))
204
            socks <- c(socks, list(listener))
205
        if (bitwAnd(a, 32L) != 0L && length(socks) > 0L)
206
            socks <- c(socks, socks[1L])
207
        if (bitwAnd(a, 64L) != 0L)
208
            socks <- c(socks, list(stdin()))
209
210
        write <- as.logical(intToBits(b)[seq_along(socks)])
211
        socketSelect(socks, write, timeout = 0)
212
    }
213
214
    # Never a positive timeout: reads and writes would start to wait.
215
    set_timeout <- function(k, a) {
216
        con <- if (bitwAnd(a, 4L) != 0L) listener else cons[[k]]
217
        socketTimeout(con, c(0L, -1L, NA)[a %% 3L + 1L])
218
    }
219
220
    # The cap keeps the loopback buffers from filling when nothing reads.
221
    send <- function(k, a, b, x) {
222
        if (!usable(k) || written > 32768L)
223
            return(invisible())
224
225
        con <- cons[[k]]
226
        was_open <- isOpen(con)
227
        on.exit(note_open(k, was_open))
228
229
        from <- (b + seq_len(a %/% 8L + 1L) - 1L) %% length(x) + 1L
230
        payload <- x[from]
231
        text <- rawToChar(payload[payload != as.raw(0L)])
232
        long <- rep_len(payload, sizes[b %% 6L + 1L])
233
        written <<- written + length(long)
234
235
        switch(a %% 4L + 1L,
236
            writeBin(payload, con),
237
            writeBin(long, con),
238
            writeLines(text, con),
239
            writeChar(text, con, eos = NULL)
240
        )
241
    }
242
243
    receive <- function(k, a, b) {
244
        if (!usable(k))
245
            return(invisible())
246
247
        con <- cons[[k]]
248
        was_open <- isOpen(con)
249
        on.exit(note_open(k, was_open))
250
251
        switch(a %% 5L + 1L,
252
            readLines(con, n = b %% 4L, warn = FALSE),
253
            readBin(con, "raw", sizes[b %% 6L + 1L]),
254
            readChar(con, c(1L, b %% 64L), useBytes = TRUE),
255
            readChar(con, b %% 64L, useBytes = FALSE),
256
            readBin(con, "integer", 3L, size = 2L)
257
        )
258
        isIncomplete(con)
259
    }
260
261
    # None of these opens a connection, so any slot will do.
262
    status <- function(k, a) {
263
        con <- cons[[k]]
264
        if (is.null(con))
265
            return(invisible())
266
267
        switch(a %% 6L + 1L,
268
            summary(con),
269
            isIncomplete(con),
270
            flush(con),
271
            seek(con, 0L),
272
            truncate(con),
273
            pushBack("pushed back", con)
274
        )
275
    }
276
277
    step <- function(op, k, a, b, x) {
278
        switch(op + 1L,
279
            client(k, a, ""),
280
            client(k, a, modes[b %% 8L + 1L]),
281
            passive_connection(k, a),
282
            listen(),
283
            unlisten(),
284
            open_slot(k, b),
285
            accept(k, a, b),
286
            select(a, b),
287
            set_timeout(k, a),
288
            send(k, a, b, x),
289
            receive(k, a, b),
290
            drop(k),
291
            status(k, a)
292
        )
293
    }
294
295
    reset <- function() {
296
        for (k in seq_along(cons))
297
            tryCatch(drop(k), error = function(e) NULL)
298
        tryCatch(unlisten(), error = function(e) NULL)
299
    }
300
301
    function(x, base) {
302
        if (port == 0L)
303
            port <<- base
304
        written <<- 0L
305
        on.exit(reset())
306
307
        for (i in seq_len(min(length(x) %/% 3L, 64L))) {
308
            op <- as.integer(x[3L * i - 2L])
309
            a <- as.integer(x[3L * i - 1L])
310
            b <- as.integer(x[3L * i])
311
            tryCatch(
312
                step(op %% 13L, op %/% 13L %% 4L + 1L, a, b, x),
313
                error = function(e) NULL
314
            )
315
        }
316
    }
317
})
318
)";
319
320
/* Creating a socket connection is what loads the module; nothing is
321
 * opened, so this touches no network. */
322
static const char module_probe[] = R"(
323
function() {
324
    close(socketConnection("127.0.0.1", 0L, open = ""))
325
}
326
)";
327
328
/*
329
 * Load R's internet module, which ossfuzz.sh keeps out of every other
330
 * target's reach.
331
 *
332
 * R loads it on the first socket call from $R_HOME/modules, reading
333
 * R_HOME from the environment at that moment (R_moduleCdynload).  The
334
 * build moves the module to $R_HOME/fuzz-internet/modules instead, so
335
 * pointing R_HOME there for that one call loads it, and for every other
336
 * target the same call fails with "internet routines cannot be loaded".
337
 * A local R build has the module in the usual place and needs none of
338
 * this.
339
 *
340
 * R remembers a failed load and never retries, so a build that cannot
341
 * load the module would run every input as a no-op and report nothing.
342
 * That is a build error, not an input to skip: abort.
343
 */
344
static void sockets_load_module(void)
345
1
{
346
1
    const char *home = getenv("R_HOME");
347
1
    char *real_home = NULL;
348
349
1
    if (home != NULL) {
350
1
        char stash[PATH_MAX], module[PATH_MAX];
351
1
        snprintf(stash, sizeof stash, "%s/fuzz-internet", home);
352
1
        snprintf(module, sizeof module, "%s/modules/internet.so", stash);
353
1
        if (access(module, R_OK) == 0) {
354
1
            real_home = strdup(home);
355
1
            if (real_home == NULL)
356
0
                abort();
357
1
            setenv("R_HOME", stash, 1);
358
1
        }
359
1
    }
360
361
1
    int error = 0;
362
1
    SEXP probe;
363
1
    Rf_protect(probe = Rf_lang1(fuzz_make_wrapper(module_probe)));
364
1
    R_tryEvalSilent(probe, R_GlobalEnv, &error);
365
1
    Rf_unprotect(1);
366
367
1
    if (real_home != NULL) {
368
1
        setenv("R_HOME", real_home, 1);
369
1
        free(real_home);
370
1
    }
371
372
1
    if (error) {
373
0
        fprintf(stderr, "sockets: cannot load R's internet module: %s\n",
374
0
                R_curErrorBuf());
375
0
        abort();
376
0
    }
377
1
}
378
379
int fuzz_target_init(int *argc, char ***argv)
380
1
{
381
1
    (void)argc;
382
1
    (void)argv;
383
1
    fuzz_init_r();
384
1
    sockets_load_module();
385
386
    /* Spread concurrent fuzzing processes over the ports below the
387
     * ephemeral range; the interpreter moves on if one is taken. */
388
1
    int base = 10000 + (int)((unsigned)getpid() * 7919u % 20000u);
389
390
1
    SEXP placeholder, port, wrapper;
391
1
    Rf_protect(placeholder = Rf_allocVector(RAWSXP, 1));
392
1
    Rf_protect(port = Rf_ScalarInteger(base));
393
1
    Rf_protect(wrapper = fuzz_make_wrapper(interpreter));
394
1
    Rf_protect(calls[0] = Rf_lang3(wrapper, placeholder, port));
395
396
1
    fuzz_label_calls(calls, N_CALLS);
397
1
    return 0;
398
1
}
399
400
int fuzz_target_run(const uint8_t *data, size_t size)
401
0
{
402
0
    if (size < 3 || size > FUZZ_MAX_INPUT)
403
0
        return 0;
404
405
0
    if (!fuzz_set_raw_arg(calls[0], data, size))
406
0
        return 0;
407
408
0
    fuzz_eval_silent(calls[0], R_GlobalEnv);
409
0
    return 0;
410
0
}