2 * Copyright (c) 2014, Peter Thorson. All rights reserved.
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.
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.
28 #ifndef WEBSOCKETPP_PROCESSOR_HYBI00_HPP
29 #define WEBSOCKETPP_PROCESSOR_HYBI00_HPP
31 #include <websocketpp/frame.hpp>
32 #include <websocketpp/http/constants.hpp>
34 #include <websocketpp/utf8_validator.hpp>
35 #include <websocketpp/common/network.hpp>
36 #include <websocketpp/common/md5.hpp>
37 #include <websocketpp/common/platforms.hpp>
39 #include <websocketpp/processors/processor.hpp>
46 namespace websocketpp {
49 /// Processor for Hybi Draft version 00
51 * There are many differences between Hybi 00 and Hybi 13
53 template <typename config>
54 class hybi00 : public processor<config> {
56 typedef processor<config> base;
58 typedef typename config::request_type request_type;
59 typedef typename config::response_type response_type;
61 typedef typename config::message_type message_type;
62 typedef typename message_type::ptr message_ptr;
64 typedef typename config::con_msg_manager_type::ptr msg_manager_ptr;
66 explicit hybi00(bool secure, bool p_is_server, msg_manager_ptr manager)
67 : processor<config>(secure, p_is_server)
71 , m_msg_manager(manager) {}
73 int get_version() const {
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);
82 if (r.get_version() != "HTTP/1.1") {
83 return make_error_code(error::invalid_http_version);
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())
94 return make_error_code(error::missing_required_header);
97 return lib::error_code();
100 lib::error_code process_handshake(request_type const & req,
101 std::string const & subprotocol, response_type & res) const
105 // copy key1 into final key
106 decode_client_key(req.get_header("Sec-WebSocket-Key1"), &key_final[0]);
108 // copy key2 into final key
109 decode_client_key(req.get_header("Sec-WebSocket-Key2"), &key_final[4]);
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()),
122 "Sec-WebSocket-Key3",
123 md5::md5_hash_string(std::string(key_final,16))
126 res.append_header("Upgrade","WebSocket");
127 res.append_header("Connection","Upgrade");
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"));
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());
142 if (!subprotocol.empty()) {
143 res.replace_header("Sec-WebSocket-Protocol",subprotocol);
146 return lib::error_code();
149 /// Fill in a set of request headers for a client connection request
151 * The Hybi 00 processor only implements incoming connections so this will
152 * always return an error.
154 * @param [out] req Set of headers to fill in
155 * @param [in] uri The uri being connected to
156 * @param [in] subprotocols The list of subprotocols to request
158 lib::error_code client_handshake_request(request_type &, uri_ptr,
159 std::vector<std::string> const &) const
161 return error::make_error_code(error::no_protocol_support);
164 /// Validate the server's response to an outgoing handshake request
166 * The Hybi 00 processor only implements incoming connections so this will
167 * always return an error.
169 * @param req The original request sent
170 * @param res The reponse to generate
171 * @return An error code, 0 on success, non-zero for other errors
173 lib::error_code validate_server_handshake_response(request_type const &,
174 response_type &) const
176 return error::make_error_code(error::no_protocol_support);
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");
185 std::string const & get_origin(request_type const & r) const {
186 return r.get_header("Origin");
189 /// Extracts requested subprotocols from a handshake request
191 * hybi00 does support subprotocols
192 * https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.9
194 * @param [in] req The request to extract from
195 * @param [out] subprotocol_list A reference to a vector of strings to store
198 lib::error_code extract_subprotocols(request_type const & req,
199 std::vector<std::string> & subprotocol_list)
201 if (!req.get_header("Sec-WebSocket-Protocol").empty()) {
202 http::parameter_list p;
204 if (!req.get_header_as_plist("Sec-WebSocket-Protocol",p)) {
205 http::parameter_list::const_iterator it;
207 for (it = p.begin(); it != p.end(); ++it) {
208 subprotocol_list.push_back(it->first);
211 return error::make_error_code(error::subprotocol_parse_error);
214 return lib::error_code();
217 uri_ptr get_uri(request_type const & request) const {
218 std::string h = request.get_header("Host");
220 size_t last_colon = h.rfind(":");
221 size_t last_sbrace = h.rfind("]");
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
228 if (last_colon == std::string::npos ||
229 (last_sbrace != std::string::npos && last_sbrace > last_colon))
231 return lib::make_shared<uri>(base::m_secure, h, request.get_uri());
233 return lib::make_shared<uri>(base::m_secure,
234 h.substr(0,last_colon),
235 h.substr(last_colon+1),
239 // TODO: check if get_uri is a full uri
242 /// Get hybi00 handshake key3
244 * @todo This doesn't appear to be used anymore. It might be able to be
247 std::string get_key3() const {
251 /// Process new websocket connection bytes
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
258 ec = lib::error_code();
261 if (m_state == HEADER) {
262 if (buf[p] == msg_hdr) {
264 m_msg_ptr = m_msg_manager->get_message(frame::opcode::text,1);
267 ec = make_error_code(websocketpp::error::no_incoming_buffers);
268 m_state = FATAL_ERROR;
273 ec = make_error_code(error::protocol_violation);
274 m_state = FATAL_ERROR;
276 } else if (m_state == PAYLOAD) {
277 uint8_t *it = std::find(buf+p,buf+len,msg_ftr);
280 // 0x00 0x23 0x23 0x23 0xff 0xXX
282 // Copy payload bytes into message
283 l = static_cast<size_t>(it-(buf+p));
284 m_msg_ptr->append_payload(buf+p,l);
288 // message is done, copy it and the trailing
298 // If we get one, we create a new message and move to application state
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
305 //ec = make_error_code(error::not_implemented);
310 return (m_state == READY);
313 bool get_error() const {
317 message_ptr get_message() {
318 message_ptr ret = m_msg_ptr;
319 m_msg_ptr = message_ptr();
324 /// Prepare a message for writing
326 * Performs validation, masking, compression, etc. will return an error if
327 * there was an error, otherwise msg will be ready to be written
329 virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
332 return make_error_code(error::invalid_arguments);
335 // TODO: check if the message is prepared already
338 if (in->get_opcode() != frame::opcode::text) {
339 return make_error_code(error::invalid_opcode);
342 std::string& i = in->get_raw_payload();
343 //std::string& o = out->get_raw_payload();
345 // validate payload utf8
346 if (!utf8_validator::validate(i)) {
347 return make_error_code(error::invalid_payload);
351 out->set_header(std::string(reinterpret_cast<char const *>(&msg_hdr),1));
355 out->append_payload(std::string(reinterpret_cast<char const *>(&msg_ftr),1));
357 // hybi00 doesn't support compression
358 // hybi00 doesn't have masking
360 out->set_prepared(true);
362 return lib::error_code();
365 /// Prepare a ping frame
367 * Hybi 00 doesn't support pings so this will always return an error
369 * @param in The string to use for the ping payload
370 * @param out The message buffer to prepare the ping in.
371 * @return Status code, zero on success, non-zero on failure
373 lib::error_code prepare_ping(std::string const &, message_ptr) const
375 return lib::error_code(error::no_protocol_support);
378 /// Prepare a pong frame
380 * Hybi 00 doesn't support pongs so this will always return an error
382 * @param in The string to use for the pong payload
383 * @param out The message buffer to prepare the pong in.
384 * @return Status code, zero on success, non-zero on failure
386 lib::error_code prepare_pong(std::string const &, message_ptr) const
388 return lib::error_code(error::no_protocol_support);
391 /// Prepare a close frame
393 * Hybi 00 doesn't support the close code or reason so these parameters are
396 * @param code The close code to send
397 * @param reason The reason string to send
398 * @param out The message buffer to prepare the fame in
399 * @return Status code, zero on success, non-zero on failure
401 lib::error_code prepare_close(close::status::value, std::string const &,
402 message_ptr out) const
405 return lib::error_code(error::invalid_arguments);
409 val.append(1,'\xff');
410 val.append(1,'\x00');
411 out->set_payload(val);
412 out->set_prepared(true);
414 return lib::error_code();
417 void decode_client_key(std::string const & key, char * result) const {
418 unsigned int spaces = 0;
423 for (size_t i = 0; i < key.size(); i++) {
426 } else if (key[i] >= '0' && key[i] <= '9') {
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,
438 std::fill(result,result+4,0);
449 uint8_t const msg_hdr;
450 uint8_t const msg_ftr;
454 msg_manager_ptr m_msg_manager;
455 message_ptr m_msg_ptr;
456 utf8_validator::validator m_validator;
459 } // namespace processor
460 } // namespace websocketpp
462 #endif //WEBSOCKETPP_PROCESSOR_HYBI00_HPP