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 <sys/smack.h>
39 #include <ipc/ipc_message.h>
41 #include <FBaseRtMutex.h>
42 #include <FBaseSysLog.h>
43 #include <FBase_StringConverter.h>
44 #include <FBaseRt_EventDispatcher.h>
46 #include "IIpcServerEventListener.h"
47 #include "IpcServer.h"
52 using namespace Tizen::Base;
53 using namespace Tizen::Base::Runtime;
54 using namespace Tizen::App;
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)
102 : __runOnCallerThread(false)
103 , __pEventDispatcher(null)
106 , __pHandlerGMainContext(null)
107 , __pHandlerGMainLoop(null)
108 , __pConnectGSource(null)
109 , __pCurrentChannel(null)
110 , __pCurrentClientInfo(null)
112 __messageBuffer[0] = '\0';
116 IpcServer::~IpcServer(void)
118 if (__pConnectGSource != null)
120 g_source_destroy(__pConnectGSource);
121 g_source_unref(__pConnectGSource);
122 __pConnectGSource = null;
125 if (!__runOnCallerThread)
127 if (__pEventDispatcher)
129 delete __pEventDispatcher;
130 __pEventDispatcher = null;
133 if (__pHandlerGMainLoop)
135 g_main_loop_unref(__pHandlerGMainLoop);
136 __pHandlerGMainLoop = null;
139 if (__pHandlerGMainContext)
141 g_main_context_unref(__pHandlerGMainContext);
142 __pHandlerGMainContext = null;
151 IpcServer::Construct(const String& name, const IIpcServerEventListener& listener, bool runOnCallerThread)
153 result r = E_SUCCESS;
155 GIOChannel* pGIOChannel = null;
156 GSource* pGSource = null;
158 struct sockaddr_un serverAddress;
159 int serverSocket = -1;
162 std::string socketName;
164 size_t socketNameLength = 0;
167 __pListener = const_cast <IIpcServerEventListener*>(&listener);
168 __runOnCallerThread = runOnCallerThread;
170 pName = _StringConverter::CopyToCharArrayN(name);
171 SysTryReturnResult(NID_IO, pName != null, E_OUT_OF_MEMORY, "Not enough memory");
173 socketName.append("/tmp/");
174 socketName.append(pName);
178 socketNameLength = socketName.size() + 1;
179 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long");
181 if (!__runOnCallerThread)
183 __pHandlerGMainContext = g_main_context_new();
184 __pHandlerGMainLoop = g_main_loop_new(__pHandlerGMainContext, FALSE);
189 __pHandlerGMainContext = g_main_context_get_thread_default();
190 if (__pHandlerGMainContext == null) // is global?
192 __pHandlerGMainContext = g_main_context_default();
193 if (__pHandlerGMainContext == null)
200 ret = unlink(socketName.c_str());
201 SysTryLog(NID_IO, ret == 0, "Unlink a socket has failed.. but it is not a problem.");
203 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
204 SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, "Failed to create a socket.");
206 // SMACK (Add a * label to socket)
207 if(smack_fsetlabel(serverSocket, "@", SMACK_LABEL_IPOUT) != 0)
209 SysTryCatch(NID_IO, errno == EOPNOTSUPP, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] SMACK labeling failed");
210 SysLog(NID_IO, "Kernel doesn't have Smack.");
213 if(smack_fsetlabel(serverSocket, "*", SMACK_LABEL_IPIN) != 0)
215 SysTryCatch(NID_IO, errno == EOPNOTSUPP, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] SMACK labeling failed");
216 SysLog(NID_IO, "Kernel doesn't have Smack.");
219 bzero(&serverAddress, sizeof(serverAddress));
220 serverAddress.sun_family = AF_UNIX;
221 strncpy(serverAddress.sun_path, socketName.c_str(), socketNameLength);
222 serverLen = sizeof(serverAddress);
224 ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen);
225 SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket,
226 socketName.c_str(), strerror(errno));
228 ret = chmod(socketName.c_str(), 0666);
229 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket,
230 socketName.c_str(), strerror(errno));
232 ret = listen(serverSocket, 15);
233 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to listen a socket(%d, %s): %s", serverSocket,
234 socketName.c_str(), strerror(errno));
236 pGIOChannel = g_io_channel_unix_new(serverSocket);
237 SysTryCatch(NID_IO, pGIOChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
239 // socket will be closed when pGIOChannel is deleted.
240 g_io_channel_set_close_on_unref(pGIOChannel, TRUE);
243 pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
244 SysTryCatch(NID_IO, pGSource != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
245 "[E_OUT_OF_MEMORY] Failed to create watch for socket.");
247 // channel will be delete when pGSource is deleted.
248 g_io_channel_unref(pGIOChannel);
251 g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL);
252 g_source_attach(pGSource, __pHandlerGMainContext);
254 if (__runOnCallerThread)
256 __pListener->OnIpcServerStarted(*this);
260 ret = pthread_create(&__handlerThread, null, &ThreadProc, (void*) this);
261 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to an IPC thread");
264 __pConnectGSource = pGSource;
269 if (pGIOChannel != null)
271 g_io_channel_unref(pGIOChannel);
274 if (serverSocket != -1)
279 if (runOnCallerThread && __pHandlerGMainContext)
281 g_main_context_unref(__pHandlerGMainContext);
282 __pHandlerGMainContext = null;
291 bool reverse; // true if the connection is for reverse message
296 IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data)
298 IpcServer* pIpcServer = (IpcServer*) data;
299 GError* pGError = null;
300 HelloMessage helloMessage;
301 _ClientInfo* pClientInfo = null;
302 _ChannelInfo* pChannelInfo = null;
303 GSource* pGSource = null;
304 GIOChannel* pChannel = null;
308 struct sockaddr_un clientAddress;
309 socklen_t clientLen = sizeof(clientAddress);
311 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
312 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
314 server = g_io_channel_unix_get_fd(source);
316 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
317 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
319 read(client, &helloMessage, sizeof(helloMessage));
320 helloMessage.appId[255] = '\0';
322 pChannel = g_io_channel_unix_new(client);
323 SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
325 g_io_channel_set_encoding(pChannel, NULL, &pGError);
326 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
328 g_io_channel_set_close_on_unref(pChannel, TRUE);
331 pClientInfo = pIpcServer->__clients[helloMessage.pid];
332 if (pClientInfo == null) // first connection request from this client
334 pClientInfo = new (std::nothrow) _ClientInfo;
335 SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
337 pClientInfo->pIpcServer = pIpcServer;
338 pClientInfo->clientId = helloMessage.pid;
339 pClientInfo->appId.Append((wchar_t*) helloMessage.appId);
340 pClientInfo->pReverseChannel = null;
342 pIpcServer->__clients[helloMessage.pid] = pClientInfo;
344 pIpcServer->__pCurrentClientInfo = pClientInfo;
345 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid);
346 pIpcServer->__pCurrentClientInfo = null;
349 if (helloMessage.reverse)
351 pClientInfo->pReverseChannel = pChannel;
355 pChannelInfo = new (std::nothrow) _ChannelInfo;
356 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
358 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
359 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
360 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
362 pChannelInfo->pClientInfo = pClientInfo;
363 pChannelInfo->pGIOChannel = pChannel;
364 pChannelInfo->pGSource = pGSource;
366 pClientInfo->channels.push_back(pChannelInfo);
372 if (pChannel != null)
374 g_io_channel_unref(pChannel);
386 IpcServer::GetClientId(void) const
388 if (__pCurrentClientInfo)
390 return __pCurrentClientInfo->clientId;
397 IpcServer::GetClientApplicationId(void) const
399 static String nullString;
401 if (__pCurrentClientInfo)
403 return __pCurrentClientInfo->appId;
410 IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
412 GError* pGError = NULL;
414 IPC::Message* pMessage = NULL;
415 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
416 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
418 if (condition & G_IO_HUP)
420 SysLog(NID_IO, "Connection closed");
421 int clientId = pClientInfo->clientId;
423 g_io_channel_shutdown(source, FALSE, &pGError);
425 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
427 if (pChannelInfo == pClientInfo->channels[i])
429 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
431 // Do not destroy a source in a dispatch callback
432 // because main loop will do it if the callback return FALSE.
433 pChannelInfo->destroySource = false;
440 if (pClientInfo->channels.size() == 0)
442 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
444 __pListener->OnIpcClientDisconnected(*this, clientId);
446 __clients[clientId] = null;
453 else if (condition & G_IO_IN)
456 const char* pStart = NULL;
457 const char* pEnd = NULL;
458 const char* pEndOfMessage = NULL;
463 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
464 if (status != G_IO_STATUS_NORMAL)
466 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
468 if (status == G_IO_STATUS_EOF)
470 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
474 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
478 g_io_channel_shutdown(source, FALSE, &pGError);
480 int clientId = pClientInfo->clientId;
482 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
484 if (pChannelInfo == pClientInfo->channels[i])
486 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
488 pChannelInfo->destroySource = false;
494 if (pClientInfo->channels.size() == 0)
496 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
500 __pListener->OnIpcClientDisconnected(*this, clientId);
503 __clients[clientId] = null;
517 if (__pending.empty())
519 pStart = __messageBuffer;
520 pEnd = pStart + readSize;
524 __pending.append(__messageBuffer, readSize);
525 pStart = __pending.data();
526 pEnd = pStart + __pending.size();
531 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
532 if (pEndOfMessage == NULL)
534 __pending.assign(pStart, pEnd - pStart);
538 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
539 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
541 __pCurrentChannel = source;
545 __pListener->OnIpcRequestReceived(*this, *pMessage);
550 __pCurrentChannel = NULL;
552 pStart = pEndOfMessage;
565 IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
567 gboolean ret = FALSE;
568 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
569 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
570 IpcServer* pIpcServer = (IpcServer*) pClientInfo->pIpcServer;
572 pIpcServer->__pCurrentClientInfo = pClientInfo;
573 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
574 pIpcServer->__pCurrentClientInfo = null;
580 IpcServer::ThreadProc(void* pParam)
582 IpcServer* pIpcServer = (IpcServer*) pParam;
583 if (pIpcServer != NULL)
585 pIpcServer->Run(NULL);
592 IpcServer::Run(void* pParam)
594 result r = E_SUCCESS;
596 if (__pListener == null)
601 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
602 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
604 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
607 delete __pEventDispatcher;
608 __pEventDispatcher = null;
611 __pListener->OnIpcServerStarted(*this);
613 g_main_loop_run(__pHandlerGMainLoop);
615 __pListener->OnIpcServerStopped(*this);
619 IpcServer::Start(void)
625 IpcServer::GetName(void) const
631 IpcServer::Stop(void)
633 result r = E_SUCCESS;
636 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
638 if (!__runOnCallerThread)
640 pthread_t self = pthread_self();
642 if (__pHandlerGMainLoop)
644 g_main_loop_quit(__pHandlerGMainLoop);
647 if (__handlerThread != self)
649 ret = pthread_join(__handlerThread, null);
650 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
655 __pListener->OnIpcServerStopped(*this);
662 IpcServer::Send(IPC::Message* msg)
667 GError* pGError = NULL;
670 pData = (char*) msg->data();
671 remain = msg->size();
678 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
684 g_io_channel_flush(__pCurrentChannel, &pGError);
695 IpcServer::SendResponse(int client, IPC::Message* pMessage)
697 result r = E_SUCCESS;
701 GError* pGError = null;
702 _ClientInfo* pClientInfo = null;
704 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
705 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
707 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
709 pClientInfo = __clients[client];
710 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
711 "[E_INVALID_ARG] client(%d) has not been registered.",
714 pData = (char*) pMessage->data();
715 remain = pMessage->size();
720 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
721 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
727 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
739 IpcServer::SendResponse(int client, const IPC::Message& message)
741 result r = E_SUCCESS;
745 GError* pGError = null;
746 _ClientInfo* pClientInfo = null;
748 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
749 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
751 pClientInfo = __clients[client];
752 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
753 "[E_INVALID_ARG] client(%d) has not been registered.",
756 pData = (char*) message.data();
757 remain = message.size();
762 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
763 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
769 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);