merge with master
[platform/framework/web/wrt-commons.git] / modules / rpc / include / dpl / rpc / generic_socket_rpc_server.h
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /*
17  * @file        generic_socket_rpc_server.h
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version     1.0
20  * @brief       This file is the header file for generic socket RPC server
21  */
22 #ifndef DPL_GENERIC_SOCKET_RPC_SERVER_H
23 #define DPL_GENERIC_SOCKET_RPC_SERVER_H
24
25 #include <dpl/rpc/abstract_rpc_connector.h>
26 #include <dpl/socket/abstract_socket.h>
27 #include <set>
28
29 namespace DPL {
30 namespace RPC {
31 template<typename SocketType>
32 class GenericSocketRPCServer :
33     public AbstractRPCConnector,
34     private DPL::Event::EventListener<DPL::Socket::AbstractSocketEvents::
35                                           AcceptEvent>
36 {
37   public:
38     class Exception
39     {
40       public:
41         DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
42         DECLARE_EXCEPTION_TYPE(Base, OpenFailed)
43         DECLARE_EXCEPTION_TYPE(Base, CloseFailed)
44     };
45
46   protected:
47     // Derived class implementations for connection managment
48     virtual AbstractRPCConnection *OpenSpecificConnection(SocketType *socket) =
49         0;
50
51   private:
52     typedef std::set<SocketType *> InternalInterfaceSet;
53     InternalInterfaceSet m_internalInterfacesSet;
54
55     virtual void OnEventReceived(
56         const DPL::Socket::AbstractSocketEvents::AcceptEvent &event)
57     {
58         // Retrieve socket sender
59         SocketType *server = static_cast<SocketType *>(event.GetSender());
60
61         // Is this interface still tracked ?
62         // It might have disappeared on close
63         typename InternalInterfaceSet::iterator iterator =
64             m_internalInterfacesSet.find(server);
65
66         if (iterator == m_internalInterfacesSet.end()) {
67             LogPedantic("RPC server interface socket disappeared");
68             return;
69         }
70
71         // Accept incoming client
72         SocketType *client = static_cast<SocketType *>(server->Accept());
73         if (client == NULL) {
74             LogPedantic("Spontaneous accept on socket occurred");
75             return;
76         }
77
78         LogPedantic(
79             "Client connected to server: " <<
80             client->GetRemoteAddress().ToString());
81
82         // Open specific connection implementation
83         AbstractRPCConnection *connection = OpenSpecificConnection(client);
84
85         // Retrieve ID once again
86         AbstractRPCConnectionID connectionID =
87             static_cast<AbstractRPCConnectionID>(server);
88
89         // Inform listeners
90         DPL::Event::EventSupport<AbstractRPCConnectorEvents::
91                                      ConnectionEstablishedEvent>::
92             EmitEvent(AbstractRPCConnectorEvents::ConnectionEstablishedEvent(
93                           connectionID, connection, EventSender(
94                               this)), DPL::Event::EmitMode::Queued);
95     }
96
97   public:
98     explicit GenericSocketRPCServer()
99     {}
100
101     virtual ~GenericSocketRPCServer()
102     {
103         // Always close connection
104         CloseAll();
105     }
106
107     AbstractRPCConnectionID Open(const Address &socketAddress)
108     {
109         LogPedantic("Starting server: " << socketAddress.ToString());
110
111         // Alloc new socket
112         SocketType *socket = new SocketType();
113
114         // Add socket listener
115         socket->EventSupport<DPL::Socket::AbstractSocketEvents::AcceptEvent>::
116             AddListener(this);
117
118         Try
119         {
120             // Open socket
121             socket->Open();
122
123             // Bind socket address
124             socket->Bind(socketAddress);
125
126             // Start listening
127             socket->Listen(8);
128         }
129         Catch(DPL::Socket::AbstractSocket::Exception::Base)
130         {
131             // Remove back socket listener
132             socket->EventSupport<DPL::Socket::AbstractSocketEvents::AcceptEvent>
133                 ::RemoveListener(this);
134
135             // Log debug
136             LogPedantic("Cannot start server: " << socketAddress.ToString());
137
138             // Problem with server startup
139             ReThrowMsg(typename Exception::OpenFailed, socketAddress.ToString());
140         }
141
142         // Register new internal connection
143         m_internalInterfacesSet.insert(socket);
144
145         // Debug info
146         LogPedantic(
147             "Server started on interface: " <<
148             socket->GetLocalAddress().ToString());
149
150         // Return unique identifier
151         return static_cast<AbstractRPCConnectionID>(socket);
152     }
153
154     void Close(AbstractRPCConnectionID connectionID)
155     {
156         LogPedantic("Closing server interface...");
157
158         // Get socket from ID
159         SocketType *socket = static_cast<SocketType *>(connectionID);
160
161         // Find corresponding internal connection
162         typename InternalInterfaceSet::iterator iterator =
163             m_internalInterfacesSet.find(socket);
164
165         if (iterator == m_internalInterfacesSet.end()) {
166             return;
167         }
168
169         // Close socket
170         socket->Close();
171
172         // Remove socket listeners
173         socket->EventSupport<DPL::Socket::AbstractSocketEvents::AcceptEvent>::
174             RemoveListener(this);
175         delete socket;
176
177         m_internalInterfacesSet.erase(iterator);
178
179         // Done
180         LogPedantic("Closed");
181     }
182
183     void CloseAll()
184     {
185         while (!m_internalInterfacesSet.empty()) {
186             Close(static_cast<AbstractRPCConnectionID>(*m_internalInterfacesSet
187                                                            .begin()));
188         }
189     }
190 };
191 }
192 } // namespace DPL
193
194 #endif // DPL_GENERIC_SOCKET_RPC_SERVER_H