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 <app_manager.h>
43 #include <FBaseRtMutex.h>
44 #include <FBaseSysLog.h>
45 #include <FBase_StringConverter.h>
46 #include <FBaseRt_EventDispatcher.h>
48 #include "IIpcServerEventListener.h"
49 #include "IpcServer.h"
54 using namespace Tizen::Base;
55 using namespace Tizen::Base::Runtime;
56 using namespace Tizen::App;
58 IpcServer::_ChannelInfo::_ChannelInfo(void)
67 IpcServer::_ChannelInfo::~_ChannelInfo(void)
69 if (pGIOChannel != null)
71 g_io_channel_unref(pGIOChannel);
78 g_source_destroy(pGSource);
81 g_source_unref(pGSource);
85 IpcServer::_ClientInfo::_ClientInfo(void)
88 , pReverseChannel(null)
93 IpcServer::_ClientInfo::~_ClientInfo(void)
95 if (pReverseChannel != null)
97 g_io_channel_unref(pReverseChannel);
103 IpcServer::IpcServer(void)
104 : __runOnCallerThread(false)
105 , __pEventDispatcher(null)
108 , __pHandlerGMainContext(null)
109 , __pHandlerGMainLoop(null)
110 , __pConnectGSource(null)
111 , __pCurrentChannel(null)
112 , __pCurrentClientInfo(null)
114 __messageBuffer[0] = '\0';
118 IpcServer::~IpcServer(void)
120 if (__pConnectGSource != null)
122 g_source_destroy(__pConnectGSource);
123 g_source_unref(__pConnectGSource);
124 __pConnectGSource = null;
127 if (!__runOnCallerThread)
129 if (__pEventDispatcher)
131 delete __pEventDispatcher;
132 __pEventDispatcher = null;
135 if (__pHandlerGMainLoop)
137 g_main_loop_unref(__pHandlerGMainLoop);
138 __pHandlerGMainLoop = null;
141 if (__pHandlerGMainContext)
143 g_main_context_unref(__pHandlerGMainContext);
144 __pHandlerGMainContext = null;
153 IpcServer::Construct(const String& name, const IIpcServerEventListener& listener, bool runOnCallerThread)
155 result r = E_SUCCESS;
157 GIOChannel* pGIOChannel = null;
158 GSource* pGSource = null;
160 struct sockaddr_un serverAddress;
161 int serverSocket = -1;
164 std::string socketName;
166 size_t socketNameLength = 0;
169 __pListener = const_cast <IIpcServerEventListener*>(&listener);
170 __runOnCallerThread = runOnCallerThread;
172 pName = _StringConverter::CopyToCharArrayN(name);
173 SysTryReturnResult(NID_IO, pName != null, E_OUT_OF_MEMORY, "Not enough memory");
175 socketName.append("/tmp/");
176 socketName.append(pName);
180 socketNameLength = socketName.size() + 1;
181 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long");
183 if (!__runOnCallerThread)
185 __pHandlerGMainContext = g_main_context_new();
186 __pHandlerGMainLoop = g_main_loop_new(__pHandlerGMainContext, FALSE);
191 __pHandlerGMainContext = g_main_context_get_thread_default();
192 if (__pHandlerGMainContext == null) // is global?
194 __pHandlerGMainContext = g_main_context_default();
195 if (__pHandlerGMainContext == null)
202 ret = unlink(socketName.c_str());
203 SysTryLog(NID_IO, ret == 0, "Unlink a socket has failed.. but it is not a problem.");
205 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
206 SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, "Failed to create a socket.");
208 // SMACK (Add a * label to socket)
209 if(smack_fsetlabel(serverSocket, "@", SMACK_LABEL_IPOUT) != 0)
211 SysTryCatch(NID_IO, errno == EOPNOTSUPP, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] SMACK labeling failed");
212 SysLog(NID_IO, "Kernel doesn't have Smack.");
215 if(smack_fsetlabel(serverSocket, "*", SMACK_LABEL_IPIN) != 0)
217 SysTryCatch(NID_IO, errno == EOPNOTSUPP, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] SMACK labeling failed");
218 SysLog(NID_IO, "Kernel doesn't have Smack.");
221 bzero(&serverAddress, sizeof(serverAddress));
222 serverAddress.sun_family = AF_UNIX;
223 strncpy(serverAddress.sun_path, socketName.c_str(), socketNameLength);
224 serverLen = sizeof(serverAddress);
226 ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen);
227 SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket,
228 socketName.c_str(), strerror(errno));
230 ret = chmod(socketName.c_str(), 0666);
231 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket,
232 socketName.c_str(), strerror(errno));
234 ret = listen(serverSocket, 128);
235 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to listen a socket(%d, %s): %s", serverSocket,
236 socketName.c_str(), strerror(errno));
238 pGIOChannel = g_io_channel_unix_new(serverSocket);
239 SysTryCatch(NID_IO, pGIOChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
241 // socket will be closed when pGIOChannel is deleted.
242 g_io_channel_set_close_on_unref(pGIOChannel, TRUE);
245 pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
246 SysTryCatch(NID_IO, pGSource != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
247 "[E_OUT_OF_MEMORY] Failed to create watch for socket.");
249 // channel will be delete when pGSource is deleted.
250 g_io_channel_unref(pGIOChannel);
253 g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL);
254 g_source_attach(pGSource, __pHandlerGMainContext);
256 if (__runOnCallerThread)
258 __pListener->OnIpcServerStarted(*this);
262 ret = pthread_create(&__handlerThread, null, &ThreadProc, (void*) this);
263 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to an IPC thread");
266 __pConnectGSource = pGSource;
271 if (pGIOChannel != null)
273 g_io_channel_unref(pGIOChannel);
276 if (serverSocket != -1)
281 if (runOnCallerThread && __pHandlerGMainContext)
283 g_main_context_unref(__pHandlerGMainContext);
284 __pHandlerGMainContext = null;
293 int reverse; // if the connection is for reverse message
297 IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data)
299 IpcServer* pIpcServer = (IpcServer*) data;
300 GError* pGError = null;
301 HelloMessage helloMessage;
302 _ClientInfo* pClientInfo = null;
303 _ChannelInfo* pChannelInfo = null;
304 GSource* pGSource = null;
305 GIOChannel* pChannel = null;
310 struct sockaddr_un clientAddress;
311 socklen_t clientLen = sizeof(clientAddress);
313 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
314 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
316 server = g_io_channel_unix_get_fd(source);
318 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
319 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
321 res = read(client, &helloMessage, sizeof(helloMessage));
323 pChannel = g_io_channel_unix_new(client);
324 SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
326 g_io_channel_set_encoding(pChannel, NULL, &pGError);
327 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
329 g_io_channel_set_close_on_unref(pChannel, TRUE);
332 pClientInfo = pIpcServer->__clients[helloMessage.pid];
333 if (pClientInfo == null) // first connection request from this client
335 pClientInfo = new (std::nothrow) _ClientInfo;
336 SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
338 pClientInfo->pIpcServer = pIpcServer;
339 pClientInfo->clientId = helloMessage.pid;
342 int ret = app_manager_get_app_id(helloMessage.pid, &pAppId);
343 SysTryCatch(NID_IO, ret >= 0, delete pClientInfo, E_SYSTEM, "[E_SYSTEM] Failed to get_app_id: %d", ret);
345 pClientInfo->appId = pAppId;
348 pClientInfo->pReverseChannel = null;
350 pIpcServer->__clients[helloMessage.pid] = pClientInfo;
351 pIpcServer->__pCurrentClientInfo = pClientInfo;
352 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid);
353 pIpcServer->__pCurrentClientInfo = null;
356 if (helloMessage.reverse != 0)
358 pClientInfo->pReverseChannel = pChannel;
362 pChannelInfo = new (std::nothrow) _ChannelInfo;
363 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
365 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
366 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
367 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
369 pChannelInfo->pClientInfo = pClientInfo;
370 pChannelInfo->pGIOChannel = pChannel;
371 pChannelInfo->pGSource = pGSource;
373 pClientInfo->channels.push_back(pChannelInfo);
379 if (pChannel != null)
381 g_io_channel_unref(pChannel);
393 IpcServer::GetClientId(void) const
395 if (__pCurrentClientInfo)
397 return __pCurrentClientInfo->clientId;
404 IpcServer::GetClientApplicationId(void) const
406 static String nullString;
408 if (__pCurrentClientInfo)
410 return __pCurrentClientInfo->appId;
417 IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
419 GError* pGError = NULL;
421 IPC::Message* pMessage = NULL;
422 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
423 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
425 if (condition & G_IO_HUP)
427 SysLog(NID_IO, "Connection closed");
428 int clientId = pClientInfo->clientId;
430 g_io_channel_shutdown(source, FALSE, &pGError);
432 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
434 if (pChannelInfo == pClientInfo->channels[i])
436 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
438 // Do not destroy a source in a dispatch callback
439 // because main loop will do it if the callback return FALSE.
440 pChannelInfo->destroySource = false;
447 if (pClientInfo->channels.size() == 0)
449 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
451 __pListener->OnIpcClientDisconnected(*this, clientId);
453 __clients[clientId] = null;
460 else if (condition & G_IO_IN)
463 const char* pStart = NULL;
464 const char* pEnd = NULL;
465 const char* pEndOfMessage = NULL;
470 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
471 if (status != G_IO_STATUS_NORMAL)
473 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
475 if (status == G_IO_STATUS_EOF)
477 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
481 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
485 g_io_channel_shutdown(source, FALSE, &pGError);
487 int clientId = pClientInfo->clientId;
489 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
491 if (pChannelInfo == pClientInfo->channels[i])
493 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
495 pChannelInfo->destroySource = false;
501 if (pClientInfo->channels.size() == 0)
503 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
507 __pListener->OnIpcClientDisconnected(*this, clientId);
510 __clients[clientId] = null;
524 if (__pending.empty())
526 pStart = __messageBuffer;
527 pEnd = pStart + readSize;
531 __pending.append(__messageBuffer, readSize);
532 pStart = __pending.data();
533 pEnd = pStart + __pending.size();
538 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
539 if (pEndOfMessage == NULL)
541 __pending.assign(pStart, pEnd - pStart);
545 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
546 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
548 __pCurrentChannel = source;
552 __pListener->OnIpcRequestReceived(*this, *pMessage);
557 __pCurrentChannel = NULL;
559 pStart = pEndOfMessage;
572 IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
574 gboolean ret = FALSE;
575 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
576 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
577 IpcServer* pIpcServer = (IpcServer*) pClientInfo->pIpcServer;
579 pIpcServer->__pCurrentClientInfo = pClientInfo;
580 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
581 pIpcServer->__pCurrentClientInfo = null;
587 IpcServer::ThreadProc(void* pParam)
589 IpcServer* pIpcServer = (IpcServer*) pParam;
590 if (pIpcServer != NULL)
592 pIpcServer->Run(NULL);
599 IpcServer::Run(void* pParam)
601 result r = E_SUCCESS;
603 if (__pListener == null)
608 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
609 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
611 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
614 delete __pEventDispatcher;
615 __pEventDispatcher = null;
618 __pListener->OnIpcServerStarted(*this);
620 g_main_loop_run(__pHandlerGMainLoop);
622 __pListener->OnIpcServerStopped(*this);
626 IpcServer::Start(void)
632 IpcServer::GetName(void) const
638 IpcServer::Stop(void)
640 result r = E_SUCCESS;
643 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
645 if (!__runOnCallerThread)
647 pthread_t self = pthread_self();
649 if (__pHandlerGMainLoop)
651 g_main_loop_quit(__pHandlerGMainLoop);
654 if (__handlerThread != self)
656 ret = pthread_join(__handlerThread, null);
657 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
662 __pListener->OnIpcServerStopped(*this);
669 IpcServer::Send(IPC::Message* msg)
674 GError* pGError = NULL;
677 pData = (char*) msg->data();
678 remain = msg->size();
685 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
691 g_io_channel_flush(__pCurrentChannel, &pGError);
704 IpcServer::SendResponse(int client, IPC::Message* pMessage)
706 result r = E_SUCCESS;
710 GError* pGError = null;
711 _ClientInfo* pClientInfo = null;
714 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
715 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
717 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
719 pClientInfo = __clients[client];
720 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
721 "[E_INVALID_ARG] client(%d) has not been registered.",
724 pData = (char*) pMessage->data();
725 remain = pMessage->size();
730 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
731 if (ret != G_IO_STATUS_NORMAL)
733 SysLog(NID_IO, "Failed to send a response: %d", ret);
734 SysTryCatch(NID_IO, ret != G_IO_STATUS_ERROR, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
741 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
753 IpcServer::SendResponse(int client, const IPC::Message& message)
755 result r = E_SUCCESS;
759 GError* pGError = null;
760 _ClientInfo* pClientInfo = null;
763 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
764 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
766 pClientInfo = __clients[client];
767 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
768 "[E_INVALID_ARG] client(%d) has not been registered.",
771 pData = (char*) message.data();
772 remain = message.size();
777 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
778 if (ret != G_IO_STATUS_NORMAL)
780 SysLog(NID_IO, "Failed to send a response: %d", ret);
781 SysTryCatch(NID_IO, ret != G_IO_STATUS_ERROR, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
788 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);