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)
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
139 char appExecutableName[256];
143 _IpcClient::MakeConnection(bool forReverse)
145 result r = E_SUCCESS;
147 struct sockaddr_un server;
148 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 pkgId = _AppInfo::GetPackageId();
182 int length = (pkgId.GetLength() + 1) * sizeof(wchar_t);
188 SysTryReturnResult(NID_IO, pkgId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
190 memcpy(helloMessage.pkgId, pkgId.GetPointer(), length);
192 // Set an executableName
193 String appExecutableName = _AppInfo::GetAppExecutableName();
194 length = (appExecutableName.GetLength() + 1) * sizeof(wchar_t);
200 if (appExecutableName.GetLength() != 0)
202 memcpy(helloMessage.appExecutableName, appExecutableName.GetPointer(), length);
206 client = socket(AF_UNIX, SOCK_STREAM, 0);
207 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
209 flags = fcntl(client, F_GETFL, 0);
210 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
211 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
212 errno, strerror(errno));
214 bzero(&server, sizeof(server));
215 server.sun_family = AF_UNIX;
216 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
217 serverLen = sizeof(server);
219 ret = connect(client, (struct sockaddr*) &server, serverLen);
222 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
223 socketName.c_str(), strerror(errno));
227 struct timeval timeout;
230 socklen_t socketLength = 0;
233 FD_SET(client, &rset);
240 ret = select(client+1, &rset, &wset, NULL, &timeout);
243 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
250 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
259 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
261 length = sizeof(error);
262 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
263 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
264 socketName.c_str(), strerror(errno));
269 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
274 ret = fcntl(client, F_SETFL, flags);
275 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
276 errno, strerror(errno));
278 write(client, &helloMessage, sizeof(helloMessage));
282 GError* pGError = null;
283 GSource* pGSource = null;
285 GIOChannel* pChannel = g_io_channel_unix_new(client);
286 GMainContext* pGMainContext = g_main_context_default();
288 g_io_channel_set_encoding(pChannel, null, &pGError);
289 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
290 g_io_channel_set_close_on_unref(pChannel, TRUE);
292 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
293 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
294 g_source_attach(pGSource, pGMainContext);
296 g_io_channel_unref(pChannel);
297 __pReverseSource = pGSource;
318 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
321 _IpcClient* pIpcClient = (_IpcClient*) data;
323 return pIpcClient->HandleReceivedMessage(source, condition);
327 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
329 GError* pGError = null;
331 IPC::Message* pMessage = null;
333 if (condition & G_IO_HUP)
335 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
337 g_source_destroy(__pReverseSource);
338 g_source_unref(__pReverseSource);
339 __pReverseSource = null;
343 __pListener->OnIpcServerDisconnected(*this);
348 else if (condition & G_IO_IN)
351 const char* pStart = null;
352 const char* pEnd = null;
353 const char* pEndOfMessage = null;
358 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
359 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
361 if (status == G_IO_STATUS_EOF)
363 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
367 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
372 g_io_channel_shutdown(source, FALSE, &pGError);
374 g_source_destroy(__pReverseSource);
375 g_source_unref(__pReverseSource);
376 __pReverseSource = null;
380 __pListener->OnIpcServerDisconnected(*this);
391 if (__pending.empty())
393 pStart = __messageBuffer;
394 pEnd = pStart + readSize;
398 __pending.append(__messageBuffer, readSize);
399 pStart = __pending.data();
400 pEnd = pStart + __pending.size();
405 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
406 if (pEndOfMessage == null)
408 __pending.assign(pStart, pEnd - pStart);
412 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
413 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
417 __pListener->OnIpcResponseReceived(*this, *pMessage);
422 pStart = pEndOfMessage;
435 _IpcClient::AcquireFd(void)
437 result r = E_SUCCESS;
442 __pFdLock->Acquire();
443 if (__fds.size() == 0)
445 __pFdLock->Release();
446 r = MakeConnection(false);
447 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
455 __pFdLock->Release();
462 _IpcClient::ReleaseFd(int fd)
464 __pFdLock->Acquire();
468 __pFdLock->Release();
472 _IpcClient::SendAsync(IPC::Message* pMessage)
474 result r = E_SUCCESS;
481 pData = (char*) pMessage->data();
482 remain = pMessage->size();
485 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
489 written = write(fd, (char*) pData, remain);
500 _IpcClient::SendSync(IPC::Message* pMessage)
502 result r = E_SUCCESS;
512 char* pEndOfMessage = null;
518 IPC::Message* pReply = null;
519 MessageReplyDeserializer* pReplyDeserializer = null;
520 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
521 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
523 messageId = SyncMessage::GetMessageId(*pSyncMessage);
526 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
528 pData = (char*) pSyncMessage->data();
529 remain = pSyncMessage->size();
533 written = write(fd, (char*) pData, remain);
540 pfd.events = POLLIN | POLLRDHUP;
547 if (pfd.revents & POLLRDHUP)
553 if (pfd.revents & POLLIN)
555 readSize = read(fd, buffer, 1024);
558 message.append(buffer, readSize);
560 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
563 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
564 SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
569 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
570 pReplyDeserializer->SerializeOutputParameters(*pReply);
573 delete pReplyDeserializer;
581 _IpcClient::Send(IPC::Message* pMessage)
583 result r = E_SUCCESS;
585 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
587 if (pMessage->is_sync())
589 r = SendSync(pMessage);
593 r = SendAsync(pMessage);
600 _IpcClient::SendRequest(IPC::Message* pMessage)
602 return Send(pMessage);
606 _IpcClient::SendRequest(const IPC::Message& message)
608 result r = E_SUCCESS;
610 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
612 if (message.is_sync())
614 r = SendSync(const_cast<IPC::Message*>(&message));
618 r = SendAsync(const_cast<IPC::Message*>(&message));