lib: remove remaining declaration of old-style attributes.
[nit.git] / lib / websocket.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Lucas Bajolet <r4pass@hotmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Adds support for a websocket connection in Nit
18 # Uses standard sockets
19 module websocket
20
21 import socket
22 import sha1
23 import base64
24
25 intrude import standard::stream
26
27 # Websocket compatible server, works as an extra layer to the original Sockets
28 class WebSocket
29 super BufferedIStream
30 super OStream
31 super PollableIStream
32
33 # Client connection to the server
34 var client: Socket
35
36 # Socket listening to connections on a defined port
37 var listener: Socket
38
39 # Creates a new Websocket server listening on given port with `max_clients` slots available
40 init(port: Int, max_clients: Int)
41 do
42 _buffer = new FlatBuffer
43 _buffer_pos = 0
44 listener = new Socket.server(port, max_clients)
45 end
46
47 # Accept an incoming connection and initializes the handshake
48 fun accept
49 do
50 assert not listener.eof
51
52 client = listener.accept
53
54 var headers = parse_handshake
55 var resp = handshake_response(headers)
56
57 client.write(resp)
58 end
59
60 # Disconnect from a client
61 fun disconnect_client
62 do
63 client.close
64 end
65
66 # Disconnects the client if one is connected
67 # And stops the server
68 redef fun close
69 do
70 client.close
71 listener.close
72 end
73
74 # Parses the input handshake sent by the client
75 # See RFC 6455 for information
76 private fun parse_handshake: Map[String,String]
77 do
78 var recved = read_http_frame(new FlatBuffer)
79 var headers = recved.split("\r\n")
80 var headmap = new HashMap[String,String]
81 for i in headers do
82 var temp_head = i.split(" ")
83 var head = temp_head.shift
84 if head.is_empty or head.length == 1 then continue
85 if head.chars.last == ':' then
86 head = head.substring(0, head.length - 1)
87 end
88 var body = temp_head.join(" ")
89 headmap[head] = body
90 end
91 return headmap
92 end
93
94 # Generates the handshake
95 private fun handshake_response(heads: Map[String,String]): String
96 do
97 var resp_map = new HashMap[String,String]
98 resp_map["HTTP/1.1"] = "101 Switching Protocols"
99 resp_map["Upgrade:"] = "websocket"
100 resp_map["Connection:"] = "Upgrade"
101 var key = heads["Sec-WebSocket-Key"]
102 key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
103 key = key.sha1.encode_base64
104 resp_map["Sec-WebSocket-Accept:"] = key
105 var resp = resp_map.join("\r\n", " ")
106 resp += "\r\n\r\n"
107 return resp
108 end
109
110 # Frames a text message to be sent to a client
111 private fun frame_message(msg: String): String
112 do
113 var ans_buffer = new FlatBuffer
114 # Flag for final frame set to 1
115 # opcode set to 1 (for text)
116 ans_buffer.add(129.ascii)
117 if msg.length < 126 then
118 ans_buffer.add(msg.length.ascii)
119 end
120 if msg.length >= 126 and msg.length <= 65535 then
121 ans_buffer.add(126.ascii)
122 ans_buffer.add(msg.length.rshift(8).ascii)
123 ans_buffer.add(msg.length.ascii)
124 end
125 ans_buffer.append(msg)
126 return ans_buffer.to_s
127 end
128
129 # Reads an HTTP frame
130 protected fun read_http_frame(buf: Buffer): String
131 do
132 client.append_line_to(buf)
133 buf.chars.add('\n')
134 if buf.has_substring("\r\n\r\n", buf.length - 4) then return buf.to_s
135 return read_http_frame(buf)
136 end
137
138 # Gets the message from the client, unpads it and reconstitutes the message
139 private fun unpad_message do
140 var fin = false
141 while not fin do
142 var fst_char = client.read_char
143 var snd_char = client.read_char
144 # First byte in msg is formatted this way :
145 # |(fin - 1bit)|(RSV1 - 1bit)|(RSV2 - 1bit)|(RSV3 - 1bit)|(opcode - 4bits)
146 # fin = Flag indicating if current frame is the last one
147 # RSV1/2/3 = Extension flags, unsupported
148 # Opcode values :
149 # %x0 denotes a continuation frame
150 # %x1 denotes a text frame
151 # %x2 denotes a binary frame
152 # %x3-7 are reserved for further non-control frames
153 # %x8 denotes a connection close
154 # %x9 denotes a ping
155 # %xA denotes a pong
156 # %xB-F are reserved for further control frames
157 var fin_flag = fst_char.bin_and(128)
158 if fin_flag != 0 then fin = true
159 var opcode = fst_char.bin_and(15)
160 if opcode == 9 then
161 _buffer.add(138.ascii)
162 _buffer.add('\0')
163 client.write(_buffer.to_s)
164 _buffer_pos += 2
165 return
166 end
167 if opcode == 8 then
168 self.client.close
169 return
170 end
171 # Second byte is formatted this way :
172 # |(mask - 1bit)|(payload length - 7 bits)
173 # As specified, if the payload length is 126 or 127
174 # The next 16 or 64 bits contain an extended payload length
175 var mask_flag = snd_char.bin_and(128)
176 var len = snd_char.bin_and(127)
177 var payload_ext_len = 0
178 if len == 126 then
179 payload_ext_len = client.read_char.lshift(8)
180 payload_ext_len += client.read_char
181 else if len == 127 then
182 # 64 bits for length are not supported,
183 # only the last 32 will be interpreted as a Nit Integer
184 for i in [0..4[ do client.read_char
185 payload_ext_len = client.read_char.lshift(24)
186 payload_ext_len += client.read_char.lshift(16)
187 payload_ext_len += client.read_char.lshift(8)
188 payload_ext_len += client.read_char
189 end
190 if mask_flag != 0 then
191 if payload_ext_len != 0 then
192 var msg = client.read(payload_ext_len+4)
193 var mask = msg.substring(0,4)
194 _buffer.append(unmask_message(mask, msg.substring(4, payload_ext_len)))
195 else
196 if len == 0 then
197 return
198 end
199 var msg = client.read(len+4)
200 var mask = msg.substring(0,4)
201 _buffer.append(unmask_message(mask, msg.substring(4, len)))
202 end
203 end
204 end
205 end
206
207 # Unmasks a message sent by a client
208 private fun unmask_message(key: String, message: String): String
209 do
210 var return_message = new FlatBuffer.with_capacity(message.length)
211 var msg_iter = message.chars.iterator
212
213 while msg_iter.is_ok do
214 return_message.chars[msg_iter.index] = msg_iter.item.ascii.bin_xor(key.chars[msg_iter.index%4].ascii).ascii
215 msg_iter.next
216 end
217
218 return return_message.to_s
219 end
220
221 # Checks if a connection to a client is available
222 fun connected: Bool do return client.connected
223
224 redef fun write(msg: Text)
225 do
226 client.write(frame_message(msg.to_s))
227 end
228
229 redef fun is_writable do return client.connected
230
231 redef fun fill_buffer
232 do
233 _buffer.clear
234 _buffer_pos = 0
235 unpad_message
236 end
237
238 redef fun end_reached do return _buffer_pos >= _buffer.length and client.eof
239
240 # Is there some data available to be read ?
241 fun can_read(timeout: Int): Bool do return client.ready_to_read(timeout)
242
243 redef fun poll_in do return client.poll_in
244
245 end
246