2 * Copyright (c) 2014, Peter Thorson. All rights reserved.
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.
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.
28 #ifndef WEBSOCKETPP_TRANSPORT_IOSTREAM_CON_HPP
29 #define WEBSOCKETPP_TRANSPORT_IOSTREAM_CON_HPP
31 #include <websocketpp/transport/iostream/base.hpp>
33 #include <websocketpp/transport/base/connection.hpp>
35 #include <websocketpp/uri.hpp>
37 #include <websocketpp/logger/levels.hpp>
39 #include <websocketpp/common/connection_hdl.hpp>
40 #include <websocketpp/common/memory.hpp>
41 #include <websocketpp/common/platforms.hpp>
49 namespace websocketpp {
53 /// Empty timer class to stub out for timer functionality that iostream
54 /// transport doesn't support
59 template <typename config>
60 class connection : public lib::enable_shared_from_this< connection<config> > {
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;
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;
74 // Concurrency policy types
75 typedef typename concurrency_type::scoped_lock_type scoped_lock_type;
76 typedef typename concurrency_type::mutex_type mutex_type;
78 typedef lib::shared_ptr<timer> timer_ptr;
80 explicit connection(bool is_server, alog_type & alog, elog_type & elog)
81 : m_output_stream(NULL)
83 , m_is_server(is_server)
87 , m_remote_endpoint("iostream transport")
89 m_alog.write(log::alevel::devel,"iostream con transport constructor");
92 /// Get a shared pointer to this component
94 return type::shared_from_this();
97 /// Register a std::ostream with the transport for writing output
99 * Register a std::ostream with the transport. All future writes will be
100 * done to this output stream.
102 * @param o A pointer to the ostream to use for output.
104 void register_ostream(std::ostream * o) {
105 // TODO: lock transport state?
106 scoped_lock_type lock(m_read_mutex);
112 * Called by the endpoint as a connection is being established to provide
113 * the uri being connected to to the transport layer.
115 * This transport policy doesn't use the uri so it is ignored.
119 * @param u The uri to set
121 void set_uri(uri_ptr) {}
123 /// Overloaded stream input operator
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.
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
136 * You can use tellg() on the input stream to determine if all of the input
137 * bytes were read or not.
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.
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);
151 /// Manual input supply (read some)
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.
159 * @since 0.3.0-alpha4
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.
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);
169 return this->read_some_impl(buf,len);
172 /// Manual input supply (read all)
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
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.
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.
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);
192 size_t total_read = 0;
193 size_t temp_read = 0;
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);
203 /// Manual input supply (DEPRECATED)
205 * @deprecated DEPRECATED in favor of read_some()
208 size_t readsome(char const * buf, size_t len) {
209 return this->read_some(buf,len);
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.
217 * @since 0.3.0-alpha4
220 // this serializes calls to external read.
221 scoped_lock_type lock(m_read_mutex);
224 complete_read(make_error_code(transport::error::eof));
228 /// Signal transport error
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.
233 * @since 0.3.0-alpha4
236 // this serializes calls to external read.
237 scoped_lock_type lock(m_read_mutex);
240 complete_read(make_error_code(transport::error::pass_through));
244 /// Set whether or not this connection is secure
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.
253 * @since 0.3.0-alpha4
255 * @param value Whether or not this connection is secure.
257 void set_secure(bool value) {
261 /// Tests whether or not the underlying transport is secure
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
269 * @return Whether or not the underlying transport is secure
271 bool is_secure() const {
275 /// Set human readable remote endpoint address
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
283 * If none is set the default is "iostream transport".
285 * @since 0.3.0-alpha4
287 * @param value The remote endpoint address to set.
289 void set_remote_endpoint(std::string value) {
290 m_remote_endpoint = value;
293 /// Get human readable remote endpoint address
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.
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.
303 * @return A string identifying the address of the remote endpoint
305 std::string get_remote_endpoint() const {
306 return m_remote_endpoint;
309 /// Get the connection handle
311 * @return The handle for this connection.
313 connection_hdl get_handle() const {
314 return m_connection_hdl;
317 /// Call back a function after a period of time.
319 * Timers are not implemented in this transport. The timer pointer will
320 * always be empty. The handler will never be called.
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
327 timer_ptr set_timer(long, timer_handler) {
331 /// Sets the write handler
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.
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.
341 * See also, set_vector_write_handler, for an optional write handler that
342 * allows more efficient handling of multiple writes at once.
344 * @see set_vector_write_handler
348 * @param h The handler to call when data is to be written.
350 void set_write_handler(write_handler h) {
354 /// Sets the vectored write handler
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.
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.
367 * This is an optional handler. If it is not defined then multiple calls
368 * will be made to the standard write handler.
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).
378 * @param h The handler to call when vectored data is to be written.
380 void set_vector_write_handler(vector_write_handler h) {
381 m_vector_write_handler = h;
384 /// Sets the shutdown handler
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.
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.
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.
398 * @param h The handler to call on connection shutdown.
400 void set_shutdown_handler(shutdown_handler h) {
401 m_shutdown_handler = h;
404 /// Initialize the connection transport
406 * Initialize the connection's transport component.
408 * @param handler The `init_handler` to call when initialization is done
410 void init(init_handler handler) {
411 m_alog.write(log::alevel::devel,"iostream connection init");
412 handler(lib::error_code());
415 /// Initiate an async_read for at least num_bytes bytes into buf
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
422 * This method may or may not call handler from within the initial call. The
423 * application should be prepared to accept either.
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.
429 * If num_bytes or len are zero handler will be called back immediately
430 * indicating success.
432 * @param num_bytes Don't call handler until at least this many bytes have
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
439 void async_read_at_least(size_t num_bytes, char *buf, size_t len,
440 read_handler handler)
443 s << "iostream_con async_read_at_least: " << num_bytes;
444 m_alog.write(log::alevel::devel,s.str());
446 if (num_bytes > len) {
447 handler(make_error_code(error::invalid_num_bytes),size_t(0));
451 if (m_reading == true) {
452 handler(make_error_code(error::double_read),size_t(0));
456 if (num_bytes == 0 || len == 0) {
457 handler(lib::error_code(),size_t(0));
463 m_bytes_needed = num_bytes;
464 m_read_handler = handler;
469 /// Asyncronous Transport Write
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.
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
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.
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.
487 void async_write(char const * buf, size_t len, transport::write_handler
490 m_alog.write(log::alevel::devel,"iostream_con async_write");
491 // TODO: lock transport state?
495 if (m_output_stream) {
496 m_output_stream->write(buf,len);
498 if (m_output_stream->bad()) {
499 ec = make_error_code(error::bad_stream);
501 } else if (m_write_handler) {
502 ec = m_write_handler(m_connection_hdl, buf, len);
504 ec = make_error_code(error::output_stream_required);
510 /// Asyncronous Transport Write (scatter-gather)
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.
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
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.
524 * @param bufs vector of buffers to write
525 * @param handler Callback to invoke with operation status.
527 void async_write(std::vector<buffer> const & bufs, transport::write_handler
530 m_alog.write(log::alevel::devel,"iostream_con async_write buffer list");
531 // TODO: lock transport state?
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);
540 if (m_output_stream->bad()) {
541 ec = make_error_code(error::bad_stream);
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);
555 ec = make_error_code(error::output_stream_required);
561 /// Set Connection Handle
563 * @param hdl The new handle
565 void set_handle(connection_hdl hdl) {
566 m_connection_hdl = hdl;
569 /// Call given handler back within the transport's event system (if present)
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
575 * @param handler The callback to invoke
577 * @return Whether or not the transport was able to register the handler for
580 lib::error_code dispatch(dispatch_handler handler) {
582 return lib::error_code();
585 /// Perform cleanup on socket shutdown_handler
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
591 * @param handler The `shutdown_handler` to call back when complete
593 void async_shutdown(transport::shutdown_handler handler) {
596 if (m_shutdown_handler) {
597 ec = m_shutdown_handler(m_connection_hdl);
603 void read(std::istream &in) {
604 m_alog.write(log::alevel::devel,"iostream_con read");
608 m_elog.write(log::elevel::devel,"write while not reading");
612 in.read(m_buf+m_cursor,static_cast<std::streamsize>(m_len-m_cursor));
614 if (in.gcount() == 0) {
615 m_elog.write(log::elevel::devel,"read zero bytes");
619 m_cursor += static_cast<size_t>(in.gcount());
621 // TODO: error handling
624 complete_read(make_error_code(error::bad_stream));
627 if (m_cursor >= m_bytes_needed) {
629 complete_read(lib::error_code());
634 size_t read_some_impl(char const * buf, size_t len) {
635 m_alog.write(log::alevel::devel,"iostream_con read_some");
638 m_elog.write(log::elevel::devel,"write while not reading");
642 size_t bytes_to_copy = (std::min)(len,m_len-m_cursor);
644 std::copy(buf,buf+bytes_to_copy,m_buf+m_cursor);
646 m_cursor += bytes_to_copy;
648 if (m_cursor >= m_bytes_needed) {
649 complete_read(lib::error_code());
652 return bytes_to_copy;
655 /// Signal that a requested read is complete
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.
661 * It MUST NOT be called when m_reading is false.
662 * it MUST be called while holding the read lock
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.
669 * @param ec The error code to forward to the read handler
671 void complete_read(lib::error_code const & ec) {
674 read_handler handler = m_read_handler;
675 m_read_handler = read_handler();
677 handler(ec,m_cursor);
680 // Read space (Protected by m_read_mutex)
683 size_t m_bytes_needed;
684 read_handler m_read_handler;
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;
695 bool const m_is_server;
699 std::string m_remote_endpoint;
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;
710 } // namespace iostream
711 } // namespace transport
712 } // namespace websocketpp
714 #endif // WEBSOCKETPP_TRANSPORT_IOSTREAM_CON_HPP