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