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;
292 int reverse; // 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;
305 ssize_t readBytes = 0;
310 struct sockaddr_un clientAddress;
311 socklen_t clientLen = sizeof(clientAddress);
314 socklen_t ucredLen = sizeof(cr);
316 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
317 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
319 server = g_io_channel_unix_get_fd(source);
321 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
322 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
324 readBytes = read(client, &helloMessage, sizeof(helloMessage));
325 SysTryCatch(NID_IO, readBytes >= 0, , E_SYSTEM, "[E_SYSTEM] Failed to receive hello message (%d, %s).",
326 errno, strerror(errno));
328 pChannel = g_io_channel_unix_new(client);
329 SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
331 g_io_channel_set_encoding(pChannel, NULL, &pGError);
332 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
334 g_io_channel_set_close_on_unref(pChannel, TRUE);
336 ret = getsockopt(client, SOL_SOCKET, SO_PEERCRED, &cr, &ucredLen);
337 SysTryCatch(NID_IO, ret >= 0, , E_SYSTEM, "[E_SYSTEM] Failed to get peercred information: %s", strerror(errno));
341 pClientInfo = pIpcServer->__clients[cr.pid];
342 if (pClientInfo == null) // first connection request from this client
344 pClientInfo = new (std::nothrow) _ClientInfo;
345 SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
347 pClientInfo->pIpcServer = pIpcServer;
348 pClientInfo->clientId = cr.pid;
351 ret = app_manager_get_app_id(cr.pid, &pAppId);
352 SysTryCatch(NID_IO, ret >= 0, delete pClientInfo, E_SYSTEM, "[E_SYSTEM] Failed to get_app_id: %d", ret);
354 pClientInfo->appId = pAppId;
357 pClientInfo->pReverseChannel = null;
359 pIpcServer->__clients[cr.pid] = pClientInfo;
360 pIpcServer->__pCurrentClientInfo = pClientInfo;
361 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, cr.pid);
362 pIpcServer->__pCurrentClientInfo = null;
365 if (helloMessage.reverse != 0)
367 pClientInfo->pReverseChannel = pChannel;
371 pChannelInfo = new (std::nothrow) _ChannelInfo;
372 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
374 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
375 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
376 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
378 pChannelInfo->pClientInfo = pClientInfo;
379 pChannelInfo->pGIOChannel = pChannel;
380 pChannelInfo->pGSource = pGSource;
382 pClientInfo->channels.push_back(pChannelInfo);
388 if (pChannel != null)
390 g_io_channel_unref(pChannel);
402 IpcServer::GetClientId(void) const
404 if (__pCurrentClientInfo)
406 return __pCurrentClientInfo->clientId;
413 IpcServer::GetClientApplicationId(void) const
415 static String nullString;
417 if (__pCurrentClientInfo)
419 return __pCurrentClientInfo->appId;
426 IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
428 GError* pGError = NULL;
430 IPC::Message* pMessage = NULL;
431 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
432 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
434 if (condition & G_IO_HUP)
436 SysLog(NID_IO, "Connection closed");
437 int clientId = pClientInfo->clientId;
439 g_io_channel_shutdown(source, FALSE, &pGError);
441 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
443 if (pChannelInfo == pClientInfo->channels[i])
445 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
447 // Do not destroy a source in a dispatch callback
448 // because main loop will do it if the callback return FALSE.
449 pChannelInfo->destroySource = false;
456 if (pClientInfo->channels.size() == 0)
458 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
460 __pListener->OnIpcClientDisconnected(*this, clientId);
462 __clients[clientId] = null;
469 else if (condition & G_IO_IN)
472 const char* pStart = NULL;
473 const char* pEnd = NULL;
474 const char* pEndOfMessage = NULL;
479 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
480 if (status != G_IO_STATUS_NORMAL)
482 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
484 if (status == G_IO_STATUS_EOF)
486 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
490 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
494 g_io_channel_shutdown(source, FALSE, &pGError);
496 int clientId = pClientInfo->clientId;
498 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
500 if (pChannelInfo == pClientInfo->channels[i])
502 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
504 pChannelInfo->destroySource = false;
510 if (pClientInfo->channels.size() == 0)
512 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
516 __pListener->OnIpcClientDisconnected(*this, clientId);
519 __clients[clientId] = null;
533 if (__pending.empty())
535 pStart = __messageBuffer;
536 pEnd = pStart + readSize;
540 __pending.append(__messageBuffer, readSize);
541 pStart = __pending.data();
542 pEnd = pStart + __pending.size();
547 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
548 if (pEndOfMessage == NULL)
550 __pending.assign(pStart, pEnd - pStart);
554 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
555 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
557 __pCurrentChannel = source;
561 __pListener->OnIpcRequestReceived(*this, *pMessage);
566 __pCurrentChannel = NULL;
568 pStart = pEndOfMessage;
581 IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
583 gboolean ret = FALSE;
584 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
585 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
586 IpcServer* pIpcServer = (IpcServer*) pClientInfo->pIpcServer;
588 pIpcServer->__pCurrentClientInfo = pClientInfo;
589 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
590 pIpcServer->__pCurrentClientInfo = null;
596 IpcServer::ThreadProc(void* pParam)
598 IpcServer* pIpcServer = (IpcServer*) pParam;
599 if (pIpcServer != NULL)
601 pIpcServer->Run(NULL);
608 IpcServer::Run(void* pParam)
610 result r = E_SUCCESS;
612 if (__pListener == null)
617 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
618 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
620 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
623 delete __pEventDispatcher;
624 __pEventDispatcher = null;
627 __pListener->OnIpcServerStarted(*this);
629 g_main_loop_run(__pHandlerGMainLoop);
631 __pListener->OnIpcServerStopped(*this);
635 IpcServer::Start(void)
641 IpcServer::GetName(void) const
647 IpcServer::Stop(void)
649 result r = E_SUCCESS;
652 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
654 if (!__runOnCallerThread)
656 pthread_t self = pthread_self();
658 if (__pHandlerGMainLoop)
660 g_main_loop_quit(__pHandlerGMainLoop);
663 if (__handlerThread != self)
665 ret = pthread_join(__handlerThread, null);
666 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
671 __pListener->OnIpcServerStopped(*this);
678 IpcServer::Send(IPC::Message* msg)
683 GError* pGError = NULL;
686 pData = (char*) msg->data();
687 remain = msg->size();
694 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
700 g_io_channel_flush(__pCurrentChannel, &pGError);
713 IpcServer::SendResponse(int client, IPC::Message* pMessage)
715 result r = E_SUCCESS;
719 GError* pGError = null;
720 _ClientInfo* pClientInfo = null;
723 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
724 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
726 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
728 pClientInfo = __clients[client];
729 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
730 "[E_INVALID_ARG] client(%d) has not been registered.",
733 pData = (char*) pMessage->data();
734 remain = pMessage->size();
739 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
740 if (ret != G_IO_STATUS_NORMAL)
742 SysLog(NID_IO, "Failed to send a response: %d", ret);
743 SysTryCatch(NID_IO, ret != G_IO_STATUS_ERROR, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
750 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
762 IpcServer::SendResponse(int client, const IPC::Message& message)
764 result r = E_SUCCESS;
768 GError* pGError = null;
769 _ClientInfo* pClientInfo = null;
772 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
773 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
775 pClientInfo = __clients[client];
776 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
777 "[E_INVALID_ARG] client(%d) has not been registered.",
780 pData = (char*) message.data();
781 remain = message.size();
786 ret = g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
787 if (ret != G_IO_STATUS_NORMAL)
789 SysLog(NID_IO, "Failed to send a response: %d", ret);
790 SysTryCatch(NID_IO, ret != G_IO_STATUS_ERROR, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
797 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);