websocketpp  0.3.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) 2013, 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 
144  // outgoing client connection processing is not supported for this version
145  lib::error_code client_handshake_request(request_type& req, uri_ptr uri,
146  std::vector<std::string> const & subprotocols) const
147  {
149  }
150 
151  lib::error_code validate_server_handshake_response(request_type const & req,
152  response_type & res) const
153  {
155  }
156 
157  std::string get_raw(response_type const & res) const {
158  response_type temp = res;
159  temp.remove_header("Sec-WebSocket-Key3");
160  return temp.raw() + res.get_header("Sec-WebSocket-Key3");
161  }
162 
163  std::string const & get_origin(request_type const & r) const {
164  return r.get_header("Origin");
165  }
166 
167  // hybi00 doesn't support subprotocols so there never will be any requested
168  lib::error_code extract_subprotocols(request_type const & req,
169  std::vector<std::string> & subprotocol_list)
170  {
171  return lib::error_code();
172  }
173 
174  uri_ptr get_uri(request_type const & request) const {
175  std::string h = request.get_header("Host");
176 
177  size_t last_colon = h.rfind(":");
178  size_t last_sbrace = h.rfind("]");
179 
180  // no : = hostname with no port
181  // last : before ] = ipv6 literal with no port
182  // : with no ] = hostname with port
183  // : after ] = ipv6 literal with port
184 
185  if (last_colon == std::string::npos ||
186  (last_sbrace != std::string::npos && last_sbrace > last_colon))
187  {
188  return uri_ptr(new uri(base::m_secure, h, request.get_uri()));
189  } else {
190  return uri_ptr(new uri(base::m_secure,
191  h.substr(0,last_colon),
192  h.substr(last_colon+1),
193  request.get_uri()));
194  }
195 
196  // TODO: check if get_uri is a full uri
197  }
198 
200 
204  std::string get_key3() const {
205  return "";
206  }
207 
209  size_t consume(uint8_t * buf, size_t len, lib::error_code & ec) {
210  // if in state header we are expecting a 0x00 byte, if we don't get one
211  // it is a fatal error
212  size_t p = 0; // bytes processed
213  size_t l = 0;
214 
215  ec = lib::error_code();
216 
217  while (p < len) {
218  if (m_state == HEADER) {
219  if (buf[p] == msg_hdr) {
220  p++;
221  m_msg_ptr = m_msg_manager->get_message(frame::opcode::text,1);
222 
223  if (!m_msg_ptr) {
224  ec = make_error_code(websocketpp::error::no_incoming_buffers);
225  m_state = FATAL_ERROR;
226  } else {
227  m_state = PAYLOAD;
228  }
229  } else {
230  ec = make_error_code(error::protocol_violation);
231  m_state = FATAL_ERROR;
232  }
233  } else if (m_state == PAYLOAD) {
234  uint8_t *it = std::find(buf+p,buf+len,msg_ftr);
235 
236  // 0 1 2 3 4 5
237  // 0x00 0x23 0x23 0x23 0xff 0xXX
238 
239  // Copy payload bytes into message
240  l = static_cast<size_t>(it-(buf+p));
241  m_msg_ptr->append_payload(buf+p,l);
242  p += l;
243 
244  if (it != buf+len) {
245  // message is done, copy it and the trailing
246  p++;
247  // TODO: validation
248  m_state = READY;
249  }
250  } else {
251  // TODO
252  break;
253  }
254  }
255  // If we get one, we create a new message and move to application state
256 
257  // if in state application we are copying bytes into the output message
258  // and validating them for UTF8 until we hit a 0xff byte. Once we hit
259  // 0x00, the message is complete and is dispatched. Then we go back to
260  // header state.
261 
262  //ec = make_error_code(error::not_implemented);
263  return p;
264  }
265 
266  bool ready() const {
267  return (m_state == READY);
268  }
269 
270  bool get_error() const {
271  return false;
272  }
273 
274  message_ptr get_message() {
275  message_ptr ret = m_msg_ptr;
276  m_msg_ptr = message_ptr();
277  m_state = HEADER;
278  return ret;
279  }
280 
282 
286  virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
287  {
288  if (!in || !out) {
289  return make_error_code(error::invalid_arguments);
290  }
291 
292  // TODO: check if the message is prepared already
293 
294  // validate opcode
295  if (in->get_opcode() != frame::opcode::text) {
296  return make_error_code(error::invalid_opcode);
297  }
298 
299  std::string& i = in->get_raw_payload();
300  //std::string& o = out->get_raw_payload();
301 
302  // validate payload utf8
303  if (!utf8_validator::validate(i)) {
304  return make_error_code(error::invalid_payload);
305  }
306 
307  // generate header
308  out->set_header(std::string(reinterpret_cast<char const *>(&msg_hdr),1));
309 
310  // process payload
311  out->set_payload(i);
312  out->append_payload(std::string(reinterpret_cast<char const *>(&msg_ftr),1));
313 
314  // hybi00 doesn't support compression
315  // hybi00 doesn't have masking
316 
317  out->set_prepared(true);
318 
319  return lib::error_code();
320  }
321 
322  lib::error_code prepare_ping(std::string const & in, message_ptr out) const
323  {
324  return lib::error_code(error::no_protocol_support);
325  }
326 
327  lib::error_code prepare_pong(const std::string & in, message_ptr out) const
328  {
329  return lib::error_code(error::no_protocol_support);
330  }
331 
332  lib::error_code prepare_close(close::status::value code,
333  std::string const & reason, message_ptr out) const
334  {
335  if (!out) {
336  return lib::error_code(error::invalid_arguments);
337  }
338 
339  std::string val;
340  val.append(1,'\xff');
341  val.append(1,'\x00');
342  out->set_payload(val);
343  out->set_prepared(true);
344 
345  return lib::error_code();
346  }
347 private:
348  void decode_client_key(std::string const & key, char * result) const {
349  unsigned int spaces = 0;
350  std::string digits = "";
351  uint32_t num;
352 
353  // key2
354  for (size_t i = 0; i < key.size(); i++) {
355  if (key[i] == ' ') {
356  spaces++;
357  } else if (key[i] >= '0' && key[i] <= '9') {
358  digits += key[i];
359  }
360  }
361 
362  num = static_cast<uint32_t>(strtoul(digits.c_str(), NULL, 10));
363  if (spaces > 0 && num > 0) {
364  num = htonl(num/spaces);
365  std::copy(reinterpret_cast<char*>(&num),
366  reinterpret_cast<char*>(&num)+4,
367  result);
368  } else {
369  std::fill(result,result+4,0);
370  }
371  }
372 
373  enum state {
374  HEADER = 0,
375  PAYLOAD = 1,
376  READY = 2,
377  FATAL_ERROR = 3
378  };
379 
380  uint8_t const msg_hdr;
381  uint8_t const msg_ftr;
382 
383  state m_state;
384 
385  msg_manager_ptr m_msg_manager;
386  message_ptr m_msg_ptr;
387  utf8_validator::validator m_validator;
388 };
389 
390 } // namespace processor
391 } // namespace websocketpp
392 
393 #endif //WEBSOCKETPP_PROCESSOR_HYBI00_HPP
bool ready() const
Checks if there is a message ready.
Definition: hybi00.hpp:266
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 validate_server_handshake_response(request_type const &req, response_type &res) const
Validate the server's response to an outgoing handshake request.
Definition: hybi00.hpp:151
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
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:168
No support for this feature in this protocol version.
Definition: base.hpp:136
lib::error_code client_handshake_request(request_type &req, uri_ptr uri, std::vector< std::string > const &subprotocols) const
Fill in an HTTP request for an outgoing connection handshake.
Definition: hybi00.hpp:145
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:163
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:174
message_ptr get_message()
Retrieves the most recently processed message.
Definition: hybi00.hpp:274
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:209
std::string get_key3() const
Get hybi00 handshake key3.
Definition: hybi00.hpp:204
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:270
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:157
virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
Prepare a message for writing.
Definition: hybi00.hpp:286
Opcode was invalid for requested operation.
Definition: base.hpp:88
The processor method was called with invalid arguments.
Definition: base.hpp:85
Processor for Hybi Draft version 00.
Definition: hybi00.hpp:49