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