websocketpp  0.6.0
C++/Boost Asio based websocket client/server library
hybi13.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_HYBI13_HPP
29 #define WEBSOCKETPP_PROCESSOR_HYBI13_HPP
30 
31 #include <websocketpp/processors/processor.hpp>
32 
33 #include <websocketpp/frame.hpp>
34 #include <websocketpp/http/constants.hpp>
35 
36 #include <websocketpp/utf8_validator.hpp>
37 #include <websocketpp/sha1/sha1.hpp>
38 #include <websocketpp/base64/base64.hpp>
39 
40 #include <websocketpp/common/network.hpp>
41 #include <websocketpp/common/platforms.hpp>
42 
43 #include <algorithm>
44 #include <cassert>
45 #include <string>
46 #include <vector>
47 #include <utility>
48 
49 namespace websocketpp {
50 namespace processor {
51 
53 template <typename config>
54 class hybi13 : public processor<config> {
55 public:
56  typedef processor<config> base;
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 msg_manager_type;
65  typedef typename msg_manager_type::ptr msg_manager_ptr;
66  typedef typename config::rng_type rng_type;
67 
68  typedef typename config::permessage_deflate_type permessage_deflate_type;
69 
70  typedef std::pair<lib::error_code,std::string> err_str_pair;
71 
72  explicit hybi13(bool secure, bool p_is_server, msg_manager_ptr manager, rng_type& rng)
73  : processor<config>(secure, p_is_server)
74  , m_msg_manager(manager)
75  , m_rng(rng)
76  {
77  reset_headers();
78  }
79 
80  int get_version() const {
81  return 13;
82  }
83 
84  bool has_permessage_deflate() const {
85  return m_permessage_deflate.is_implemented();
86  }
87 
88  err_str_pair negotiate_extensions(request_type const & req) {
89  err_str_pair ret;
90 
91  // Respect blanket disabling of all extensions and don't even parse
92  // the extension header
93  if (!config::enable_extensions) {
94  ret.first = make_error_code(error::extensions_disabled);
95  return ret;
96  }
97 
99 
100  bool error = req.get_header_as_plist("Sec-WebSocket-Extensions",p);
101 
102  if (error) {
103  ret.first = make_error_code(error::extension_parse_error);
104  return ret;
105  }
106 
107  // If there are no extensions parsed then we are done!
108  if (p.size() == 0) {
109  return ret;
110  }
111 
112  http::parameter_list::const_iterator it;
113 
114  if (m_permessage_deflate.is_implemented()) {
115  err_str_pair neg_ret;
116  for (it = p.begin(); it != p.end(); ++it) {
117  // look through each extension, if the key is permessage-deflate
118  if (it->first == "permessage-deflate") {
119  neg_ret = m_permessage_deflate.negotiate(it->second);
120 
121  if (neg_ret.first) {
122  // Figure out if this is an error that should halt all
123  // extension negotiations or simply cause negotiation of
124  // this specific extension to fail.
125  //std::cout << "permessage-compress negotiation failed: "
126  // << neg_ret.first.message() << std::endl;
127  } else {
128  // Note: this list will need commas if WebSocket++ ever
129  // supports more than one extension
130  ret.second += neg_ret.second;
131  continue;
132  }
133  }
134  }
135  }
136 
137  return ret;
138  }
139 
140  lib::error_code validate_handshake(request_type const & r) const {
141  if (r.get_method() != "GET") {
142  return make_error_code(error::invalid_http_method);
143  }
144 
145  if (r.get_version() != "HTTP/1.1") {
146  return make_error_code(error::invalid_http_version);
147  }
148 
149  // required headers
150  // Host is required by HTTP/1.1
151  // Connection is required by is_websocket_handshake
152  // Upgrade is required by is_websocket_handshake
153  if (r.get_header("Sec-WebSocket-Key") == "") {
154  return make_error_code(error::missing_required_header);
155  }
156 
157  return lib::error_code();
158  }
159 
160  /* TODO: the 'subprotocol' parameter may need to be expanded into a more
161  * generic struct if other user input parameters to the processed handshake
162  * are found.
163  */
164  lib::error_code process_handshake(request_type const & request,
165  std::string const & subprotocol, response_type & response) const
166  {
167  std::string server_key = request.get_header("Sec-WebSocket-Key");
168 
169  lib::error_code ec = process_handshake_key(server_key);
170 
171  if (ec) {
172  return ec;
173  }
174 
175  response.replace_header("Sec-WebSocket-Accept",server_key);
176  response.append_header("Upgrade",constants::upgrade_token);
177  response.append_header("Connection",constants::connection_token);
178 
179  if (!subprotocol.empty()) {
180  response.replace_header("Sec-WebSocket-Protocol",subprotocol);
181  }
182 
183  return lib::error_code();
184  }
185 
187 
192  lib::error_code client_handshake_request(request_type & req, uri_ptr
193  uri, std::vector<std::string> const & subprotocols) const
194  {
195  req.set_method("GET");
196  req.set_uri(uri->get_resource());
197  req.set_version("HTTP/1.1");
198 
199  req.append_header("Upgrade","websocket");
200  req.append_header("Connection","Upgrade");
201  req.replace_header("Sec-WebSocket-Version","13");
202  req.replace_header("Host",uri->get_host_port());
203 
204  if (!subprotocols.empty()) {
205  std::ostringstream result;
206  std::vector<std::string>::const_iterator it = subprotocols.begin();
207  result << *it++;
208  while (it != subprotocols.end()) {
209  result << ", " << *it++;
210  }
211 
212  req.replace_header("Sec-WebSocket-Protocol",result.str());
213  }
214 
215  // Generate handshake key
217  unsigned char raw_key[16];
218 
219  for (int i = 0; i < 4; i++) {
220  conv.i = m_rng();
221  std::copy(conv.c,conv.c+4,&raw_key[i*4]);
222  }
223 
224  req.replace_header("Sec-WebSocket-Key",base64_encode(raw_key, 16));
225 
226  return lib::error_code();
227  }
228 
230 
235  lib::error_code validate_server_handshake_response(request_type const & req,
236  response_type& res) const
237  {
238  // A valid response has an HTTP 101 switching protocols code
239  if (res.get_status_code() != http::status_code::switching_protocols) {
241  }
242 
243  // And the upgrade token in an upgrade header
244  std::string const & upgrade_header = res.get_header("Upgrade");
245  if (utility::ci_find_substr(upgrade_header, constants::upgrade_token,
246  sizeof(constants::upgrade_token)-1) == upgrade_header.end())
247  {
249  }
250 
251  // And the websocket token in the connection header
252  std::string const & con_header = res.get_header("Connection");
253  if (utility::ci_find_substr(con_header, constants::connection_token,
254  sizeof(constants::connection_token)-1) == con_header.end())
255  {
257  }
258 
259  // And has a valid Sec-WebSocket-Accept value
260  std::string key = req.get_header("Sec-WebSocket-Key");
261  lib::error_code ec = process_handshake_key(key);
262 
263  if (ec || key != res.get_header("Sec-WebSocket-Accept")) {
265  }
266 
267  return lib::error_code();
268  }
269 
270  std::string get_raw(response_type const & res) const {
271  return res.raw();
272  }
273 
274  std::string const & get_origin(request_type const & r) const {
275  return r.get_header("Origin");
276  }
277 
278  lib::error_code extract_subprotocols(request_type const & req,
279  std::vector<std::string> & subprotocol_list)
280  {
281  if (!req.get_header("Sec-WebSocket-Protocol").empty()) {
283 
284  if (!req.get_header_as_plist("Sec-WebSocket-Protocol",p)) {
285  http::parameter_list::const_iterator it;
286 
287  for (it = p.begin(); it != p.end(); ++it) {
288  subprotocol_list.push_back(it->first);
289  }
290  } else {
292  }
293  }
294  return lib::error_code();
295  }
296 
297  uri_ptr get_uri(request_type const & request) const {
298  return get_uri_from_host(request,(base::m_secure ? "wss" : "ws"));
299  }
300 
302 
328  size_t consume(uint8_t * buf, size_t len, lib::error_code & ec) {
329  size_t p = 0;
330 
331  ec = lib::error_code();
332 
333  //std::cout << "consume: " << utility::to_hex(buf,len) << std::endl;
334 
335  // Loop while we don't have a message ready and we still have bytes
336  // left to process.
337  while (m_state != READY && m_state != FATAL_ERROR &&
338  (p < len || m_bytes_needed == 0))
339  {
340  if (m_state == HEADER_BASIC) {
341  p += this->copy_basic_header_bytes(buf+p,len-p);
342 
343  if (m_bytes_needed > 0) {
344  continue;
345  }
346 
348  m_basic_header, base::m_server, !m_data_msg.msg_ptr
349  );
350  if (ec) {break;}
351 
352  // extract full header size and adjust consume state accordingly
353  m_state = HEADER_EXTENDED;
354  m_cursor = 0;
355  m_bytes_needed = frame::get_header_len(m_basic_header) -
357  } else if (m_state == HEADER_EXTENDED) {
358  p += this->copy_extended_header_bytes(buf+p,len-p);
359 
360  if (m_bytes_needed > 0) {
361  continue;
362  }
363 
364  ec = validate_incoming_extended_header(m_basic_header,m_extended_header);
365  if (ec){break;}
366 
367  m_state = APPLICATION;
368  m_bytes_needed = static_cast<size_t>(get_payload_size(m_basic_header,m_extended_header));
369 
370  // check if this frame is the start of a new message and set up
371  // the appropriate message metadata.
372  frame::opcode::value op = frame::get_opcode(m_basic_header);
373 
374  // TODO: get_message failure conditions
375 
376  if (frame::opcode::is_control(op)) {
377  m_control_msg = msg_metadata(
378  m_msg_manager->get_message(op,m_bytes_needed),
379  frame::get_masking_key(m_basic_header,m_extended_header)
380  );
381 
382  m_current_msg = &m_control_msg;
383  } else {
384  if (!m_data_msg.msg_ptr) {
385  if (m_bytes_needed > base::m_max_message_size) {
386  ec = make_error_code(error::message_too_big);
387  break;
388  }
389 
390  m_data_msg = msg_metadata(
391  m_msg_manager->get_message(op,m_bytes_needed),
392  frame::get_masking_key(m_basic_header,m_extended_header)
393  );
394  } else {
395  // Fetch the underlying payload buffer from the data message we
396  // are writing into.
397  std::string & out = m_data_msg.msg_ptr->get_raw_payload();
398 
399  if (out.size() + m_bytes_needed > base::m_max_message_size) {
400  ec = make_error_code(error::message_too_big);
401  break;
402  }
403 
404  // Each frame starts a new masking key. All other state
405  // remains between frames.
406  m_data_msg.prepared_key = prepare_masking_key(
408  m_basic_header,
409  m_extended_header
410  )
411  );
412 
413  out.reserve(out.size() + m_bytes_needed);
414  }
415  m_current_msg = &m_data_msg;
416  }
417  } else if (m_state == EXTENSION) {
418  m_state = APPLICATION;
419  } else if (m_state == APPLICATION) {
420  size_t bytes_to_process = (std::min)(m_bytes_needed,len-p);
421 
422  if (bytes_to_process > 0) {
423  p += this->process_payload_bytes(buf+p,bytes_to_process,ec);
424 
425  if (ec) {break;}
426  }
427 
428  if (m_bytes_needed > 0) {
429  continue;
430  }
431 
432  // If this was the last frame in the message set the ready flag.
433  // Otherwise, reset processor state to read additional frames.
434  if (frame::get_fin(m_basic_header)) {
435  // ensure that text messages end on a valid UTF8 code point
436  if (frame::get_opcode(m_basic_header) == frame::opcode::TEXT) {
437  if (!m_current_msg->validator.complete()) {
438  ec = make_error_code(error::invalid_utf8);
439  break;
440  }
441  }
442 
443  m_state = READY;
444  } else {
445  this->reset_headers();
446  }
447  } else {
448  // shouldn't be here
449  ec = make_error_code(error::general);
450  return 0;
451  }
452  }
453 
454  return p;
455  }
456 
457  void reset_headers() {
458  m_state = HEADER_BASIC;
459  m_bytes_needed = frame::BASIC_HEADER_LENGTH;
460 
461  m_basic_header.b0 = 0x00;
462  m_basic_header.b1 = 0x00;
463 
464  std::fill_n(
465  m_extended_header.bytes,
467  0x00
468  );
469  }
470 
472  bool ready() const {
473  return (m_state == READY);
474  }
475 
476  message_ptr get_message() {
477  if (!ready()) {
478  return message_ptr();
479  }
480  message_ptr ret = m_current_msg->msg_ptr;
481  m_current_msg->msg_ptr.reset();
482 
483  if (frame::opcode::is_control(ret->get_opcode())) {
484  m_control_msg.msg_ptr.reset();
485  } else {
486  m_data_msg.msg_ptr.reset();
487  }
488 
489  this->reset_headers();
490 
491  return ret;
492  }
493 
495  bool get_error() const {
496  return m_state == FATAL_ERROR;
497  }
498 
499  size_t get_bytes_needed() const {
500  return m_bytes_needed;
501  }
502 
504 
527  virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
528  {
529  if (!in || !out) {
530  return make_error_code(error::invalid_arguments);
531  }
532 
533  frame::opcode::value op = in->get_opcode();
534 
535  // validate opcode: only regular data frames
536  if (frame::opcode::is_control(op)) {
537  return make_error_code(error::invalid_opcode);
538  }
539 
540  std::string& i = in->get_raw_payload();
541  std::string& o = out->get_raw_payload();
542 
543  // validate payload utf8
544  if (op == frame::opcode::TEXT && !utf8_validator::validate(i)) {
545  return make_error_code(error::invalid_payload);
546  }
547 
549  bool masked = !base::m_server;
550  bool compressed = m_permessage_deflate.is_enabled()
551  && in->get_compressed();
552  bool fin = in->get_fin();
553 
554  // generate header
555  frame::basic_header h(op,i.size(),fin,masked,compressed);
556 
557  if (masked) {
558  // Generate masking key.
559  key.i = m_rng();
560 
561  frame::extended_header e(i.size(),key.i);
562  out->set_header(frame::prepare_header(h,e));
563  } else {
564  frame::extended_header e(i.size());
565  out->set_header(frame::prepare_header(h,e));
566  key.i = 0;
567  }
568 
569  // prepare payload
570  if (compressed) {
571  // compress and store in o after header.
572  m_permessage_deflate.compress(i,o);
573 
574  // mask in place if necessary
575  if (masked) {
576  this->masked_copy(o,o,key);
577  }
578  } else {
579  // no compression, just copy data into the output buffer
580  o.resize(i.size());
581 
582  // if we are masked, have the masking function write to the output
583  // buffer directly to avoid another copy. If not masked, copy
584  // directly without masking.
585  if (masked) {
586  this->masked_copy(i,o,key);
587  } else {
588  std::copy(i.begin(),i.end(),o.begin());
589  }
590  }
591 
592  out->set_prepared(true);
593  out->set_opcode(op);
594 
595  return lib::error_code();
596  }
597 
599  lib::error_code prepare_ping(std::string const & in, message_ptr out) const {
600  return this->prepare_control(frame::opcode::PING,in,out);
601  }
602 
603  lib::error_code prepare_pong(std::string const & in, message_ptr out) const {
604  return this->prepare_control(frame::opcode::PONG,in,out);
605  }
606 
607  virtual lib::error_code prepare_close(close::status::value code,
608  std::string const & reason, message_ptr out) const
609  {
610  if (close::status::reserved(code)) {
611  return make_error_code(error::reserved_close_code);
612  }
613 
614  if (close::status::invalid(code) && code != close::status::no_status) {
615  return make_error_code(error::invalid_close_code);
616  }
617 
618  if (code == close::status::no_status && reason.size() > 0) {
619  return make_error_code(error::reason_requires_code);
620  }
621 
622  if (reason.size() > frame:: limits::payload_size_basic-2) {
623  return make_error_code(error::control_too_big);
624  }
625 
626  std::string payload;
627 
628  if (code != close::status::no_status) {
629  close::code_converter val;
630  val.i = htons(code);
631 
632  payload.resize(reason.size()+2);
633 
634  payload[0] = val.c[0];
635  payload[1] = val.c[1];
636 
637  std::copy(reason.begin(),reason.end(),payload.begin()+2);
638  }
639 
640  return this->prepare_control(frame::opcode::CLOSE,payload,out);
641  }
642 protected:
644  lib::error_code process_handshake_key(std::string & key) const {
645  key.append(constants::handshake_guid);
646 
647  unsigned char message_digest[20];
648  sha1::calc(key.c_str(),key.length(),message_digest);
649  key = base64_encode(message_digest,20);
650 
651  return lib::error_code();
652  }
653 
655  size_t copy_basic_header_bytes(uint8_t const * buf, size_t len) {
656  if (len == 0 || m_bytes_needed == 0) {
657  return 0;
658  }
659 
660  if (len > 1) {
661  // have at least two bytes
662  if (m_bytes_needed == 2) {
663  m_basic_header.b0 = buf[0];
664  m_basic_header.b1 = buf[1];
665  m_bytes_needed -= 2;
666  return 2;
667  } else {
668  m_basic_header.b1 = buf[0];
669  m_bytes_needed--;
670  return 1;
671  }
672  } else {
673  // have exactly one byte
674  if (m_bytes_needed == 2) {
675  m_basic_header.b0 = buf[0];
676  m_bytes_needed--;
677  return 1;
678  } else {
679  m_basic_header.b1 = buf[0];
680  m_bytes_needed--;
681  return 1;
682  }
683  }
684  }
685 
687  size_t copy_extended_header_bytes(uint8_t const * buf, size_t len) {
688  size_t bytes_to_read = (std::min)(m_bytes_needed,len);
689 
690  std::copy(buf,buf+bytes_to_read,m_extended_header.bytes+m_cursor);
691  m_cursor += bytes_to_read;
692  m_bytes_needed -= bytes_to_read;
693 
694  return bytes_to_read;
695  }
696 
698 
710  size_t process_payload_bytes(uint8_t * buf, size_t len, lib::error_code& ec)
711  {
712  // unmask if masked
713  if (frame::get_masked(m_basic_header)) {
714  #ifdef WEBSOCKETPP_STRICT_MASKING
715  m_current_msg->prepared_key = frame::byte_mask_circ(
716  buf,
717  len,
718  m_current_msg->prepared_key
719  );
720  #else
721  m_current_msg->prepared_key = frame::word_mask_circ(
722  buf,
723  len,
724  m_current_msg->prepared_key
725  );
726  #endif
727  }
728 
729  std::string & out = m_current_msg->msg_ptr->get_raw_payload();
730  size_t offset = out.size();
731 
732  // decompress message if needed.
733  if (m_permessage_deflate.is_enabled()
734  && frame::get_rsv1(m_basic_header))
735  {
736  // Decompress current buffer into the message buffer
737  m_permessage_deflate.decompress(buf,len,out);
738 
739  // get the length of the newly uncompressed output
740  offset = out.size() - offset;
741  } else {
742  // No compression, straight copy
743  out.append(reinterpret_cast<char *>(buf),len);
744  }
745 
746  // validate unmasked, decompressed values
747  if (m_current_msg->msg_ptr->get_opcode() == frame::opcode::TEXT) {
748  if (!m_current_msg->validator.decode(out.begin()+offset,out.end())) {
749  ec = make_error_code(error::invalid_utf8);
750  return 0;
751  }
752  }
753 
754  m_bytes_needed -= len;
755 
756  return len;
757  }
758 
760 
770  bool is_server, bool new_msg) const
771  {
772  frame::opcode::value op = frame::get_opcode(h);
773 
774  // Check control frame size limit
775  if (frame::opcode::is_control(op) &&
777  {
778  return make_error_code(error::control_too_big);
779  }
780 
781  // Check that RSV bits are clear
782  // The only RSV bits allowed are rsv1 if the permessage_compress
783  // extension is enabled for this connection and the message is not
784  // a control message.
785  //
786  // TODO: unit tests for this
787  if (frame::get_rsv1(h) && (!m_permessage_deflate.is_enabled()
789  {
790  return make_error_code(error::invalid_rsv_bit);
791  }
792 
793  if (frame::get_rsv2(h) || frame::get_rsv3(h)) {
794  return make_error_code(error::invalid_rsv_bit);
795  }
796 
797  // Check for reserved opcodes
798  if (frame::opcode::reserved(op)) {
799  return make_error_code(error::invalid_opcode);
800  }
801 
802  // Check for invalid opcodes
803  // TODO: unit tests for this?
804  if (frame::opcode::invalid(op)) {
805  return make_error_code(error::invalid_opcode);
806  }
807 
808  // Check for fragmented control message
809  if (frame::opcode::is_control(op) && !frame::get_fin(h)) {
810  return make_error_code(error::fragmented_control);
811  }
812 
813  // Check for continuation without an active message
814  if (new_msg && op == frame::opcode::CONTINUATION) {
815  return make_error_code(error::invalid_continuation);
816  }
817 
818  // Check for new data frame when expecting continuation
819  if (!new_msg && !frame::opcode::is_control(op) &&
820  op != frame::opcode::CONTINUATION)
821  {
822  return make_error_code(error::invalid_continuation);
823  }
824 
825  // Servers should reject any unmasked frames from clients.
826  // Clients should reject any masked frames from servers.
827  if (is_server && !frame::get_masked(h)) {
828  return make_error_code(error::masking_required);
829  } else if (!is_server && frame::get_masked(h)) {
830  return make_error_code(error::masking_forbidden);
831  }
832 
833  return lib::error_code();
834  }
835 
837 
848  frame::extended_header e) const
849  {
850  uint8_t basic_size = frame::get_basic_size(h);
851  uint64_t payload_size = frame::get_payload_size(h,e);
852 
853  // Check for non-minimally encoded payloads
854  if (basic_size == frame::payload_size_code_16bit &&
855  payload_size <= frame::limits::payload_size_basic)
856  {
857  return make_error_code(error::non_minimal_encoding);
858  }
859 
860  if (basic_size == frame::payload_size_code_64bit &&
861  payload_size <= frame::limits::payload_size_extended)
862  {
863  return make_error_code(error::non_minimal_encoding);
864  }
865 
866  // Check for >32bit frames on 32 bit systems
867  if (sizeof(size_t) == 4 && (payload_size >> 32)) {
868  return make_error_code(error::requires_64bit);
869  }
870 
871  return lib::error_code();
872  }
873 
875 
882  void masked_copy (std::string const & i, std::string & o,
883  frame::masking_key_type key) const
884  {
885  #ifdef WEBSOCKETPP_STRICT_MASKING
886  frame::byte_mask(i.begin(),i.end(),o.begin(),key);
887  #else
889  reinterpret_cast<uint8_t *>(const_cast<char *>(i.data())),
890  reinterpret_cast<uint8_t *>(const_cast<char *>(o.data())),
891  i.size(),
892  key
893  );
894  #endif
895  }
896 
898 
906  lib::error_code prepare_control(frame::opcode::value op,
907  std::string const & payload, message_ptr out) const
908  {
909  if (!out) {
910  return make_error_code(error::invalid_arguments);
911  }
912 
913  if (!frame::opcode::is_control(op)) {
914  return make_error_code(error::invalid_opcode);
915  }
916 
917  if (payload.size() > frame::limits::payload_size_basic) {
918  return make_error_code(error::control_too_big);
919  }
920 
922  bool masked = !base::m_server;
923 
924  frame::basic_header h(op,payload.size(),true,masked);
925 
926  std::string & o = out->get_raw_payload();
927  o.resize(payload.size());
928 
929  if (masked) {
930  // Generate masking key.
931  key.i = m_rng();
932 
933  frame::extended_header e(payload.size(),key.i);
934  out->set_header(frame::prepare_header(h,e));
935  this->masked_copy(payload,o,key);
936  } else {
937  frame::extended_header e(payload.size());
938  out->set_header(frame::prepare_header(h,e));
939  std::copy(payload.begin(),payload.end(),o.begin());
940  }
941 
942  out->set_opcode(op);
943  out->set_prepared(true);
944 
945  return lib::error_code();
946  }
947 
948  enum state {
949  HEADER_BASIC = 0,
950  HEADER_EXTENDED = 1,
951  EXTENSION = 2,
952  APPLICATION = 3,
953  READY = 4,
954  FATAL_ERROR = 5
955  };
956 
960  struct msg_metadata {
961  msg_metadata() {}
962  msg_metadata(message_ptr m, size_t p) : msg_ptr(m),prepared_key(p) {}
963  msg_metadata(message_ptr m, frame::masking_key_type p)
964  : msg_ptr(m)
965  , prepared_key(prepare_masking_key(p)) {}
966 
967  message_ptr msg_ptr; // pointer to the message data buffer
968  size_t prepared_key; // prepared masking key
969  utf8_validator::validator validator; // utf8 validation state
970  };
971 
972  // Basic header of the frame being read
973  frame::basic_header m_basic_header;
974 
975  // Pointer to a manager that can create message buffers for us.
976  msg_manager_ptr m_msg_manager;
977 
978  // Number of bytes needed to complete the current operation
979  size_t m_bytes_needed;
980 
981  // Number of extended header bytes read
982  size_t m_cursor;
983 
984  // Metadata for the current data msg
985  msg_metadata m_data_msg;
986  // Metadata for the current control msg
987  msg_metadata m_control_msg;
988 
989  // Pointer to the metadata associated with the frame being read
990  msg_metadata * m_current_msg;
991 
992  // Extended header of current frame
993  frame::extended_header m_extended_header;
994 
995  rng_type & m_rng;
996 
997  // Overall state of the processor
998  state m_state;
999 
1000  // Extensions
1001  permessage_deflate_type m_permessage_deflate;
1002 };
1003 
1004 } // namespace processor
1005 } // namespace websocketpp
1006 
1007 #endif //WEBSOCKETPP_PROCESSOR_HYBI13_HPP
bool is_control(value v)
Check if an opcode is for a control frame.
Definition: frame.hpp:139
bool invalid(value v)
Check if an opcode is invalid.
Definition: frame.hpp:130
virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
Prepare a user data message for writing.
Definition: hybi13.hpp:527
bool get_rsv1(basic_header const &h)
check whether the frame's RSV1 bit is set
Definition: frame.hpp:339
uint16_t value
The type of a close code value.
Definition: close.hpp:49
uri_ptr get_uri_from_host(request_type &request, std::string scheme)
Extract a URI ptr from the host header of the request.
Definition: processor.hpp:136
bool get_rsv3(basic_header const &h)
check whether the frame's RSV3 bit is set
Definition: frame.hpp:375
bool ready() const
Test whether or not the processor has a message ready.
Definition: hybi13.hpp:472
bool decode(iterator_type begin, iterator_type end)
Advance validator state with input from an iterator pair.
Clients may not send unmasked frames.
Definition: base.hpp:102
lib::error_code validate_handshake(request_type const &r) const
validate a WebSocket handshake request for this version
Definition: hybi13.hpp:140
bool get_masked(basic_header const &h)
check whether the frame is masked
Definition: frame.hpp:402
void masked_copy(std::string const &i, std::string &o, frame::masking_key_type key) const
Copy and mask/unmask in one operation.
Definition: hybi13.hpp:882
WebSocket protocol processor abstract base class.
Definition: processor.hpp:160
size_t copy_extended_header_bytes(uint8_t const *buf, size_t len)
Reads bytes from buf into m_extended_header.
Definition: hybi13.hpp:687
bool get_rsv2(basic_header const &h)
check whether the frame's RSV2 bit is set
Definition: frame.hpp:357
lib::error_code process_handshake(request_type const &request, std::string const &subprotocol, response_type &response) const
Calculate the appropriate response for this websocket request.
Definition: hybi13.hpp:164
Using a reason requires a close code.
Definition: base.hpp:144
Illegal use of reserved bit.
Definition: base.hpp:93
Provides streaming UTF8 validation functionality.
opcode::value get_opcode(basic_header const &h)
Extract opcode from basic header.
Definition: frame.hpp:393
bool reserved(value code)
Test whether a close code is in a reserved range.
Definition: close.hpp:179
size_t process_payload_bytes(uint8_t *buf, size_t len, lib::error_code &ec)
Reads bytes from buf into message payload.
Definition: hybi13.hpp:710
static uint8_t const payload_size_basic
Maximum size of a basic WebSocket payload.
Definition: frame.hpp:156
std::vector< std::pair< std::string, attribute_list > > parameter_list
The type of an HTTP parameter list.
Definition: constants.hpp:53
lib::error_code prepare_control(frame::opcode::value op, std::string const &payload, message_ptr out) const
Generic prepare control frame with opcode and payload.
Definition: hybi13.hpp:906
masking_key_type get_masking_key(basic_header const &, extended_header const &)
Extract the masking key from a frame header.
Definition: frame.hpp:516
bool get_error() const
Test whether or not the processor is in a fatal error state.
Definition: hybi13.hpp:495
bool invalid(value code)
Test whether a close code is invalid on the wire.
Definition: close.hpp:194
Four byte conversion union.
Definition: frame.hpp:61
Processor encountered invalid payload data.
Definition: base.hpp:81
void byte_mask(input_iter b, input_iter e, output_iter o, masking_key_type const &key, size_t key_offset=0)
Byte by byte mask/unmask.
Definition: frame.hpp:642
std::string base64_encode(unsigned char const *input, size_t len)
Encode a char buffer into a base64 string.
Definition: base64.hpp:66
std::string const & get_origin(request_type const &r) const
Return the value of the header containing the CORS origin.
Definition: hybi13.hpp:274
size_t get_header_len(basic_header const &)
Calculates the full length of the header based on the first bytes.
Definition: frame.hpp:445
std::string get_raw(response_type const &res) const
Given a completed response, get the raw bytes to put on the wire.
Definition: hybi13.hpp:270
Continuation without message.
Definition: base.hpp:99
size_t word_mask_circ(uint8_t *input, uint8_t *output, size_t length, size_t prepared_key)
Circular word aligned mask/unmask.
Definition: frame.hpp:765
lib::error_code extract_subprotocols(request_type const &req, std::vector< std::string > &subprotocol_list)
Extracts requested subprotocols from a handshake request.
Definition: hybi13.hpp:278
The constant size component of a WebSocket frame header.
Definition: frame.hpp:189
Not supported on 32 bit systems.
Definition: base.hpp:111
Extension related operation was ignored because extensions are disabled.
Definition: base.hpp:153
message_ptr get_message()
Retrieves the most recently processed message.
Definition: hybi13.hpp:476
void word_mask_exact(uint8_t *input, uint8_t *output, size_t length, masking_key_type const &key)
Exact word aligned mask/unmask.
Definition: frame.hpp:699
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
uint8_t get_basic_size(basic_header const &)
Extracts the raw payload length specified in the basic header.
Definition: frame.hpp:431
Namespace for the WebSocket++ project.
Definition: base64.hpp:41
uint64_t get_payload_size(basic_header const &, extended_header const &)
Extract the full payload size field from a WebSocket header.
Definition: frame.hpp:573
static unsigned int const MAX_EXTENDED_HEADER_LENGTH
Maximum length of the variable portion of the WebSocket header.
Definition: frame.hpp:52
lib::error_code process_handshake_key(std::string &key) const
Convert a client handshake key into a server response key in place.
Definition: hybi13.hpp:644
lib::error_code prepare_ping(std::string const &in, message_ptr out) const
Get URI.
Definition: hybi13.hpp:599
lib::shared_ptr< uri > uri_ptr
Pointer to a URI.
Definition: uri.hpp:350
The variable size component of a WebSocket frame header.
Definition: frame.hpp:235
static value const no_status
A dummy value to indicate that no status code was received.
Definition: close.hpp:97
Servers may not send masked frames.
Definition: base.hpp:105
Fragmented control message.
Definition: base.hpp:96
Processor encountered a message that was too large.
Definition: base.hpp:78
int get_version() const
Get the protocol version of this processor.
Definition: hybi13.hpp:80
size_t copy_basic_header_bytes(uint8_t const *buf, size_t len)
Reads bytes from buf into m_basic_header.
Definition: hybi13.hpp:655
lib::error_code validate_incoming_extended_header(frame::basic_header h, frame::extended_header e) const
Validate an incoming extended header.
Definition: hybi13.hpp:847
size_t consume(uint8_t *buf, size_t len, lib::error_code &ec)
Process new websocket connection bytes.
Definition: hybi13.hpp:328
lib::error_code client_handshake_request(request_type &req, uri_ptr uri, std::vector< std::string > const &subprotocols) const
Fill in a set of request headers for a client connection request.
Definition: hybi13.hpp:192
std::string prepare_header(const basic_header &h, const extended_header &e)
Generate a properly sized contiguous string that encodes a full frame header.
Definition: frame.hpp:489
static uint16_t const payload_size_extended
Maximum size of an extended WebSocket payload (basic payload = 126)
Definition: frame.hpp:159
size_t byte_mask_circ(uint8_t *input, uint8_t *output, size_t length, size_t prepared_key)
Circular byte aligned mask/unmask.
Definition: frame.hpp:827
Opcode was invalid for requested operation.
Definition: base.hpp:87
lib::error_code validate_incoming_basic_header(frame::basic_header const &h, bool is_server, bool new_msg) const
Validate an incoming basic header.
Definition: hybi13.hpp:769
bool reserved(value v)
Check if an opcode is reserved.
Definition: frame.hpp:118
bool get_fin(basic_header const &h)
Check whether the frame's FIN bit is set.
Definition: frame.hpp:321
uri_ptr get_uri(request_type const &request) const
Extracts client uri from a handshake request.
Definition: hybi13.hpp:297
size_t get_bytes_needed() const
Definition: hybi13.hpp:499
Processor for Hybi version 13 (RFC6455)
Definition: hybi13.hpp:54
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: hybi13.hpp:235
static unsigned int const BASIC_HEADER_LENGTH
Minimum length of a WebSocket frame header.
Definition: frame.hpp:48
T::const_iterator ci_find_substr(T const &haystack, T const &needle, std::locale const &loc=std::locale())
Find substring (case insensitive)
Definition: utilities.hpp:103
The processor method was called with invalid arguments.
Definition: base.hpp:84
Payload length not minimally encoded.
Definition: base.hpp:108
bool complete()
Return whether the input sequence ended on a valid utf8 codepoint.
err_str_pair negotiate_extensions(request_type const &req)
Initializes extensions based on the Sec-WebSocket-Extensions header.
Definition: hybi13.hpp:88