2020-04-08 19:44:30 +02:00
|
|
|
module websocket
|
2020-04-08 14:22:31 +02:00
|
|
|
|
2020-04-26 13:49:31 +02:00
|
|
|
import rand
|
|
|
|
import crypto.sha1
|
|
|
|
import encoding.base64
|
2020-04-08 14:22:31 +02:00
|
|
|
|
|
|
|
fn htonl64(payload_len u64) byteptr {
|
|
|
|
mut ret := malloc(8)
|
|
|
|
ret[0] = byte(((payload_len & (u64(0xff) << 56)) >> 56) & 0xff)
|
|
|
|
ret[1] = byte(((payload_len & (u64(0xff) << 48)) >> 48) & 0xff)
|
|
|
|
ret[2] = byte(((payload_len & (u64(0xff) << 40)) >> 40) & 0xff)
|
|
|
|
ret[3] = byte(((payload_len & (u64(0xff) << 32)) >> 32) & 0xff)
|
|
|
|
ret[4] = byte(((payload_len & (u64(0xff) << 24)) >> 24) & 0xff)
|
|
|
|
ret[5] = byte(((payload_len & (u64(0xff) << 16)) >> 16) & 0xff)
|
|
|
|
ret[6] = byte(((payload_len & (u64(0xff) << 8)) >> 8) & 0xff)
|
2020-04-26 13:49:31 +02:00
|
|
|
ret[7] = byte(((payload_len & (u64(0xff) << 0)) >> 0) & 0xff)
|
2020-04-08 14:22:31 +02:00
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
fn create_masking_key() []byte {
|
2020-06-09 15:06:07 +02:00
|
|
|
mask_bit := byte(rand.intn(255))
|
2020-04-08 14:22:31 +02:00
|
|
|
buf := [`0`].repeat(4)
|
2020-07-22 16:31:22 +02:00
|
|
|
unsafe {
|
|
|
|
C.memcpy(buf.data, &mask_bit, 4)
|
|
|
|
}
|
2020-04-08 14:22:31 +02:00
|
|
|
return buf
|
|
|
|
}
|
|
|
|
|
|
|
|
fn create_key_challenge_response(seckey string) string {
|
2020-05-26 12:50:37 +02:00
|
|
|
guid := '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
|
2020-04-08 14:22:31 +02:00
|
|
|
sha1buf := seckey + guid
|
|
|
|
hash := sha1.sum(sha1buf.bytes())
|
|
|
|
hashstr := string(byteptr(hash.data))
|
|
|
|
b64 := base64.encode(hashstr)
|
|
|
|
unsafe {
|
|
|
|
sha1buf.free()
|
|
|
|
hash.free()
|
|
|
|
}
|
|
|
|
return b64
|
|
|
|
}
|
|
|
|
|
2020-06-01 19:31:45 +02:00
|
|
|
fn get_nonce(nonce_size int) string {
|
|
|
|
mut nonce := []byte{len: nonce_size, cap: nonce_size}
|
2020-05-26 12:50:37 +02:00
|
|
|
alphanum := '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz'
|
2020-06-01 19:31:45 +02:00
|
|
|
for i in 0 .. nonce_size {
|
2020-06-09 15:06:07 +02:00
|
|
|
nonce[i] = alphanum[rand.intn(alphanum.len)]
|
2020-04-08 14:22:31 +02:00
|
|
|
}
|
2020-06-01 19:31:45 +02:00
|
|
|
return tos(nonce.data, nonce.len).clone()
|
2020-05-26 12:50:37 +02:00
|
|
|
}
|