You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1193 lines
34 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2015, 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. #ifndef WEBSOCKETPP_PROCESSOR_HYBI13_HPP
  28. #define WEBSOCKETPP_PROCESSOR_HYBI13_HPP
  29. #include <algorithm>
  30. #include <cassert>
  31. #include <string>
  32. #include <utility>
  33. #include <vector>
  34. #include <websocketpp/base64/base64.hpp>
  35. #include <websocketpp/common/network.hpp>
  36. #include <websocketpp/common/platforms.hpp>
  37. #include <websocketpp/frame.hpp>
  38. #include <websocketpp/http/constants.hpp>
  39. #include <websocketpp/processors/processor.hpp>
  40. #include <websocketpp/sha1/sha1.hpp>
  41. #include <websocketpp/utf8_validator.hpp>
  42. namespace websocketpp
  43. {
  44. namespace processor
  45. {
  46. /// Processor for Hybi version 13 (RFC6455)
  47. template <typename config> class hybi13 : public processor<config>
  48. {
  49. public:
  50. typedef processor<config> base;
  51. typedef typename config::request_type request_type;
  52. typedef typename config::response_type response_type;
  53. typedef typename config::message_type message_type;
  54. typedef typename message_type::ptr message_ptr;
  55. typedef typename config::con_msg_manager_type msg_manager_type;
  56. typedef typename msg_manager_type::ptr msg_manager_ptr;
  57. typedef typename config::rng_type rng_type;
  58. typedef typename config::permessage_deflate_type permessage_deflate_type;
  59. typedef std::pair<lib::error_code, std::string> err_str_pair;
  60. explicit hybi13(bool secure, bool p_is_server, msg_manager_ptr manager, rng_type & rng) :
  61. processor<config>(secure, p_is_server),
  62. m_msg_manager(manager),
  63. m_rng(rng)
  64. {
  65. reset_headers();
  66. }
  67. int get_version() const
  68. {
  69. return 13;
  70. }
  71. bool has_permessage_deflate() const
  72. {
  73. return m_permessage_deflate.is_implemented();
  74. }
  75. err_str_pair negotiate_extensions(const request_type & request)
  76. {
  77. return negotiate_extensions_helper(request);
  78. }
  79. err_str_pair negotiate_extensions(const response_type & response)
  80. {
  81. return negotiate_extensions_helper(response);
  82. }
  83. /// Extension negotiation helper function
  84. /**
  85. * This exists mostly because the code for requests and responses is
  86. * identical and I can't have virtual template methods.
  87. */
  88. template <typename header_type> err_str_pair negotiate_extensions_helper(const header_type & header)
  89. {
  90. err_str_pair ret;
  91. // Respect blanket disabling of all extensions and don't even parse
  92. // the extension header
  93. if (! config::enable_extensions)
  94. {
  95. ret.first = make_error_code(error::extensions_disabled);
  96. return ret;
  97. }
  98. http::parameter_list p;
  99. bool error = header.get_header_as_plist("Sec-WebSocket-Extensions", p);
  100. if (error)
  101. {
  102. ret.first = make_error_code(error::extension_parse_error);
  103. return ret;
  104. }
  105. // If there are no extensions parsed then we are done!
  106. if (p.size() == 0)
  107. {
  108. return ret;
  109. }
  110. http::parameter_list::const_iterator it;
  111. // look through the list of extension requests to find the first
  112. // one that we can accept.
  113. if (m_permessage_deflate.is_implemented())
  114. {
  115. err_str_pair neg_ret;
  116. for (it = p.begin(); it != p.end(); ++it)
  117. {
  118. // not a permessage-deflate extension request, ignore
  119. if (it->first != "permessage-deflate")
  120. {
  121. continue;
  122. }
  123. // if we have already successfully negotiated this extension
  124. // then skip any other requests to negotiate the same one
  125. // with different parameters
  126. if (m_permessage_deflate.is_enabled())
  127. {
  128. continue;
  129. }
  130. // attempt to negotiate this offer
  131. neg_ret = m_permessage_deflate.negotiate(it->second);
  132. if (neg_ret.first)
  133. {
  134. // negotiation offer failed. Do nothing. We will continue
  135. // searching for a permessage-deflate config that succeeds
  136. continue;
  137. }
  138. // Negotiation tentatively succeeded
  139. // Actually try to initialize the extension before we
  140. // deem negotiation complete
  141. lib::error_code ec = m_permessage_deflate.init(base::m_server);
  142. if (ec)
  143. {
  144. // Negotiation succeeded but initialization failed this is
  145. // an error that should stop negotiation of permessage
  146. // deflate. Return the reason for the init failure
  147. ret.first = ec;
  148. break;
  149. }
  150. else
  151. {
  152. // Successfully initialized, push the negotiated response into
  153. // the reply and stop looking for additional permessage-deflate
  154. // extensions
  155. ret.second += neg_ret.second;
  156. break;
  157. }
  158. }
  159. }
  160. // support for future extensions would go here. Should check the value of
  161. // ret.first before continuing. Might need to consider whether failure of
  162. // negotiation of an earlier extension should stop negotiation of subsequent
  163. // ones
  164. return ret;
  165. }
  166. lib::error_code validate_handshake(const request_type & r) const
  167. {
  168. if (r.get_method() != "GET")
  169. {
  170. return make_error_code(error::invalid_http_method);
  171. }
  172. if (r.get_version() != "HTTP/1.1")
  173. {
  174. return make_error_code(error::invalid_http_version);
  175. }
  176. // required headers
  177. // Host is required by HTTP/1.1
  178. // Connection is required by is_websocket_handshake
  179. // Upgrade is required by is_websocket_handshake
  180. if (r.get_header("Sec-WebSocket-Key").empty())
  181. {
  182. return make_error_code(error::missing_required_header);
  183. }
  184. return lib::error_code();
  185. }
  186. /* TODO: the 'subprotocol' parameter may need to be expanded into a more
  187. * generic struct if other user input parameters to the processed handshake
  188. * are found.
  189. */
  190. lib::error_code process_handshake(const request_type & request, const std::string & subprotocol, response_type & response) const
  191. {
  192. std::string server_key = request.get_header("Sec-WebSocket-Key");
  193. lib::error_code ec = process_handshake_key(server_key);
  194. if (ec)
  195. {
  196. return ec;
  197. }
  198. response.replace_header("Sec-WebSocket-Accept", server_key);
  199. response.append_header("Upgrade", constants::upgrade_token);
  200. response.append_header("Connection", constants::connection_token);
  201. if (! subprotocol.empty())
  202. {
  203. response.replace_header("Sec-WebSocket-Protocol", subprotocol);
  204. }
  205. return lib::error_code();
  206. }
  207. /// Fill in a set of request headers for a client connection request
  208. /**
  209. * @param [out] req Set of headers to fill in
  210. * @param [in] uri The uri being connected to
  211. * @param [in] subprotocols The list of subprotocols to request
  212. */
  213. lib::error_code client_handshake_request(request_type & req, uri_ptr uri, const std::vector<std::string> & subprotocols) const
  214. {
  215. req.set_method("GET");
  216. req.set_uri(uri->get_resource());
  217. req.set_version("HTTP/1.1");
  218. req.append_header("Upgrade", "websocket");
  219. req.append_header("Connection", "Upgrade");
  220. req.replace_header("Sec-WebSocket-Version", "13");
  221. req.replace_header("Host", uri->get_host_port());
  222. if (! subprotocols.empty())
  223. {
  224. std::ostringstream result;
  225. std::vector<std::string>::const_iterator it = subprotocols.begin();
  226. result << *it++;
  227. while (it != subprotocols.end())
  228. {
  229. result << ", " << *it++;
  230. }
  231. req.replace_header("Sec-WebSocket-Protocol", result.str());
  232. }
  233. // Generate handshake key
  234. frame::uint32_converter conv;
  235. unsigned char raw_key[16];
  236. for (int i = 0; i < 4; i++)
  237. {
  238. conv.i = m_rng();
  239. std::copy(conv.c, conv.c + 4, &raw_key[i * 4]);
  240. }
  241. req.replace_header("Sec-WebSocket-Key", base64_encode(raw_key, 16));
  242. if (m_permessage_deflate.is_implemented())
  243. {
  244. std::string offer = m_permessage_deflate.generate_offer();
  245. if (! offer.empty())
  246. {
  247. req.replace_header("Sec-WebSocket-Extensions", offer);
  248. }
  249. }
  250. return lib::error_code();
  251. }
  252. /// Validate the server's response to an outgoing handshake request
  253. /**
  254. * @param req The original request sent
  255. * @param res The reponse to generate
  256. * @return An error code, 0 on success, non-zero for other errors
  257. */
  258. lib::error_code validate_server_handshake_response(const request_type & req, response_type & res) const
  259. {
  260. // A valid response has an HTTP 101 switching protocols code
  261. if (res.get_status_code() != http::status_code::switching_protocols)
  262. {
  263. return error::make_error_code(error::invalid_http_status);
  264. }
  265. // And the upgrade token in an upgrade header
  266. const std::string & upgrade_header = res.get_header("Upgrade");
  267. if (utility::ci_find_substr(upgrade_header, constants::upgrade_token, sizeof(constants::upgrade_token) - 1) == upgrade_header.end())
  268. {
  269. return error::make_error_code(error::missing_required_header);
  270. }
  271. // And the websocket token in the connection header
  272. const std::string & con_header = res.get_header("Connection");
  273. if (utility::ci_find_substr(con_header, constants::connection_token, sizeof(constants::connection_token) - 1) == con_header.end())
  274. {
  275. return error::make_error_code(error::missing_required_header);
  276. }
  277. // And has a valid Sec-WebSocket-Accept value
  278. std::string key = req.get_header("Sec-WebSocket-Key");
  279. lib::error_code ec = process_handshake_key(key);
  280. if (ec || key != res.get_header("Sec-WebSocket-Accept"))
  281. {
  282. return error::make_error_code(error::missing_required_header);
  283. }
  284. // check extensions
  285. return lib::error_code();
  286. }
  287. std::string get_raw(const response_type & res) const
  288. {
  289. return res.raw();
  290. }
  291. const std::string & get_origin(const request_type & r) const
  292. {
  293. return r.get_header("Origin");
  294. }
  295. lib::error_code extract_subprotocols(const request_type & req, std::vector<std::string> & subprotocol_list)
  296. {
  297. if (! req.get_header("Sec-WebSocket-Protocol").empty())
  298. {
  299. http::parameter_list p;
  300. if (! req.get_header_as_plist("Sec-WebSocket-Protocol", p))
  301. {
  302. http::parameter_list::const_iterator it;
  303. for (it = p.begin(); it != p.end(); ++it)
  304. {
  305. subprotocol_list.push_back(it->first);
  306. }
  307. }
  308. else
  309. {
  310. return error::make_error_code(error::subprotocol_parse_error);
  311. }
  312. }
  313. return lib::error_code();
  314. }
  315. uri_ptr get_uri(const request_type & request) const
  316. {
  317. return get_uri_from_host(request, base::m_secure ? "wss" : "ws");
  318. }
  319. /// Process new websocket connection bytes
  320. /**
  321. *
  322. * Hybi 13 data streams represent a series of variable length frames. Each
  323. * frame is made up of a series of fixed length fields. The lengths of later
  324. * fields are contained in earlier fields. The first field length is fixed
  325. * by the spec.
  326. *
  327. * This processor represents a state machine that keeps track of what field
  328. * is presently being read and how many more bytes are needed to complete it
  329. *
  330. *
  331. *
  332. *
  333. * Read two header bytes
  334. * Extract full frame length.
  335. * Read extra header bytes
  336. * Validate frame header (including extension validate)
  337. * Read extension data into extension message state object
  338. * Read payload data into payload
  339. *
  340. * @param buf Input buffer
  341. *
  342. * @param len Length of input buffer
  343. *
  344. * @return Number of bytes processed or zero on error
  345. */
  346. size_t consume(uint8_t * buf, size_t len, lib::error_code & ec)
  347. {
  348. size_t p = 0;
  349. ec = lib::error_code();
  350. // std::cout << "consume: " << utility::to_hex(buf,len) << std::endl;
  351. // Loop while we don't have a message ready and we still have bytes
  352. // left to process.
  353. while (m_state != READY && m_state != FATAL_ERROR && (p < len || m_bytes_needed == 0))
  354. {
  355. if (m_state == HEADER_BASIC)
  356. {
  357. p += this->copy_basic_header_bytes(buf + p, len - p);
  358. if (m_bytes_needed > 0)
  359. {
  360. continue;
  361. }
  362. ec = this->validate_incoming_basic_header(m_basic_header, base::m_server, ! m_data_msg.msg_ptr);
  363. if (ec)
  364. {
  365. break;
  366. }
  367. // extract full header size and adjust consume state accordingly
  368. m_state = HEADER_EXTENDED;
  369. m_cursor = 0;
  370. m_bytes_needed = frame::get_header_len(m_basic_header) - frame::BASIC_HEADER_LENGTH;
  371. }
  372. else if (m_state == HEADER_EXTENDED)
  373. {
  374. p += this->copy_extended_header_bytes(buf + p, len - p);
  375. if (m_bytes_needed > 0)
  376. {
  377. continue;
  378. }
  379. ec = validate_incoming_extended_header(m_basic_header, m_extended_header);
  380. if (ec)
  381. {
  382. break;
  383. }
  384. m_state = APPLICATION;
  385. m_bytes_needed = static_cast<size_t>(get_payload_size(m_basic_header, m_extended_header));
  386. // check if this frame is the start of a new message and set up
  387. // the appropriate message metadata.
  388. frame::opcode::value op = frame::get_opcode(m_basic_header);
  389. // TODO: get_message failure conditions
  390. if (frame::opcode::is_control(op))
  391. {
  392. m_control_msg = msg_metadata(m_msg_manager->get_message(op, m_bytes_needed), frame::get_masking_key(m_basic_header, m_extended_header));
  393. m_current_msg = &m_control_msg;
  394. }
  395. else
  396. {
  397. if (! m_data_msg.msg_ptr)
  398. {
  399. if (m_bytes_needed > base::m_max_message_size)
  400. {
  401. ec = make_error_code(error::message_too_big);
  402. break;
  403. }
  404. m_data_msg = msg_metadata(m_msg_manager->get_message(op, m_bytes_needed), frame::get_masking_key(m_basic_header, m_extended_header));
  405. if (m_permessage_deflate.is_enabled())
  406. {
  407. m_data_msg.msg_ptr->set_compressed(frame::get_rsv1(m_basic_header));
  408. }
  409. }
  410. else
  411. {
  412. // Fetch the underlying payload buffer from the data message we
  413. // are writing into.
  414. std::string & out = m_data_msg.msg_ptr->get_raw_payload();
  415. if (out.size() + m_bytes_needed > base::m_max_message_size)
  416. {
  417. ec = make_error_code(error::message_too_big);
  418. break;
  419. }
  420. // Each frame starts a new masking key. All other state
  421. // remains between frames.
  422. m_data_msg.prepared_key = prepare_masking_key(frame::get_masking_key(m_basic_header, m_extended_header));
  423. out.reserve(out.size() + m_bytes_needed);
  424. }
  425. m_current_msg = &m_data_msg;
  426. }
  427. }
  428. else if (m_state == EXTENSION)
  429. {
  430. m_state = APPLICATION;
  431. }
  432. else if (m_state == APPLICATION)
  433. {
  434. size_t bytes_to_process = (std::min) (m_bytes_needed, len - p);
  435. if (bytes_to_process > 0)
  436. {
  437. p += this->process_payload_bytes(buf + p, bytes_to_process, ec);
  438. if (ec)
  439. {
  440. break;
  441. }
  442. }
  443. if (m_bytes_needed > 0)
  444. {
  445. continue;
  446. }
  447. // If this was the last frame in the message set the ready flag.
  448. // Otherwise, reset processor state to read additional frames.
  449. if (frame::get_fin(m_basic_header))
  450. {
  451. ec = finalize_message();
  452. if (ec)
  453. {
  454. break;
  455. }
  456. }
  457. else
  458. {
  459. this->reset_headers();
  460. }
  461. }
  462. else
  463. {
  464. // shouldn't be here
  465. ec = make_error_code(error::general);
  466. return 0;
  467. }
  468. }
  469. return p;
  470. }
  471. /// Perform any finalization actions on an incoming message
  472. /**
  473. * Called after the full message is received. Provides the opportunity for
  474. * extensions to complete any data post processing as well as final UTF8
  475. * validation checks for text messages.
  476. *
  477. * @return A code indicating errors, if any
  478. */
  479. lib::error_code finalize_message()
  480. {
  481. std::string & out = m_current_msg->msg_ptr->get_raw_payload();
  482. // if the frame is compressed, append the compression
  483. // trailer and flush the compression buffer.
  484. if (m_permessage_deflate.is_enabled() && m_current_msg->msg_ptr->get_compressed())
  485. {
  486. uint8_t trailer[4] = {0x00, 0x00, 0xff, 0xff};
  487. // Decompress current buffer into the message buffer
  488. lib::error_code ec;
  489. ec = m_permessage_deflate.decompress(trailer, 4, out);
  490. if (ec)
  491. {
  492. return ec;
  493. }
  494. }
  495. // ensure that text messages end on a valid UTF8 code point
  496. if (frame::get_opcode(m_basic_header) == frame::opcode::TEXT)
  497. {
  498. if (! m_current_msg->validator.complete())
  499. {
  500. return make_error_code(error::invalid_utf8);
  501. }
  502. }
  503. m_state = READY;
  504. return lib::error_code();
  505. }
  506. void reset_headers()
  507. {
  508. m_state = HEADER_BASIC;
  509. m_bytes_needed = frame::BASIC_HEADER_LENGTH;
  510. m_basic_header.b0 = 0x00;
  511. m_basic_header.b1 = 0x00;
  512. std::fill_n(m_extended_header.bytes, frame::MAX_EXTENDED_HEADER_LENGTH, 0x00);
  513. }
  514. /// Test whether or not the processor has a message ready
  515. bool ready() const
  516. {
  517. return (m_state == READY);
  518. }
  519. message_ptr get_message()
  520. {
  521. if (! ready())
  522. {
  523. return message_ptr();
  524. }
  525. message_ptr ret = m_current_msg->msg_ptr;
  526. m_current_msg->msg_ptr.reset();
  527. if (frame::opcode::is_control(ret->get_opcode()))
  528. {
  529. m_control_msg.msg_ptr.reset();
  530. }
  531. else
  532. {
  533. m_data_msg.msg_ptr.reset();
  534. }
  535. this->reset_headers();
  536. return ret;
  537. }
  538. /// Test whether or not the processor is in a fatal error state.
  539. bool get_error() const
  540. {
  541. return m_state == FATAL_ERROR;
  542. }
  543. size_t get_bytes_needed() const
  544. {
  545. return m_bytes_needed;
  546. }
  547. /// Prepare a user data message for writing
  548. /**
  549. * Performs validation, masking, compression, etc. will return an error if
  550. * there was an error, otherwise msg will be ready to be written
  551. *
  552. * TODO: tests
  553. *
  554. * @param in An unprepared message to prepare
  555. * @param out A message to be overwritten with the prepared message
  556. * @return error code
  557. */
  558. virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
  559. {
  560. if (! in || ! out)
  561. {
  562. return make_error_code(error::invalid_arguments);
  563. }
  564. frame::opcode::value op = in->get_opcode();
  565. // validate opcode: only regular data frames
  566. if (frame::opcode::is_control(op))
  567. {
  568. return make_error_code(error::invalid_opcode);
  569. }
  570. std::string & i = in->get_raw_payload();
  571. std::string & o = out->get_raw_payload();
  572. // validate payload utf8
  573. if (op == frame::opcode::TEXT && ! utf8_validator::validate(i))
  574. {
  575. return make_error_code(error::invalid_payload);
  576. }
  577. frame::masking_key_type key;
  578. bool masked = ! base::m_server;
  579. bool compressed = m_permessage_deflate.is_enabled() && in->get_compressed();
  580. bool fin = in->get_fin();
  581. if (masked)
  582. {
  583. // Generate masking key.
  584. key.i = m_rng();
  585. }
  586. else
  587. {
  588. key.i = 0;
  589. }
  590. // prepare payload
  591. if (compressed)
  592. {
  593. // compress and store in o after header.
  594. m_permessage_deflate.compress(i, o);
  595. if (o.size() < 4)
  596. {
  597. return make_error_code(error::general);
  598. }
  599. // Strip trailing 4 0x00 0x00 0xff 0xff bytes before writing to the
  600. // wire
  601. o.resize(o.size() - 4);
  602. // mask in place if necessary
  603. if (masked)
  604. {
  605. this->masked_copy(o, o, key);
  606. }
  607. }
  608. else
  609. {
  610. // no compression, just copy data into the output buffer
  611. o.resize(i.size());
  612. // if we are masked, have the masking function write to the output
  613. // buffer directly to avoid another copy. If not masked, copy
  614. // directly without masking.
  615. if (masked)
  616. {
  617. this->masked_copy(i, o, key);
  618. }
  619. else
  620. {
  621. std::copy(i.begin(), i.end(), o.begin());
  622. }
  623. }
  624. // generate header
  625. frame::basic_header h(op, o.size(), fin, masked, compressed);
  626. if (masked)
  627. {
  628. frame::extended_header e(o.size(), key.i);
  629. out->set_header(frame::prepare_header(h, e));
  630. }
  631. else
  632. {
  633. frame::extended_header e(o.size());
  634. out->set_header(frame::prepare_header(h, e));
  635. }
  636. out->set_prepared(true);
  637. out->set_opcode(op);
  638. return lib::error_code();
  639. }
  640. /// Get URI
  641. lib::error_code prepare_ping(const std::string & in, message_ptr out) const
  642. {
  643. return this->prepare_control(frame::opcode::PING, in, out);
  644. }
  645. lib::error_code prepare_pong(const std::string & in, message_ptr out) const
  646. {
  647. return this->prepare_control(frame::opcode::PONG, in, out);
  648. }
  649. virtual lib::error_code prepare_close(close::status::value code, const std::string & reason, message_ptr out) const
  650. {
  651. if (close::status::reserved(code))
  652. {
  653. return make_error_code(error::reserved_close_code);
  654. }
  655. if (close::status::invalid(code) && code != close::status::no_status)
  656. {
  657. return make_error_code(error::invalid_close_code);
  658. }
  659. if (code == close::status::no_status && reason.size() > 0)
  660. {
  661. return make_error_code(error::reason_requires_code);
  662. }
  663. if (reason.size() > frame::limits::payload_size_basic - 2)
  664. {
  665. return make_error_code(error::control_too_big);
  666. }
  667. std::string payload;
  668. if (code != close::status::no_status)
  669. {
  670. close::code_converter val;
  671. val.i = htons(code);
  672. payload.resize(reason.size() + 2);
  673. payload[0] = val.c[0];
  674. payload[1] = val.c[1];
  675. std::copy(reason.begin(), reason.end(), payload.begin() + 2);
  676. }
  677. return this->prepare_control(frame::opcode::CLOSE, payload, out);
  678. }
  679. protected:
  680. /// Convert a client handshake key into a server response key in place
  681. lib::error_code process_handshake_key(std::string & key) const
  682. {
  683. key.append(constants::handshake_guid);
  684. unsigned char message_digest[20];
  685. sha1::calc(key.c_str(), key.length(), message_digest);
  686. key = base64_encode(message_digest, 20);
  687. return lib::error_code();
  688. }
  689. /// Reads bytes from buf into m_basic_header
  690. size_t copy_basic_header_bytes(const uint8_t * buf, size_t len)
  691. {
  692. if (len == 0 || m_bytes_needed == 0)
  693. {
  694. return 0;
  695. }
  696. if (len > 1)
  697. {
  698. // have at least two bytes
  699. if (m_bytes_needed == 2)
  700. {
  701. m_basic_header.b0 = buf[0];
  702. m_basic_header.b1 = buf[1];
  703. m_bytes_needed -= 2;
  704. return 2;
  705. }
  706. else
  707. {
  708. m_basic_header.b1 = buf[0];
  709. m_bytes_needed--;
  710. return 1;
  711. }
  712. }
  713. else
  714. {
  715. // have exactly one byte
  716. if (m_bytes_needed == 2)
  717. {
  718. m_basic_header.b0 = buf[0];
  719. m_bytes_needed--;
  720. return 1;
  721. }
  722. else
  723. {
  724. m_basic_header.b1 = buf[0];
  725. m_bytes_needed--;
  726. return 1;
  727. }
  728. }
  729. }
  730. /// Reads bytes from buf into m_extended_header
  731. size_t copy_extended_header_bytes(const uint8_t * buf, size_t len)
  732. {
  733. size_t bytes_to_read = (std::min) (m_bytes_needed, len);
  734. std::copy(buf, buf + bytes_to_read, m_extended_header.bytes + m_cursor);
  735. m_cursor += bytes_to_read;
  736. m_bytes_needed -= bytes_to_read;
  737. return bytes_to_read;
  738. }
  739. /// Reads bytes from buf into message payload
  740. /**
  741. * This function performs unmasking and uncompression, validates the
  742. * decoded bytes, and writes them to the appropriate message buffer.
  743. *
  744. * This member function will use the input buffer as stratch space for its
  745. * work. The raw input bytes will not be preserved. This applies only to the
  746. * bytes actually needed. At most min(m_bytes_needed,len) will be processed.
  747. *
  748. * @param buf Input/working buffer
  749. * @param len Length of buf
  750. * @return Number of bytes processed or zero in case of an error
  751. */
  752. size_t process_payload_bytes(uint8_t * buf, size_t len, lib::error_code & ec)
  753. {
  754. // unmask if masked
  755. if (frame::get_masked(m_basic_header))
  756. {
  757. m_current_msg->prepared_key = frame::byte_mask_circ(buf, len, m_current_msg->prepared_key);
  758. // TODO: SIMD masking
  759. }
  760. std::string & out = m_current_msg->msg_ptr->get_raw_payload();
  761. size_t offset = out.size();
  762. // decompress message if needed.
  763. if (m_permessage_deflate.is_enabled() && m_current_msg->msg_ptr->get_compressed())
  764. {
  765. // Decompress current buffer into the message buffer
  766. ec = m_permessage_deflate.decompress(buf, len, out);
  767. if (ec)
  768. {
  769. return 0;
  770. }
  771. }
  772. else
  773. {
  774. // No compression, straight copy
  775. out.append(reinterpret_cast<char *>(buf), len);
  776. }
  777. // validate unmasked, decompressed values
  778. if (m_current_msg->msg_ptr->get_opcode() == frame::opcode::TEXT)
  779. {
  780. if (! m_current_msg->validator.decode(out.begin() + offset, out.end()))
  781. {
  782. ec = make_error_code(error::invalid_utf8);
  783. return 0;
  784. }
  785. }
  786. m_bytes_needed -= len;
  787. return len;
  788. }
  789. /// Validate an incoming basic header
  790. /**
  791. * Validates an incoming hybi13 basic header.
  792. *
  793. * @param h The basic header to validate
  794. * @param is_server Whether or not the endpoint that received this frame
  795. * is a server.
  796. * @param new_msg Whether or not this is the first frame of the message
  797. * @return 0 on success or a non-zero error code on failure
  798. */
  799. lib::error_code validate_incoming_basic_header(const frame::basic_header & h, bool is_server, bool new_msg) const
  800. {
  801. frame::opcode::value op = frame::get_opcode(h);
  802. // Check control frame size limit
  803. if (frame::opcode::is_control(op) && frame::get_basic_size(h) > frame::limits::payload_size_basic)
  804. {
  805. return make_error_code(error::control_too_big);
  806. }
  807. // Check that RSV bits are clear
  808. // The only RSV bits allowed are rsv1 if the permessage_compress
  809. // extension is enabled for this connection and the message is not
  810. // a control message.
  811. //
  812. // TODO: unit tests for this
  813. if (frame::get_rsv1(h) && (! m_permessage_deflate.is_enabled() || frame::opcode::is_control(op)))
  814. {
  815. return make_error_code(error::invalid_rsv_bit);
  816. }
  817. if (frame::get_rsv2(h) || frame::get_rsv3(h))
  818. {
  819. return make_error_code(error::invalid_rsv_bit);
  820. }
  821. // Check for reserved opcodes
  822. if (frame::opcode::reserved(op))
  823. {
  824. return make_error_code(error::invalid_opcode);
  825. }
  826. // Check for invalid opcodes
  827. // TODO: unit tests for this?
  828. if (frame::opcode::invalid(op))
  829. {
  830. return make_error_code(error::invalid_opcode);
  831. }
  832. // Check for fragmented control message
  833. if (frame::opcode::is_control(op) && ! frame::get_fin(h))
  834. {
  835. return make_error_code(error::fragmented_control);
  836. }
  837. // Check for continuation without an active message
  838. if (new_msg && op == frame::opcode::CONTINUATION)
  839. {
  840. return make_error_code(error::invalid_continuation);
  841. }
  842. // Check for new data frame when expecting continuation
  843. if (! new_msg && ! frame::opcode::is_control(op) && op != frame::opcode::CONTINUATION)
  844. {
  845. return make_error_code(error::invalid_continuation);
  846. }
  847. // Servers should reject any unmasked frames from clients.
  848. // Clients should reject any masked frames from servers.
  849. if (is_server && ! frame::get_masked(h))
  850. {
  851. return make_error_code(error::masking_required);
  852. }
  853. else if (! is_server && frame::get_masked(h))
  854. {
  855. return make_error_code(error::masking_forbidden);
  856. }
  857. return lib::error_code();
  858. }
  859. /// Validate an incoming extended header
  860. /**
  861. * Validates an incoming hybi13 full header.
  862. *
  863. * @todo unit test for the >32 bit frames on 32 bit systems case
  864. *
  865. * @param h The basic header to validate
  866. * @param e The extended header to validate
  867. * @return An error_code, non-zero values indicate why the validation
  868. * failed
  869. */
  870. lib::error_code validate_incoming_extended_header(frame::basic_header h, frame::extended_header e) const
  871. {
  872. uint8_t basic_size = frame::get_basic_size(h);
  873. uint64_t payload_size = frame::get_payload_size(h, e);
  874. // Check for non-minimally encoded payloads
  875. if (basic_size == frame::payload_size_code_16bit && payload_size <= frame::limits::payload_size_basic)
  876. {
  877. return make_error_code(error::non_minimal_encoding);
  878. }
  879. if (basic_size == frame::payload_size_code_64bit && payload_size <= frame::limits::payload_size_extended)
  880. {
  881. return make_error_code(error::non_minimal_encoding);
  882. }
  883. // Check for >32bit frames on 32 bit systems
  884. if (sizeof(size_t) == 4 && (payload_size >> 32))
  885. {
  886. return make_error_code(error::requires_64bit);
  887. }
  888. return lib::error_code();
  889. }
  890. /// Copy and mask/unmask in one operation
  891. /**
  892. * Reads input from one string and writes unmasked output to another.
  893. *
  894. * @param [in] i The input string.
  895. * @param [out] o The output string.
  896. * @param [in] key The masking key to use for masking/unmasking
  897. */
  898. void masked_copy(const std::string & i, std::string & o, frame::masking_key_type key) const
  899. {
  900. frame::byte_mask(i.begin(), i.end(), o.begin(), key);
  901. // TODO: SIMD masking
  902. }
  903. /// Generic prepare control frame with opcode and payload.
  904. /**
  905. * Internal control frame building method. Handles validation, masking, etc
  906. *
  907. * @param op The control opcode to use
  908. * @param payload The payload to use
  909. * @param out The message buffer to store the prepared frame in
  910. * @return Status code, zero on success, non-zero on error
  911. */
  912. lib::error_code prepare_control(frame::opcode::value op, const std::string & payload, message_ptr out) const
  913. {
  914. if (! out)
  915. {
  916. return make_error_code(error::invalid_arguments);
  917. }
  918. if (! frame::opcode::is_control(op))
  919. {
  920. return make_error_code(error::invalid_opcode);
  921. }
  922. if (payload.size() > frame::limits::payload_size_basic)
  923. {
  924. return make_error_code(error::control_too_big);
  925. }
  926. frame::masking_key_type key;
  927. bool masked = ! base::m_server;
  928. frame::basic_header h(op, payload.size(), true, masked);
  929. std::string & o = out->get_raw_payload();
  930. o.resize(payload.size());
  931. if (masked)
  932. {
  933. // Generate masking key.
  934. key.i = m_rng();
  935. frame::extended_header e(payload.size(), key.i);
  936. out->set_header(frame::prepare_header(h, e));
  937. this->masked_copy(payload, o, key);
  938. }
  939. else
  940. {
  941. frame::extended_header e(payload.size());
  942. out->set_header(frame::prepare_header(h, e));
  943. std::copy(payload.begin(), payload.end(), o.begin());
  944. }
  945. out->set_opcode(op);
  946. out->set_prepared(true);
  947. return lib::error_code();
  948. }
  949. enum state
  950. {
  951. HEADER_BASIC = 0,
  952. HEADER_EXTENDED = 1,
  953. EXTENSION = 2,
  954. APPLICATION = 3,
  955. READY = 4,
  956. FATAL_ERROR = 5
  957. };
  958. /// This data structure holds data related to processing a message, such as
  959. /// the buffer it is being written to, its masking key, its UTF8 validation
  960. /// state, and sometimes its compression state.
  961. struct msg_metadata
  962. {
  963. msg_metadata() {}
  964. msg_metadata(message_ptr m, size_t p) :
  965. msg_ptr(m),
  966. prepared_key(p)
  967. {
  968. }
  969. msg_metadata(message_ptr m, frame::masking_key_type p) :
  970. msg_ptr(m),
  971. prepared_key(prepare_masking_key(p))
  972. {
  973. }
  974. message_ptr msg_ptr; // pointer to the message data buffer
  975. size_t prepared_key; // prepared masking key
  976. utf8_validator::validator validator; // utf8 validation state
  977. };
  978. // Basic header of the frame being read
  979. frame::basic_header m_basic_header;
  980. // Pointer to a manager that can create message buffers for us.
  981. msg_manager_ptr m_msg_manager;
  982. // Number of bytes needed to complete the current operation
  983. size_t m_bytes_needed;
  984. // Number of extended header bytes read
  985. size_t m_cursor;
  986. // Metadata for the current data msg
  987. msg_metadata m_data_msg;
  988. // Metadata for the current control msg
  989. msg_metadata m_control_msg;
  990. // Pointer to the metadata associated with the frame being read
  991. msg_metadata * m_current_msg;
  992. // Extended header of current frame
  993. frame::extended_header m_extended_header;
  994. rng_type & m_rng;
  995. // Overall state of the processor
  996. state m_state;
  997. // Extensions
  998. permessage_deflate_type m_permessage_deflate;
  999. };
  1000. } // namespace processor
  1001. } // namespace websocketpp
  1002. #endif // WEBSOCKETPP_PROCESSOR_HYBI13_HPP