hybi00.hpp 15 KB

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