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 listen(serverSocket, 15);
234 pGIOChannel = g_io_channel_unix_new(serverSocket);
235 SysTryCatch(NID_IO, pGIOChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
237 // socket will be closed when pGIOChannel is deleted.
238 g_io_channel_set_close_on_unref(pGIOChannel, TRUE);
241 pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
242 SysTryCatch(NID_IO, pGSource != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
243 "[E_OUT_OF_MEMORY] Failed to create watch for socket.");
245 // channel will be delete when pGSource is deleted.
246 g_io_channel_unref(pGIOChannel);
249 g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL);
250 g_source_attach(pGSource, __pHandlerGMainContext);
252 if (__runOnCallerThread)
254 __pListener->OnIpcServerStarted(*this);
258 ret = pthread_create(&__handlerThread, null, &ThreadProc, (void*) this);
259 SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to an IPC thread");
262 __pConnectGSource = pGSource;
267 if (pGIOChannel != null)
269 g_io_channel_unref(pGIOChannel);
272 if (serverSocket != -1)
277 if (runOnCallerThread && __pHandlerGMainContext)
279 g_main_context_unref(__pHandlerGMainContext);
280 __pHandlerGMainContext = null;
289 bool reverse; // true if the connection is for reverse message
294 IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data)
296 IpcServer* pIpcServer = (IpcServer*) data;
297 GError* pGError = null;
298 HelloMessage helloMessage;
299 _ClientInfo* pClientInfo = null;
300 _ChannelInfo* pChannelInfo = null;
301 GSource* pGSource = null;
302 GIOChannel* pChannel = null;
306 struct sockaddr_un clientAddress;
307 socklen_t clientLen = sizeof(clientAddress);
309 SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n");
310 SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n");
312 server = g_io_channel_unix_get_fd(source);
314 client = accept(server, (struct sockaddr*) &clientAddress, &clientLen);
315 SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed.");
317 read(client, &helloMessage, sizeof(helloMessage));
318 helloMessage.appId[255] = '\0';
320 pChannel = g_io_channel_unix_new(client);
321 SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
323 g_io_channel_set_encoding(pChannel, NULL, &pGError);
324 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
326 g_io_channel_set_close_on_unref(pChannel, TRUE);
329 pClientInfo = pIpcServer->__clients[helloMessage.pid];
330 if (pClientInfo == null) // first connection request from this client
332 pClientInfo = new (std::nothrow) _ClientInfo;
333 SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
335 pClientInfo->pIpcServer = pIpcServer;
336 pClientInfo->clientId = helloMessage.pid;
337 pClientInfo->appId.Append((wchar_t*) helloMessage.appId);
338 pClientInfo->pReverseChannel = null;
340 pIpcServer->__clients[helloMessage.pid] = pClientInfo;
342 pIpcServer->__pCurrentClientInfo = pClientInfo;
343 pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid);
344 pIpcServer->__pCurrentClientInfo = null;
347 if (helloMessage.reverse)
349 pClientInfo->pReverseChannel = pChannel;
353 pChannelInfo = new (std::nothrow) _ChannelInfo;
354 SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory.");
356 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
357 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL);
358 g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext);
360 pChannelInfo->pClientInfo = pClientInfo;
361 pChannelInfo->pGIOChannel = pChannel;
362 pChannelInfo->pGSource = pGSource;
364 pClientInfo->channels.push_back(pChannelInfo);
370 if (pChannel != null)
372 g_io_channel_unref(pChannel);
384 IpcServer::GetClientId(void) const
386 if (__pCurrentClientInfo)
388 return __pCurrentClientInfo->clientId;
395 IpcServer::GetClientApplicationId(void) const
397 static String nullString;
399 if (__pCurrentClientInfo)
401 return __pCurrentClientInfo->appId;
408 IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data)
410 GError* pGError = NULL;
412 IPC::Message* pMessage = NULL;
413 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
414 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
416 if (condition & G_IO_HUP)
418 SysLog(NID_IO, "Connection closed");
419 int clientId = pClientInfo->clientId;
421 g_io_channel_shutdown(source, FALSE, &pGError);
423 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
425 if (pChannelInfo == pClientInfo->channels[i])
427 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
429 // Do not destroy a source in a dispatch callback
430 // because main loop will do it if the callback return FALSE.
431 pChannelInfo->destroySource = false;
438 if (pClientInfo->channels.size() == 0)
440 SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId);
442 __pListener->OnIpcClientDisconnected(*this, clientId);
444 __clients[clientId] = null;
451 else if (condition & G_IO_IN)
454 const char* pStart = NULL;
455 const char* pEnd = NULL;
456 const char* pEndOfMessage = NULL;
461 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
462 if (status != G_IO_STATUS_NORMAL)
464 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
466 if (status == G_IO_STATUS_EOF)
468 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
472 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
476 g_io_channel_shutdown(source, FALSE, &pGError);
478 int clientId = pClientInfo->clientId;
480 for (unsigned int i = 0; i < pClientInfo->channels.size(); i++)
482 if (pChannelInfo == pClientInfo->channels[i])
484 pClientInfo->channels.erase(pClientInfo->channels.begin() + i);
486 pChannelInfo->destroySource = false;
492 if (pClientInfo->channels.size() == 0)
494 SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId);
498 __pListener->OnIpcClientDisconnected(*this, clientId);
501 __clients[clientId] = null;
515 if (__pending.empty())
517 pStart = __messageBuffer;
518 pEnd = pStart + readSize;
522 __pending.append(__messageBuffer, readSize);
523 pStart = __pending.data();
524 pEnd = pStart + __pending.size();
529 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
530 if (pEndOfMessage == NULL)
532 __pending.assign(pStart, pEnd - pStart);
536 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
537 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
539 __pCurrentChannel = source;
543 __pListener->OnIpcRequestReceived(*this, *pMessage);
548 __pCurrentChannel = NULL;
550 pStart = pEndOfMessage;
563 IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
565 gboolean ret = FALSE;
566 _ChannelInfo* pChannelInfo = (_ChannelInfo*) data;
567 _ClientInfo* pClientInfo = pChannelInfo->pClientInfo;
568 IpcServer* pIpcServer = (IpcServer*) pClientInfo->pIpcServer;
570 pIpcServer->__pCurrentClientInfo = pClientInfo;
571 ret = pIpcServer->HandleReceivedMessage(source, condition, data);
572 pIpcServer->__pCurrentClientInfo = null;
578 IpcServer::ThreadProc(void* pParam)
580 IpcServer* pIpcServer = (IpcServer*) pParam;
581 if (pIpcServer != NULL)
583 pIpcServer->Run(NULL);
590 IpcServer::Run(void* pParam)
592 result r = E_SUCCESS;
594 if (__pListener == null)
599 __pEventDispatcher = new (std::nothrow) _EventDispatcher;
600 SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
602 r = __pEventDispatcher->Construct(__pHandlerGMainContext);
605 delete __pEventDispatcher;
606 __pEventDispatcher = null;
609 __pListener->OnIpcServerStarted(*this);
611 g_main_loop_run(__pHandlerGMainLoop);
613 __pListener->OnIpcServerStopped(*this);
617 IpcServer::Start(void)
623 IpcServer::GetName(void) const
629 IpcServer::Stop(void)
631 result r = E_SUCCESS;
634 SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null.");
636 if (!__runOnCallerThread)
638 pthread_t self = pthread_self();
640 if (__pHandlerGMainLoop)
642 g_main_loop_quit(__pHandlerGMainLoop);
645 if (__handlerThread != self)
647 ret = pthread_join(__handlerThread, null);
648 SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error");
653 __pListener->OnIpcServerStopped(*this);
660 IpcServer::Send(IPC::Message* msg)
665 GError* pGError = NULL;
668 pData = (char*) msg->data();
669 remain = msg->size();
676 g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError);
682 g_io_channel_flush(__pCurrentChannel, &pGError);
693 IpcServer::SendResponse(int client, IPC::Message* pMessage)
695 result r = E_SUCCESS;
699 GError* pGError = null;
700 _ClientInfo* pClientInfo = null;
702 SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG,
703 "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage,
705 SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
707 pClientInfo = __clients[client];
708 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
709 "[E_INVALID_ARG] client(%d) has not been registered.",
712 pData = (char*) pMessage->data();
713 remain = pMessage->size();
718 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
719 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
725 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);
737 IpcServer::SendResponse(int client, const IPC::Message& message)
739 result r = E_SUCCESS;
743 GError* pGError = null;
744 _ClientInfo* pClientInfo = null;
746 SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client);
747 SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee.");
749 pClientInfo = __clients[client];
750 SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG,
751 "[E_INVALID_ARG] client(%d) has not been registered.",
754 pData = (char*) message.data();
755 remain = message.size();
760 g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError);
761 SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket.");
767 g_io_channel_flush(pClientInfo->pReverseChannel, &pGError);