fixed adding file problem
[c11concurrency-benchmarks.git] / gdax-orderbook-hpp / demo / dependencies / websocketpp-0.7.0 / websocketpp / transport / iostream / connection.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_TRANSPORT_IOSTREAM_CON_HPP
29 #define WEBSOCKETPP_TRANSPORT_IOSTREAM_CON_HPP
30
31 #include <websocketpp/transport/iostream/base.hpp>
32
33 #include <websocketpp/transport/base/connection.hpp>
34
35 #include <websocketpp/uri.hpp>
36
37 #include <websocketpp/logger/levels.hpp>
38
39 #include <websocketpp/common/connection_hdl.hpp>
40 #include <websocketpp/common/memory.hpp>
41 #include <websocketpp/common/platforms.hpp>
42
43 #include <algorithm>
44 #include <iostream>
45 #include <sstream>
46 #include <string>
47 #include <vector>
48
49 namespace websocketpp {
50 namespace transport {
51 namespace iostream {
52
53 /// Empty timer class to stub out for timer functionality that iostream
54 /// transport doesn't support
55 struct timer {
56     void cancel() {}
57 };
58
59 template <typename config>
60 class connection : public lib::enable_shared_from_this< connection<config> > {
61 public:
62     /// Type of this connection transport component
63     typedef connection<config> type;
64     /// Type of a shared pointer to this connection transport component
65     typedef lib::shared_ptr<type> ptr;
66
67     /// transport concurrency policy
68     typedef typename config::concurrency_type concurrency_type;
69     /// Type of this transport's access logging policy
70     typedef typename config::alog_type alog_type;
71     /// Type of this transport's error logging policy
72     typedef typename config::elog_type elog_type;
73
74     // Concurrency policy types
75     typedef typename concurrency_type::scoped_lock_type scoped_lock_type;
76     typedef typename concurrency_type::mutex_type mutex_type;
77
78     typedef lib::shared_ptr<timer> timer_ptr;
79
80     explicit connection(bool is_server, alog_type & alog, elog_type & elog)
81       : m_output_stream(NULL)
82       , m_reading(false)
83       , m_is_server(is_server)
84       , m_is_secure(false)
85       , m_alog(alog)
86       , m_elog(elog)
87       , m_remote_endpoint("iostream transport")
88     {
89         m_alog.write(log::alevel::devel,"iostream con transport constructor");
90     }
91
92     /// Get a shared pointer to this component
93     ptr get_shared() {
94         return type::shared_from_this();
95     }
96
97     /// Register a std::ostream with the transport for writing output
98     /**
99      * Register a std::ostream with the transport. All future writes will be
100      * done to this output stream.
101      *
102      * @param o A pointer to the ostream to use for output.
103      */
104     void register_ostream(std::ostream * o) {
105         // TODO: lock transport state?
106         scoped_lock_type lock(m_read_mutex);
107         m_output_stream = o;
108     }
109
110     /// Set uri hook
111     /**
112      * Called by the endpoint as a connection is being established to provide
113      * the uri being connected to to the transport layer.
114      *
115      * This transport policy doesn't use the uri so it is ignored.
116      *
117      * @since 0.6.0
118      *
119      * @param u The uri to set
120      */
121     void set_uri(uri_ptr) {}
122
123     /// Overloaded stream input operator
124     /**
125      * Attempts to read input from the given stream into the transport. Bytes
126      * will be extracted from the input stream to fulfill any pending reads.
127      * Input in this manner will only read until the current read buffer has
128      * been filled. Then it will signal the library to process the input. If the
129      * library's input handler adds a new async_read, additional bytes will be
130      * read, otherwise the input operation will end.
131      *
132      * When this function returns one of the following conditions is true:
133      * - There is no outstanding read operation
134      * - There are no more bytes available in the input stream
135      *
136      * You can use tellg() on the input stream to determine if all of the input
137      * bytes were read or not.
138      *
139      * If there is no pending read operation when the input method is called, it
140      * will return immediately and tellg() will not have changed.
141      */
142     friend std::istream & operator>> (std::istream & in, type & t) {
143         // this serializes calls to external read.
144         scoped_lock_type lock(t.m_read_mutex);
145
146         t.read(in);
147
148         return in;
149     }
150
151     /// Manual input supply (read some)
152     /**
153      * Copies bytes from buf into WebSocket++'s input buffers. Bytes will be
154      * copied from the supplied buffer to fulfill any pending library reads. It
155      * will return the number of bytes successfully processed. If there are no
156      * pending reads read_some will return immediately. Not all of the bytes may
157      * be able to be read in one call.
158      *
159      * @since 0.3.0-alpha4
160      *
161      * @param buf Char buffer to read into the websocket
162      * @param len Length of buf
163      * @return The number of characters from buf actually read.
164      */
165     size_t read_some(char const * buf, size_t len) {
166         // this serializes calls to external read.
167         scoped_lock_type lock(m_read_mutex);
168
169         return this->read_some_impl(buf,len);
170     }
171
172     /// Manual input supply (read all)
173     /**
174      * Similar to read_some, but continues to read until all bytes in the
175      * supplied buffer have been read or the connection runs out of read
176      * requests.
177      *
178      * This method still may not read all of the bytes in the input buffer. if
179      * it doesn't it indicates that the connection was most likely closed or
180      * is in an error state where it is no longer accepting new input.
181      *
182      * @since 0.3.0
183      *
184      * @param buf Char buffer to read into the websocket
185      * @param len Length of buf
186      * @return The number of characters from buf actually read.
187      */
188     size_t read_all(char const * buf, size_t len) {
189         // this serializes calls to external read.
190         scoped_lock_type lock(m_read_mutex);
191
192         size_t total_read = 0;
193         size_t temp_read = 0;
194
195         do {
196             temp_read = this->read_some_impl(buf+total_read,len-total_read);
197             total_read += temp_read;
198         } while (temp_read != 0 && total_read < len);
199
200         return total_read;
201     }
202
203     /// Manual input supply (DEPRECATED)
204     /**
205      * @deprecated DEPRECATED in favor of read_some()
206      * @see read_some()
207      */
208     size_t readsome(char const * buf, size_t len) {
209         return this->read_some(buf,len);
210     }
211
212     /// Signal EOF
213     /**
214      * Signals to the transport that data stream being read has reached EOF and
215      * that no more bytes may be read or written to/from the transport.
216      *
217      * @since 0.3.0-alpha4
218      */
219     void eof() {
220         // this serializes calls to external read.
221         scoped_lock_type lock(m_read_mutex);
222
223         if (m_reading) {
224             complete_read(make_error_code(transport::error::eof));
225         }
226     }
227
228     /// Signal transport error
229     /**
230      * Signals to the transport that a fatal data stream error has occurred and
231      * that no more bytes may be read or written to/from the transport.
232      *
233      * @since 0.3.0-alpha4
234      */
235     void fatal_error() {
236         // this serializes calls to external read.
237         scoped_lock_type lock(m_read_mutex);
238
239         if (m_reading) {
240             complete_read(make_error_code(transport::error::pass_through));
241         }
242     }
243
244     /// Set whether or not this connection is secure
245     /**
246      * The iostream transport does not provide any security features. As such
247      * it defaults to returning false when `is_secure` is called. However, the
248      * iostream transport may be used to wrap an external socket API that may
249      * provide secure transport. This method allows that external API to flag
250      * whether or not this connection is secure so that users of the WebSocket++
251      * API will get more accurate information.
252      *
253      * @since 0.3.0-alpha4
254      *
255      * @param value Whether or not this connection is secure.
256      */
257     void set_secure(bool value) {
258         m_is_secure = value;
259     }
260
261     /// Tests whether or not the underlying transport is secure
262     /**
263      * iostream transport will return false always because it has no information
264      * about the ultimate remote endpoint. This may or may not be accurate
265      * depending on the real source of bytes being input. The `set_secure`
266      * method may be used to flag connections that are secured by an external
267      * API
268      *
269      * @return Whether or not the underlying transport is secure
270      */
271     bool is_secure() const {
272         return m_is_secure;
273     }
274
275     /// Set human readable remote endpoint address
276     /**
277      * Sets the remote endpoint address returned by `get_remote_endpoint`. This
278      * value should be a human readable string that describes the remote
279      * endpoint. Typically an IP address or hostname, perhaps with a port. But
280      * may be something else depending on the nature of the underlying
281      * transport.
282      *
283      * If none is set the default is "iostream transport".
284      *
285      * @since 0.3.0-alpha4
286      *
287      * @param value The remote endpoint address to set.
288      */
289     void set_remote_endpoint(std::string value) {
290         m_remote_endpoint = value;
291     }
292
293     /// Get human readable remote endpoint address
294     /**
295      * The iostream transport has no information about the ultimate remote
296      * endpoint. It will return the string "iostream transport". The
297      * `set_remote_endpoint` method may be used by external network code to set
298      * a more accurate value.
299      *
300      * This value is used in access and error logs and is available to the end
301      * application for including in user facing interfaces and messages.
302      *
303      * @return A string identifying the address of the remote endpoint
304      */
305     std::string get_remote_endpoint() const {
306         return m_remote_endpoint;
307     }
308
309     /// Get the connection handle
310     /**
311      * @return The handle for this connection.
312      */
313     connection_hdl get_handle() const {
314         return m_connection_hdl;
315     }
316
317     /// Call back a function after a period of time.
318     /**
319      * Timers are not implemented in this transport. The timer pointer will
320      * always be empty. The handler will never be called.
321      *
322      * @param duration Length of time to wait in milliseconds
323      * @param callback The function to call back when the timer has expired
324      * @return A handle that can be used to cancel the timer if it is no longer
325      * needed.
326      */
327     timer_ptr set_timer(long, timer_handler) {
328         return timer_ptr();
329     }
330
331     /// Sets the write handler
332     /**
333      * The write handler is called when the iostream transport receives data
334      * that needs to be written to the appropriate output location. This handler
335      * can be used in place of registering an ostream for output.
336      *
337      * The signature of the handler is
338      * `lib::error_code (connection_hdl, char const *, size_t)` The
339      * code returned will be reported and logged by the core library.
340      *
341      * See also, set_vector_write_handler, for an optional write handler that
342      * allows more efficient handling of multiple writes at once.
343      *
344      * @see set_vector_write_handler
345      *
346      * @since 0.5.0
347      *
348      * @param h The handler to call when data is to be written.
349      */
350     void set_write_handler(write_handler h) {
351         m_write_handler = h;
352     }
353
354     /// Sets the vectored write handler
355     /**
356      * The vectored write handler is called when the iostream transport receives
357      * multiple chunks of data that need to be written to the appropriate output
358      * location. This handler can be used in conjunction with the write_handler
359      * in place of registering an ostream for output.
360      *
361      * The sequence of buffers represents bytes that should be written
362      * consecutively and it is suggested to group the buffers into as few next
363      * layer packets as possible. Vector write is used to allow implementations
364      * that support it to coalesce writes into a single TCP packet or TLS
365      * segment for improved efficiency.
366      *
367      * This is an optional handler. If it is not defined then multiple calls
368      * will be made to the standard write handler.
369      *
370      * The signature of the handler is
371      * `lib::error_code (connection_hdl, std::vector<websocketpp::transport::buffer>
372      * const & bufs)`. The code returned will be reported and logged by the core
373      * library. The `websocketpp::transport::buffer` type is a struct with two
374      * data members. buf (char const *) and len (size_t).
375      *
376      * @since 0.6.0
377      *
378      * @param h The handler to call when vectored data is to be written.
379      */
380     void set_vector_write_handler(vector_write_handler h) {
381         m_vector_write_handler = h;
382     }
383
384     /// Sets the shutdown handler
385     /**
386      * The shutdown handler is called when the iostream transport receives a
387      * notification from the core library that it is finished with all read and
388      * write operations and that the underlying transport can be cleaned up.
389      *
390      * If you are using iostream transport with another socket library, this is
391      * a good time to close/shutdown the socket for this connection.
392      *
393      * The signature of the handler is `lib::error_code (connection_hdl)`. The
394      * code returned will be reported and logged by the core library.
395      *
396      * @since 0.5.0
397      *
398      * @param h The handler to call on connection shutdown.
399      */
400     void set_shutdown_handler(shutdown_handler h) {
401         m_shutdown_handler = h;
402     }
403 protected:
404     /// Initialize the connection transport
405     /**
406      * Initialize the connection's transport component.
407      *
408      * @param handler The `init_handler` to call when initialization is done
409      */
410     void init(init_handler handler) {
411         m_alog.write(log::alevel::devel,"iostream connection init");
412         handler(lib::error_code());
413     }
414
415     /// Initiate an async_read for at least num_bytes bytes into buf
416     /**
417      * Initiates an async_read request for at least num_bytes bytes. The input
418      * will be read into buf. A maximum of len bytes will be input. When the
419      * operation is complete, handler will be called with the status and number
420      * of bytes read.
421      *
422      * This method may or may not call handler from within the initial call. The
423      * application should be prepared to accept either.
424      *
425      * The application should never call this method a second time before it has
426      * been called back for the first read. If this is done, the second read
427      * will be called back immediately with a double_read error.
428      *
429      * If num_bytes or len are zero handler will be called back immediately
430      * indicating success.
431      *
432      * @param num_bytes Don't call handler until at least this many bytes have
433      * been read.
434      * @param buf The buffer to read bytes into
435      * @param len The size of buf. At maximum, this many bytes will be read.
436      * @param handler The callback to invoke when the operation is complete or
437      * ends in an error
438      */
439     void async_read_at_least(size_t num_bytes, char *buf, size_t len,
440         read_handler handler)
441     {
442         std::stringstream s;
443         s << "iostream_con async_read_at_least: " << num_bytes;
444         m_alog.write(log::alevel::devel,s.str());
445
446         if (num_bytes > len) {
447             handler(make_error_code(error::invalid_num_bytes),size_t(0));
448             return;
449         }
450
451         if (m_reading == true) {
452             handler(make_error_code(error::double_read),size_t(0));
453             return;
454         }
455
456         if (num_bytes == 0 || len == 0) {
457             handler(lib::error_code(),size_t(0));
458             return;
459         }
460
461         m_buf = buf;
462         m_len = len;
463         m_bytes_needed = num_bytes;
464         m_read_handler = handler;
465         m_cursor = 0;
466         m_reading = true;
467     }
468
469     /// Asyncronous Transport Write
470     /**
471      * Write len bytes in buf to the output method. Call handler to report
472      * success or failure. handler may or may not be called during async_write,
473      * but it must be safe for this to happen.
474      *
475      * Will return 0 on success. Other possible errors (not exhaustive)
476      * output_stream_required: No output stream was registered to write to
477      * bad_stream: a ostream pass through error
478      *
479      * This method will attempt to write to the registered ostream first. If an
480      * ostream is not registered it will use the write handler. If neither are
481      * registered then an error is passed up to the connection.
482      *
483      * @param buf buffer to read bytes from
484      * @param len number of bytes to write
485      * @param handler Callback to invoke with operation status.
486      */
487     void async_write(char const * buf, size_t len, transport::write_handler
488         handler)
489     {
490         m_alog.write(log::alevel::devel,"iostream_con async_write");
491         // TODO: lock transport state?
492
493         lib::error_code ec;
494
495         if (m_output_stream) {
496             m_output_stream->write(buf,len);
497
498             if (m_output_stream->bad()) {
499                 ec = make_error_code(error::bad_stream);
500             }
501         } else if (m_write_handler) {
502             ec = m_write_handler(m_connection_hdl, buf, len);
503         } else {
504             ec = make_error_code(error::output_stream_required);
505         }
506
507         handler(ec);
508     }
509
510     /// Asyncronous Transport Write (scatter-gather)
511     /**
512      * Write a sequence of buffers to the output method. Call handler to report
513      * success or failure. handler may or may not be called during async_write,
514      * but it must be safe for this to happen.
515      *
516      * Will return 0 on success. Other possible errors (not exhaustive)
517      * output_stream_required: No output stream was registered to write to
518      * bad_stream: a ostream pass through error
519      *
520      * This method will attempt to write to the registered ostream first. If an
521      * ostream is not registered it will use the write handler. If neither are
522      * registered then an error is passed up to the connection.
523      *
524      * @param bufs vector of buffers to write
525      * @param handler Callback to invoke with operation status.
526      */
527     void async_write(std::vector<buffer> const & bufs, transport::write_handler
528         handler)
529     {
530         m_alog.write(log::alevel::devel,"iostream_con async_write buffer list");
531         // TODO: lock transport state?
532
533         lib::error_code ec;
534
535         if (m_output_stream) {
536             std::vector<buffer>::const_iterator it;
537             for (it = bufs.begin(); it != bufs.end(); it++) {
538                 m_output_stream->write((*it).buf,(*it).len);
539
540                 if (m_output_stream->bad()) {
541                     ec = make_error_code(error::bad_stream);
542                     break;
543                 }
544             }
545         } else if (m_vector_write_handler) {
546             ec = m_vector_write_handler(m_connection_hdl, bufs);
547         } else if (m_write_handler) {
548             std::vector<buffer>::const_iterator it;
549             for (it = bufs.begin(); it != bufs.end(); it++) {
550                 ec = m_write_handler(m_connection_hdl, (*it).buf, (*it).len);
551                 if (ec) {break;}
552             }
553
554         } else {
555             ec = make_error_code(error::output_stream_required);
556         }
557
558         handler(ec);
559     }
560
561     /// Set Connection Handle
562     /**
563      * @param hdl The new handle
564      */
565     void set_handle(connection_hdl hdl) {
566         m_connection_hdl = hdl;
567     }
568
569     /// Call given handler back within the transport's event system (if present)
570     /**
571      * Invoke a callback within the transport's event system if it has one. If
572      * it doesn't, the handler will be invoked immediately before this function
573      * returns.
574      *
575      * @param handler The callback to invoke
576      *
577      * @return Whether or not the transport was able to register the handler for
578      * callback.
579      */
580     lib::error_code dispatch(dispatch_handler handler) {
581         handler();
582         return lib::error_code();
583     }
584
585     /// Perform cleanup on socket shutdown_handler
586     /**
587      * If a shutdown handler is set, call it and pass through its return error
588      * code. Otherwise assume there is nothing to do and pass through a success
589      * code.
590      *
591      * @param handler The `shutdown_handler` to call back when complete
592      */
593     void async_shutdown(transport::shutdown_handler handler) {
594         lib::error_code ec;
595
596         if (m_shutdown_handler) {
597             ec = m_shutdown_handler(m_connection_hdl);
598         }
599
600         handler(ec);
601     }
602 private:
603     void read(std::istream &in) {
604         m_alog.write(log::alevel::devel,"iostream_con read");
605
606         while (in.good()) {
607             if (!m_reading) {
608                 m_elog.write(log::elevel::devel,"write while not reading");
609                 break;
610             }
611
612             in.read(m_buf+m_cursor,static_cast<std::streamsize>(m_len-m_cursor));
613
614             if (in.gcount() == 0) {
615                 m_elog.write(log::elevel::devel,"read zero bytes");
616                 break;
617             }
618
619             m_cursor += static_cast<size_t>(in.gcount());
620
621             // TODO: error handling
622             if (in.bad()) {
623                 m_reading = false;
624                 complete_read(make_error_code(error::bad_stream));
625             }
626
627             if (m_cursor >= m_bytes_needed) {
628                 m_reading = false;
629                 complete_read(lib::error_code());
630             }
631         }
632     }
633
634     size_t read_some_impl(char const * buf, size_t len) {
635         m_alog.write(log::alevel::devel,"iostream_con read_some");
636
637         if (!m_reading) {
638             m_elog.write(log::elevel::devel,"write while not reading");
639             return 0;
640         }
641
642         size_t bytes_to_copy = (std::min)(len,m_len-m_cursor);
643
644         std::copy(buf,buf+bytes_to_copy,m_buf+m_cursor);
645
646         m_cursor += bytes_to_copy;
647
648         if (m_cursor >= m_bytes_needed) {
649             complete_read(lib::error_code());
650         }
651
652         return bytes_to_copy;
653     }
654
655     /// Signal that a requested read is complete
656     /**
657      * Sets the reading flag to false and returns the handler that should be
658      * called back with the result of the read. The cursor position that is sent
659      * is whatever the value of m_cursor is.
660      *
661      * It MUST NOT be called when m_reading is false.
662      * it MUST be called while holding the read lock
663      *
664      * It is important to use this method rather than directly setting/calling
665      * m_read_handler back because this function makes sure to delete the
666      * locally stored handler which contains shared pointers that will otherwise
667      * cause circular reference based memory leaks.
668      *
669      * @param ec The error code to forward to the read handler
670      */
671     void complete_read(lib::error_code const & ec) {
672         m_reading = false;
673
674         read_handler handler = m_read_handler;
675         m_read_handler = read_handler();
676
677         handler(ec,m_cursor);
678     }
679
680     // Read space (Protected by m_read_mutex)
681     char *          m_buf;
682     size_t          m_len;
683     size_t          m_bytes_needed;
684     read_handler    m_read_handler;
685     size_t          m_cursor;
686
687     // transport resources
688     std::ostream *  m_output_stream;
689     connection_hdl  m_connection_hdl;
690     write_handler   m_write_handler;
691     vector_write_handler m_vector_write_handler;
692     shutdown_handler    m_shutdown_handler;
693
694     bool            m_reading;
695     bool const      m_is_server;
696     bool            m_is_secure;
697     alog_type &     m_alog;
698     elog_type &     m_elog;
699     std::string     m_remote_endpoint;
700
701     // This lock ensures that only one thread can edit read data for this
702     // connection. This is a very coarse lock that is basically locked all the
703     // time. The nature of the connection is such that it cannot be
704     // parallelized, the locking is here to prevent intra-connection concurrency
705     // in order to allow inter-connection concurrency.
706     mutex_type      m_read_mutex;
707 };
708
709
710 } // namespace iostream
711 } // namespace transport
712 } // namespace websocketpp
713
714 #endif // WEBSOCKETPP_TRANSPORT_IOSTREAM_CON_HPP