Debian Codegraph @

contrib/epee/include/net/levin_protocol_handler_async.h

raw symbols SCIP
1 // Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
2 // 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 Andrey N. Sabelnikov 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" AND
16 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 #pragma once
28 #include <boost/asio/deadline_timer.hpp>
29 #include <boost/uuid/uuid_generators.hpp>
30 #include <boost/unordered_map.hpp>
31 #include <boost/smart_ptr/make_shared.hpp>
32
33 #include <atomic>
34 #include <deque>
35
36 #include "levin_base.h"
37 #include "buffer.h"
38 #include "misc_language.h"
39 #include "syncobj.h"
40 #include "time_helper.h"
41 #include "int-util.h"
42
43 #include <random>
44 #include <chrono>
45
46 #undef MONERO_DEFAULT_LOG_CATEGORY
47 #define MONERO_DEFAULT_LOG_CATEGORY "net"
48
49 #ifndef MIN_BYTES_WANTED
50 #define MIN_BYTES_WANTED 512
51 #endif
52
53 template<typename context_t>
54 void on_levin_traffic(const context_t &context, bool initiator, bool sent, bool error, size_t bytes, const char* category)
55 {
56 MCINFO("net.p2p.traffic", context << bytes << " bytes " << (sent ? "sent" : "received") << (error ? "/corrupt" : "")
57 << " for category " << category << " initiated by " << (initiator ? "us" : "peer"));
58 }
59
60 template<typename context_t>
61 void on_levin_traffic(const context_t &context, bool initiator, bool sent, bool error, size_t bytes, int command)
62 {
63 char buf[32];
64 snprintf(buf, sizeof(buf), "command-%u", command);
65 on_levin_traffic(context, initiator, sent, error, bytes, buf);
66 }
67
68 namespace epee
69 {
70 namespace levin
71 {
72
73 /************************************************************************/
74 /* */
75 /************************************************************************/
76 template<class t_connection_context>
77 class async_protocol_handler;
78
79 template<class t_connection_context>
80 class async_protocol_handler_config
81 {
82 typedef boost::unordered_map<boost::uuids::uuid, async_protocol_handler<t_connection_context>* > connections_map;
83 critical_section m_connects_lock;
84 connections_map m_connects;
85
86 void add_connection(async_protocol_handler<t_connection_context>* pc);
87 void del_connection(async_protocol_handler<t_connection_context>* pc);
88
89 async_protocol_handler<t_connection_context>* find_connection(boost::uuids::uuid connection_id) const;
90 int find_and_lock_connection(boost::uuids::uuid connection_id, async_protocol_handler<t_connection_context>*& aph);
91
92 friend class async_protocol_handler<t_connection_context>;
93
94 levin_commands_handler<t_connection_context>* m_pcommands_handler;
95 void (*m_pcommands_handler_destroy)(levin_commands_handler<t_connection_context>*);
96
97 void delete_connections (size_t count, bool incoming);
98
99 public:
100 typedef t_connection_context connection_context;
101 uint64_t m_initial_max_packet_size;
102 uint64_t m_max_packet_size;
103 uint64_t m_invoke_timeout;
104
105 int invoke(int command, message_writer in_msg, std::string& buff_out, boost::uuids::uuid connection_id);
106 template<class callback_t>
107 int invoke_async(int command, message_writer in_msg, boost::uuids::uuid connection_id, const callback_t &cb, size_t timeout = LEVIN_DEFAULT_TIMEOUT_PRECONFIGURED);
108
109 int send(epee::byte_slice message, const boost::uuids::uuid& connection_id);
110 bool close(boost::uuids::uuid connection_id, const bool wait_for_shutdown);
111 bool update_connection_context(const t_connection_context& contxt);
112 bool request_callback(boost::uuids::uuid connection_id);
113 template<class callback_t>
114 bool foreach_connection(const callback_t &cb);
115 template<class callback_t>
116 bool for_connection(const boost::uuids::uuid &connection_id, const callback_t &cb);
117 size_t get_connections_count();
118 size_t get_out_connections_count();
119 size_t get_in_connections_count();
120 void set_handler(levin_commands_handler<t_connection_context>* handler, void (*destroy)(levin_commands_handler<t_connection_context>*) = NULL);
121
122 async_protocol_handler_config():m_pcommands_handler(NULL), m_pcommands_handler_destroy(NULL), m_initial_max_packet_size(LEVIN_INITIAL_MAX_PACKET_SIZE), m_max_packet_size(LEVIN_DEFAULT_MAX_PACKET_SIZE), m_invoke_timeout(LEVIN_DEFAULT_TIMEOUT_PRECONFIGURED)
123 {}
124 virtual ~async_protocol_handler_config() { set_handler(NULL, NULL); }
125 void del_out_connections(size_t count);
126 void del_in_connections(size_t count);
127 };
128
129
130 /************************************************************************/
131 /* */
132 /************************************************************************/
133 template<class t_connection_context = net_utils::connection_context_base>
134 class async_protocol_handler
135 {
136 std::string m_fragment_buffer;
137
138 bool send_message(byte_slice message)
139 {
140 if (message.size() < sizeof(message_writer::header))
141 return false;
142
143 message_writer::header head;
144 std::memcpy(std::addressof(head), message.data(), sizeof(head));
145 if(!m_pservice_endpoint->do_send(std::move(message)))
146 return false;
147
148 on_levin_traffic(m_connection_context, true, true, false, head.m_cb, head.m_command);
149 MDEBUG(m_connection_context << "LEVIN_PACKET_SENT. [len=" << head.m_cb
150 << ", flags" << head.m_flags
151 << ", r?=" << head.m_have_to_return_data
152 <<", cmd = " << head.m_command
153 << ", ver=" << head.m_protocol_version);
154 return true;
155 }
156
157 public:
158 typedef t_connection_context connection_context;
159 typedef async_protocol_handler_config<t_connection_context> config_type;
160
161 enum stream_state
162 {
163 stream_state_head,
164 stream_state_body
165 };
166
167 std::atomic<bool> m_protocol_released;
168 std::atomic<bool> m_invoke_buf_ready;
169
170 volatile int m_invoke_result_code;
171
172 critical_section m_local_inv_buff_lock;
173 std::string m_local_inv_buff;
174
175 critical_section m_call_lock;
176
177 std::atomic<uint32_t> m_wait_count;
178 std::atomic<uint32_t> m_close_called;
179 bucket_head2 m_current_head;
180 net_utils::i_service_endpoint* m_pservice_endpoint;
181 config_type& m_config;
182 t_connection_context& m_connection_context;
183 std::atomic<uint64_t> m_max_packet_size;
184
185 net_utils::buffer m_cache_in_buffer;
186 stream_state m_state;
187
188 int32_t m_oponent_protocol_ver;
189 bool m_connection_initialized;
190
191 struct invoke_response_handler_base
192 {
193 virtual bool handle(int res, const epee::span<const uint8_t> buff, connection_context& context)=0;
194 virtual bool is_timer_started() const=0;
195 virtual void cancel()=0;
196 virtual bool cancel_timer()=0;
197 virtual void reset_timer()=0;
198 };
199 template <class callback_t>
200 struct anvoke_handler: invoke_response_handler_base
201 {
202 anvoke_handler(const callback_t& cb, uint64_t timeout, async_protocol_handler& con, int command)
203 :m_cb(cb), m_timeout(timeout), m_con(con), m_timer(con.m_pservice_endpoint->get_io_context()), m_timer_started(false),
204 m_cancel_timer_called(false), m_timer_cancelled(false), m_command(command)
205 {
206 if(m_con.start_outer_call())
207 {
208 MDEBUG(con.get_context_ref() << "anvoke_handler, timeout: " << timeout);
209 m_timer.expires_from_now(boost::posix_time::milliseconds(timeout));
210 m_timer.async_wait([&con, command, cb, timeout](const boost::system::error_code& ec)
211 {
212 if(ec == boost::asio::error::operation_aborted)
213 return;
214 MINFO(con.get_context_ref() << "Timeout on invoke operation happened, command: " << command << " timeout: " << timeout);
215 epee::span<const uint8_t> fake;
216 cb(LEVIN_ERROR_CONNECTION_TIMEDOUT, fake, con.get_context_ref());
217 con.close(false);
218 con.finish_outer_call();
219 });
220 m_timer_started = true;
221 }
222 }
223 virtual ~anvoke_handler()
224 {}
225 callback_t m_cb;
226 async_protocol_handler& m_con;
227 boost::asio::deadline_timer m_timer;
228 bool m_timer_started;
229 bool m_cancel_timer_called;
230 bool m_timer_cancelled;
231 uint64_t m_timeout;
232 int m_command;
233 virtual bool handle(int res, const epee::span<const uint8_t> buff, typename async_protocol_handler::connection_context& context)
234 {
235 if(!cancel_timer())
236 return false;
237 m_cb(res, buff, context);
238 m_con.finish_outer_call();
239 return true;
240 }
241 virtual bool is_timer_started() const
242 {
243 return m_timer_started;
244 }
245 virtual void cancel()
246 {
247 if(cancel_timer())
248 {
249 epee::span<const uint8_t> fake;
250 m_cb(LEVIN_ERROR_CONNECTION_DESTROYED, fake, m_con.get_context_ref());
251 m_con.finish_outer_call();
252 }
253 }
254 virtual bool cancel_timer()
255 {
256 if(!m_cancel_timer_called)
257 {
258 m_cancel_timer_called = true;
259 boost::system::error_code ignored_ec;
260 m_timer_cancelled = 1 == m_timer.cancel(ignored_ec);
261 }
262 return m_timer_cancelled;
263 }
264 virtual void reset_timer()
265 {
266 boost::system::error_code ignored_ec;
267 if (!m_cancel_timer_called && m_timer.cancel(ignored_ec) > 0)
268 {
269 callback_t& cb = m_cb;
270 uint64_t timeout = m_timeout;
271 async_protocol_handler& con = m_con;
272 int command = m_command;
273 m_timer.expires_from_now(boost::posix_time::milliseconds(m_timeout));
274 m_timer.async_wait([&con, cb, command, timeout](const boost::system::error_code& ec)
275 {
276 if(ec == boost::asio::error::operation_aborted)
277 return;
278 MINFO(con.get_context_ref() << "Timeout on invoke operation happened, command: " << command << " timeout: " << timeout);
279 epee::span<const uint8_t> fake;
280 cb(LEVIN_ERROR_CONNECTION_TIMEDOUT, fake, con.get_context_ref());
281 con.close(false);
282 con.finish_outer_call();
283 });
284 }
285 }
286 };
287 critical_section m_invoke_response_handlers_lock;
288 std::list<boost::shared_ptr<invoke_response_handler_base> > m_invoke_response_handlers;
289
290 template<class callback_t>
291 bool add_invoke_response_handler(const callback_t &cb, uint64_t timeout, async_protocol_handler& con, int command)
292 {
293 CRITICAL_REGION_LOCAL(m_invoke_response_handlers_lock);
294 if (m_protocol_released)
295 {
296 MERROR("Adding response handler to a released object");
297 return false;
298 }
299 boost::shared_ptr<invoke_response_handler_base> handler(boost::make_shared<anvoke_handler<callback_t>>(cb, timeout, con, command));
300 m_invoke_response_handlers.push_back(handler);
301 return handler->is_timer_started();
302 }
303 template<class callback_t> friend struct anvoke_handler;
304 public:
305 async_protocol_handler(net_utils::i_service_endpoint* psnd_hndlr,
306 config_type& config,
307 t_connection_context& conn_context):
308 m_current_head(bucket_head2()),
309 m_pservice_endpoint(psnd_hndlr),
310 m_config(config),
311 m_connection_context(conn_context),
312 m_max_packet_size(config.m_initial_max_packet_size),
313 m_cache_in_buffer(4 * 1024),
314 m_state(stream_state_head)
315 {
316 m_close_called = 0;
317 m_protocol_released = false;
318 m_wait_count = 0;
319 m_oponent_protocol_ver = 0;
320 m_connection_initialized = false;
321 m_invoke_buf_ready = false;
322 m_invoke_result_code = LEVIN_ERROR_CONNECTION;
323 }
324 virtual ~async_protocol_handler()
325 {
326 try
327 {
328
329 if(m_connection_initialized)
330 {
331 m_config.del_connection(this);
332 }
333
334 for (size_t i = 0; i < 60 * 1000 / 100 && 0 != m_wait_count; ++i)
335 {
336 misc_utils::sleep_no_w(100);
337 }
338 CHECK_AND_ASSERT_MES_NO_RET(0 == m_wait_count, "Failed to wait for operation completion. m_wait_count = " << m_wait_count.load());
339
340 MTRACE(m_connection_context << "~async_protocol_handler()");
341
342 }
343 catch (...) { /* ignore */ }
344 }
345
346 bool start_outer_call()
347 {
348 MTRACE(m_connection_context << "[levin_protocol] -->> start_outer_call");
349 if(!m_pservice_endpoint->add_ref())
350 {
351 MERROR(m_connection_context << "[levin_protocol] -->> start_outer_call failed");
352 return false;
353 }
354 ++m_wait_count;
355 return true;
356 }
357 bool finish_outer_call()
358 {
359 MTRACE(m_connection_context << "[levin_protocol] <<-- finish_outer_call");
360 --m_wait_count;
361 m_pservice_endpoint->release();
362 return true;
363 }
364
365 bool release_protocol()
366 {
367 decltype(m_invoke_response_handlers) local_invoke_response_handlers;
368 CRITICAL_REGION_BEGIN(m_invoke_response_handlers_lock);
369 local_invoke_response_handlers.swap(m_invoke_response_handlers);
370 m_protocol_released = true;
371 CRITICAL_REGION_END();
372
373 // Never call callback inside critical section, that can cause deadlock. Callback can be called when
374 // invoke_response_handler_base is cancelled
375 std::for_each(local_invoke_response_handlers.begin(), local_invoke_response_handlers.end(), [](const boost::shared_ptr<invoke_response_handler_base>& pinv_resp_hndlr) {
376 pinv_resp_hndlr->cancel();
377 });
378
379 return true;
380 }
381
382 bool close(const bool wait_for_shutdown)
383 {
384 ++m_close_called;
385
386 m_pservice_endpoint->close(wait_for_shutdown);
387 return true;
388 }
389
390 void update_connection_context(const connection_context& contxt)
391 {
392 m_connection_context = contxt;
393 }
394
395 void request_callback()
396 {
397 misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler(
398 boost::bind(&async_protocol_handler::finish_outer_call, this));
399
400 m_pservice_endpoint->request_callback();
401 }
402
403 void handle_qued_callback()
404 {
405 m_config.m_pcommands_handler->callback(m_connection_context);
406 }
407
408 virtual bool handle_recv(const void* ptr, size_t cb)
409 {
410 if(m_close_called)
411 return false; //closing connections
412
413 if(!m_config.m_pcommands_handler)
414 {
415 MERROR(m_connection_context << "Commands handler not set!");
416 return false;
417 }
418
419 // these should never fail, but do runtime check for safety
420 const uint64_t max_packet_size = m_max_packet_size;
421 CHECK_AND_ASSERT_MES(max_packet_size >= m_cache_in_buffer.size(), false, "Bad m_cache_in_buffer.size()");
422 CHECK_AND_ASSERT_MES(max_packet_size - m_cache_in_buffer.size() >= m_fragment_buffer.size(), false, "Bad m_cache_in_buffer.size() + m_fragment_buffer.size()");
423
424 // flipped to subtraction; prevent overflow since m_max_packet_size is variable and public
425 if(cb > max_packet_size - m_cache_in_buffer.size() - m_fragment_buffer.size())
426 {
427 MWARNING(m_connection_context << "Maximum packet size exceed!, m_max_packet_size = " << max_packet_size
428 << ", packet received " << m_cache_in_buffer.size() + cb
429 << ", connection will be closed.");
430 return false;
431 }
432
433 m_cache_in_buffer.append((const char*)ptr, cb);
434
435 bool is_continue = true;
436 while(is_continue)
437 {
438 switch(m_state)
439 {
440 case stream_state_body:
441 if(m_cache_in_buffer.size() < m_current_head.m_cb)
442 {
443 is_continue = false;
444 if(cb >= MIN_BYTES_WANTED)
445 {
446 CRITICAL_REGION_LOCAL(m_invoke_response_handlers_lock);
447 if (!m_invoke_response_handlers.empty())
448 {
449 //async call scenario
450 boost::shared_ptr<invoke_response_handler_base> response_handler = m_invoke_response_handlers.front();
451 response_handler->reset_timer();
452 MDEBUG(m_connection_context << "LEVIN_PACKET partial msg received. len=" << cb << ", current total " << m_cache_in_buffer.size() << "/" << m_current_head.m_cb << " (" << (100.0f * m_cache_in_buffer.size() / (m_current_head.m_cb ? m_current_head.m_cb : 1)) << "%)");
453 }
454 }
455 break;
456 }
457
458 {
459 std::string temp{};
460 epee::span<const uint8_t> buff_to_invoke = m_cache_in_buffer.carve((std::string::size_type)m_current_head.m_cb);
461 m_state = stream_state_head;
462
463 // abstract_tcp_server2.h manages max bandwidth for a p2p link
464 if (!(m_current_head.m_flags & (LEVIN_PACKET_REQUEST | LEVIN_PACKET_RESPONSE)))
465 {
466 // special noise/fragment command
467 static constexpr const uint32_t both_flags = (LEVIN_PACKET_BEGIN | LEVIN_PACKET_END);
468 if ((m_current_head.m_flags & both_flags) == both_flags)
469 break; // noise message, skip to next message
470
471 if (m_current_head.m_flags & LEVIN_PACKET_BEGIN)
472 m_fragment_buffer.clear();
473
474 m_fragment_buffer.append(reinterpret_cast<const char*>(buff_to_invoke.data()), buff_to_invoke.size());
475 if (!(m_current_head.m_flags & LEVIN_PACKET_END))
476 break; // skip to next message
477
478 if (m_fragment_buffer.size() < sizeof(bucket_head2))
479 {
480 MERROR(m_connection_context << "Fragmented data too small for levin header");
481 return false;
482 }
483
484 temp.swap(m_fragment_buffer);
485 std::memcpy(std::addressof(m_current_head), std::addressof(temp[0]), sizeof(bucket_head2));
486 const std::uint64_t inner_size = SWAP64LE(m_current_head.m_cb);
487 buff_to_invoke = {reinterpret_cast<const uint8_t*>(temp.data()) + sizeof(bucket_head2), temp.size() - sizeof(bucket_head2)};
488 if (buff_to_invoke.size() < inner_size)
489 {
490 MERROR(m_connection_context << "Invalid fragmented buffer size: " << buff_to_invoke.size() << " vs " << inner_size);
491 return false;
492 }
493
494 buff_to_invoke = {buff_to_invoke.data(), std::size_t(inner_size)};
495
496 const size_t max_bytes = m_connection_context.get_max_bytes(m_current_head.m_command);
497 if(buff_to_invoke.size() > std::min<size_t>(max_packet_size, max_bytes))
498 {
499 MERROR(m_connection_context << "Maximum packet size exceed!, m_max_packet_size = " << std::min<size_t>(max_packet_size, max_bytes)
500 << ", packet header received " << m_current_head.m_cb << ", command " << m_current_head.m_command
501 << ", connection will be closed.");
502 return false;
503 }
504 }
505
506 bool is_response = (m_oponent_protocol_ver == LEVIN_PROTOCOL_VER_1 && m_current_head.m_flags&LEVIN_PACKET_RESPONSE);
507
508 MDEBUG(m_connection_context << "LEVIN_PACKET_RECEIVED. [len=" << m_current_head.m_cb
509 << ", flags" << m_current_head.m_flags
510 << ", r?=" << m_current_head.m_have_to_return_data
511 <<", cmd = " << m_current_head.m_command
512 << ", v=" << m_current_head.m_protocol_version);
513
514 if(is_response)
515 {//response to some invoke
516
517 epee::critical_region_t<decltype(m_invoke_response_handlers_lock)> invoke_response_handlers_guard(m_invoke_response_handlers_lock);
518 if(!m_invoke_response_handlers.empty())
519 {//async call scenario
520 boost::shared_ptr<invoke_response_handler_base> response_handler = m_invoke_response_handlers.front();
521 bool timer_cancelled = response_handler->cancel_timer();
522 // Don't pop handler, to avoid destroying it
523 if(timer_cancelled)
524 m_invoke_response_handlers.pop_front();
525 invoke_response_handlers_guard.unlock();
526
527 if(timer_cancelled)
528 response_handler->handle(m_current_head.m_return_code, buff_to_invoke, m_connection_context);
529 }
530 else
531 {
532 invoke_response_handlers_guard.unlock();
533 //use sync call scenario
534 if(!m_wait_count && !m_close_called)
535 {
536 MERROR(m_connection_context << "no active invoke when response came, wtf?");
537 return false;
538 }else
539 {
540 CRITICAL_REGION_BEGIN(m_local_inv_buff_lock);
541 m_local_inv_buff = std::string((const char*)buff_to_invoke.data(), buff_to_invoke.size());
542 buff_to_invoke = epee::span<const uint8_t>((const uint8_t*)NULL, 0);
543 m_invoke_result_code = m_current_head.m_return_code;
544 CRITICAL_REGION_END();
545 m_invoke_buf_ready = true;
546 }
547 }
548 }else
549 {
550 if(m_current_head.m_have_to_return_data)
551 {
552 levin::message_writer return_message{32 * 1024};
553 const uint32_t return_code = m_config.m_pcommands_handler->invoke(
554 m_current_head.m_command, buff_to_invoke, return_message.buffer, m_connection_context
555 );
556
557 // peer_id remains unset if dropped
558 if (m_current_head.m_command == m_connection_context.handshake_command() && m_connection_context.handshake_complete())
559 m_max_packet_size = m_config.m_max_packet_size;
560
561 if(!send_message(return_message.finalize_response(m_current_head.m_command, return_code)))
562 return false;
563 }
564 else
565 m_config.m_pcommands_handler->notify(m_current_head.m_command, buff_to_invoke, m_connection_context);
566 }
567 // reuse small buffer
568 if (!temp.empty() && temp.capacity() <= 64 * 1024)
569 {
570 temp.clear();
571 m_fragment_buffer = std::move(temp);
572 }
573 }
574 break;
575 case stream_state_head:
576 {
577 if(m_cache_in_buffer.size() < sizeof(bucket_head2))
578 {
579 if(m_cache_in_buffer.size() >= sizeof(uint64_t) && *((uint64_t*)m_cache_in_buffer.span(8).data()) != SWAP64LE(LEVIN_SIGNATURE))
580 {
581 MWARNING(m_connection_context << "Signature mismatch, connection will be closed");
582 return false;
583 }
584 is_continue = false;
585 break;
586 }
587
588 #if BYTE_ORDER == LITTLE_ENDIAN
589 bucket_head2& phead = *(bucket_head2*)m_cache_in_buffer.span(sizeof(bucket_head2)).data();
590 #else
591 bucket_head2 phead = *(bucket_head2*)m_cache_in_buffer.span(sizeof(bucket_head2)).data();
592 phead.m_signature = SWAP64LE(phead.m_signature);
593 phead.m_cb = SWAP64LE(phead.m_cb);
594 phead.m_command = SWAP32LE(phead.m_command);
595 phead.m_return_code = SWAP32LE(phead.m_return_code);
596 phead.m_flags = SWAP32LE(phead.m_flags);
597 phead.m_protocol_version = SWAP32LE(phead.m_protocol_version);
598 #endif
599 if(LEVIN_SIGNATURE != phead.m_signature)
600 {
601 LOG_ERROR_CC(m_connection_context, "Signature mismatch, connection will be closed");
602 return false;
603 }
604 m_current_head = phead;
605
606 m_cache_in_buffer.erase(sizeof(bucket_head2));
607 m_state = stream_state_body;
608 m_oponent_protocol_ver = m_current_head.m_protocol_version;
609 const size_t max_bytes = m_connection_context.get_max_bytes(m_current_head.m_command);
610 if(m_current_head.m_cb > std::min<size_t>(max_packet_size, max_bytes))
611 {
612 LOG_ERROR_CC(m_connection_context, "Maximum packet size exceed!, m_max_packet_size = " << std::min<size_t>(max_packet_size, max_bytes)
613 << ", packet header received " << m_current_head.m_cb << ", command " << m_current_head.m_command
614 << ", connection will be closed.");
615 return false;
616 }
617 }
618 break;
619 default:
620 LOG_ERROR_CC(m_connection_context, "Undefined state in levin_server_impl::connection_handler, m_state=" << m_state);
621 return false;
622 }
623 }
624
625 return true;
626 }
627
628 bool after_init_connection()
629 {
630 if (!m_connection_initialized)
631 {
632 m_connection_initialized = true;
633 m_config.add_connection(this);
634 }
635 return true;
636 }
637
638 template<class callback_t>
639 bool async_invoke(int command, message_writer in_msg, const callback_t &cb, size_t timeout = LEVIN_DEFAULT_TIMEOUT_PRECONFIGURED)
640 {
641 misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler(
642 boost::bind(&async_protocol_handler::finish_outer_call, this));
643
644 if(timeout == LEVIN_DEFAULT_TIMEOUT_PRECONFIGURED)
645 timeout = m_config.m_invoke_timeout;
646
647 int err_code = LEVIN_OK;
648 do
649 {
650 CRITICAL_REGION_LOCAL(m_call_lock);
651
652 m_invoke_buf_ready = false;
653 CRITICAL_REGION_BEGIN(m_invoke_response_handlers_lock);
654
655 if (command == m_connection_context.handshake_command())
656 m_max_packet_size = m_config.m_max_packet_size;
657
658 if(!send_message(in_msg.finalize_invoke(command)))
659 {
660 LOG_ERROR_CC(m_connection_context, "Failed to do_send");
661 err_code = LEVIN_ERROR_CONNECTION;
662 break;
663 }
664
665 if(!add_invoke_response_handler(cb, timeout, *this, command))
666 {
667 err_code = LEVIN_ERROR_CONNECTION_DESTROYED;
668 break;
669 }
670 CRITICAL_REGION_END();
671 } while (false);
672
673 if (LEVIN_OK != err_code)
674 {
675 epee::span<const uint8_t> stub_buff = nullptr;
676 // Never call callback inside critical section, that can cause deadlock
677 cb(err_code, stub_buff, m_connection_context);
678 return false;
679 }
680
681 return true;
682 }
683
684 int invoke(int command, message_writer in_msg, std::string& buff_out)
685 {
686 misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler(
687 boost::bind(&async_protocol_handler::finish_outer_call, this));
688
689 CRITICAL_REGION_LOCAL(m_call_lock);
690
691 m_invoke_buf_ready = false;
692
693 if (command == m_connection_context.handshake_command())
694 m_max_packet_size = m_config.m_max_packet_size;
695
696 if (!send_message(in_msg.finalize_invoke(command)))
697 {
698 LOG_ERROR_CC(m_connection_context, "Failed to send request");
699 return LEVIN_ERROR_CONNECTION;
700 }
701
702 uint64_t ticks_start = misc_utils::get_tick_count();
703 size_t prev_size = 0;
704
705 while(!m_invoke_buf_ready && !m_protocol_released)
706 {
707 if(m_cache_in_buffer.size() - prev_size >= MIN_BYTES_WANTED)
708 {
709 prev_size = m_cache_in_buffer.size();
710 ticks_start = misc_utils::get_tick_count();
711 }
712 if(misc_utils::get_tick_count() - ticks_start > m_config.m_invoke_timeout)
713 {
714 MWARNING(m_connection_context << "invoke timeout (" << m_config.m_invoke_timeout << "), closing connection ");
715 close();
716 return LEVIN_ERROR_CONNECTION_TIMEDOUT;
717 }
718 if(!m_pservice_endpoint->call_run_once_service_io())
719 return LEVIN_ERROR_CONNECTION_DESTROYED;
720 }
721
722 if(m_protocol_released)
723 return LEVIN_ERROR_CONNECTION_DESTROYED;
724
725 CRITICAL_REGION_BEGIN(m_local_inv_buff_lock);
726 buff_out.swap(m_local_inv_buff);
727 m_local_inv_buff.clear();
728 CRITICAL_REGION_END();
729
730 return m_invoke_result_code;
731 }
732
733 /*! Sends `message` without adding a levin header. The message must have been
734 created with `make_noise_notify`, `make_fragmented_notify`, or
735 `message_writer::finalize_notify`. See additional instructions for
736 `make_fragmented_notify`.
737
738 \return 1 on success */
739 int send(byte_slice message)
740 {
741 const misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler(
742 boost::bind(&async_protocol_handler::finish_outer_call, this)
743 );
744
745 if (!send_message(std::move(message)))
746 {
747 LOG_ERROR_CC(m_connection_context, "Failed to send message, dropping it");
748 return -1;
749 }
750 return 1;
751 }
752 //------------------------------------------------------------------------------------------
753 boost::uuids::uuid get_connection_id() {return m_connection_context.m_connection_id;}
754 //------------------------------------------------------------------------------------------
755 t_connection_context& get_context_ref() {return m_connection_context;}
756 };
757 //------------------------------------------------------------------------------------------
758 template<class t_connection_context>
759 void async_protocol_handler_config<t_connection_context>::del_connection(async_protocol_handler<t_connection_context>* pconn)
760 {
761 CRITICAL_REGION_BEGIN(m_connects_lock);
762 m_connects.erase(pconn->get_connection_id());
763 CRITICAL_REGION_END();
764 m_pcommands_handler->on_connection_close(pconn->m_connection_context);
765 }
766 //------------------------------------------------------------------------------------------
767 template<class t_connection_context>
768 void async_protocol_handler_config<t_connection_context>::delete_connections(size_t count, bool incoming)
769 {
770 std::vector<typename connections_map::mapped_type> connections;
771
772 auto scope_exit_handler = misc_utils::create_scope_leave_handler([&connections]{
773 for (auto &aph: connections)
774 aph->finish_outer_call();
775 });
776
777 CRITICAL_REGION_BEGIN(m_connects_lock);
778 for (auto& c: m_connects)
779 {
780 if (c.second->m_connection_context.m_is_income == incoming)
781 if (c.second->start_outer_call())
782 connections.push_back(c.second);
783 }
784
785 // close random connections from the provided set
786 // TODO or better just keep removing random elements (performance)
787 unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
788 shuffle(connections.begin(), connections.end(), std::default_random_engine(seed));
789 for (size_t i = 0; i < connections.size() && i < count; ++i)
790 m_connects.erase(connections[i]->get_connection_id());
791
792 CRITICAL_REGION_END();
793
794 for (size_t i = 0; i < connections.size() && i < count; ++i)
795 connections[i]->close(false);
796 }
797 //------------------------------------------------------------------------------------------
798 template<class t_connection_context>
799 void async_protocol_handler_config<t_connection_context>::del_out_connections(size_t count)
800 {
801 delete_connections(count, false);
802 }
803 //------------------------------------------------------------------------------------------
804 template<class t_connection_context>
805 void async_protocol_handler_config<t_connection_context>::del_in_connections(size_t count)
806 {
807 delete_connections(count, true);
808 }
809 //------------------------------------------------------------------------------------------
810 template<class t_connection_context>
811 void async_protocol_handler_config<t_connection_context>::add_connection(async_protocol_handler<t_connection_context>* pconn)
812 {
813 CRITICAL_REGION_BEGIN(m_connects_lock);
814 m_connects[pconn->get_connection_id()] = pconn;
815 CRITICAL_REGION_END();
816 m_pcommands_handler->on_connection_new(pconn->m_connection_context);
817 }
818 //------------------------------------------------------------------------------------------
819 template<class t_connection_context>
820 async_protocol_handler<t_connection_context>* async_protocol_handler_config<t_connection_context>::find_connection(boost::uuids::uuid connection_id) const
821 {
822 auto it = m_connects.find(connection_id);
823 return it == m_connects.end() ? 0 : it->second;
824 }
825 //------------------------------------------------------------------------------------------
826 template<class t_connection_context>
827 int async_protocol_handler_config<t_connection_context>::find_and_lock_connection(boost::uuids::uuid connection_id, async_protocol_handler<t_connection_context>*& aph)
828 {
829 CRITICAL_REGION_LOCAL(m_connects_lock);
830 aph = find_connection(connection_id);
831 if(0 == aph)
832 return LEVIN_ERROR_CONNECTION_NOT_FOUND;
833 if(!aph->start_outer_call())
834 return LEVIN_ERROR_CONNECTION_DESTROYED;
835 return LEVIN_OK;
836 }
837 //------------------------------------------------------------------------------------------
838 template<class t_connection_context>
839 int async_protocol_handler_config<t_connection_context>::invoke(int command, message_writer in_msg, std::string& buff_out, boost::uuids::uuid connection_id)
840 {
841 async_protocol_handler<t_connection_context>* aph;
842 int r = find_and_lock_connection(connection_id, aph);
843 return LEVIN_OK == r ? aph->invoke(command, std::move(in_msg), buff_out) : r;
844 }
845 //------------------------------------------------------------------------------------------
846 template<class t_connection_context> template<class callback_t>
847 int async_protocol_handler_config<t_connection_context>::invoke_async(int command, message_writer in_msg, boost::uuids::uuid connection_id, const callback_t &cb, size_t timeout)
848 {
849 async_protocol_handler<t_connection_context>* aph;
850 int r = find_and_lock_connection(connection_id, aph);
851 return LEVIN_OK == r ? aph->async_invoke(command, std::move(in_msg), cb, timeout) : r;
852 }
853 //------------------------------------------------------------------------------------------
854 template<class t_connection_context> template<class callback_t>
855 bool async_protocol_handler_config<t_connection_context>::foreach_connection(const callback_t &cb)
856 {
857 std::vector<typename connections_map::mapped_type> conn;
858
859 auto scope_exit_handler = misc_utils::create_scope_leave_handler([&conn]{
860 for (auto &aph: conn)
861 aph->finish_outer_call();
862 });
863
864 CRITICAL_REGION_BEGIN(m_connects_lock);
865 conn.reserve(m_connects.size());
866 for (auto &e: m_connects)
867 if (e.second->start_outer_call())
868 conn.push_back(e.second);
869 CRITICAL_REGION_END()
870
871 for (auto &aph: conn)
872 if (!cb(aph->get_context_ref()))
873 return false;
874
875 return true;
876 }
877 //------------------------------------------------------------------------------------------
878 template<class t_connection_context> template<class callback_t>
879 bool async_protocol_handler_config<t_connection_context>::for_connection(const boost::uuids::uuid &connection_id, const callback_t &cb)
880 {
881 async_protocol_handler<t_connection_context>* aph = nullptr;
882 if (find_and_lock_connection(connection_id, aph) != LEVIN_OK)
883 return false;
884 auto scope_exit_handler = misc_utils::create_scope_leave_handler(
885 boost::bind(&async_protocol_handler<t_connection_context>::finish_outer_call, aph));
886 if(!cb(aph->get_context_ref()))
887 return false;
888 return true;
889 }
890 //------------------------------------------------------------------------------------------
891 template<class t_connection_context>
892 size_t async_protocol_handler_config<t_connection_context>::get_connections_count()
893 {
894 CRITICAL_REGION_LOCAL(m_connects_lock);
895 return m_connects.size();
896 }
897 //------------------------------------------------------------------------------------------
898 template<class t_connection_context>
899 size_t async_protocol_handler_config<t_connection_context>::get_out_connections_count()
900 {
901 CRITICAL_REGION_LOCAL(m_connects_lock);
902 size_t count = 0;
903 for (const auto &c: m_connects)
904 if (!c.second->m_connection_context.m_is_income)
905 ++count;
906 return count;
907 }
908 //------------------------------------------------------------------------------------------
909 template<class t_connection_context>
910 size_t async_protocol_handler_config<t_connection_context>::get_in_connections_count()
911 {
912 CRITICAL_REGION_LOCAL(m_connects_lock);
913 size_t count = 0;
914 for (const auto &c: m_connects)
915 if (c.second->m_connection_context.m_is_income)
916 ++count;
917 return count;
918 }
919 //------------------------------------------------------------------------------------------
920 template<class t_connection_context>
921 void async_protocol_handler_config<t_connection_context>::set_handler(levin_commands_handler<t_connection_context>* handler, void (*destroy)(levin_commands_handler<t_connection_context>*))
922 {
923 if (m_pcommands_handler && m_pcommands_handler_destroy)
924 (*m_pcommands_handler_destroy)(m_pcommands_handler);
925 m_pcommands_handler = handler;
926 m_pcommands_handler_destroy = destroy;
927 }
928 //------------------------------------------------------------------------------------------
929 template<class t_connection_context>
930 int async_protocol_handler_config<t_connection_context>::send(byte_slice message, const boost::uuids::uuid& connection_id)
931 {
932 async_protocol_handler<t_connection_context>* aph;
933 int r = find_and_lock_connection(connection_id, aph);
934 return LEVIN_OK == r ? aph->send(std::move(message)) : 0;
935 }
936 //------------------------------------------------------------------------------------------
937 template<class t_connection_context>
938 bool async_protocol_handler_config<t_connection_context>::close(boost::uuids::uuid connection_id, const bool wait_for_shutdown)
939 {
940 async_protocol_handler<t_connection_context>* aph = nullptr;
941 if (find_and_lock_connection(connection_id, aph) != LEVIN_OK)
942 return false;
943 auto scope_exit_handler = misc_utils::create_scope_leave_handler(
944 boost::bind(&async_protocol_handler<t_connection_context>::finish_outer_call, aph));
945 if (!aph->close(wait_for_shutdown))
946 return false;
947 CRITICAL_REGION_LOCAL(m_connects_lock);
948 m_connects.erase(connection_id);
949 return true;
950 }
951 //------------------------------------------------------------------------------------------
952 template<class t_connection_context>
953 bool async_protocol_handler_config<t_connection_context>::update_connection_context(const t_connection_context& contxt)
954 {
955 CRITICAL_REGION_LOCAL(m_connects_lock);
956 async_protocol_handler<t_connection_context>* aph = find_connection(contxt.m_connection_id);
957 if(0 == aph)
958 return false;
959 aph->update_connection_context(contxt);
960 return true;
961 }
962 //------------------------------------------------------------------------------------------
963 template<class t_connection_context>
964 bool async_protocol_handler_config<t_connection_context>::request_callback(boost::uuids::uuid connection_id)
965 {
966 async_protocol_handler<t_connection_context>* aph;
967 int r = find_and_lock_connection(connection_id, aph);
968 if(LEVIN_OK == r)
969 {
970 aph->request_callback();
971 return true;
972 }
973 else
974 {
975 return false;
976 }
977 }
978 }
979 }