2 // Open Service Platform
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
19 * @file FIo_IpcServer.cpp
20 * @brief This is the implementation file for the _IpcServer class.
32 #include <sys/types.h>
33 #include <sys/socket.h>
37 #include <ipc/ipc_message.h>
39 #include <FBaseRtMutex.h>
40 #include <FBaseSysLog.h>
41 #include <FBase_StringConverter.h>
42 #include <FBaseRt_EventDispatcher.h>
44 #include "FIo_IIpcServerEventListener.h"
45 #include "FIo_IpcServer.h"
49 using namespace Tizen::Base;
50 using namespace Tizen::Base::Runtime;
51 using namespace Tizen::App;
53 namespace Tizen { namespace Io
56 _IpcServer::_ChannelInfo::_ChannelInfo(void)
65 _IpcServer::_ChannelInfo::~_ChannelInfo(void)
67 if (pGIOChannel != null)
69 g_io_channel_unref(pGIOChannel);
76 g_source_destroy(pGSource);
79 g_source_unref(pGSource);
83 _IpcServer::_ClientInfo::_ClientInfo(void)
86 , pReverseChannel(null)
91 _IpcServer::_ClientInfo::~_ClientInfo(void)
93 if (pReverseChannel != null)
95 g_io_channel_unref(pReverseChannel);
101 _IpcServer::_IpcServer(void)
103 , __runOnCallerThread(false)
104 , __pEventDispatcher(null)
107 , __pHandlerGMainContext(null)
108 , __pHandlerGMainLoop(null)
109 , __pConnectGSource(null)
110 , __pCurrentChannel(null)
111 , __pCurrentClientInfo(null)
113 __messageBuffer[0] = '\0';
117 _IpcServer::~_IpcServer(void)
119 if (__pConnectGSource != null)
121 g_source_destroy(__pConnectGSource);
122 g_source_unref(__pConnectGSource);
123 __pConnectGSource = null;
126 if (!__runOnCallerThread)
128 if (__pEventDispatcher)
130 delete __pEventDispatcher;
131 __pEventDispatcher = null;
134 if (__pHandlerGMainLoop)
136 g_main_loop_unref(__pHandlerGMainLoop);
137 __pHandlerGMainLoop = null;
140 if (__pHandlerGMainContext)
142 g_main_context_unref(__pHandlerGMainContext);
143 __pHandlerGMainContext = null;
152 _IpcServer::Construct(const String& name, const _IIpcServerEventListener& listener, bool runOnCallerThread)
154 result r = E_SUCCESS;
156 GIOChannel* pGIOChannel = null;
157 GSource* pGSource = null;
159 struct sockaddr_un serverAddress;
160 int serverSocket = -1;
163 std::string socketName;
165 size_t socketNameLength = 0;
168 __pListener = const_cast <_IIpcServerEventListener*>(&listener);
169 __runOnCallerThread = runOnCallerThread;
171 pName = _StringConverter::CopyToCharArrayN(name);
172 SysTryReturnResult(NID_IO, pName != null, E_OUT_OF_MEMORY, "Not enough memory");
174 socketName.append("/tmp/");
175 socketName.append(pName);
179 socketNameLength = socketName.size() + 1;
180 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long");
182 if (!__runOnCallerThread)
184 __pHandlerGMainContext = g_main_context_new();
185 __pHandlerGMainLoop = g_main_loop_new(__pHandlerGMainContext, FALSE);
190 __pHandlerGMainContext = g_main_context_get_thread_default();
191 if (__pHandlerGMainContext == null) // is global?
193 __pHandlerGMainContext = g_main_context_default();
194 if (__pHandlerGMainContext == null)
201 ret = unlink(socketName.c_str());
202 SysTryLog(NID_IO, ret == 0, "Unlink a socket has failed.. but it is not a problem.");
204 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
205 SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, "Failed to create a socket.");
207 bzero(&serverAddress, sizeof(serverAddress));
208 serverAddress.sun_family = AF_UNIX;
209 strncpy(serverAddress.sun_path, socketName.c_str(), socketNameLength);
210 serverLen = sizeof(serverAddress);
212 ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen);
213 SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket,
214 socketName.c_str(), strerror(errno));
216 ret = chmod(socketName.c_str(), 0666);
217 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket,
218 socketName.c_str(), strerror(errno));
220 listen(serverSocket, 15);
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;
255 if (pGIOChannel != null)
257 g_io_channel_unref(pGIOChannel);
260 if (serverSocket != -1)
265 if (runOnCallerThread && __pHandlerGMainContext)
267 g_main_context_unref(__pHandlerGMainContext);
268 __pHandlerGMainContext = null;
277 bool reverse; // true if the connection is for reverse message
279 char appExecutableName[256];
283 _IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data)
285 _IpcServer* pIpcServer = (_IpcServer*) data;
286 GError* pGError = null;
287 HelloMessage helloMessage;
288 _ClientInfo* pClientInfo = null;
289 _ChannelInfo* pChannelInfo = null;
290 GSource* pGSource = null;
291 GIOChannel* pChannel = null;
295 struct sockaddr_un clientAddress;
296 socklen_t clientLen = sizeof(clientAddress);
298 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
299 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
301 server = g_io_channel_unix_get_fd(source);
303 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
304 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
306 read(client, &helloMessage, sizeof(helloMessage));
307 helloMessage.pkgId[255] = '\0';
308 helloMessage.appExecutableName[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->pkgId.Append((wchar_t*) helloMessage.pkgId);
328 pClientInfo->appExecutableName.Append((wchar_t*) helloMessage.appExecutableName);
329 pClientInfo->pReverseChannel = null;
331 pIpcServer->__clients[helloMessage.pid] = pClientInfo;
333 pIpcServer->__pCurrentClientInfo = pClientInfo;
334 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid);
335 pIpcServer->__pCurrentClientInfo = null;
338 if (helloMessage.reverse)
340 pClientInfo->pReverseChannel = pChannel;
344 pChannelInfo = new (std::nothrow) _ChannelInfo;
345 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
347 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
348 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
349 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
351 pChannelInfo->pClientInfo = pClientInfo;
352 pChannelInfo->pGIOChannel = pChannel;
353 pChannelInfo->pGSource = pGSource;
355 pClientInfo->channels.push_back(pChannelInfo);
361 if (pChannel != null)
363 g_io_channel_unref(pChannel);
375 _IpcServer::GetClientId(void) const
377 if (__pCurrentClientInfo)
379 return __pCurrentClientInfo->clientId;
386 _IpcServer::GetClientProcessId(void) const
388 if (__pCurrentClientInfo)
390 return __pCurrentClientInfo->clientId;
397 _IpcServer::GetClientAppId(void) const
399 static String nullString;
401 if (__pCurrentClientInfo)
403 return __pCurrentClientInfo->pkgId;
410 _IpcServer::GetClientAppExecutableName(void) const
412 static String nullString;
414 if (__pCurrentClientInfo)
416 return __pCurrentClientInfo->appExecutableName;
423 _IpcServer::GetClientApplicationId(void) const
425 static String nullString;
427 if (__pCurrentClientInfo)
429 String appId(__pCurrentClientInfo->pkgId);
431 appId.Append(__pCurrentClientInfo->appExecutableName);
440 _IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
442 GError* pGError = NULL;
444 IPC::Message* pMessage = NULL;
445 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
446 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
448 if (condition & G_IO_HUP)
450 SysLog(NID_IO, "Connection closed");
451 int clientId = pClientInfo->clientId;
453 g_io_channel_shutdown(source, FALSE, &pGError);
455 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
457 if (pChannelInfo == pClientInfo->channels[i])
459 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
461 // Do not destroy a source in a dispatch callback
462 // because main loop will do it if the callback return FALSE.
463 pChannelInfo->destroySource = false;
470 if (pClientInfo->channels.size() == 0)
472 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
474 __pListener->OnIpcClientDisconnected(*this, clientId);
476 __clients[clientId] = null;
483 else if (condition & G_IO_IN)
486 const char* pStart = NULL;
487 const char* pEnd = NULL;
488 const char* pEndOfMessage = NULL;
493 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
494 if (status != G_IO_STATUS_NORMAL)
496 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
498 if (status == G_IO_STATUS_EOF)
500 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
504 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
508 g_io_channel_shutdown(source, FALSE, &pGError);
510 int clientId = pClientInfo->clientId;
512 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
514 if (pChannelInfo == pClientInfo->channels[i])
516 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
518 pChannelInfo->destroySource = false;
524 if (pClientInfo->channels.size() == 0)
526 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
530 __pListener->OnIpcClientDisconnected(*this, clientId);
533 __clients[clientId] = null;
547 if (__pending.empty())
549 pStart = __messageBuffer;
550 pEnd = pStart + readSize;
554 __pending.append(__messageBuffer, readSize);
555 pStart = __pending.data();
556 pEnd = pStart + __pending.size();
561 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
562 if (pEndOfMessage == NULL)
564 __pending.assign(pStart, pEnd - pStart);
568 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
569 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
571 __pCurrentChannel = source;
575 __pListener->OnIpcRequestReceived(*this, *pMessage);
580 __pCurrentChannel = NULL;
582 pStart = pEndOfMessage;
595 _IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
597 gboolean ret = FALSE;
598 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
599 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
600 _IpcServer* pIpcServer = (_IpcServer*) pClientInfo->pIpcServer;
602 pIpcServer->__pCurrentClientInfo = pClientInfo;
603 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
604 pIpcServer->__pCurrentClientInfo = null;
610 _IpcServer::ThreadProc(void* pParam)
612 _IpcServer* pIpcServer = (_IpcServer*) pParam;
613 if (pIpcServer != NULL)
615 pIpcServer->Run(NULL);
622 _IpcServer::Run(void* pParam)
624 result r = E_SUCCESS;
626 if (__pListener == null)
631 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
632 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
634 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
637 delete __pEventDispatcher;
638 __pEventDispatcher = null;
641 __pListener->OnIpcServerStarted(*this);
643 g_main_loop_run(__pHandlerGMainLoop);
645 __pListener->OnIpcServerStopped(*this);
649 _IpcServer::Start(void)
655 _IpcServer::GetName(void) const
661 _IpcServer::Stop(void)
663 result r = E_SUCCESS;
666 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
668 if (!__runOnCallerThread)
670 pthread_t self = pthread_self();
672 if (__pHandlerGMainLoop)
674 g_main_loop_quit(__pHandlerGMainLoop);
677 if (__handlerThread != self)
679 ret = pthread_join(__handlerThread, null);
680 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
685 __pListener->OnIpcServerStopped(*this);
692 _IpcServer::Send(IPC::Message* msg)
697 GError* pGError = NULL;
700 pData = (char*) msg->data();
701 remain = msg->size();
708 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
714 g_io_channel_flush(__pCurrentChannel, &pGError);
725 _IpcServer::SendResponse(int client, IPC::Message* pMessage)
727 result r = E_SUCCESS;
731 GError* pGError = null;
732 _ClientInfo* pClientInfo = null;
734 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
735 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
737 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
739 pClientInfo = __clients[client];
740 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
741 "[E_INVALID_ARG] client(%d) has not been registered.",
744 pData = (char*) pMessage->data();
745 remain = pMessage->size();
750 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
751 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
757 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
769 _IpcServer::SendResponse(int client, const IPC::Message& message)
771 result r = E_SUCCESS;
775 GError* pGError = null;
776 _ClientInfo* pClientInfo = null;
778 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
779 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
781 pClientInfo = __clients[client];
782 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
783 "[E_INVALID_ARG] client(%d) has not been registered.",
786 pData = (char*) message.data();
787 remain = message.size();
792 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
793 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
799 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);