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