2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 // Licensed under the Apache License, Version 2.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
18 * @file FIo_IpcClient.cpp
19 * @brief This is the implementation file for the _IpcClient class.
25 #include <sys/types.h>
26 #include <sys/socket.h>
39 #include <FBaseRtMutex.h>
40 #include <FApp_AppInfo.h>
41 #include <FAppPkg_PackageManagerImpl.h>
42 #include <FBaseSysLog.h>
43 #include <FBase_StringConverter.h>
44 #include "FIo_IpcClient.h"
45 #include "FIo_IIpcClientEventListener.h"
49 using namespace Tizen::App;
50 using namespace Tizen::App::Package;
51 using namespace Tizen::Base;
52 using namespace Tizen::Base::Runtime;
54 namespace Tizen { namespace Io
57 _IpcClient::_IpcClient(void)
58 : __pReverseSource(null)
64 __messageBuffer[0] = '\0';
67 _IpcClient::~_IpcClient(void)
71 if (__pReverseSource != null)
73 g_source_destroy(__pReverseSource);
74 g_source_unref(__pReverseSource);
75 __pReverseSource = null;
78 while (__fds.size() > 0)
90 _IpcClient::Construct(const String& name, const _IIpcClientEventListener* pListener)
92 SysAssertf(__pFdLock == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class.");
97 __pListener = const_cast <_IIpcClientEventListener*>(pListener);
99 pMutex = new (std::nothrow) Mutex();
100 SysTryReturnResult(NID_IO, pMutex != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
102 r = pMutex->Create();
103 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create SourceLock.", GetErrorMessage(r));
107 r = MakeConnection();
108 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
112 r = MakeConnection(true);
113 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
129 _IpcClient::GetName(void) const
142 _IpcClient::MakeConnection(bool forReverse)
144 result r = E_SUCCESS;
146 struct sockaddr_un server;
147 socklen_t serverLen = 0;
151 HelloMessage helloMessage = {0, 0};
152 std::string socketName;
153 char* pSocketName = null;
154 size_t socketNameLength = 0;
157 helloMessage.pid = getpid();
160 helloMessage.reverse = 1;
164 helloMessage.reverse = 0;
167 pSocketName = _StringConverter::CopyToCharArrayN(__name);
168 SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
170 socketName.append("/tmp/");
171 socketName.append(pSocketName);
173 delete[] pSocketName;
175 socketNameLength = socketName.size() + 1;
176 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
181 String appId = _AppInfo::GetApplicationId();
182 int length = (appId.GetLength() + 1) * sizeof(wchar_t);
188 SysTryReturnResult(NID_IO, appId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
190 memcpy(helloMessage.appId, appId.GetPointer(), length);
193 client = socket(AF_UNIX, SOCK_STREAM, 0);
194 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
196 flags = fcntl(client, F_GETFL, 0);
197 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
198 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
199 errno, strerror(errno));
201 bzero(&server, sizeof(server));
202 server.sun_family = AF_UNIX;
203 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
204 serverLen = sizeof(server);
206 // Retry if the server is not ready
210 ret = connect(client, (struct sockaddr*) &server, serverLen);
211 if (ret < 0 && errno == ENOENT)
213 SysLog(NID_IO, "The server is not ready. %d", retry);
227 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
228 socketName.c_str(), strerror(errno));
232 struct timeval timeout;
235 socklen_t socketLength = 0;
238 FD_SET(client, &rset);
245 ret = select(client+1, &rset, &wset, NULL, &timeout);
248 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
255 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
264 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
266 length = sizeof(error);
267 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
268 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
269 socketName.c_str(), strerror(errno));
274 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
279 ret = fcntl(client, F_SETFL, flags);
280 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
281 errno, strerror(errno));
283 write(client, &helloMessage, sizeof(helloMessage));
287 GError* pGError = null;
288 GSource* pGSource = null;
290 GIOChannel* pChannel = g_io_channel_unix_new(client);
291 GMainContext* pGMainContext = g_main_context_default();
293 g_io_channel_set_encoding(pChannel, null, &pGError);
294 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
295 g_io_channel_set_close_on_unref(pChannel, TRUE);
297 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
298 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
299 g_source_attach(pGSource, pGMainContext);
301 g_io_channel_unref(pChannel);
302 __pReverseSource = pGSource;
323 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
326 _IpcClient* pIpcClient = (_IpcClient*) data;
328 return pIpcClient->HandleReceivedMessage(source, condition);
332 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
334 GError* pGError = null;
336 IPC::Message* pMessage = null;
338 if (condition & G_IO_HUP)
340 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
342 g_source_destroy(__pReverseSource);
343 g_source_unref(__pReverseSource);
344 __pReverseSource = null;
348 __pListener->OnIpcServerDisconnected(*this);
353 else if (condition & G_IO_IN)
356 const char* pStart = null;
357 const char* pEnd = null;
358 const char* pEndOfMessage = null;
363 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
364 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
366 if (status == G_IO_STATUS_EOF)
368 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
372 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
377 g_io_channel_shutdown(source, FALSE, &pGError);
379 g_source_destroy(__pReverseSource);
380 g_source_unref(__pReverseSource);
381 __pReverseSource = null;
385 __pListener->OnIpcServerDisconnected(*this);
396 if (__pending.empty())
398 pStart = __messageBuffer;
399 pEnd = pStart + readSize;
403 __pending.append(__messageBuffer, readSize);
404 pStart = __pending.data();
405 pEnd = pStart + __pending.size();
410 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
411 if (pEndOfMessage == null)
413 __pending.assign(pStart, pEnd - pStart);
417 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
418 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
422 __pListener->OnIpcResponseReceived(*this, *pMessage);
427 pStart = pEndOfMessage;
440 _IpcClient::AcquireFd(void)
442 result r = E_SUCCESS;
447 __pFdLock->Acquire();
448 if (__fds.size() == 0)
450 __pFdLock->Release();
451 r = MakeConnection(false);
452 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
460 __pFdLock->Release();
467 _IpcClient::ReleaseFd(int fd)
469 __pFdLock->Acquire();
473 __pFdLock->Release();
477 _IpcClient::SendAsync(IPC::Message* pMessage)
479 result r = E_SUCCESS;
486 pData = (char*) pMessage->data();
487 remain = pMessage->size();
490 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
494 written = write(fd, (char*) pData, remain);
497 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
513 _IpcClient::SendSync(IPC::Message* pMessage)
515 result r = E_SUCCESS;
525 char* pEndOfMessage = null;
529 IPC::Message* pReply = null;
530 MessageReplyDeserializer* pReplyDeserializer = null;
531 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
532 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
534 messageId = SyncMessage::GetMessageId(*pSyncMessage);
537 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
539 pData = (char*) pSyncMessage->data();
540 remain = pSyncMessage->size();
544 written = write(fd, (char*) pData, remain);
547 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
561 pfd.events = POLLIN | POLLRDHUP;
568 ret = poll(&pfd, 1, __timeout);
576 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to poll (%d, %s).", errno, strerror(errno));
583 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Timeout.");
589 if (pfd.revents & POLLRDHUP)
591 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] POLLRDHUP");
597 if (pfd.revents & POLLIN)
599 readSize = read(fd, buffer, 1024);
604 message.append(buffer, readSize);
607 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
610 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
613 SysLogException(NID_IO, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
616 return E_OUT_OF_MEMORY;
623 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
624 pReplyDeserializer->SerializeOutputParameters(*pReply);
627 delete pReplyDeserializer;
635 _IpcClient::Send(IPC::Message* pMessage)
637 result r = E_SUCCESS;
639 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
641 if (pMessage->is_sync())
643 r = SendSync(pMessage);
647 r = SendAsync(pMessage);
654 _IpcClient::SendRequest(IPC::Message* pMessage)
656 return Send(pMessage);
660 _IpcClient::SendRequest(const IPC::Message& message)
662 result r = E_SUCCESS;
664 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
666 if (message.is_sync())
668 r = SendSync(const_cast<IPC::Message*>(&message));
672 r = SendAsync(const_cast<IPC::Message*>(&message));
679 _IpcClient::SetTimeout(int timeout)
685 _IpcClient::GetTimeout(void) const