2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
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
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
18 * @file FIo_IpcServer.cpp
19 * @brief This is the implementation file for the _IpcServer class.
31 #include <sys/types.h>
32 #include <sys/socket.h>
36 #include <ipc/ipc_message.h>
38 #include <FBaseRtMutex.h>
39 #include <FBaseSysLog.h>
40 #include <FBase_StringConverter.h>
41 #include <FBaseRt_EventDispatcher.h>
43 #include "FIo_IIpcServerEventListener.h"
44 #include "FIo_IpcServer.h"
48 using namespace Tizen::Base;
49 using namespace Tizen::Base::Runtime;
50 using namespace Tizen::App;
52 namespace Tizen { namespace Io
55 _IpcServer::_ChannelInfo::_ChannelInfo(void)
64 _IpcServer::_ChannelInfo::~_ChannelInfo(void)
66 if (pGIOChannel != null)
68 g_io_channel_unref(pGIOChannel);
75 g_source_destroy(pGSource);
78 g_source_unref(pGSource);
82 _IpcServer::_ClientInfo::_ClientInfo(void)
85 , pReverseChannel(null)
90 _IpcServer::_ClientInfo::~_ClientInfo(void)
92 if (pReverseChannel != null)
94 g_io_channel_unref(pReverseChannel);
100 _IpcServer::_IpcServer(void)
101 : __runOnCallerThread(false)
102 , __pEventDispatcher(null)
105 , __pHandlerGMainContext(null)
106 , __pHandlerGMainLoop(null)
107 , __pConnectGSource(null)
108 , __pCurrentChannel(null)
109 , __pCurrentClientInfo(null)
111 __messageBuffer[0] = '\0';
115 _IpcServer::~_IpcServer(void)
117 if (__pConnectGSource != null)
119 g_source_destroy(__pConnectGSource);
120 g_source_unref(__pConnectGSource);
121 __pConnectGSource = null;
124 if (!__runOnCallerThread)
126 if (__pEventDispatcher)
128 delete __pEventDispatcher;
129 __pEventDispatcher = null;
132 if (__pHandlerGMainLoop)
134 g_main_loop_unref(__pHandlerGMainLoop);
135 __pHandlerGMainLoop = null;
138 if (__pHandlerGMainContext)
140 g_main_context_unref(__pHandlerGMainContext);
141 __pHandlerGMainContext = null;
150 _IpcServer::Construct(const String& name, const _IIpcServerEventListener& listener, bool runOnCallerThread)
152 result r = E_SUCCESS;
154 GIOChannel* pGIOChannel = null;
155 GSource* pGSource = null;
157 struct sockaddr_un serverAddress;
158 int serverSocket = -1;
161 std::string socketName;
163 size_t socketNameLength = 0;
166 __pListener = const_cast <_IIpcServerEventListener*>(&listener);
167 __runOnCallerThread = runOnCallerThread;
169 pName = _StringConverter::CopyToCharArrayN(name);
170 SysTryReturnResult(NID_IO, pName != null, E_OUT_OF_MEMORY, "Not enough memory");
172 socketName.append("/tmp/");
173 socketName.append(pName);
177 socketNameLength = socketName.size() + 1;
178 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long");
180 if (!__runOnCallerThread)
182 __pHandlerGMainContext = g_main_context_new();
183 __pHandlerGMainLoop = g_main_loop_new(__pHandlerGMainContext, FALSE);
188 __pHandlerGMainContext = g_main_context_get_thread_default();
189 if (__pHandlerGMainContext == null) // is global?
191 __pHandlerGMainContext = g_main_context_default();
192 if (__pHandlerGMainContext == null)
199 ret = unlink(socketName.c_str());
200 SysTryLog(NID_IO, ret == 0, "Unlink a socket has failed.. but it is not a problem.");
202 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
203 SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, "Failed to create a socket.");
205 bzero(&serverAddress, sizeof(serverAddress));
206 serverAddress.sun_family = AF_UNIX;
207 strncpy(serverAddress.sun_path, socketName.c_str(), socketNameLength);
208 serverLen = sizeof(serverAddress);
210 ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen);
211 SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket,
212 socketName.c_str(), strerror(errno));
214 ret = chmod(socketName.c_str(), 0666);
215 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket,
216 socketName.c_str(), strerror(errno));
218 ret = listen(serverSocket, 128);
219 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to listen the socket(%d, %s): %s", serverSocket,
220 socketName.c_str(), strerror(errno));
222 pGIOChannel = g_io_channel_unix_new(serverSocket);
223 SysTryCatch(NID_IO, pGIOChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
225 // socket will be closed when pGIOChannel is deleted.
226 g_io_channel_set_close_on_unref(pGIOChannel, TRUE);
229 pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
230 SysTryCatch(NID_IO, pGSource != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
231 "[E_OUT_OF_MEMORY] Failed to create watch for socket.");
233 // channel will be delete when pGSource is deleted.
234 g_io_channel_unref(pGIOChannel);
237 g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL);
238 g_source_attach(pGSource, __pHandlerGMainContext);
240 if (__runOnCallerThread)
242 __pListener->OnIpcServerStarted(*this);
246 ret = pthread_create(&__handlerThread, null, &ThreadProc, (void*) this);
247 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to an IPC thread");
250 __pConnectGSource = pGSource;
257 if (pGIOChannel != null)
259 g_io_channel_unref(pGIOChannel);
262 if (serverSocket != -1)
267 if (runOnCallerThread && __pHandlerGMainContext)
269 g_main_context_unref(__pHandlerGMainContext);
270 __pHandlerGMainContext = null;
279 bool reverse; // true if the connection is for reverse message
284 _IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data)
286 _IpcServer* pIpcServer = (_IpcServer*) data;
287 GError* pGError = null;
288 HelloMessage helloMessage;
289 _ClientInfo* pClientInfo = null;
290 _ChannelInfo* pChannelInfo = null;
291 GSource* pGSource = null;
292 GIOChannel* pChannel = null;
296 struct sockaddr_un clientAddress;
297 socklen_t clientLen = sizeof(clientAddress);
299 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
300 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
302 server = g_io_channel_unix_get_fd(source);
304 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
305 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
307 read(client, &helloMessage, sizeof(helloMessage));
308 helloMessage.appId[255] = '\0';
310 pChannel = g_io_channel_unix_new(client);
311 SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
313 g_io_channel_set_encoding(pChannel, NULL, &pGError);
314 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
316 g_io_channel_set_close_on_unref(pChannel, TRUE);
319 pClientInfo = pIpcServer->__clients[helloMessage.pid];
320 if (pClientInfo == null) // first connection request from this client
322 pClientInfo = new (std::nothrow) _ClientInfo;
323 SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
325 pClientInfo->pIpcServer = pIpcServer;
326 pClientInfo->clientId = helloMessage.pid;
327 pClientInfo->appId.Append((wchar_t*) helloMessage.appId);
328 pClientInfo->pReverseChannel = null;
330 pIpcServer->__clients[helloMessage.pid] = pClientInfo;
332 pIpcServer->__pCurrentClientInfo = pClientInfo;
333 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid);
334 pIpcServer->__pCurrentClientInfo = null;
337 if (helloMessage.reverse != 0)
339 pClientInfo->pReverseChannel = pChannel;
343 pChannelInfo = new (std::nothrow) _ChannelInfo;
344 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
346 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
347 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
348 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
350 pChannelInfo->pClientInfo = pClientInfo;
351 pChannelInfo->pGIOChannel = pChannel;
352 pChannelInfo->pGSource = pGSource;
354 pClientInfo->channels.push_back(pChannelInfo);
360 if (pChannel != null)
362 g_io_channel_unref(pChannel);
374 _IpcServer::GetClientId(void) const
376 if (__pCurrentClientInfo)
378 return __pCurrentClientInfo->clientId;
385 _IpcServer::GetClientPackageId(void) const
387 static String nullString;
389 if (__pCurrentClientInfo)
392 __pCurrentClientInfo->appId.SubString(0, 10, pkgId);
401 _IpcServer::GetClientApplicationId(void) const
403 static String nullString;
405 if (__pCurrentClientInfo)
407 return __pCurrentClientInfo->appId;
414 _IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
416 GError* pGError = NULL;
418 IPC::Message* pMessage = NULL;
419 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
420 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
422 if (condition & G_IO_HUP)
424 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
426 int clientId = pClientInfo->clientId;
428 g_io_channel_shutdown(source, FALSE, &pGError);
430 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
432 if (pChannelInfo == pClientInfo->channels[i])
434 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
436 // Do not destroy a source in a dispatch callback
437 // because main loop will do it if the callback return FALSE.
438 pChannelInfo->destroySource = false;
445 if (pClientInfo->channels.size() == 0)
447 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
449 __pListener->OnIpcClientDisconnected(*this, clientId);
451 __clients[clientId] = null;
458 else if (condition & G_IO_IN)
461 const char* pStart = NULL;
462 const char* pEnd = NULL;
463 const char* pEndOfMessage = NULL;
468 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
469 if (status != G_IO_STATUS_NORMAL)
471 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
473 if (status == G_IO_STATUS_EOF)
475 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
479 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
483 g_io_channel_shutdown(source, FALSE, &pGError);
485 int clientId = pClientInfo->clientId;
487 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
489 if (pChannelInfo == pClientInfo->channels[i])
491 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
493 pChannelInfo->destroySource = false;
499 if (pClientInfo->channels.size() == 0)
501 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
505 __pListener->OnIpcClientDisconnected(*this, clientId);
508 __clients[clientId] = null;
522 if (__pending.empty())
524 pStart = __messageBuffer;
525 pEnd = pStart + readSize;
529 __pending.append(__messageBuffer, readSize);
530 pStart = __pending.data();
531 pEnd = pStart + __pending.size();
536 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
537 if (pEndOfMessage == NULL)
539 __pending.assign(pStart, pEnd - pStart);
543 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
544 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
546 __pCurrentChannel = source;
550 __pListener->OnIpcRequestReceived(*this, *pMessage);
555 __pCurrentChannel = NULL;
557 pStart = pEndOfMessage;
570 _IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
572 gboolean ret = FALSE;
573 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
574 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
575 _IpcServer* pIpcServer = (_IpcServer*) pClientInfo->pIpcServer;
577 pIpcServer->__pCurrentClientInfo = pClientInfo;
578 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
579 pIpcServer->__pCurrentClientInfo = null;
585 _IpcServer::ThreadProc(void* pParam)
587 _IpcServer* pIpcServer = (_IpcServer*) pParam;
588 if (pIpcServer != NULL)
590 pIpcServer->Run(NULL);
597 _IpcServer::Run(void* pParam)
599 result r = E_SUCCESS;
601 if (__pListener == null)
606 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
607 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
609 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
612 delete __pEventDispatcher;
613 __pEventDispatcher = null;
616 __pListener->OnIpcServerStarted(*this);
618 g_main_loop_run(__pHandlerGMainLoop);
620 __pListener->OnIpcServerStopped(*this);
624 _IpcServer::Start(void)
630 _IpcServer::GetName(void) const
636 _IpcServer::Stop(void)
638 result r = E_SUCCESS;
641 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
643 if (!__runOnCallerThread)
645 pthread_t self = pthread_self();
647 if (__pHandlerGMainLoop)
649 g_main_loop_quit(__pHandlerGMainLoop);
652 if (__handlerThread != self)
654 ret = pthread_join(__handlerThread, null);
655 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
660 __pListener->OnIpcServerStopped(*this);
667 _IpcServer::Send(IPC::Message* msg)
672 GError* pGError = NULL;
675 pData = (char*) msg->data();
676 remain = msg->size();
683 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
689 g_io_channel_flush(__pCurrentChannel, &pGError);
700 _IpcServer::SendResponse(int client, IPC::Message* pMessage)
702 result r = E_SUCCESS;
706 GError* pGError = null;
707 _ClientInfo* pClientInfo = null;
710 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
711 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
713 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
715 pClientInfo = __clients[client];
716 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
717 "[E_INVALID_ARG] client(%d) has not been registered.",
720 pData = (char*) pMessage->data();
721 remain = pMessage->size();
726 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
727 if (ret != G_IO_STATUS_NORMAL)
729 SysTryCatch(NID_IO, ret != G_IO_STATUS_AGAIN, , E_RESOURCE_UNAVAILABLE, "[E_RESOURCE_UNAVAILABLE] The socket buffer is full.");
731 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
740 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
752 _IpcServer::SendResponse(int client, const IPC::Message& message)
754 result r = E_SUCCESS;
758 GError* pGError = null;
759 _ClientInfo* pClientInfo = null;
762 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
763 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
765 pClientInfo = __clients[client];
766 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
767 "[E_INVALID_ARG] client(%d) has not been registered.",
770 pData = (char*) message.data();
771 remain = message.size();
776 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
777 if (ret != G_IO_STATUS_NORMAL)
779 SysTryCatch(NID_IO, ret != G_IO_STATUS_AGAIN, , E_RESOURCE_UNAVAILABLE, "[E_RESOURCE_UNAVAILABLE] The socket buffer is full.");
781 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
789 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);