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_IpcClient.cpp
20 * @brief This is the implementation file for the _IpcClient class.
26 #include <sys/types.h>
27 #include <sys/socket.h>
40 #include <FBaseRtMutex.h>
41 #include <FApp_AppInfo.h>
42 #include <FAppPkg_PackageManagerImpl.h>
43 #include <FBaseSysLog.h>
44 #include <FBase_StringConverter.h>
45 #include "FIo_IpcClient.h"
46 #include "FIo_IIpcClientEventListener.h"
50 using namespace Tizen::App;
51 using namespace Tizen::App::Package;
52 using namespace Tizen::Base;
53 using namespace Tizen::Base::Runtime;
55 namespace Tizen { namespace Io
58 _IpcClient::_IpcClient(void)
59 : __pReverseSource(null)
63 __messageBuffer[0] = '\0';
66 _IpcClient::~_IpcClient(void)
70 if (__pReverseSource != null)
72 g_source_destroy(__pReverseSource);
73 g_source_unref(__pReverseSource);
74 __pReverseSource = null;
77 while (__fds.size() > 0)
89 _IpcClient::Construct(const String& name, const _IIpcClientEventListener* pListener)
91 SysAssertf(__pFdLock == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class.");
96 __pListener = const_cast <_IIpcClientEventListener*>(pListener);
98 pMutex = new (std::nothrow) Mutex();
99 SysTryReturnResult(NID_IO, pMutex != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
101 r = pMutex->Create();
102 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create SourceLock.", GetErrorMessage(r));
106 r = MakeConnection();
107 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
111 r = MakeConnection(true);
112 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
128 _IpcClient::GetName(void) const
140 _IpcClient::MakeConnection(bool forReverse)
142 result r = E_SUCCESS;
144 struct sockaddr_un server;
145 socklen_t serverLen = 0;
148 HelloMessage helloMessage = {0, 0};
149 std::string socketName;
150 char* pSocketName = null;
151 size_t socketNameLength = 0;
154 helloMessage.pid = getpid();
157 helloMessage.reverse = 1;
161 helloMessage.reverse = 0;
164 pSocketName = _StringConverter::CopyToCharArrayN(__name);
165 SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
167 socketName.append("/tmp/");
168 socketName.append(pSocketName);
170 delete[] pSocketName;
172 socketNameLength = socketName.size() + 1;
173 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
175 client = socket(AF_UNIX, SOCK_STREAM, 0);
176 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
178 flags = fcntl(client, F_GETFL, 0);
179 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
180 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
181 errno, strerror(errno));
183 bzero(&server, sizeof(server));
184 server.sun_family = AF_UNIX;
185 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
186 serverLen = sizeof(server);
188 ret = connect(client, (struct sockaddr*) &server, serverLen);
191 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
192 socketName.c_str(), strerror(errno));
196 struct timeval timeout;
199 socklen_t socketLength = 0;
202 FD_SET(client, &rset);
209 ret = select(client+1, &rset, &wset, NULL, &timeout);
212 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
219 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
228 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
230 length = sizeof(error);
231 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
232 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
233 socketName.c_str(), strerror(errno));
238 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
243 ret = fcntl(client, F_SETFL, flags);
244 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
245 errno, strerror(errno));
247 write(client, &helloMessage, sizeof(helloMessage));
251 GError* pGError = null;
252 GSource* pGSource = null;
254 GIOChannel* pChannel = g_io_channel_unix_new(client);
255 GMainContext* pGMainContext = g_main_context_default();
257 g_io_channel_set_encoding(pChannel, null, &pGError);
258 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
259 g_io_channel_set_close_on_unref(pChannel, TRUE);
261 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
262 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
263 g_source_attach(pGSource, pGMainContext);
265 g_io_channel_unref(pChannel);
266 __pReverseSource = pGSource;
285 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
288 _IpcClient* pIpcClient = (_IpcClient*) data;
290 return pIpcClient->HandleReceivedMessage(source, condition);
294 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
296 GError* pGError = null;
298 IPC::Message* pMessage = null;
300 if (condition & G_IO_HUP)
302 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
304 g_source_destroy(__pReverseSource);
305 g_source_unref(__pReverseSource);
306 __pReverseSource = null;
310 __pListener->OnIpcServerDisconnected(*this);
315 else if (condition & G_IO_IN)
318 const char* pStart = null;
319 const char* pEnd = null;
320 const char* pEndOfMessage = null;
325 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
326 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
328 if (status == G_IO_STATUS_EOF)
330 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
334 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
339 g_io_channel_shutdown(source, FALSE, &pGError);
341 g_source_destroy(__pReverseSource);
342 g_source_unref(__pReverseSource);
343 __pReverseSource = null;
347 __pListener->OnIpcServerDisconnected(*this);
358 if (__pending.empty())
360 pStart = __messageBuffer;
361 pEnd = pStart + readSize;
365 __pending.append(__messageBuffer, readSize);
366 pStart = __pending.data();
367 pEnd = pStart + __pending.size();
372 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
373 if (pEndOfMessage == null)
375 __pending.assign(pStart, pEnd - pStart);
379 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
380 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
384 __pListener->OnIpcResponseReceived(*this, *pMessage);
389 pStart = pEndOfMessage;
402 _IpcClient::AcquireFd(void)
404 result r = E_SUCCESS;
409 __pFdLock->Acquire();
410 if (__fds.size() == 0)
412 __pFdLock->Release();
413 r = MakeConnection(false);
414 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
422 __pFdLock->Release();
429 _IpcClient::ReleaseFd(int fd)
431 __pFdLock->Acquire();
435 __pFdLock->Release();
439 _IpcClient::SendAsync(IPC::Message* pMessage)
441 result r = E_SUCCESS;
448 pData = (char*) pMessage->data();
449 remain = pMessage->size();
452 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
456 written = write(fd, (char*) pData, remain);
467 _IpcClient::SendSync(IPC::Message* pMessage)
469 result r = E_SUCCESS;
479 char* pEndOfMessage = null;
485 IPC::Message* pReply = null;
486 MessageReplyDeserializer* pReplyDeserializer = null;
487 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
488 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
490 messageId = SyncMessage::GetMessageId(*pSyncMessage);
493 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
495 pData = (char*) pSyncMessage->data();
496 remain = pSyncMessage->size();
500 written = write(fd, (char*) pData, remain);
507 pfd.events = POLLIN | POLLRDHUP;
514 if (pfd.revents & POLLRDHUP)
519 if (pfd.revents & POLLIN)
521 readSize = read(fd, buffer, 1024);
524 message.append(buffer, readSize);
526 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
529 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
530 SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
535 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
536 pReplyDeserializer->SerializeOutputParameters(*pReply);
539 delete pReplyDeserializer;
547 _IpcClient::Send(IPC::Message* pMessage)
549 result r = E_SUCCESS;
551 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
553 if (pMessage->is_sync())
555 r = SendSync(pMessage);
559 r = SendAsync(pMessage);
566 _IpcClient::SendRequest(IPC::Message* pMessage)
568 return Send(pMessage);
572 _IpcClient::SendRequest(const IPC::Message& message)
574 result r = E_SUCCESS;
576 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
578 if (message.is_sync())
580 r = SendSync(const_cast<IPC::Message*>(&message));
584 r = SendAsync(const_cast<IPC::Message*>(&message));