Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
hybi00.hpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2014, Peter Thorson. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 * * Redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer.
8 * * Redistributions in binary form must reproduce the above copyright
9 * notice, this list of conditions and the following disclaimer in the
10 * documentation and/or other materials provided with the distribution.
11 * * Neither the name of the WebSocket++ Project nor the
12 * names of its contributors may be used to endorse or promote products
13 * derived from this software without specific prior written permission.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
19 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 *
26 */
27
28#ifndef WEBSOCKETPP_PROCESSOR_HYBI00_HPP
29#define WEBSOCKETPP_PROCESSOR_HYBI00_HPP
30
31#include <websocketpp/frame.hpp>
33
38
40
41#include <algorithm>
42#include <cstdlib>
43#include <string>
44#include <vector>
45
46namespace websocketpp {
47namespace processor {
48
50
53template <typename config>
54class hybi00 : public processor<config> {
55public:
57
58 typedef typename config::request_type request_type;
59 typedef typename config::response_type response_type;
60
61 typedef typename config::message_type message_type;
62 typedef typename message_type::ptr message_ptr;
63
64 typedef typename config::con_msg_manager_type::ptr msg_manager_ptr;
65
66 explicit hybi00(bool secure, bool p_is_server, msg_manager_ptr manager)
67 : processor<config>(secure, p_is_server)
68 , msg_hdr(0x00)
69 , msg_ftr(0xff)
70 , m_state(HEADER)
71 , m_msg_manager(manager) {}
72
73 int get_version() const {
74 return 0;
75 }
76
77 lib::error_code validate_handshake(request_type const & r) const {
78 if (r.get_method() != "GET") {
79 return make_error_code(error::invalid_http_method);
80 }
81
82 if (r.get_version() != "HTTP/1.1") {
83 return make_error_code(error::invalid_http_version);
84 }
85
86 // required headers
87 // Host is required by HTTP/1.1
88 // Connection is required by is_websocket_handshake
89 // Upgrade is required by is_websocket_handshake
90 if (r.get_header("Sec-WebSocket-Key1").empty() ||
91 r.get_header("Sec-WebSocket-Key2").empty() ||
92 r.get_header("Sec-WebSocket-Key3").empty())
93 {
94 return make_error_code(error::missing_required_header);
95 }
96
97 return lib::error_code();
98 }
99
100 lib::error_code process_handshake(request_type const & req,
101 std::string const & subprotocol, response_type & res) const
102 {
103 char key_final[16];
104
105 // copy key1 into final key
106 decode_client_key(req.get_header("Sec-WebSocket-Key1"), &key_final[0]);
107
108 // copy key2 into final key
109 decode_client_key(req.get_header("Sec-WebSocket-Key2"), &key_final[4]);
110
111 // copy key3 into final key
112 // key3 should be exactly 8 bytes. If it is more it will be truncated
113 // if it is less the final key will almost certainly be wrong.
114 // TODO: decide if it is best to silently fail here or produce some sort
115 // of warning or exception.
116 std::string const & key3 = req.get_header("Sec-WebSocket-Key3");
117 std::copy(key3.c_str(),
118 key3.c_str()+(std::min)(static_cast<size_t>(8), key3.size()),
119 &key_final[8]);
120
121 res.append_header(
122 "Sec-WebSocket-Key3",
123 md5::md5_hash_string(std::string(key_final,16))
124 );
125
126 res.append_header("Upgrade","WebSocket");
127 res.append_header("Connection","Upgrade");
128
129 // Echo back client's origin unless our local application set a
130 // more restrictive one.
131 if (res.get_header("Sec-WebSocket-Origin").empty()) {
132 res.append_header("Sec-WebSocket-Origin",req.get_header("Origin"));
133 }
134
135 // Echo back the client's request host unless our local application
136 // set a different one.
137 if (res.get_header("Sec-WebSocket-Location").empty()) {
138 uri_ptr uri = get_uri(req);
139 res.append_header("Sec-WebSocket-Location",uri->str());
140 }
141
142 if (!subprotocol.empty()) {
143 res.replace_header("Sec-WebSocket-Protocol",subprotocol);
144 }
145
146 return lib::error_code();
147 }
148
150
159 std::vector<std::string> const &) const
160 {
162 }
163
165
178
179 std::string get_raw(response_type const & res) const {
180 response_type temp = res;
181 temp.remove_header("Sec-WebSocket-Key3");
182 return temp.raw() + res.get_header("Sec-WebSocket-Key3");
183 }
184
185 std::string const & get_origin(request_type const & r) const {
186 return r.get_header("Origin");
187 }
188
190
198 lib::error_code extract_subprotocols(request_type const & req,
199 std::vector<std::string> & subprotocol_list)
200 {
201 if (!req.get_header("Sec-WebSocket-Protocol").empty()) {
202 http::parameter_list p;
203
204 if (!req.get_header_as_plist("Sec-WebSocket-Protocol",p)) {
205 http::parameter_list::const_iterator it;
206
207 for (it = p.begin(); it != p.end(); ++it) {
208 subprotocol_list.push_back(it->first);
209 }
210 } else {
212 }
213 }
214 return lib::error_code();
215 }
216
217 uri_ptr get_uri(request_type const & request) const {
218 std::string h = request.get_header("Host");
219
220 size_t last_colon = h.rfind(":");
221 size_t last_sbrace = h.rfind("]");
222
223 // no : = hostname with no port
224 // last : before ] = ipv6 literal with no port
225 // : with no ] = hostname with port
226 // : after ] = ipv6 literal with port
227
228 if (last_colon == std::string::npos ||
229 (last_sbrace != std::string::npos && last_sbrace > last_colon))
230 {
231 return lib::make_shared<uri>(base::m_secure, h, request.get_uri());
232 } else {
233 return lib::make_shared<uri>(base::m_secure,
234 h.substr(0,last_colon),
235 h.substr(last_colon+1),
236 request.get_uri());
237 }
238
239 // TODO: check if get_uri is a full uri
240 }
241
243
247 std::string get_key3() const {
248 return "";
249 }
250
252 size_t consume(uint8_t * buf, size_t len, lib::error_code & ec) {
253 // if in state header we are expecting a 0x00 byte, if we don't get one
254 // it is a fatal error
255 size_t p = 0; // bytes processed
256 size_t l = 0;
257
258 ec = lib::error_code();
259
260 while (p < len) {
261 if (m_state == HEADER) {
262 if (buf[p] == msg_hdr) {
263 p++;
264 m_msg_ptr = m_msg_manager->get_message(frame::opcode::text,1);
265
266 if (!m_msg_ptr) {
267 ec = make_error_code(websocketpp::error::no_incoming_buffers);
268 m_state = FATAL_ERROR;
269 } else {
270 m_state = PAYLOAD;
271 }
272 } else {
273 ec = make_error_code(error::protocol_violation);
274 m_state = FATAL_ERROR;
275 }
276 } else if (m_state == PAYLOAD) {
277 uint8_t *it = std::find(buf+p,buf+len,msg_ftr);
278
279 // 0 1 2 3 4 5
280 // 0x00 0x23 0x23 0x23 0xff 0xXX
281
282 // Copy payload bytes into message
283 l = static_cast<size_t>(it-(buf+p));
284 m_msg_ptr->append_payload(buf+p,l);
285 p += l;
286
287 if (it != buf+len) {
288 // message is done, copy it and the trailing
289 p++;
290 // TODO: validation
291 m_state = READY;
292 }
293 } else {
294 // TODO
295 break;
296 }
297 }
298 // If we get one, we create a new message and move to application state
299
300 // if in state application we are copying bytes into the output message
301 // and validating them for UTF8 until we hit a 0xff byte. Once we hit
302 // 0x00, the message is complete and is dispatched. Then we go back to
303 // header state.
304
305 //ec = make_error_code(error::not_implemented);
306 return p;
307 }
308
309 bool ready() const {
310 return (m_state == READY);
311 }
312
313 bool get_error() const {
314 return false;
315 }
316
318 message_ptr ret = m_msg_ptr;
319 m_msg_ptr = message_ptr();
320 m_state = HEADER;
321 return ret;
322 }
323
325
329 virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
330 {
331 if (!in || !out) {
332 return make_error_code(error::invalid_arguments);
333 }
334
335 // TODO: check if the message is prepared already
336
337 // validate opcode
338 if (in->get_opcode() != frame::opcode::text) {
339 return make_error_code(error::invalid_opcode);
340 }
341
342 std::string& i = in->get_raw_payload();
343 //std::string& o = out->get_raw_payload();
344
345 // validate payload utf8
346 if (!utf8_validator::validate(i)) {
347 return make_error_code(error::invalid_payload);
348 }
349
350 // generate header
351 out->set_header(std::string(reinterpret_cast<char const *>(&msg_hdr),1));
352
353 // process payload
354 out->set_payload(i);
355 out->append_payload(std::string(reinterpret_cast<char const *>(&msg_ftr),1));
356
357 // hybi00 doesn't support compression
358 // hybi00 doesn't have masking
359
360 out->set_prepared(true);
361
362 return lib::error_code();
363 }
364
366
373 lib::error_code prepare_ping(std::string const &, message_ptr) const
374 {
375 return lib::error_code(error::no_protocol_support);
376 }
377
379
386 lib::error_code prepare_pong(std::string const &, message_ptr) const
387 {
388 return lib::error_code(error::no_protocol_support);
389 }
390
392
401 lib::error_code prepare_close(close::status::value, std::string const &,
402 message_ptr out) const
403 {
404 if (!out) {
405 return lib::error_code(error::invalid_arguments);
406 }
407
408 std::string val;
409 val.append(1,'\xff');
410 val.append(1,'\x00');
411 out->set_payload(val);
412 out->set_prepared(true);
413
414 return lib::error_code();
415 }
416private:
417 void decode_client_key(std::string const & key, char * result) const {
418 unsigned int spaces = 0;
419 std::string digits;
420 uint32_t num;
421
422 // key2
423 for (size_t i = 0; i < key.size(); i++) {
424 if (key[i] == ' ') {
425 spaces++;
426 } else if (key[i] >= '0' && key[i] <= '9') {
427 digits += key[i];
428 }
429 }
430
431 num = static_cast<uint32_t>(strtoul(digits.c_str(), NULL, 10));
432 if (spaces > 0 && num > 0) {
433 num = htonl(num/spaces);
434 std::copy(reinterpret_cast<char*>(&num),
435 reinterpret_cast<char*>(&num)+4,
436 result);
437 } else {
438 std::fill(result,result+4,0);
439 }
440 }
441
442 enum state {
443 HEADER = 0,
444 PAYLOAD = 1,
445 READY = 2,
446 FATAL_ERROR = 3
447 };
448
449 uint8_t const msg_hdr;
450 uint8_t const msg_ftr;
451
452 state m_state;
453
454 msg_manager_ptr m_msg_manager;
455 message_ptr m_msg_ptr;
456 utf8_validator::validator m_validator;
457};
458
459} // namespace processor
460} // namespace websocketpp
461
462#endif //WEBSOCKETPP_PROCESSOR_HYBI00_HPP
const mie::Vuint & p
Definition bn.cpp:27
const mie::Vuint & r
Definition bn.cpp:28
Processor for Hybi Draft version 00.
Definition hybi00.hpp:54
config::request_type request_type
Definition hybi00.hpp:58
std::string get_raw(response_type const &res) const
Given a completed response, get the raw bytes to put on the wire.
Definition hybi00.hpp:179
lib::error_code prepare_ping(std::string const &, message_ptr) const
Prepare a ping frame.
Definition hybi00.hpp:373
lib::error_code prepare_pong(std::string const &, message_ptr) const
Prepare a pong frame.
Definition hybi00.hpp:386
lib::error_code process_handshake(request_type const &req, std::string const &subprotocol, response_type &res) const
Calculate the appropriate response for this websocket request.
Definition hybi00.hpp:100
processor< config > base
Definition hybi00.hpp:56
lib::error_code client_handshake_request(request_type &, uri_ptr, std::vector< std::string > const &) const
Fill in a set of request headers for a client connection request.
Definition hybi00.hpp:158
message_type::ptr message_ptr
Definition hybi00.hpp:62
std::string get_key3() const
Get hybi00 handshake key3.
Definition hybi00.hpp:247
config::con_msg_manager_type::ptr msg_manager_ptr
Definition hybi00.hpp:64
size_t consume(uint8_t *buf, size_t len, lib::error_code &ec)
Process new websocket connection bytes.
Definition hybi00.hpp:252
bool get_error() const
Tests whether the processor is in a fatal error state.
Definition hybi00.hpp:313
bool ready() const
Checks if there is a message ready.
Definition hybi00.hpp:309
lib::error_code validate_server_handshake_response(request_type const &, response_type &) const
Validate the server's response to an outgoing handshake request.
Definition hybi00.hpp:173
config::message_type message_type
Definition hybi00.hpp:61
lib::error_code prepare_close(close::status::value, std::string const &, message_ptr out) const
Prepare a close frame.
Definition hybi00.hpp:401
virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
Prepare a message for writing.
Definition hybi00.hpp:329
lib::error_code validate_handshake(request_type const &r) const
validate a WebSocket handshake request for this version
Definition hybi00.hpp:77
int get_version() const
Get the protocol version of this processor.
Definition hybi00.hpp:73
uri_ptr get_uri(request_type const &request) const
Extracts client uri from a handshake request.
Definition hybi00.hpp:217
config::response_type response_type
Definition hybi00.hpp:59
lib::error_code extract_subprotocols(request_type const &req, std::vector< std::string > &subprotocol_list)
Extracts requested subprotocols from a handshake request.
Definition hybi00.hpp:198
hybi00(bool secure, bool p_is_server, msg_manager_ptr manager)
Definition hybi00.hpp:66
std::string const & get_origin(request_type const &r) const
Return the value of the header containing the CORS origin.
Definition hybi00.hpp:185
message_ptr get_message()
Retrieves the most recently processed message.
Definition hybi00.hpp:317
WebSocket protocol processor abstract base class.
std::string str() const
Definition uri.hpp:273
websocketpp::config::asio_tls_client::message_type::ptr message_ptr
uint16_t value
The type of a close code value.
Definition close.hpp:49
@ no_incoming_buffers
The endpoint is out of incoming message buffers.
Definition error.hpp:71
std::string md5_hash_string(std::string const &s)
Definition md5.hpp:415
@ missing_required_header
Missing Required Header.
Definition base.hpp:129
@ invalid_http_method
Invalid HTTP method.
Definition base.hpp:120
@ protocol_violation
Processor encountered a protocol violation in an incoming message.
Definition base.hpp:75
@ invalid_opcode
Opcode was invalid for requested operation.
Definition base.hpp:87
@ subprotocol_parse_error
Error parsing subprotocols.
Definition base.hpp:147
@ invalid_payload
Processor encountered invalid payload data.
Definition base.hpp:81
@ invalid_http_version
Invalid HTTP version.
Definition base.hpp:123
@ no_protocol_support
No support for this feature in this protocol version.
Definition base.hpp:135
@ invalid_arguments
The processor method was called with invalid arguments.
Definition base.hpp:84
lib::error_code make_error_code(error::processor_errors e)
Create an error code with the given value and the processor category.
Definition base.hpp:244
bool validate(std::string const &s)
Validate a UTF8 string.
Namespace for the WebSocket++ project.
Definition base64.hpp:41
lib::shared_ptr< uri > uri_ptr
Pointer to a URI.
Definition uri.hpp:351
unsigned int uint32_t
Definition stdint.h:126
unsigned char uint8_t
Definition stdint.h:124
CK_RV ret
size_t len
uint8_t buf[2048]
int l