websocketpp  0.6.0
C++/Boost Asio based websocket client/server library
hybi00.hpp
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>
32 #include <websocketpp/utf8_validator.hpp>
33 #include <websocketpp/common/network.hpp>
34 #include <websocketpp/common/md5.hpp>
35 #include <websocketpp/common/platforms.hpp>
36 
37 #include <websocketpp/processors/processor.hpp>
38 
39 #include <algorithm>
40 #include <cstdlib>
41 #include <string>
42 #include <vector>
43 
44 namespace websocketpp {
45 namespace processor {
46 
48 
51 template <typename config>
52 class hybi00 : public processor<config> {
53 public:
54  typedef processor<config> base;
55 
56  typedef typename config::request_type request_type;
57  typedef typename config::response_type response_type;
58 
59  typedef typename config::message_type message_type;
60  typedef typename message_type::ptr message_ptr;
61 
62  typedef typename config::con_msg_manager_type::ptr msg_manager_ptr;
63 
64  explicit hybi00(bool secure, bool p_is_server, msg_manager_ptr manager)
65  : processor<config>(secure, p_is_server)
66  , msg_hdr(0x00)
67  , msg_ftr(0xff)
68  , m_state(HEADER)
69  , m_msg_manager(manager) {}
70 
71  int get_version() const {
72  return 0;
73  }
74 
75  lib::error_code validate_handshake(request_type const & r) const {
76  if (r.get_method() != "GET") {
77  return make_error_code(error::invalid_http_method);
78  }
79 
80  if (r.get_version() != "HTTP/1.1") {
81  return make_error_code(error::invalid_http_version);
82  }
83 
84  // required headers
85  // Host is required by HTTP/1.1
86  // Connection is required by is_websocket_handshake
87  // Upgrade is required by is_websocket_handshake
88  if (r.get_header("Sec-WebSocket-Key1") == "" ||
89  r.get_header("Sec-WebSocket-Key2") == "" ||
90  r.get_header("Sec-WebSocket-Key3") == "")
91  {
92  return make_error_code(error::missing_required_header);
93  }
94 
95  return lib::error_code();
96  }
97 
98  lib::error_code process_handshake(request_type const & req,
99  std::string const & subprotocol, response_type & res) const
100  {
101  char key_final[16];
102 
103  // copy key1 into final key
104  decode_client_key(req.get_header("Sec-WebSocket-Key1"), &key_final[0]);
105 
106  // copy key2 into final key
107  decode_client_key(req.get_header("Sec-WebSocket-Key2"), &key_final[4]);
108 
109  // copy key3 into final key
110  // key3 should be exactly 8 bytes. If it is more it will be truncated
111  // if it is less the final key will almost certainly be wrong.
112  // TODO: decide if it is best to silently fail here or produce some sort
113  // of warning or exception.
114  std::string const & key3 = req.get_header("Sec-WebSocket-Key3");
115  std::copy(key3.c_str(),
116  key3.c_str()+(std::min)(static_cast<size_t>(8), key3.size()),
117  &key_final[8]);
118 
119  res.append_header(
120  "Sec-WebSocket-Key3",
121  md5::md5_hash_string(std::string(key_final,16))
122  );
123 
124  res.append_header("Upgrade","WebSocket");
125  res.append_header("Connection","Upgrade");
126 
127  // Echo back client's origin unless our local application set a
128  // more restrictive one.
129  if (res.get_header("Sec-WebSocket-Origin") == "") {
130  res.append_header("Sec-WebSocket-Origin",req.get_header("Origin"));
131  }
132 
133  // Echo back the client's request host unless our local application
134  // set a different one.
135  if (res.get_header("Sec-WebSocket-Location") == "") {
136  uri_ptr uri = get_uri(req);
137  res.append_header("Sec-WebSocket-Location",uri->str());
138  }
139 
140  if (subprotocol != "") {
141  res.replace_header("Sec-WebSocket-Protocol",subprotocol);
142  }
143 
144  return lib::error_code();
145  }
146 
148 
156  lib::error_code client_handshake_request(request_type &, uri_ptr,
157  std::vector<std::string> const &) const
158  {
160  }
161 
163 
171  lib::error_code validate_server_handshake_response(request_type const &,
172  response_type &) const
173  {
175  }
176 
177  std::string get_raw(response_type const & res) const {
178  response_type temp = res;
179  temp.remove_header("Sec-WebSocket-Key3");
180  return temp.raw() + res.get_header("Sec-WebSocket-Key3");
181  }
182 
183  std::string const & get_origin(request_type const & r) const {
184  return r.get_header("Origin");
185  }
186 
188 
195  lib::error_code extract_subprotocols(request_type const &,
196  std::vector<std::string> &)
197  {
198  return lib::error_code();
199  }
200 
201  uri_ptr get_uri(request_type const & request) const {
202  std::string h = request.get_header("Host");
203 
204  size_t last_colon = h.rfind(":");
205  size_t last_sbrace = h.rfind("]");
206 
207  // no : = hostname with no port
208  // last : before ] = ipv6 literal with no port
209  // : with no ] = hostname with port
210  // : after ] = ipv6 literal with port
211 
212  if (last_colon == std::string::npos ||
213  (last_sbrace != std::string::npos && last_sbrace > last_colon))
214  {
215  return lib::make_shared<uri>(base::m_secure, h, request.get_uri());
216  } else {
217  return lib::make_shared<uri>(base::m_secure,
218  h.substr(0,last_colon),
219  h.substr(last_colon+1),
220  request.get_uri());
221  }
222 
223  // TODO: check if get_uri is a full uri
224  }
225 
227 
231  std::string get_key3() const {
232  return "";
233  }
234 
236  size_t consume(uint8_t * buf, size_t len, lib::error_code & ec) {
237  // if in state header we are expecting a 0x00 byte, if we don't get one
238  // it is a fatal error
239  size_t p = 0; // bytes processed
240  size_t l = 0;
241 
242  ec = lib::error_code();
243 
244  while (p < len) {
245  if (m_state == HEADER) {
246  if (buf[p] == msg_hdr) {
247  p++;
248  m_msg_ptr = m_msg_manager->get_message(frame::opcode::text,1);
249 
250  if (!m_msg_ptr) {
251  ec = make_error_code(websocketpp::error::no_incoming_buffers);
252  m_state = FATAL_ERROR;
253  } else {
254  m_state = PAYLOAD;
255  }
256  } else {
257  ec = make_error_code(error::protocol_violation);
258  m_state = FATAL_ERROR;
259  }
260  } else if (m_state == PAYLOAD) {
261  uint8_t *it = std::find(buf+p,buf+len,msg_ftr);
262 
263  // 0 1 2 3 4 5
264  // 0x00 0x23 0x23 0x23 0xff 0xXX
265 
266  // Copy payload bytes into message
267  l = static_cast<size_t>(it-(buf+p));
268  m_msg_ptr->append_payload(buf+p,l);
269  p += l;
270 
271  if (it != buf+len) {
272  // message is done, copy it and the trailing
273  p++;
274  // TODO: validation
275  m_state = READY;
276  }
277  } else {
278  // TODO
279  break;
280  }
281  }
282  // If we get one, we create a new message and move to application state
283 
284  // if in state application we are copying bytes into the output message
285  // and validating them for UTF8 until we hit a 0xff byte. Once we hit
286  // 0x00, the message is complete and is dispatched. Then we go back to
287  // header state.
288 
289  //ec = make_error_code(error::not_implemented);
290  return p;
291  }
292 
293  bool ready() const {
294  return (m_state == READY);
295  }
296 
297  bool get_error() const {
298  return false;
299  }
300 
301  message_ptr get_message() {
302  message_ptr ret = m_msg_ptr;
303  m_msg_ptr = message_ptr();
304  m_state = HEADER;
305  return ret;
306  }
307 
309 
313  virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
314  {
315  if (!in || !out) {
316  return make_error_code(error::invalid_arguments);
317  }
318 
319  // TODO: check if the message is prepared already
320 
321  // validate opcode
322  if (in->get_opcode() != frame::opcode::text) {
323  return make_error_code(error::invalid_opcode);
324  }
325 
326  std::string& i = in->get_raw_payload();
327  //std::string& o = out->get_raw_payload();
328 
329  // validate payload utf8
330  if (!utf8_validator::validate(i)) {
331  return make_error_code(error::invalid_payload);
332  }
333 
334  // generate header
335  out->set_header(std::string(reinterpret_cast<char const *>(&msg_hdr),1));
336 
337  // process payload
338  out->set_payload(i);
339  out->append_payload(std::string(reinterpret_cast<char const *>(&msg_ftr),1));
340 
341  // hybi00 doesn't support compression
342  // hybi00 doesn't have masking
343 
344  out->set_prepared(true);
345 
346  return lib::error_code();
347  }
348 
350 
357  lib::error_code prepare_ping(std::string const &, message_ptr) const
358  {
359  return lib::error_code(error::no_protocol_support);
360  }
361 
363 
370  lib::error_code prepare_pong(std::string const &, message_ptr) const
371  {
372  return lib::error_code(error::no_protocol_support);
373  }
374 
376 
385  lib::error_code prepare_close(close::status::value, std::string const &,
386  message_ptr out) const
387  {
388  if (!out) {
389  return lib::error_code(error::invalid_arguments);
390  }
391 
392  std::string val;
393  val.append(1,'\xff');
394  val.append(1,'\x00');
395  out->set_payload(val);
396  out->set_prepared(true);
397 
398  return lib::error_code();
399  }
400 private:
401  void decode_client_key(std::string const & key, char * result) const {
402  unsigned int spaces = 0;
403  std::string digits = "";
404  uint32_t num;
405 
406  // key2
407  for (size_t i = 0; i < key.size(); i++) {
408  if (key[i] == ' ') {
409  spaces++;
410  } else if (key[i] >= '0' && key[i] <= '9') {
411  digits += key[i];
412  }
413  }
414 
415  num = static_cast<uint32_t>(strtoul(digits.c_str(), NULL, 10));
416  if (spaces > 0 && num > 0) {
417  num = htonl(num/spaces);
418  std::copy(reinterpret_cast<char*>(&num),
419  reinterpret_cast<char*>(&num)+4,
420  result);
421  } else {
422  std::fill(result,result+4,0);
423  }
424  }
425 
426  enum state {
427  HEADER = 0,
428  PAYLOAD = 1,
429  READY = 2,
430  FATAL_ERROR = 3
431  };
432 
433  uint8_t const msg_hdr;
434  uint8_t const msg_ftr;
435 
436  state m_state;
437 
438  msg_manager_ptr m_msg_manager;
439  message_ptr m_msg_ptr;
440  utf8_validator::validator m_validator;
441 };
442 
443 } // namespace processor
444 } // namespace websocketpp
445 
446 #endif //WEBSOCKETPP_PROCESSOR_HYBI00_HPP
bool ready() const
Checks if there is a message ready.
Definition: hybi00.hpp:293
int get_version() const
Get the protocol version of this processor.
Definition: hybi00.hpp:71
uint16_t value
The type of a close code value.
Definition: close.hpp:49
lib::error_code validate_handshake(request_type const &r) const
validate a WebSocket handshake request for this version
Definition: hybi00.hpp:75
lib::error_code extract_subprotocols(request_type const &, std::vector< std::string > &)
Extracts requested subprotocols from a handshake request.
Definition: hybi00.hpp:195
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:98
WebSocket protocol processor abstract base class.
Definition: processor.hpp:160
No support for this feature in this protocol version.
Definition: base.hpp:135
Processor encountered invalid payload data.
Definition: base.hpp:81
std::string const & get_origin(request_type const &r) const
Return the value of the header containing the CORS origin.
Definition: hybi00.hpp:183
Processor encountered a protocol violation in an incoming message.
Definition: base.hpp:75
uri_ptr get_uri(request_type const &request) const
Extracts client uri from a handshake request.
Definition: hybi00.hpp:201
lib::error_code prepare_close(close::status::value, std::string const &, message_ptr out) const
Prepare a close frame.
Definition: hybi00.hpp:385
message_ptr get_message()
Retrieves the most recently processed message.
Definition: hybi00.hpp:301
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
size_t consume(uint8_t *buf, size_t len, lib::error_code &ec)
Process new websocket connection bytes.
Definition: hybi00.hpp:236
std::string get_key3() const
Get hybi00 handshake key3.
Definition: hybi00.hpp:231
Namespace for the WebSocket++ project.
Definition: base64.hpp:41
bool get_error() const
Tests whether the processor is in a fatal error state.
Definition: hybi00.hpp:297
The endpoint is out of incoming message buffers.
Definition: error.hpp:71
lib::shared_ptr< uri > uri_ptr
Pointer to a URI.
Definition: uri.hpp:350
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:177
virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
Prepare a message for writing.
Definition: hybi00.hpp:313
Opcode was invalid for requested operation.
Definition: base.hpp:87
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:156
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:171
lib::error_code prepare_pong(std::string const &, message_ptr) const
Prepare a pong frame.
Definition: hybi00.hpp:370
lib::error_code prepare_ping(std::string const &, message_ptr) const
Prepare a ping frame.
Definition: hybi00.hpp:357
The processor method was called with invalid arguments.
Definition: base.hpp:84
Processor for Hybi Draft version 00.
Definition: hybi00.hpp:52