tiny_httpd/src/ws/tiny_httpd_ws_stubs.c
Simon Cruanes 3393c13c00
fix websocket: properly remember the offset in current frame
not doing so means we always unmask from offset 0, which means we might
use the wrong index in the mask if we do, say, `read()=3` followed by
another read: the second one would start from mask[0] instead of
mask[3], producing raw unfiltered garbage.
2024-04-05 13:21:54 -04:00

22 lines
708 B
C

#include <caml/alloc.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>
CAMLprim value tiny_httpd_ws_apply_masking(value _mask_key, value _mask_offset, value _buf,
value _offset, value _len) {
CAMLparam5(_mask_key, _mask_offset, _buf, _offset, _len);
char const *mask_key = String_val(_mask_key);
char *buf = Bytes_val(_buf);
intnat mask_offset = Int_val(_mask_offset);
intnat offset = Int_val(_offset);
intnat len = Int_val(_len);
for (intnat i = 0; i < len; ++i) {
unsigned char c = buf[offset + i];
unsigned char c_m = mask_key[(i + mask_offset) & 0x3];
buf[offset + i] = (unsigned char)(c ^ c_m);
}
CAMLreturn(Val_unit);
}