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;
149 HelloMessage helloMessage = {0, 0};
150 std::string socketName;
151 char* pSocketName = null;
152 size_t socketNameLength = 0;
155 helloMessage.pid = getpid();
158 helloMessage.reverse = 1;
162 helloMessage.reverse = 0;
165 pSocketName = _StringConverter::CopyToCharArrayN(__name);
166 SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
168 socketName.append("/tmp/");
169 socketName.append(pSocketName);
171 delete[] pSocketName;
173 socketNameLength = socketName.size() + 1;
174 SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
179 String appId = _AppInfo::GetApplicationId();
180 int length = (appId.GetLength() + 1) * sizeof(wchar_t);
186 SysTryReturnResult(NID_IO, appId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
188 memcpy(helloMessage.appId, appId.GetPointer(), length);
191 client = socket(AF_UNIX, SOCK_STREAM, 0);
192 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
194 flags = fcntl(client, F_GETFL, 0);
195 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
196 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
197 errno, strerror(errno));
199 bzero(&server, sizeof(server));
200 server.sun_family = AF_UNIX;
201 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
202 serverLen = sizeof(server);
204 // Retry if the server is not ready
208 ret = connect(client, (struct sockaddr*) &server, serverLen);
209 if (ret < 0 && errno == ENOENT)
211 SysLog(NID_IO, "The server is not ready. %d", retry);
225 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
226 socketName.c_str(), strerror(errno));
230 struct timeval timeout;
233 socklen_t socketLength = 0;
236 FD_SET(client, &rset);
243 ret = select(client+1, &rset, &wset, NULL, &timeout);
246 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
253 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
262 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
264 length = sizeof(error);
265 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
266 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
267 socketName.c_str(), strerror(errno));
272 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
277 ret = fcntl(client, F_SETFL, flags);
278 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
279 errno, strerror(errno));
281 write(client, &helloMessage, sizeof(helloMessage));
285 GError* pGError = null;
286 GSource* pGSource = null;
288 GIOChannel* pChannel = g_io_channel_unix_new(client);
289 GMainContext* pGMainContext = g_main_context_default();
291 g_io_channel_set_encoding(pChannel, null, &pGError);
292 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
293 g_io_channel_set_close_on_unref(pChannel, TRUE);
295 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
296 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
297 g_source_attach(pGSource, pGMainContext);
299 g_io_channel_unref(pChannel);
300 __pReverseSource = pGSource;
321 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
324 _IpcClient* pIpcClient = (_IpcClient*) data;
326 return pIpcClient->HandleReceivedMessage(source, condition);
330 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
332 GError* pGError = null;
334 IPC::Message* pMessage = null;
336 if (condition & G_IO_HUP)
338 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
340 g_source_destroy(__pReverseSource);
341 g_source_unref(__pReverseSource);
342 __pReverseSource = null;
346 __pListener->OnIpcServerDisconnected(*this);
351 else if (condition & G_IO_IN)
354 const char* pStart = null;
355 const char* pEnd = null;
356 const char* pEndOfMessage = null;
361 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
362 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
364 if (status == G_IO_STATUS_EOF)
366 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
370 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
375 g_io_channel_shutdown(source, FALSE, &pGError);
377 g_source_destroy(__pReverseSource);
378 g_source_unref(__pReverseSource);
379 __pReverseSource = null;
383 __pListener->OnIpcServerDisconnected(*this);
394 if (__pending.empty())
396 pStart = __messageBuffer;
397 pEnd = pStart + readSize;
401 __pending.append(__messageBuffer, readSize);
402 pStart = __pending.data();
403 pEnd = pStart + __pending.size();
408 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
409 if (pEndOfMessage == null)
411 __pending.assign(pStart, pEnd - pStart);
415 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
416 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
420 __pListener->OnIpcResponseReceived(*this, *pMessage);
425 pStart = pEndOfMessage;
438 _IpcClient::AcquireFd(void)
440 result r = E_SUCCESS;
445 __pFdLock->Acquire();
446 if (__fds.size() == 0)
448 __pFdLock->Release();
449 r = MakeConnection(false);
450 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
458 __pFdLock->Release();
465 _IpcClient::ReleaseFd(int fd)
467 __pFdLock->Acquire();
471 __pFdLock->Release();
475 _IpcClient::SendAsync(IPC::Message* pMessage)
477 result r = E_SUCCESS;
484 pData = (char*) pMessage->data();
485 remain = pMessage->size();
488 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
492 written = write(fd, (char*) pData, remain);
503 _IpcClient::SendSync(IPC::Message* pMessage)
505 result r = E_SUCCESS;
515 char* pEndOfMessage = null;
519 IPC::Message* pReply = null;
520 MessageReplyDeserializer* pReplyDeserializer = null;
521 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
522 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
524 messageId = SyncMessage::GetMessageId(*pSyncMessage);
527 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
529 pData = (char*) pSyncMessage->data();
530 remain = pSyncMessage->size();
534 written = write(fd, (char*) pData, remain);
537 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
551 pfd.events = POLLIN | POLLRDHUP;
558 ret = poll(&pfd, 1, -1);
566 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to poll (%d, %s).", errno, strerror(errno));
570 if (pfd.revents & POLLRDHUP)
572 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] POLLRDHUP");
578 if (pfd.revents & POLLIN)
580 readSize = read(fd, buffer, 1024);
585 message.append(buffer, readSize);
588 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
591 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
592 SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
597 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
598 pReplyDeserializer->SerializeOutputParameters(*pReply);
601 delete pReplyDeserializer;
609 _IpcClient::Send(IPC::Message* pMessage)
611 result r = E_SUCCESS;
613 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
615 if (pMessage->is_sync())
617 r = SendSync(pMessage);
621 r = SendAsync(pMessage);
628 _IpcClient::SendRequest(IPC::Message* pMessage)
630 return Send(pMessage);
634 _IpcClient::SendRequest(const IPC::Message& message)
636 result r = E_SUCCESS;
638 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
640 if (message.is_sync())
642 r = SendSync(const_cast<IPC::Message*>(&message));
646 r = SendAsync(const_cast<IPC::Message*>(&message));