Module: Hyperion::WebSocket::CFrame

Defined in:
ext/hyperion_http/websocket.c

Constant Summary collapse

GVL_RELEASE_THRESHOLD =

Expose constants for the Ruby façade & specs.

INT2NUM(HYP_WS_GVL_RELEASE_THRESHOLD)
CONTROL_MAX_PAYLOAD =
INT2NUM(HYP_WS_CONTROL_MAX_PAYLOAD)

Class Method Summary collapse

Class Method Details

.build(*args) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'ext/hyperion_http/websocket.c', line 316

static VALUE rb_cframe_build(int argc, VALUE *argv, VALUE self) {
    (void)self;

    VALUE rb_opcode, rb_payload, rb_kwargs;
    rb_scan_args(argc, argv, "20:", &rb_opcode, &rb_payload, &rb_kwargs);

    long opcode_l = NUM2LONG(rb_opcode);
    if (opcode_l < 0 || opcode_l > 0xF) {
        rb_raise(rb_eArgError, "opcode must be 0..15 (got %ld)", opcode_l);
    }
    uint8_t opcode = (uint8_t)opcode_l;
    if (!hyp_ws_is_known_opcode(opcode)) {
        rb_raise(rb_eArgError, "unknown opcode 0x%x", (unsigned)opcode);
    }

    Check_Type(rb_payload, T_STRING);
    long payload_len = RSTRING_LEN(rb_payload);

    int fin  = 1;
    int mask = 0;
    int rsv1 = 0;
    VALUE rb_mask_key = Qnil;

    if (!NIL_P(rb_kwargs)) {
        VALUE kw_vals[4] = { Qundef, Qundef, Qundef, Qundef };
        ID    kw_ids[4]  = { id_kw_fin, id_kw_mask, id_kw_mask_key, id_kw_rsv1 };
        rb_get_kwargs(rb_kwargs, kw_ids, 0, 4, kw_vals);
        if (kw_vals[0] != Qundef) {
            fin = RTEST(kw_vals[0]) ? 1 : 0;
        }
        if (kw_vals[1] != Qundef) {
            mask = RTEST(kw_vals[1]) ? 1 : 0;
        }
        if (kw_vals[2] != Qundef) {
            rb_mask_key = kw_vals[2];
        }
        if (kw_vals[3] != Qundef) {
            rsv1 = RTEST(kw_vals[3]) ? 1 : 0;
        }
    }

    /* §5.5 control-frame validation. RFC 7692 §6.1 — control frames
     * MUST NOT have RSV1 set. */
    if (hyp_ws_is_control(opcode)) {
        if (!fin) {
            rb_raise(rb_eArgError,
                     "control frame (opcode 0x%x) MUST have fin=true",
                     (unsigned)opcode);
        }
        if (payload_len > HYP_WS_CONTROL_MAX_PAYLOAD) {
            rb_raise(rb_eArgError,
                     "control frame (opcode 0x%x) payload %ld exceeds 125-byte cap",
                     (unsigned)opcode, payload_len);
        }
        if (rsv1) {
            rb_raise(rb_eArgError,
                     "control frame (opcode 0x%x) MUST NOT have rsv1=true",
                     (unsigned)opcode);
        }
    }

    if (mask) {
        if (NIL_P(rb_mask_key)) {
            rb_raise(rb_eArgError, "mask: true requires a 4-byte mask_key");
        }
        Check_Type(rb_mask_key, T_STRING);
        if (RSTRING_LEN(rb_mask_key) != 4) {
            rb_raise(rb_eArgError, "mask_key must be exactly 4 bytes (got %ld)",
                     RSTRING_LEN(rb_mask_key));
        }
    }

    /* Compute header length. */
    long header_len = 2;
    if (payload_len < 126) {
        /* 7-bit length encoded inline. */
    } else if (payload_len <= 0xFFFF) {
        header_len += 2;
    } else {
        header_len += 8;
    }
    if (mask) header_len += 4;

    long frame_len = header_len + payload_len;
    VALUE out = rb_str_new(NULL, frame_len);
    rb_enc_associate(out, rb_ascii8bit_encoding());
    uint8_t *q = (uint8_t *)RSTRING_PTR(out);

    q[0] = (uint8_t)((fin ? 0x80 : 0x00) | (rsv1 ? 0x40 : 0x00) | (opcode & 0x0F));
    uint8_t mask_bit = mask ? 0x80 : 0x00;

    long body_offset;
    if (payload_len < 126) {
        q[1] = mask_bit | (uint8_t)payload_len;
        body_offset = 2;
    } else if (payload_len <= 0xFFFF) {
        q[1] = mask_bit | 126;
        q[2] = (uint8_t)((payload_len >> 8) & 0xFF);
        q[3] = (uint8_t)(payload_len & 0xFF);
        body_offset = 4;
    } else {
        q[1] = mask_bit | 127;
        uint64_t pl = (uint64_t)payload_len;
        q[2] = (uint8_t)((pl >> 56) & 0xFF);
        q[3] = (uint8_t)((pl >> 48) & 0xFF);
        q[4] = (uint8_t)((pl >> 40) & 0xFF);
        q[5] = (uint8_t)((pl >> 32) & 0xFF);
        q[6] = (uint8_t)((pl >> 24) & 0xFF);
        q[7] = (uint8_t)((pl >> 16) & 0xFF);
        q[8] = (uint8_t)((pl >> 8)  & 0xFF);
        q[9] = (uint8_t)(pl & 0xFF);
        body_offset = 10;
    }

    if (mask) {
        memcpy(q + body_offset, RSTRING_PTR(rb_mask_key), 4);
        body_offset += 4;
    }

    if (payload_len > 0) {
        if (mask) {
            /* Reuse the unmask kernel — XOR is symmetric. */
            unmask_args_t args;
            args.src = (const uint8_t *)RSTRING_PTR(rb_payload);
            args.dst = q + body_offset;
            args.len = (size_t)payload_len;
            memcpy(args.key, RSTRING_PTR(rb_mask_key), 4);
            memcpy(&args.key32, args.key, 4);
            if ((size_t)payload_len > HYP_WS_GVL_RELEASE_THRESHOLD) {
                rb_thread_call_without_gvl(hyp_ws_xor_blocking, &args, RUBY_UBF_IO, NULL);
            } else {
                hyp_ws_xor_inplace(&args);
            }
        } else {
            memcpy(q + body_offset, RSTRING_PTR(rb_payload), (size_t)payload_len);
        }
    }

    RB_GC_GUARD(rb_payload);
    RB_GC_GUARD(rb_mask_key);
    return out;
}

