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)
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
141 _IpcClient::MakeConnection(bool forReverse)
143 result r = E_SUCCESS;
145 struct sockaddr_un server;
146 socklen_t serverLen = 0;
150 HelloMessage helloMessage = {0, 0};
151 std::string socketName;
152 char* pSocketName = null;
153 size_t socketNameLength = 0;
156 helloMessage.pid = getpid();
159 helloMessage.reverse = 1;
163 helloMessage.reverse = 0;
166 pSocketName = _StringConverter::CopyToCharArrayN(__name);
167 SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
169 socketName.append("/tmp/");
170 socketName.append(pSocketName);
172 delete[] pSocketName;
174 socketNameLength = socketName.size() + 1;
175 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
180 String appId = _AppInfo::GetApplicationId();
181 int length = (appId.GetLength() + 1) * sizeof(wchar_t);
187 SysTryReturnResult(NID_IO, appId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
189 memcpy(helloMessage.appId, appId.GetPointer(), length);
192 client = socket(AF_UNIX, SOCK_STREAM, 0);
193 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
195 flags = fcntl(client, F_GETFL, 0);
196 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
197 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
198 errno, strerror(errno));
200 bzero(&server, sizeof(server));
201 server.sun_family = AF_UNIX;
202 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
203 serverLen = sizeof(server);
205 // Retry if the server is not ready
209 ret = connect(client, (struct sockaddr*) &server, serverLen);
210 if (ret < 0 && errno == ENOENT)
212 SysLog(NID_IO, "The server is not ready. %d", retry);
226 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
227 socketName.c_str(), strerror(errno));
231 struct timeval timeout;
234 socklen_t socketLength = 0;
237 FD_SET(client, &rset);
244 ret = select(client+1, &rset, &wset, NULL, &timeout);
247 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
254 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
263 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
265 length = sizeof(error);
266 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
267 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
268 socketName.c_str(), strerror(errno));
273 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
278 ret = fcntl(client, F_SETFL, flags);
279 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
280 errno, strerror(errno));
282 write(client, &helloMessage, sizeof(helloMessage));
286 GError* pGError = null;
287 GSource* pGSource = null;
289 GIOChannel* pChannel = g_io_channel_unix_new(client);
290 GMainContext* pGMainContext = g_main_context_default();
292 g_io_channel_set_encoding(pChannel, null, &pGError);
293 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
294 g_io_channel_set_close_on_unref(pChannel, TRUE);
296 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
297 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
298 g_source_attach(pGSource, pGMainContext);
300 g_io_channel_unref(pChannel);
301 __pReverseSource = pGSource;
322 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
325 _IpcClient* pIpcClient = (_IpcClient*) data;
327 return pIpcClient->HandleReceivedMessage(source, condition);
331 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
333 GError* pGError = null;
335 IPC::Message* pMessage = null;
337 if (condition & G_IO_HUP)
339 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
341 g_source_destroy(__pReverseSource);
342 g_source_unref(__pReverseSource);
343 __pReverseSource = null;
347 __pListener->OnIpcServerDisconnected(*this);
352 else if (condition & G_IO_IN)
355 const char* pStart = null;
356 const char* pEnd = null;
357 const char* pEndOfMessage = null;
362 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
363 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
365 if (status == G_IO_STATUS_EOF)
367 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
371 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
376 g_io_channel_shutdown(source, FALSE, &pGError);
378 g_source_destroy(__pReverseSource);
379 g_source_unref(__pReverseSource);
380 __pReverseSource = null;
384 __pListener->OnIpcServerDisconnected(*this);
395 if (__pending.empty())
397 pStart = __messageBuffer;
398 pEnd = pStart + readSize;
402 __pending.append(__messageBuffer, readSize);
403 pStart = __pending.data();
404 pEnd = pStart + __pending.size();
409 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
410 if (pEndOfMessage == null)
412 __pending.assign(pStart, pEnd - pStart);
416 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
417 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
421 __pListener->OnIpcResponseReceived(*this, *pMessage);
426 pStart = pEndOfMessage;
439 _IpcClient::AcquireFd(void)
441 result r = E_SUCCESS;
446 __pFdLock->Acquire();
447 if (__fds.size() == 0)
449 __pFdLock->Release();
450 r = MakeConnection(false);
451 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
459 __pFdLock->Release();
466 _IpcClient::ReleaseFd(int fd)
468 __pFdLock->Acquire();
472 __pFdLock->Release();
476 _IpcClient::SendAsync(IPC::Message* pMessage)
478 result r = E_SUCCESS;
485 pData = (char*) pMessage->data();
486 remain = pMessage->size();
489 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
493 written = write(fd, (char*) pData, remain);
500 SysLogException(NID_IO, E_RESOURCE_UNAVAILABLE, "[E_RESOURCE_UNAVAILABLE] The socket buffer is full.");
501 return E_RESOURCE_UNAVAILABLE;
504 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
518 _IpcClient::SendSync(IPC::Message* pMessage)
520 result r = E_SUCCESS;
530 char* pEndOfMessage = null;
534 IPC::Message* pReply = null;
535 MessageReplyDeserializer* pReplyDeserializer = null;
536 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
537 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
539 messageId = SyncMessage::GetMessageId(*pSyncMessage);
542 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
544 pData = (char*) pSyncMessage->data();
545 remain = pSyncMessage->size();
549 written = write(fd, (char*) pData, remain);
556 SysLogException(NID_IO, E_RESOURCE_UNAVAILABLE, "[E_RESOURCE_UNAVAILABLE] The socket buffer is full.");
557 return E_RESOURCE_UNAVAILABLE;
560 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
572 pfd.events = POLLIN | POLLRDHUP;
579 ret = poll(&pfd, 1, -1);
587 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to poll (%d, %s).", errno, strerror(errno));
593 if (pfd.revents & POLLRDHUP)
595 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] POLLRDHUP");
601 if (pfd.revents & POLLIN)
603 readSize = read(fd, buffer, 1024);
608 message.append(buffer, readSize);
611 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
614 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
617 SysLogException(NID_IO, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
620 return E_OUT_OF_MEMORY;
627 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
628 pReplyDeserializer->SerializeOutputParameters(*pReply);
631 delete pReplyDeserializer;
639 _IpcClient::Send(IPC::Message* pMessage)
641 result r = E_SUCCESS;
643 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
645 if (pMessage->is_sync())
647 r = SendSync(pMessage);
651 r = SendAsync(pMessage);
658 _IpcClient::SendRequest(IPC::Message* pMessage)
660 return Send(pMessage);
664 _IpcClient::SendRequest(const IPC::Message& message)
666 result r = E_SUCCESS;
668 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
670 if (message.is_sync())
672 r = SendSync(const_cast<IPC::Message*>(&message));
676 r = SendAsync(const_cast<IPC::Message*>(&message));