1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
open Astring
let b64_encoded_sha1sum s = Sha1.sha_1 s |> B64.encode ~pad:true
let websocket_uuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
module Option = struct
let value ~default = function
| None -> default
| Some v -> v
let value_map ~default ~f = function
| None -> default
| Some v -> f v
let value_exn = function
| None -> invalid_arg "Option.value_exn"
| Some v -> v
let map ~f = function
| None -> None
| Some v -> Some (f v)
end
module Rng = struct
let init ?state () =
let state =
Option.value state ~default:(Random.self_init (); Random.get_state ()) in
fun len ->
String.v ~len (fun _ -> Char.of_byte (Random.State.bits state land 0xFF))
end
module Frame = struct
module Opcode = struct
type t =
| Continuation
| Text
| Binary
| Close
| Ping
| Pong
| Ctrl of int
| Nonctrl of int
let to_string = function
| Continuation -> "continuation"
| Text -> "text"
| Binary -> "binary"
| Close -> "close"
| Ping -> "ping"
| Pong -> "pong"
| Ctrl i -> "ctrl " ^ string_of_int i
| Nonctrl i -> "nonctrl " ^ string_of_int i
let pp ppf t = Format.fprintf ppf "%s" (to_string t)
let of_enum = function
| i when (i < 0 || i > 0xf) -> invalid_arg "Frame.Opcode.of_enum"
| 0 -> Continuation
| 1 -> Text
| 2 -> Binary
| 8 -> Close
| 9 -> Ping
| 10 -> Pong
| i when i < 8 -> Nonctrl i
| i -> Ctrl i
let to_enum = function
| Continuation -> 0
| Text -> 1
| Binary -> 2
| Close -> 8
| Ping -> 9
| Pong -> 10
| Ctrl i -> i
| Nonctrl i -> i
let is_ctrl opcode = to_enum opcode > 7
end
type t = {
opcode: Opcode.t ;
extension: int ;
final: bool ;
content: string ;
}
let pp ppf { opcode ; extension ; final ; content } =
Format.fprintf ppf
"[%a (0x%x) (final=%b) %s]" Opcode.pp opcode extension final content
let show t = Format.asprintf "%a" pp t
let create
?(opcode = Opcode.Text) ?(extension=0) ?(final=true) ?(content="") () =
{ opcode ; extension ; final ; content }
let of_bytes ?opcode ?extension ?final content =
let content = Bytes.unsafe_to_string content in
create ?opcode ?extension ?final ~content ()
let close code =
let content = Bytes.create 2 in
EndianBytes.BigEndian.set_int16 content 0 code;
of_bytes ~opcode:Opcode.Close content
end
let xor mask msg =
for i = 0 to Bytes.length msg - 1 do
Bytes.set msg i Char.(to_int mask.[i mod 4] lxor to_int (Bytes.get msg i) |> of_byte)
done
let is_bit_set idx v =
(v lsr idx) land 1 = 1
let set_bit v idx b =
if b then v lor (1 lsl idx) else v land (lnot (1 lsl idx))
let int_value shift len v = (v lsr shift) land ((1 lsl len) - 1)
let upgrade_present hs =
Cohttp.Header.get_multi hs "connection" |> fun hs ->
List.map (String.cuts ~sep:",") hs |> fun hs ->
List.flatten hs |> fun hs ->
List.map String.(fun h -> h |> String.Ascii.lowercase |> trim) hs |>
List.mem "upgrade"
exception Protocol_error of string
module IO(IO: Cohttp.S.IO) = struct
open IO
type mode =
| Client of (int -> string)
| Server
let is_client mode = mode <> Server
let rec read_exactly ic remaining buf =
read ic remaining >>= fun s ->
if s = "" then return None
else
let recv_len = String.length s in
Buffer.add_string buf s;
if remaining - recv_len <= 0 then return @@ Some (Buffer.contents buf)
else read_exactly ic (remaining - recv_len) buf
let read_uint16 ic buf =
read_exactly ic 2 buf >>= fun s ->
match s with
| None -> return None
| Some s ->
return @@ Some (EndianString.BigEndian.get_uint16 s 0)
let read_int64 ic buf =
read_exactly ic 8 buf >>= fun s ->
match s with
| None -> return None
| Some s ->
return @@ Some (Int64.to_int @@ EndianString.BigEndian.get_int64 s 0)
let write_frame_to_buf ~mode buf fr =
let scratch = Bytes.create 8 in
let open Frame in
let content = Bytes.unsafe_of_string fr.content in
let len = Bytes.length content in
let opcode = Opcode.to_enum fr.opcode in
let payload_len = match len with
| n when n < 126 -> len
| n when n < 1 lsl 16 -> 126
| _ -> 127
in
let hdr = set_bit 0 15 (fr.final) in
let hdr = hdr lor (opcode lsl 8) in
let hdr = set_bit hdr 7 (is_client mode) in
let hdr = hdr lor payload_len in
EndianBytes.BigEndian.set_int16 scratch 0 hdr;
Buffer.add_subbytes buf scratch 0 2;
begin match len with
| n when n < 126 -> ()
| n when n < (1 lsl 16) ->
EndianBytes.BigEndian.set_int16 scratch 0 n;
Buffer.add_subbytes buf scratch 0 2
| n ->
EndianBytes.BigEndian.set_int64 scratch 0 Int64.(of_int n);
Buffer.add_subbytes buf scratch 0 8;
end;
begin match mode with
| Server -> ()
| Client random_string ->
let mask = random_string 4 in
Buffer.add_string buf mask;
if len > 0 then xor mask content;
end;
Buffer.add_bytes buf content
let close_with_code mode buf oc code =
Buffer.clear buf;
write_frame_to_buf ~mode buf @@ Frame.close code;
write oc @@ Buffer.contents buf
let make_read_frame ?(buf=Buffer.create 128) ~mode ic oc = fun () ->
Buffer.clear buf;
read_exactly ic 2 buf >>= fun hdr ->
match hdr with
| None -> raise End_of_file
| Some hdr ->
let hdr_part1 = EndianString.BigEndian.get_int8 hdr 0 in
let hdr_part2 = EndianString.BigEndian.get_int8 hdr 1 in
let final = is_bit_set 7 hdr_part1 in
let extension = int_value 4 3 hdr_part1 in
let opcode = int_value 0 4 hdr_part1 in
let frame_masked = is_bit_set 7 hdr_part2 in
let length = int_value 0 7 hdr_part2 in
let opcode = Frame.Opcode.of_enum opcode in
Buffer.clear buf;
(match length with
| i when i < 126 -> return i
| 126 -> (read_uint16 ic buf >>= function Some i -> return i | None -> return @@ -1)
| 127 -> (read_int64 ic buf >>= function Some i -> return i | None -> return @@ -1)
| _ -> return @@ -1
) >>= fun payload_len ->
if payload_len = -1 then
raise (Protocol_error ("payload len = " ^ string_of_int length))
else if extension <> 0 then
close_with_code mode buf oc 1002 >>= fun () ->
raise (Protocol_error "unsupported extension")
else if Frame.Opcode.is_ctrl opcode && payload_len > 125 then
close_with_code mode buf oc 1002 >>= fun () ->
raise (Protocol_error "control frame too big")
else
(if frame_masked then
(Buffer.clear buf;
read_exactly ic 4 buf >>= function
| None -> raise (Protocol_error "could not read mask");
| Some mask -> return mask)
else return String.empty) >>= fun mask ->
if payload_len = 0 then
return @@ Frame.create ~opcode ~extension ~final ()
else
(Buffer.clear buf;
read_exactly ic payload_len buf) >>= fun payload ->
match payload with
| None -> raise (Protocol_error "could not read payload")
| Some payload ->
let payload = Bytes.unsafe_of_string payload in
if frame_masked then xor mask payload;
let frame = Frame.of_bytes ~opcode ~extension ~final payload in
return frame
end