.parse(*args) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'ext/hyperion_http/websocket.c', line 181

static VALUE rb_cframe_parse(int argc, VALUE *argv, VALUE self) {
    (void)self;

    VALUE rb_buf, rb_offset;
    rb_scan_args(argc, argv, "11", &rb_buf, &rb_offset);

    Check_Type(rb_buf, T_STRING);
    long offset = NIL_P(rb_offset) ? 0 : NUM2LONG(rb_offset);
    if (offset < 0) {
        rb_raise(rb_eArgError, "offset must be >= 0 (got %ld)", offset);
    }

    long buf_len = RSTRING_LEN(rb_buf);
    if (offset > buf_len) {
        return sym_incomplete;
    }

    long avail = buf_len - offset;
    if (avail < 2) {
        return sym_incomplete;
    }

    const uint8_t *p = (const uint8_t *)RSTRING_PTR(rb_buf) + offset;
    uint8_t b0 = p[0];
    uint8_t b1 = p[1];

    int     fin       = (b0 & 0x80) != 0;
    int     rsv1      = (b0 & 0x40) != 0;
    int     rsv2      = (b0 & 0x20) != 0;
    int     rsv3      = (b0 & 0x10) != 0;
    uint8_t opcode    = b0 & 0x0F;
    int     masked    = (b1 & 0x80) != 0;
    uint8_t len7      = b1 & 0x7F;

    /* RSV2/RSV3 are still reserved with no negotiated semantics; reject.
     * RSV1 is the permessage-deflate marker (RFC 7692 §6) — allow it to
     * pass through here so the Ruby façade can decide what to do based
     * on whether the extension was negotiated for this connection. The
     * Connection wrapper closes 1002 if it sees RSV1 without a
     * negotiated extension. RSV1 on a control frame is always a
     * protocol error per RFC 7692 §6.1 ("control frames MUST NOT be
     * compressed"); we trap that one case below. */
    if (rsv2 || rsv3) {
        return sym_error;
    }

    if (!hyp_ws_is_known_opcode(opcode)) {
        return sym_error;
    }

    /* §5.5 — control frames MUST have FIN=1 and len <= 125. RFC 7692
     * §6.1 — control frames MUST NOT have RSV1 set. */
    if (hyp_ws_is_control(opcode)) {
        if (!fin) {
            return sym_error;
        }
        if (len7 > HYP_WS_CONTROL_MAX_PAYLOAD) {
            return sym_error;
        }
        if (rsv1) {
            return sym_error;
        }
    }

    long header_len = 2;
    uint64_t payload_len64 = 0;

    if (len7 < 126) {
        payload_len64 = len7;
    } else if (len7 == 126) {
        if (avail < header_len + 2) return sym_incomplete;
        payload_len64 = ((uint64_t)p[2] << 8) | (uint64_t)p[3];
        header_len += 2;
    } else { /* len7 == 127 */
        if (avail < header_len + 8) return sym_incomplete;
        /* Network byte order; high bit MUST be 0 per RFC 6455 §5.2. */
        if (p[2] & 0x80) {
            return sym_error;
        }
        payload_len64 =
            ((uint64_t)p[2]  << 56) | ((uint64_t)p[3]  << 48) |
            ((uint64_t)p[4]  << 40) | ((uint64_t)p[5]  << 32) |
            ((uint64_t)p[6]  << 24) | ((uint64_t)p[7]  << 16) |
            ((uint64_t)p[8]  << 8)  |  (uint64_t)p[9];
        header_len += 8;
    }

    VALUE rb_mask_key = Qnil;
    if (masked) {
        if (avail < header_len + 4) return sym_incomplete;
        rb_mask_key = rb_str_new((const char *)(p + header_len), 4);
        rb_enc_associate(rb_mask_key, rb_ascii8bit_encoding());
        header_len += 4;
    }

    /* Bound payload_len64: a frame_total_len that overflows a Ruby
     * Integer is fine (Bignum), but we still want to make sure the
     * header_len + payload_len arithmetic below doesn't overflow size_t
     * on 32-bit hosts.  On 64-bit Linux/Darwin this is academic; the
     * cap is 2^63-1 and Ruby Strings can't be larger than LONG_MAX
     * anyway. */
    if (payload_len64 > (uint64_t)LONG_MAX - (uint64_t)header_len) {
        return sym_error;
    }

    /* Incomplete payload — the caller should buffer more bytes. */
    long payload_offset_abs = offset + header_len;
    long frame_total_len    = header_len + (long)payload_len64;
    if (avail < frame_total_len) {
        return sym_incomplete;
    }

    VALUE result = rb_ary_new_capa(8);
    rb_ary_push(result, fin ? Qtrue : Qfalse);
    rb_ary_push(result, INT2FIX(opcode));
    rb_ary_push(result, ULL2NUM(payload_len64));
    rb_ary_push(result, masked ? Qtrue : Qfalse);
    rb_ary_push(result, rb_mask_key);
    rb_ary_push(result, LONG2NUM(payload_offset_abs));
    rb_ary_push(result, LONG2NUM(frame_total_len));
    rb_ary_push(result, rsv1 ? Qtrue : Qfalse);

    RB_GC_GUARD(rb_buf);
    return result;
}

