RESTinio
Loading...
Searching...
No Matches
websocket.hpp
Go to the documentation of this file.
1/*
2 restinio
3*/
4
9#pragma once
10
11#include <functional>
12
18
19namespace restinio
20{
21
22namespace websocket
23{
24
25namespace basic
26{
27
28//
29// ws_t
30//
31
33
38class ws_t
39 : public std::enable_shared_from_this< ws_t >
40{
41 public:
42 //
43 // activate()
44 //
45
47 friend void activate( ws_t & ws )
48 {
49 ws.m_ws_connection_handle->init_read( ws.shared_from_this() );
50 }
51
52 ws_t( const ws_t & ) = delete;
53 ws_t( ws_t && ) = delete;
54 ws_t & operator = ( const ws_t & ) = delete;
55 ws_t & operator = ( ws_t && ) = delete;
56
63
65 {
66 try
67 {
68 shutdown();
69 }
70 catch( ... )
71 {}
72 }
73
75
81 {
82 return m_ws_connection_handle ? m_ws_connection_handle->connection_id() : 0;
83 }
84
87 void
89 {
91 {
92 auto con = std::move( m_ws_connection_handle );
93 con->shutdown();
94 }
95 }
96
99 void
101 {
103 {
104 auto con = std::move( m_ws_connection_handle );
105 con->kill();
106 }
107 }
108
110 void
112 final_frame_flag_t final_flag,
113 opcode_t opcode,
114 writable_item_t payload,
116 {
118 {
120 payload.write_type() )
121 {
123 bufs.reserve( 2 );
124
125 // Create header serialize it and append to bufs .
127 final_flag, opcode, asio_ns::buffer_size( payload.buf() ) };
128
129 bufs.emplace_back(
130 impl::write_message_details( details ) );
131
132 bufs.emplace_back( std::move( payload ) );
133
134 write_group_t wg{ std::move( bufs ) };
135
136 if( wscb )
137 {
138 wg.after_write_notificator( std::move( wscb ) );
139 }
140
141 // TODO: set flag.
142 const bool is_close_frame =
143 opcode_t::connection_close_frame == opcode;
144
145 if( is_close_frame )
146 {
147 auto con = std::move( m_ws_connection_handle );
148 con->write_data(
149 std::move( wg ),
151 }
152 else
153 {
154 m_ws_connection_handle->write_data(
155 std::move( wg ),
157 }
158 }
159 else
160 {
161 throw exception_t{ "ws doesn't support sendfile" };
162 }
163 }
164 else
165 {
166 throw exception_t{ "websocket is not available" };
167 }
168 }
169
170 void
172 {
174 msg.final_flag(),
175 msg.opcode(),
176 writable_item_t{ std::move( msg.payload() ) },
177 std::move( wscb ) );
178 }
179
182
183 private:
185
188};
189
191using ws_handle_t = std::shared_ptr< ws_t >;
192
193//
194// activation_t
195//
196
198enum class activation_t
199{
201 immediate,
203 delayed
204};
205
206//
207// upgrade()
208//
209
211template <
212 typename Traits,
213 typename WS_Message_Handler >
224{
225 // TODO: check if upgrade request?
226
228 if( !upgrade_response_header_fields.has_field( http_field::sec_websocket_accept ) )
229 {
230 throw exception_t{
231 fmt::format( "{} field is mandatory for upgrade response",
232 field_to_string( http_field::sec_websocket_accept ) ) };
233 }
234
235 if( !upgrade_response_header_fields.has_field( http_field::upgrade ) )
236 {
237 upgrade_response_header_fields.set_field( http_field::upgrade, "websocket" );
238 }
239
240 using connection_t = restinio::impl::connection_t< Traits >;
242 if( !conn_ptr )
243 {
244 throw exception_t{ "no connection for upgrade: already moved" };
245 }
246 auto & con = dynamic_cast< connection_t & >( *conn_ptr );
247
249
250 auto upgrade_internals = con.move_upgrade_internals();
251 auto ws_connection =
252 std::make_shared< ws_connection_t >(
253 con.connection_id(),
254 std::move( upgrade_internals.m_settings ),
255 std::move( upgrade_internals.m_socket ),
256 std::move( upgrade_internals.m_lifetime_monitor ),
257 std::move( ws_message_handler ) );
258
260 {
264
265 const auto content_length_flag =
267
268 upgrade_response_bufs.emplace_back(
272 }
273
274 ws_connection->write_data(
275 write_group_t{ std::move( upgrade_response_bufs ) },
276 false );
277
278 auto result =
279 std::make_shared< ws_t >( std::move( ws_connection ), req.remote_endpoint() );
280
282 {
283 activate( *result );
284 }
285
286 // Returns strong handle on websocket, thus giving an ownership.
287 return result;
288}
289
290template <
291 typename Traits,
292 typename WS_Message_Handler >
293auto
312
313template <
314 typename Traits,
315 typename WS_Message_Handler >
316auto
340
341template <
342 typename Traits,
343 typename WS_Message_Handler >
344auto
349{
350 const char * websocket_accept_field_suffix = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
351 const auto ws_key =
352 req.header().get_field( restinio::http_field::sec_websocket_key ) +
354
356
359
362 http_field::sec_websocket_accept,
364
365 return
367 req,
370 std::move( ws_message_handler ) );
371}
372
373} /* namespace basic */
374
375} /* namespace websocket */
376
377} /* namespace restinio */
Exception class for all exceptions thrown by RESTinio.
Definition exception.hpp:26
void set_field(http_header_field_t http_header_field)
Set header field via http_header_field_t.
Context for handling http connections.
Websocket message class with more detailed protocol information.
Definition ws_parser.hpp:63
Context for handling websocket connections.
final_frame_flag_t final_flag() const noexcept
Get final flag.
Definition message.hpp:168
opcode_t opcode() const noexcept
Definition message.hpp:186
void send_message(message_t msg, write_status_cb_t wscb=write_status_cb_t{})
ws_t(impl::ws_connection_handle_t ws_connection_handle, endpoint_t remote_endpoint)
Definition websocket.hpp:57
ws_t & operator=(const ws_t &)=delete
impl::ws_connection_handle_t m_ws_connection_handle
connection_id_t connection_id() const
Get connection id.
Definition websocket.hpp:80
void shutdown()
Shutdown websocket: wait for all outgoing data to be sent, and close connection.
Definition websocket.hpp:88
void kill()
Kill websocket: close underlying tcp socket. Do not tolerate unsent outgoing data.
friend void activate(ws_t &ws)
Activate websocket: start receiving messages.
Definition websocket.hpp:47
const endpoint_t & remote_endpoint() const noexcept
Get the remote endpoint of the underlying connection.
const endpoint_t m_remote_endpoint
Remote endpoint for this ws-connection.
void send_message(final_frame_flag_t final_flag, opcode_t opcode, writable_item_t payload, write_status_cb_t wscb=write_status_cb_t{})
Send_websocket message.
Class for storing the buffers used for streaming body (request/response).
Definition buffers.hpp:496
asio_ns::const_buffer buf() const
Create a buf reference object used by ASIO.
Definition buffers.hpp:594
writable_item_type_t write_type() const noexcept
Get a type of a stored buffer object.
Definition buffers.hpp:582
Group of writable items transported to the context of underlying connection as one solid piece.
Definition buffers.hpp:692
void after_write_notificator(write_status_cb_t notificator) noexcept
Set after write notificator.
Definition buffers.hpp:801
connection_handle_t & access_req_connection(generic_request_t< Extra_Data > &) noexcept
std::string create_header_string(const http_response_header_t &h, content_length_field_presence_t content_length_field_presence=content_length_field_presence_t::add_content_length, std::size_t buffer_size=0)
Creates a string for http response header.
std::string encode(string_view_t str)
Definition base64.hpp:123
std::string to_string(const digest_t &what)
Definition sha1.hpp:398
digest_t make_digest(const std::uint8_t *what, std::size_t length)
Definition sha1.hpp:417
raw_data_t write_message_details(const message_details_t &message)
Serialize websocket message details into bytes buffer.
std::shared_ptr< ws_connection_base_t > ws_connection_handle_t
Alias for WebSocket connection handle.
activation_t
Flags for websocket activation policies.
@ immediate
Activate immediately after upgrade operation.
@ delayed
User will initiate activation later.
final_frame_flag_t
WS frame (message) "final"/"not final" flag.
Definition message.hpp:133
std::shared_ptr< ws_t > ws_handle_t
Alias for ws_t handle.
std::vector< writable_item_t > writable_items_container_t
Definition buffers.hpp:668
run_on_this_thread_settings_t< Traits > on_this_thread()
A special marker for the case when http_server must be run on the context of the current thread.
@ trivial_write_operation
Item is a buffer and must be written trivially.
const char * field_to_string(http_field_t f) noexcept
Helper sunction to get method string name.
http_status_line_t status_switching_protocols()
std::function< void(const asio_ns::error_code &ec) > write_status_cb_t
An alias for a callback to be invoked after the write operation of a particular group of "buffers".
Definition buffers.hpp:680
asio_ns::ip::tcp::endpoint endpoint_t
An alias for endpoint type from Asio.
std::uint64_t connection_id_t
Type for ID of connection.
STL namespace.
#define const
Definition zconf.h:230