hybi00.hpp 15 KB

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