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.

496 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #ifndef WEBSOCKETPP_PROCESSOR_HYBI00_HPP
  28. #define WEBSOCKETPP_PROCESSOR_HYBI00_HPP
  29. #include <algorithm>
  30. #include <cstdlib>
  31. #include <string>
  32. #include <vector>
  33. #include <websocketpp/common/md5.hpp>
  34. #include <websocketpp/common/network.hpp>
  35. #include <websocketpp/common/platforms.hpp>
  36. #include <websocketpp/frame.hpp>
  37. #include <websocketpp/http/constants.hpp>
  38. #include <websocketpp/processors/processor.hpp>
  39. #include <websocketpp/utf8_validator.hpp>
  40. namespace websocketpp
  41. {
  42. namespace processor
  43. {
  44. /// Processor for Hybi Draft version 00
  45. /**
  46. * There are many differences between Hybi 00 and Hybi 13
  47. */
  48. template <typename config> class hybi00 : public processor<config>
  49. {
  50. public:
  51. typedef processor<config> base;
  52. typedef typename config::request_type request_type;
  53. typedef typename config::response_type response_type;
  54. typedef typename config::message_type message_type;
  55. typedef typename message_type::ptr message_ptr;
  56. typedef typename config::con_msg_manager_type::ptr msg_manager_ptr;
  57. explicit hybi00(bool secure, bool p_is_server, msg_manager_ptr manager) :
  58. processor<config>(secure, p_is_server),
  59. msg_hdr(0x00),
  60. msg_ftr(0xff),
  61. m_state(HEADER),
  62. m_msg_manager(manager)
  63. {
  64. }
  65. int get_version() const
  66. {
  67. return 0;
  68. }
  69. lib::error_code validate_handshake(const request_type & r) const
  70. {
  71. if (r.get_method() != "GET")
  72. {
  73. return make_error_code(error::invalid_http_method);
  74. }
  75. if (r.get_version() != "HTTP/1.1")
  76. {
  77. return make_error_code(error::invalid_http_version);
  78. }
  79. // required headers
  80. // Host is required by HTTP/1.1
  81. // Connection is required by is_websocket_handshake
  82. // Upgrade is required by is_websocket_handshake
  83. if (r.get_header("Sec-WebSocket-Key1").empty() || r.get_header("Sec-WebSocket-Key2").empty() || r.get_header("Sec-WebSocket-Key3").empty())
  84. {
  85. return make_error_code(error::missing_required_header);
  86. }
  87. return lib::error_code();
  88. }
  89. lib::error_code process_handshake(const request_type & req, const std::string & subprotocol, response_type & res) const
  90. {
  91. char key_final[16];
  92. // copy key1 into final key
  93. decode_client_key(req.get_header("Sec-WebSocket-Key1"), &key_final[0]);
  94. // copy key2 into final key
  95. decode_client_key(req.get_header("Sec-WebSocket-Key2"), &key_final[4]);
  96. // copy key3 into final key
  97. // key3 should be exactly 8 bytes. If it is more it will be truncated
  98. // if it is less the final key will almost certainly be wrong.
  99. // TODO: decide if it is best to silently fail here or produce some sort
  100. // of warning or exception.
  101. const std::string & key3 = req.get_header("Sec-WebSocket-Key3");
  102. std::copy(key3.c_str(), key3.c_str() + (std::min) (static_cast<size_t>(8), key3.size()), &key_final[8]);
  103. res.append_header("Sec-WebSocket-Key3", md5::md5_hash_string(std::string(key_final, 16)));
  104. res.append_header("Upgrade", "WebSocket");
  105. res.append_header("Connection", "Upgrade");
  106. // Echo back client's origin unless our local application set a
  107. // more restrictive one.
  108. if (res.get_header("Sec-WebSocket-Origin").empty())
  109. {
  110. res.append_header("Sec-WebSocket-Origin", req.get_header("Origin"));
  111. }
  112. // Echo back the client's request host unless our local application
  113. // set a different one.
  114. if (res.get_header("Sec-WebSocket-Location").empty())
  115. {
  116. uri_ptr uri = get_uri(req);
  117. res.append_header("Sec-WebSocket-Location", uri->str());
  118. }
  119. if (! subprotocol.empty())
  120. {
  121. res.replace_header("Sec-WebSocket-Protocol", subprotocol);
  122. }
  123. return lib::error_code();
  124. }
  125. /// Fill in a set of request headers for a client connection request
  126. /**
  127. * The Hybi 00 processor only implements incoming connections so this will
  128. * always return an error.
  129. *
  130. * @param [out] req Set of headers to fill in
  131. * @param [in] uri The uri being connected to
  132. * @param [in] subprotocols The list of subprotocols to request
  133. */
  134. lib::error_code client_handshake_request(request_type &, uri_ptr, const std::vector<std::string> &) const
  135. {
  136. return error::make_error_code(error::no_protocol_support);
  137. }
  138. /// Validate the server's response to an outgoing handshake request
  139. /**
  140. * The Hybi 00 processor only implements incoming connections so this will
  141. * always return an error.
  142. *
  143. * @param req The original request sent
  144. * @param res The reponse to generate
  145. * @return An error code, 0 on success, non-zero for other errors
  146. */
  147. lib::error_code validate_server_handshake_response(const request_type &, response_type &) const
  148. {
  149. return error::make_error_code(error::no_protocol_support);
  150. }
  151. std::string get_raw(const response_type & res) const
  152. {
  153. response_type temp = res;
  154. temp.remove_header("Sec-WebSocket-Key3");
  155. return temp.raw() + res.get_header("Sec-WebSocket-Key3");
  156. }
  157. const std::string & get_origin(const request_type & r) const
  158. {
  159. return r.get_header("Origin");
  160. }
  161. /// Extracts requested subprotocols from a handshake request
  162. /**
  163. * hybi00 does support subprotocols
  164. * https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.9
  165. *
  166. * @param [in] req The request to extract from
  167. * @param [out] subprotocol_list A reference to a vector of strings to store
  168. * the results in.
  169. */
  170. lib::error_code extract_subprotocols(const request_type & req, std::vector<std::string> & subprotocol_list)
  171. {
  172. if (! req.get_header("Sec-WebSocket-Protocol").empty())
  173. {
  174. http::parameter_list p;
  175. if (! req.get_header_as_plist("Sec-WebSocket-Protocol", p))
  176. {
  177. http::parameter_list::const_iterator it;
  178. for (it = p.begin(); it != p.end(); ++it)
  179. {
  180. subprotocol_list.push_back(it->first);
  181. }
  182. }
  183. else
  184. {
  185. return error::make_error_code(error::subprotocol_parse_error);
  186. }
  187. }
  188. return lib::error_code();
  189. }
  190. uri_ptr get_uri(const request_type & request) const
  191. {
  192. std::string h = request.get_header("Host");
  193. size_t last_colon = h.rfind(":");
  194. size_t last_sbrace = h.rfind("]");
  195. // no : = hostname with no port
  196. // last : before ] = ipv6 literal with no port
  197. // : with no ] = hostname with port
  198. // : after ] = ipv6 literal with port
  199. if (last_colon == std::string::npos || (last_sbrace != std::string::npos && last_sbrace > last_colon))
  200. {
  201. return lib::make_shared<uri>(base::m_secure, h, request.get_uri());
  202. }
  203. else
  204. {
  205. return lib::make_shared<uri>(base::m_secure, h.substr(0, last_colon), h.substr(last_colon + 1), request.get_uri());
  206. }
  207. // TODO: check if get_uri is a full uri
  208. }
  209. /// Get hybi00 handshake key3
  210. /**
  211. * @todo This doesn't appear to be used anymore. It might be able to be
  212. * removed
  213. */
  214. std::string get_key3() const
  215. {
  216. return "";
  217. }
  218. /// Process new websocket connection bytes
  219. size_t consume(uint8_t * buf, size_t len, lib::error_code & ec)
  220. {
  221. // if in state header we are expecting a 0x00 byte, if we don't get one
  222. // it is a fatal error
  223. size_t p = 0; // bytes processed
  224. size_t l = 0;
  225. ec = lib::error_code();
  226. while (p < len)
  227. {
  228. if (m_state == HEADER)
  229. {
  230. if (buf[p] == msg_hdr)
  231. {
  232. p++;
  233. m_msg_ptr = m_msg_manager->get_message(frame::opcode::text, 1);
  234. if (! m_msg_ptr)
  235. {
  236. ec = make_error_code(websocketpp::error::no_incoming_buffers);
  237. m_state = FATAL_ERROR;
  238. }
  239. else
  240. {
  241. m_state = PAYLOAD;
  242. }
  243. }
  244. else
  245. {
  246. ec = make_error_code(error::protocol_violation);
  247. m_state = FATAL_ERROR;
  248. }
  249. }
  250. else if (m_state == PAYLOAD)
  251. {
  252. uint8_t * it = std::find(buf + p, buf + len, msg_ftr);
  253. // 0 1 2 3 4 5
  254. // 0x00 0x23 0x23 0x23 0xff 0xXX
  255. // Copy payload bytes into message
  256. l = static_cast<size_t>(it - (buf + p));
  257. m_msg_ptr->append_payload(buf + p, l);
  258. p += l;
  259. if (it != buf + len)
  260. {
  261. // message is done, copy it and the trailing
  262. p++;
  263. // TODO: validation
  264. m_state = READY;
  265. }
  266. }
  267. else
  268. {
  269. // TODO
  270. break;
  271. }
  272. }
  273. // If we get one, we create a new message and move to application state
  274. // if in state application we are copying bytes into the output message
  275. // and validating them for UTF8 until we hit a 0xff byte. Once we hit
  276. // 0x00, the message is complete and is dispatched. Then we go back to
  277. // header state.
  278. // ec = make_error_code(error::not_implemented);
  279. return p;
  280. }
  281. bool ready() const
  282. {
  283. return (m_state == READY);
  284. }
  285. bool get_error() const
  286. {
  287. return false;
  288. }
  289. message_ptr get_message()
  290. {
  291. message_ptr ret = m_msg_ptr;
  292. m_msg_ptr = message_ptr();
  293. m_state = HEADER;
  294. return ret;
  295. }
  296. /// Prepare a message for writing
  297. /**
  298. * Performs validation, masking, compression, etc. will return an error if
  299. * there was an error, otherwise msg will be ready to be written
  300. */
  301. virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out)
  302. {
  303. if (! in || ! out)
  304. {
  305. return make_error_code(error::invalid_arguments);
  306. }
  307. // TODO: check if the message is prepared already
  308. // validate opcode
  309. if (in->get_opcode() != frame::opcode::text)
  310. {
  311. return make_error_code(error::invalid_opcode);
  312. }
  313. std::string & i = in->get_raw_payload();
  314. // std::string& o = out->get_raw_payload();
  315. // validate payload utf8
  316. if (! utf8_validator::validate(i))
  317. {
  318. return make_error_code(error::invalid_payload);
  319. }
  320. // generate header
  321. out->set_header(std::string(reinterpret_cast<const char *>(&msg_hdr), 1));
  322. // process payload
  323. out->set_payload(i);
  324. out->append_payload(std::string(reinterpret_cast<const char *>(&msg_ftr), 1));
  325. // hybi00 doesn't support compression
  326. // hybi00 doesn't have masking
  327. out->set_prepared(true);
  328. return lib::error_code();
  329. }
  330. /// Prepare a ping frame
  331. /**
  332. * Hybi 00 doesn't support pings so this will always return an error
  333. *
  334. * @param in The string to use for the ping payload
  335. * @param out The message buffer to prepare the ping in.
  336. * @return Status code, zero on success, non-zero on failure
  337. */
  338. lib::error_code prepare_ping(const std::string &, message_ptr) const
  339. {
  340. return lib::error_code(error::no_protocol_support);
  341. }
  342. /// Prepare a pong frame
  343. /**
  344. * Hybi 00 doesn't support pongs so this will always return an error
  345. *
  346. * @param in The string to use for the pong payload
  347. * @param out The message buffer to prepare the pong in.
  348. * @return Status code, zero on success, non-zero on failure
  349. */
  350. lib::error_code prepare_pong(const std::string &, message_ptr) const
  351. {
  352. return lib::error_code(error::no_protocol_support);
  353. }
  354. /// Prepare a close frame
  355. /**
  356. * Hybi 00 doesn't support the close code or reason so these parameters are
  357. * ignored.
  358. *
  359. * @param code The close code to send
  360. * @param reason The reason string to send
  361. * @param out The message buffer to prepare the fame in
  362. * @return Status code, zero on success, non-zero on failure
  363. */
  364. lib::error_code prepare_close(close::status::value, const std::string &, message_ptr out) const
  365. {
  366. if (! out)
  367. {
  368. return lib::error_code(error::invalid_arguments);
  369. }
  370. std::string val;
  371. val.append(1, '\xff');
  372. val.append(1, '\x00');
  373. out->set_payload(val);
  374. out->set_prepared(true);
  375. return lib::error_code();
  376. }
  377. private:
  378. void decode_client_key(const std::string & key, char * result) const
  379. {
  380. unsigned int spaces = 0;
  381. std::string digits;
  382. uint32_t num;
  383. // key2
  384. for (size_t i = 0; i < key.size(); i++)
  385. {
  386. if (key[i] == ' ')
  387. {
  388. spaces++;
  389. }
  390. else if (key[i] >= '0' && key[i] <= '9')
  391. {
  392. digits += key[i];
  393. }
  394. }
  395. num = static_cast<uint32_t>(strtoul(digits.c_str(), NULL, 10));
  396. if (spaces > 0 && num > 0)
  397. {
  398. num = htonl(num / spaces);
  399. std::copy(reinterpret_cast<char *>(&num), reinterpret_cast<char *>(&num) + 4, result);
  400. }
  401. else
  402. {
  403. std::fill(result, result + 4, 0);
  404. }
  405. }
  406. enum state
  407. {
  408. HEADER = 0,
  409. PAYLOAD = 1,
  410. READY = 2,
  411. FATAL_ERROR = 3
  412. };
  413. const uint8_t msg_hdr;
  414. const uint8_t msg_ftr;
  415. state m_state;
  416. msg_manager_ptr m_msg_manager;
  417. message_ptr m_msg_ptr;
  418. utf8_validator::validator m_validator;
  419. };
  420. } // namespace processor
  421. } // namespace websocketpp
  422. #endif // WEBSOCKETPP_PROCESSOR_HYBI00_HPP