.unmask(rb_payload, rb_key) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'ext/hyperion_http/websocket.c', line 115

static VALUE rb_cframe_unmask(VALUE self, VALUE rb_payload, VALUE rb_key) {
    (void)self;

    Check_Type(rb_payload, T_STRING);
    Check_Type(rb_key, T_STRING);

    long key_len = RSTRING_LEN(rb_key);
    if (key_len != 4) {
        rb_raise(rb_eArgError,
                 "Hyperion::WebSocket::CFrame.unmask: mask_key must be exactly "
                 "4 bytes (got %ld)", key_len);
    }

    long payload_len = RSTRING_LEN(rb_payload);
    /* Empty payload — return an empty binary String of the right encoding. */
    if (payload_len == 0) {
        VALUE empty = rb_str_new(NULL, 0);
        rb_enc_associate(empty, rb_ascii8bit_encoding());
        return empty;
    }

    VALUE out = rb_str_new(NULL, payload_len);
    rb_enc_associate(out, rb_ascii8bit_encoding());

    unmask_args_t args;
    args.src = (const uint8_t *)RSTRING_PTR(rb_payload);
    args.dst = (uint8_t *)RSTRING_PTR(out);
    args.len = (size_t)payload_len;
    memcpy(args.key, RSTRING_PTR(rb_key), 4);
    /* Smear the 4 mask bytes into a host-order uint32. memcpy() handles
     * platform endianness — we treat the key as a stream of 4 bytes that
     * we want to apply at offsets {0,1,2,3,4,5,...} ≡ {0,1,2,3,0,1,2,3,...},
     * and reading 4 bytes at a time with memcpy preserves that pattern
     * independent of endianness. */
    memcpy(&args.key32, args.key, 4);

    if ((size_t)payload_len > HYP_WS_GVL_RELEASE_THRESHOLD) {
        rb_thread_call_without_gvl(hyp_ws_xor_blocking, &args, RUBY_UBF_IO, NULL);
    } else {
        hyp_ws_xor_inplace(&args);
    }

    /* Keep `rb_payload` and `out` alive across the GVL release. */
    RB_GC_GUARD(rb_payload);
    RB_GC_GUARD(rb_key);

    return out;
}