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
138 char appExecutableName[256];
142 _IpcClient::MakeConnection(bool forReverse)
144 result r = E_SUCCESS;
146 struct sockaddr_un server;
147 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 pkgId = _AppInfo::GetPackageId();
181 int length = (pkgId.GetLength() + 1) * sizeof(wchar_t);
187 SysTryReturnResult(NID_IO, pkgId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
189 memcpy(helloMessage.pkgId, pkgId.GetPointer(), length);
191 // Set an executableName
192 String appExecutableName = _AppInfo::GetAppExecutableName();
193 length = (appExecutableName.GetLength() + 1) * sizeof(wchar_t);
199 if (appExecutableName.GetLength() != 0)
201 memcpy(helloMessage.appExecutableName, appExecutableName.GetPointer(), length);
205 client = socket(AF_UNIX, SOCK_STREAM, 0);
206 SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
208 flags = fcntl(client, F_GETFL, 0);
209 ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
210 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
211 errno, strerror(errno));
213 bzero(&server, sizeof(server));
214 server.sun_family = AF_UNIX;
215 strncpy(server.sun_path, socketName.c_str(), socketNameLength);
216 serverLen = sizeof(server);
218 ret = connect(client, (struct sockaddr*) &server, serverLen);
221 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
222 socketName.c_str(), strerror(errno));
226 struct timeval timeout;
229 socklen_t socketLength = 0;
232 FD_SET(client, &rset);
239 ret = select(client+1, &rset, &wset, NULL, &timeout);
242 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
249 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
258 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
260 length = sizeof(error);
261 ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
262 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
263 socketName.c_str(), strerror(errno));
268 SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
273 ret = fcntl(client, F_SETFL, flags);
274 SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
275 errno, strerror(errno));
277 write(client, &helloMessage, sizeof(helloMessage));
281 GError* pGError = null;
282 GSource* pGSource = null;
284 GIOChannel* pChannel = g_io_channel_unix_new(client);
285 GMainContext* pGMainContext = g_main_context_default();
287 g_io_channel_set_encoding(pChannel, null, &pGError);
288 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
289 g_io_channel_set_close_on_unref(pChannel, TRUE);
291 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
292 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
293 g_source_attach(pGSource, pGMainContext);
295 g_io_channel_unref(pChannel);
296 __pReverseSource = pGSource;
317 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
320 _IpcClient* pIpcClient = (_IpcClient*) data;
322 return pIpcClient->HandleReceivedMessage(source, condition);
326 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
328 GError* pGError = null;
330 IPC::Message* pMessage = null;
332 if (condition & G_IO_HUP)
334 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
336 g_source_destroy(__pReverseSource);
337 g_source_unref(__pReverseSource);
338 __pReverseSource = null;
342 __pListener->OnIpcServerDisconnected(*this);
347 else if (condition & G_IO_IN)
350 const char* pStart = null;
351 const char* pEnd = null;
352 const char* pEndOfMessage = null;
357 status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
358 if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
360 if (status == G_IO_STATUS_EOF)
362 SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
366 SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
371 g_io_channel_shutdown(source, FALSE, &pGError);
373 g_source_destroy(__pReverseSource);
374 g_source_unref(__pReverseSource);
375 __pReverseSource = null;
379 __pListener->OnIpcServerDisconnected(*this);
390 if (__pending.empty())
392 pStart = __messageBuffer;
393 pEnd = pStart + readSize;
397 __pending.append(__messageBuffer, readSize);
398 pStart = __pending.data();
399 pEnd = pStart + __pending.size();
404 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
405 if (pEndOfMessage == null)
407 __pending.assign(pStart, pEnd - pStart);
411 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
412 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
416 __pListener->OnIpcResponseReceived(*this, *pMessage);
421 pStart = pEndOfMessage;
434 _IpcClient::AcquireFd(void)
436 result r = E_SUCCESS;
441 __pFdLock->Acquire();
442 if (__fds.size() == 0)
444 __pFdLock->Release();
445 r = MakeConnection(false);
446 SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
454 __pFdLock->Release();
461 _IpcClient::ReleaseFd(int fd)
463 __pFdLock->Acquire();
467 __pFdLock->Release();
471 _IpcClient::SendAsync(IPC::Message* pMessage)
473 result r = E_SUCCESS;
480 pData = (char*) pMessage->data();
481 remain = pMessage->size();
484 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
488 written = write(fd, (char*) pData, remain);
499 _IpcClient::SendSync(IPC::Message* pMessage)
501 result r = E_SUCCESS;
511 char* pEndOfMessage = null;
517 IPC::Message* pReply = null;
518 MessageReplyDeserializer* pReplyDeserializer = null;
519 IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
520 SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
522 messageId = SyncMessage::GetMessageId(*pSyncMessage);
525 SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
527 pData = (char*) pSyncMessage->data();
528 remain = pSyncMessage->size();
532 written = write(fd, (char*) pData, remain);
539 pfd.events = POLLIN | POLLRDHUP;
546 ret = poll(&pfd, 1, -1);
554 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to poll (%d, %s).", errno, strerror(errno));
558 if (pfd.revents & POLLRDHUP)
560 SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] POLLRDHUP");
564 if (pfd.revents & POLLIN)
566 readSize = read(fd, buffer, 1024);
571 message.append(buffer, readSize);
574 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
577 pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
578 SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
583 pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
584 pReplyDeserializer->SerializeOutputParameters(*pReply);
587 delete pReplyDeserializer;
595 _IpcClient::Send(IPC::Message* pMessage)
597 result r = E_SUCCESS;
599 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
601 if (pMessage->is_sync())
603 r = SendSync(pMessage);
607 r = SendAsync(pMessage);
614 _IpcClient::SendRequest(IPC::Message* pMessage)
616 return Send(pMessage);
620 _IpcClient::SendRequest(const IPC::Message& message)
622 result r = E_SUCCESS;
624 SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
626 if (message.is_sync())
628 r = SendSync(const_cast<IPC::Message*>(&message));
632 r = SendAsync(const_cast<IPC::Message*>(&message));