Electroneum
abstract_tcp_server.h
Go to the documentation of this file.
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 
28 
29 #ifndef _ABSTRACT_TCP_SERVER_H_
30 #define _ABSTRACT_TCP_SERVER_H_
31 
32 #include <process.h>
33 #include <list>
34 #include <winsock2.h>
35 #include "winobj.h"
36 //#include "threads_helper.h"
37 #include "net_utils_base.h"
38 
39 #pragma comment(lib, "Ws2_32.lib")
40 
41 #undef ELECTRONEUM_DEFAULT_LOG_CATEGORY
42 #define ELECTRONEUM_DEFAULT_LOG_CATEGORY "net"
43 
44 namespace epee
45 {
46 namespace net_utils
47 {
48  /************************************************************************/
49  /* */
50  /************************************************************************/
52  {
53  public:
54  soket_sender(SOCKET sock):m_sock(sock){}
55  private:
56  virtual bool handle_send(const void* ptr, size_t cb)
57  {
58  if(cb != send(m_sock, (char*)ptr, (int)cb, 0))
59  {
60  int sock_err = WSAGetLastError();
61  LOG_ERROR("soket_sender: Failed to send " << cb << " bytes, Error=" << sock_err);
62  return false;
63  }
64  return true;
65 
66  }
67 
68  SOCKET m_sock;
69  };
70 
71 
72 
73  /************************************************************************/
74  /* */
75  /************************************************************************/
76  template<class THandler>
78  {
79  public:
81 
82  bool init_server(int port_no);
83  bool deinit_server();
84  bool run_server();
85  bool send_stop_signal();
86 
87  typename THandler::config_type& get_config_object(){return m_config;}
88 
89  private:
90  bool invoke_connection(SOCKET hnew_sock, long ip_from, int post_from);
91  static unsigned __stdcall ConnectionHandlerProc(void* lpParameter);
92 
93  class thread_context;
94  typedef std::list<thread_context> connections_container;
95  typedef typename connections_container::iterator connections_iterator;
96 
97  struct thread_context
98  {
99  HANDLE m_htread;
100  SOCKET m_socket;
101  abstract_tcp_server* powner;
102  connection_context m_context;
103  typename connections_iterator m_self_it;
104  };
105 
106  SOCKET m_listen_socket;
107  int m_port;
108  bool m_initialized;
109  volatile LONG m_stop_server;
110  volatile LONG m_threads_count;
111  typename THandler::config_type m_config;
112  connections_container m_connections;
113  critical_section m_connections_lock;
114  };
115 
116  template<class THandler>
117  unsigned __stdcall abstract_tcp_server<THandler>::ConnectionHandlerProc(void* lpParameter)
118  {
119 
120  thread_context* pthread_context = (thread_context*)lpParameter;
121  if(!pthread_context)
122  return 0;
123  abstract_tcp_server<THandler>* pthis = pthread_context->powner;
124 
125  ::InterlockedIncrement(&pthis->m_threads_count);
126 
127  ::CoInitialize(NULL);
128 
129 
130  LOG_PRINT("Handler thread STARTED with socket=" << pthread_context->m_socket, LOG_LEVEL_2);
131  int res = 0;
132 
133  soket_sender sndr(pthread_context->m_socket);
134  THandler srv(&sndr, pthread_context->powner->m_config, pthread_context->m_context);
135 
136 
137  srv.after_init_connection();
138 
139  char buff[1000] = {0};
140  std::string ansver;
141  while ( (res = recv(pthread_context->m_socket, (char*)buff, 1000, 0)) > 0)
142  {
143  LOG_PRINT("Data in, " << res << " bytes", LOG_LEVEL_3);
144  if(!srv.handle_recv(buff, res))
145  break;
146  }
147  shutdown(pthread_context->m_socket, SD_BOTH);
148  closesocket(pthread_context->m_socket);
149 
150  abstract_tcp_server* powner = pthread_context->powner;
151  LOG_PRINT("Handler thread with socket=" << pthread_context->m_socket << " STOPPED", LOG_LEVEL_2);
152  powner->m_connections_lock.lock();
153  ::CloseHandle(pthread_context->m_htread);
154  pthread_context->powner->m_connections.erase(pthread_context->m_self_it);
155  powner->m_connections_lock.unlock();
156  CoUninitialize();
157  ::InterlockedDecrement(&pthis->m_threads_count);
158  return 1;
159  }
160  //----------------------------------------------------------------------------------------
161  template<class THandler>
164  m_stop_server(0), m_port(0), m_threads_count(0)
165  {
166 
167  }
168 
169  //----------------------------------------------------------------------------------------
170  template<class THandler>
172  {
173  m_port = port_no;
174  WSADATA wsad = {0};
175  int err = ::WSAStartup(MAKEWORD(2,2), &wsad);
176  if ( err != 0 || LOBYTE( wsad.wVersion ) != 2 || HIBYTE( wsad.wVersion ) != 2 )
177  {
178  LOG_ERROR("Could not find a usable WinSock DLL, err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"");
179  return false;
180  }
181 
182  m_initialized = true;
183 
184  m_listen_socket = ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
186  {
187  err = ::WSAGetLastError();
188  LOG_ERROR("Failed to create socket, err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"");
189  return false;
190  }
191 
192  int opt = 1;
193  setsockopt (m_listen_socket, SOL_SOCKET,SO_REUSEADDR, reinterpret_cast<char*>(&opt), sizeof(int));
194 
195  sockaddr_in adr = {0};
196  adr.sin_family = AF_INET;
197  adr.sin_addr.s_addr = htonl(INADDR_ANY);
198  adr.sin_port = (u_short)htons(port_no);
199 
200  err = bind(m_listen_socket, (const sockaddr*)&adr, sizeof(adr ));
201  if(SOCKET_ERROR == err )
202  {
203  err = ::WSAGetLastError();
204  LOG_PRINT("Failed to Bind, err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"", LOG_LEVEL_2);
205  deinit_server();
206  return false;
207  }
208 
209  ::InterlockedExchange(&m_stop_server, 0);
210 
211  return true;
212  }
213  //----------------------------------------------------------------------------------------
214  template<class THandler>
216  {
217 
218  if(!m_initialized)
219  return true;
220 
222  {
223  shutdown(m_listen_socket, SD_BOTH);
224  int res = closesocket(m_listen_socket);
225  if(SOCKET_ERROR == res)
226  {
227  int err = ::WSAGetLastError();
228  LOG_ERROR("Failed to closesocket(), err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"");
229  }
231  }
232 
233  int res = ::WSACleanup();
234  if(SOCKET_ERROR == res)
235  {
236  int err = ::WSAGetLastError();
237  LOG_ERROR("Failed to WSACleanup(), err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"");
238  }
239  m_initialized = false;
240 
241  return true;
242  }
243  //----------------------------------------------------------------------------------------
244  template<class THandler>
246  {
247  InterlockedExchange(&m_stop_server, 1);
248  return true;
249  }
250  //----------------------------------------------------------------------------------------
251  template<class THandler>
253  {
254  int err = listen(m_listen_socket, 10000);
255  if(SOCKET_ERROR == err )
256  {
257  err = ::WSAGetLastError();
258  LOG_ERROR("Failed to listen, err = " << err << " \"" << socket_errors::get_socket_error_text(err) <<"\"");
259  return false;
260  }
261 
262  LOG_PRINT("Listening port "<< m_port << "...." , LOG_LEVEL_2);
263 
264  while(!m_stop_server)
265  {
266  sockaddr_in adr_from = {0};
267  int adr_len = sizeof(adr_from);
268  fd_set read_fs = {0};
269  read_fs.fd_count = 1;
270  read_fs.fd_array[0] = m_listen_socket;
271  TIMEVAL tv = {0};
272  tv.tv_usec = 100;
273  int select_res = select(0, &read_fs, NULL, NULL, &tv);
274  if(!select_res)
275  continue;
276  SOCKET new_sock = WSAAccept(m_listen_socket, (sockaddr *)&adr_from, &adr_len, NULL, NULL);
277  LOG_PRINT("Accepted connection on socket=" << new_sock, LOG_LEVEL_2);
278  invoke_connection(new_sock, adr_from.sin_addr.s_addr, adr_from.sin_port);
279  }
280 
281  deinit_server();
282 
283 #define ABSTR_TCP_SRV_WAIT_COUNT_MAX 5000
284 #define ABSTR_TCP_SRV_WAIT_COUNT_INTERVAL 1000
285 
286  int wait_count = 0;
287 
288  while(m_threads_count && wait_count*1000 < ABSTR_TCP_SRV_WAIT_COUNT_MAX)
289  {
291  wait_count++;
292  }
293  LOG_PRINT("abstract_tcp_server exit with wait count=" << wait_count*ABSTR_TCP_SRV_WAIT_COUNT_INTERVAL << "(max=" << ABSTR_TCP_SRV_WAIT_COUNT_MAX <<")", LOG_LEVEL_0);
294 
295  return true;
296  }
297  //----------------------------------------------------------------------------------------
298  template<class THandler>
299  bool abstract_tcp_server<THandler>::invoke_connection(SOCKET hnew_sock, const network_address &remote_address)
300  {
302  m_connections.push_back(thread_context());
304  m_connections.back().m_socket = hnew_sock;
305  m_connections.back().powner = this;
306  m_connections.back().m_self_it = --m_connections.end();
307  m_connections.back().m_context.m_remote_address = remote_address;
308  m_connections.back().m_htread = threads_helper::create_thread(ConnectionHandlerProc, &m_connections.back()); // ugh, seems very risky
309 
310  return true;
311  }
312  //----------------------------------------------------------------------------------------
313 
314  //----------------------------------------------------------------------------------------
315  //----------------------------------------------------------------------------------------
316 }
317 }
318 #endif //_ABSTRACT_TCP_SERVER_H_
const char * res
Definition: hmac_keccak.cpp:41
::std::string string
Definition: gtest-port.h:1097
connections_container m_connections
std::map< SOCKET, boost::shared_ptr< connection< TProtocol > > > connections_container
critical_section m_connections_lock
#define SOCKET
#define INVALID_SOCKET
#define false
Definition: stdbool.h:38
THandler::config_type & get_config_object()
#define ABSTR_TCP_SRV_WAIT_COUNT_INTERVAL
#define LOG_ERROR(x)
Definition: misc_log_ex.h:98
#define ABSTR_TCP_SRV_WAIT_COUNT_MAX
expect< void > send(const epee::span< const std::uint8_t > payload, void *const socket, const int flags) noexcept
Definition: zmq.cpp:182