1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

net.websocket: make thread safe/concurrent (#18179)

This commit is contained in:
kbkpbot
2023-05-18 17:27:00 +08:00
committed by GitHub
parent 1e88b1ab3e
commit c8d2098a14
8 changed files with 109 additions and 73 deletions

View File

@ -3,27 +3,18 @@ module websocket
import rand
import crypto.sha1
import encoding.base64
import encoding.binary
// htonl64 converts payload length to header bits
fn htonl64(payload_len u64) []u8 {
mut ret := []u8{len: 8}
ret[0] = u8(((payload_len & (u64(0xff) << 56)) >> 56) & 0xff)
ret[1] = u8(((payload_len & (u64(0xff) << 48)) >> 48) & 0xff)
ret[2] = u8(((payload_len & (u64(0xff) << 40)) >> 40) & 0xff)
ret[3] = u8(((payload_len & (u64(0xff) << 32)) >> 32) & 0xff)
ret[4] = u8(((payload_len & (u64(0xff) << 24)) >> 24) & 0xff)
ret[5] = u8(((payload_len & (u64(0xff) << 16)) >> 16) & 0xff)
ret[6] = u8(((payload_len & (u64(0xff) << 8)) >> 8) & 0xff)
ret[7] = u8(((payload_len & (u64(0xff) << 0)) >> 0) & 0xff)
binary.big_endian_put_u64(mut ret, payload_len)
return ret
}
// create_masking_key returns a new masking key to use when masking websocket messages
fn create_masking_key() []u8 {
mask_bit := rand.u8()
buf := []u8{len: 4, init: `0`}
unsafe { C.memcpy(buf.data, &mask_bit, 4) }
return buf
return rand.bytes(4) or { [0, 0, 0, 0] }
}
// create_key_challenge_response creates a key challenge response from security key
@ -45,10 +36,6 @@ fn create_key_challenge_response(seckey string) !string {
// get_nonce creates a randomized array used in handshake process
fn get_nonce(nonce_size int) string {
mut nonce := []u8{len: nonce_size, cap: nonce_size}
alphanum := '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz'
for i in 0 .. nonce_size {
nonce[i] = alphanum[rand.intn(alphanum.len) or { 0 }]
}
return unsafe { tos(nonce.data, nonce.len) }.clone()
return rand.string_from_set('0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz',
nonce_size)
}