2021-07-03 02:56:00 +03:00
|
|
|
module websocket
|
|
|
|
|
|
|
|
import rand
|
|
|
|
import crypto.sha1
|
|
|
|
import encoding.base64
|
2023-05-18 12:27:00 +03:00
|
|
|
import encoding.binary
|
2021-07-03 02:56:00 +03:00
|
|
|
|
|
|
|
// htonl64 converts payload length to header bits
|
2022-04-15 15:35:35 +03:00
|
|
|
fn htonl64(payload_len u64) []u8 {
|
|
|
|
mut ret := []u8{len: 8}
|
2023-05-18 12:27:00 +03:00
|
|
|
binary.big_endian_put_u64(mut ret, payload_len)
|
2021-07-03 02:56:00 +03:00
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2023-05-12 09:31:27 +03:00
|
|
|
// create_masking_key returns a new masking key to use when masking websocket messages
|
2022-04-15 15:35:35 +03:00
|
|
|
fn create_masking_key() []u8 {
|
2023-05-18 12:27:00 +03:00
|
|
|
return rand.bytes(4) or { [0, 0, 0, 0] }
|
2021-07-03 02:56:00 +03:00
|
|
|
}
|
|
|
|
|
2023-05-12 09:31:27 +03:00
|
|
|
// create_key_challenge_response creates a key challenge response from security key
|
2022-10-16 09:28:57 +03:00
|
|
|
fn create_key_challenge_response(seckey string) !string {
|
2021-07-03 02:56:00 +03:00
|
|
|
if seckey.len == 0 {
|
2023-05-12 09:31:27 +03:00
|
|
|
return error('unexpected seckey length zero')
|
2021-07-03 02:56:00 +03:00
|
|
|
}
|
|
|
|
guid := '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
|
|
|
|
sha1buf := seckey + guid
|
|
|
|
shabytes := sha1buf.bytes()
|
|
|
|
hash := sha1.sum(shabytes)
|
|
|
|
b64 := base64.encode(hash)
|
|
|
|
unsafe {
|
|
|
|
hash.free()
|
|
|
|
shabytes.free()
|
|
|
|
}
|
|
|
|
return b64
|
|
|
|
}
|
|
|
|
|
|
|
|
// get_nonce creates a randomized array used in handshake process
|
|
|
|
fn get_nonce(nonce_size int) string {
|
2023-05-18 12:27:00 +03:00
|
|
|
return rand.string_from_set('0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz',
|
|
|
|
nonce_size)
|
2021-07-03 02:56:00 +03:00
|
|
|
}
|