62449ed10ff3bdd802732a7a23caff33f64bd468
[platform/framework/native/appfw.git] / src / io / FIo_IpcClient.cpp
1 //
2 // Open Service Platform
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 //
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
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
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.
16 //
17
18 /**
19  * @file        FIo_IpcClient.cpp
20  * @brief       This is the implementation file for the _IpcClient class.
21  *
22  */
23
24 #include <stdio.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/un.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <poll.h>
33 #include <pthread.h>
34 #include <fcntl.h>
35
36 #include <iostream>
37 #include <queue>
38 #include <map>
39
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"
47
48 using namespace IPC;
49 using namespace std;
50 using namespace Tizen::App;
51 using namespace Tizen::App::Package;
52 using namespace Tizen::Base;
53 using namespace Tizen::Base::Runtime;
54
55 namespace Tizen { namespace Io
56 {
57
58 _IpcClient::_IpcClient(void)
59         : __pReverseSource(null)
60         , __pFdLock(null)
61         , __pListener(null)
62 {
63         __messageBuffer[0] = '\0';
64 }
65
66 _IpcClient::~_IpcClient(void)
67 {
68         int fd = 0;
69
70         if (__pReverseSource != null)
71         {
72                 g_source_destroy(__pReverseSource);
73                 g_source_unref(__pReverseSource);
74                 __pReverseSource = null;
75         }
76
77         while (__fds.size() > 0)
78         {
79                 fd = __fds.back();
80                 __fds.pop_back();
81
82                 close(fd);
83         }
84
85         delete __pFdLock;
86 }
87
88 result
89 _IpcClient::Construct(const String& name, const _IIpcClientEventListener* pListener)
90 {
91         SysAssertf(__pFdLock == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class.");
92         result r = E_SUCCESS;
93         Mutex* pMutex = null;
94
95         __name = name;
96         __pListener = const_cast <_IIpcClientEventListener*>(pListener);
97
98         pMutex = new (std::nothrow) Mutex();
99         SysTryReturnResult(NID_IO, pMutex != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
100
101         r = pMutex->Create();
102         SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create SourceLock.", GetErrorMessage(r));
103
104         __pFdLock = pMutex;
105
106         r = MakeConnection();
107         SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
108
109         if (__pListener)
110         {
111                 r = MakeConnection(true);
112                 SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r));
113         }
114
115         return E_SUCCESS;
116
117 CATCH:
118         __name.Clear();
119         __pListener = null;
120         __pFdLock = null;
121
122         delete pMutex;
123
124         return r;
125 }
126
127 String
128 _IpcClient::GetName(void) const
129 {
130         return __name;
131 }
132
133 struct HelloMessage
134 {
135         int pid;
136         bool reverse;
137 };
138
139 result
140 _IpcClient::MakeConnection(bool forReverse)
141 {
142         result r = E_SUCCESS;
143
144         struct sockaddr_un server;
145         socklen_t serverLen = 0;
146         int client = -1;
147         int ret = 0;
148         HelloMessage helloMessage = {0, false};
149         std::string socketName;
150         char* pSocketName = null;
151         size_t socketNameLength = 0;
152         int flags = 0;
153
154         helloMessage.pid = getpid();
155         helloMessage.reverse = forReverse;
156
157         pSocketName = _StringConverter::CopyToCharArrayN(__name);
158         SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
159
160         socketName.append("/tmp/");
161         socketName.append(pSocketName);
162
163         delete[] pSocketName;
164
165         socketNameLength = socketName.size() + 1;
166         SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
167
168         client = socket(AF_UNIX, SOCK_STREAM, 0);
169         SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
170
171         flags = fcntl(client, F_GETFL, 0);
172         ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
173         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
174                                            errno, strerror(errno));
175
176         bzero(&server, sizeof(server));
177         server.sun_family = AF_UNIX;
178         strncpy(server.sun_path, socketName.c_str(), socketNameLength);
179         serverLen = sizeof(server);
180
181         ret = connect(client, (struct sockaddr*) &server, serverLen);
182         if (ret != 0)
183         {
184                 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
185                                    socketName.c_str(), strerror(errno));
186
187                 fd_set rset;
188                 fd_set wset;
189                 struct timeval timeout;
190                 int length = 0;
191                 int error = 0;
192                 socklen_t socketLength = 0;
193
194                 FD_ZERO(&rset);
195                 FD_SET(client, &rset);
196                 wset = rset;
197                 timeout.tv_sec = 10;
198                 timeout.tv_usec = 0;
199
200                 while (true)
201                 {
202                         ret = select(client+1, &rset, &wset, NULL, &timeout);
203                         if (ret < 0)
204                         {
205                                 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
206
207                                 continue;
208                         }
209                         else if (ret == 0)
210                         {
211                                 r = E_TIMEOUT;
212                                 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
213                                 goto CATCH;
214                         }
215                         else
216                         {
217                                 break;
218                         }
219                 }
220
221                 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
222                 {
223                         length = sizeof(error);
224                         ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
225                         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
226                                            socketName.c_str(), strerror(errno));
227                 }
228                 else
229                 {
230                         r = E_SYSTEM;
231                         SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
232                         goto CATCH;
233                 }
234         }
235
236         ret = fcntl(client, F_SETFL, flags);
237         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
238                                            errno, strerror(errno));
239
240         write(client, &helloMessage, sizeof(helloMessage));
241
242         if (forReverse)
243         {
244                 GError* pGError = null;
245                 GSource* pGSource = null;
246                 ;
247                 GIOChannel* pChannel = g_io_channel_unix_new(client);
248                 GMainContext* pGMainContext = g_main_context_default();
249
250                 g_io_channel_set_encoding(pChannel, null, &pGError);
251                 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
252                 g_io_channel_set_close_on_unref(pChannel, TRUE);
253
254                 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
255                 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
256                 g_source_attach(pGSource, pGMainContext);
257
258                 g_io_channel_unref(pChannel);
259                 __pReverseSource = pGSource;
260         }
261         else
262         {
263                 ReleaseFd(client);
264         }
265
266         return r;
267
268 CATCH:
269         if (client != -1)
270         {
271                 close(client);
272         }
273
274         return r;
275 }
276
277 gboolean
278 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
279 {
280
281         _IpcClient* pIpcClient = (_IpcClient*) data;
282
283         return pIpcClient->HandleReceivedMessage(source, condition);
284 }
285
286 gboolean
287 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
288 {
289         GError* pGError = null;
290         GIOStatus status;
291         IPC::Message* pMessage = null;
292
293         if (condition & G_IO_HUP)
294         {
295                 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
296
297                 g_source_destroy(__pReverseSource);
298                 g_source_unref(__pReverseSource);
299                 __pReverseSource = null;
300
301                 if (__pListener)
302                 {
303                         __pListener->OnIpcServerDisconnected(*this);
304                 }
305
306                 return FALSE;
307         }
308         else if (condition & G_IO_IN)
309         {
310                 gsize readSize = 0;
311                 const char* pStart = null;
312                 const char* pEnd = null;
313                 const char* pEndOfMessage = null;
314
315                 while (true)
316                 {
317                         pGError = null;
318                         status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
319                         if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
320                         {
321                                 if (status == G_IO_STATUS_EOF)
322                                 {
323                                         SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
324                                 }
325                                 else
326                                 {
327                                         SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
328                                 }
329
330                                 pGError = null;
331
332                                 g_io_channel_shutdown(source, FALSE, &pGError);
333
334                                 g_source_destroy(__pReverseSource);
335                                 g_source_unref(__pReverseSource);
336                                 __pReverseSource = null;
337
338                                 if (__pListener)
339                                 {
340                                         __pListener->OnIpcServerDisconnected(*this);
341                                 }
342
343                                 return FALSE;
344                         }
345
346                         if (readSize == 0)
347                         {
348                                 break;
349                         }
350
351                         if (__pending.empty())
352                         {
353                                 pStart = __messageBuffer;
354                                 pEnd = pStart + readSize;
355                         }
356                         else
357                         {
358                                 __pending.append(__messageBuffer, readSize);
359                                 pStart = __pending.data();
360                                 pEnd = pStart + __pending.size();
361                         }
362
363                         while (true)
364                         {
365                                 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
366                                 if (pEndOfMessage == null)
367                                 {
368                                         __pending.assign(pStart, pEnd - pStart);
369                                         break;
370                                 }
371
372                                 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
373                                 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
374
375                                 if (__pListener)
376                                 {
377                                         __pListener->OnIpcResponseReceived(*this, *pMessage);
378                                 }
379
380                                 delete pMessage;
381
382                                 pStart = pEndOfMessage;
383                         }
384                 }
385         }
386         else
387         {
388                 // empty statement.
389         }
390
391         return TRUE;
392 }
393
394 int
395 _IpcClient::AcquireFd(void)
396 {
397         result r = E_SUCCESS;
398         int fd = -1;
399
400         while (fd == -1)
401         {
402                 __pFdLock->Acquire();
403                 if (__fds.size() == 0)
404                 {
405                         __pFdLock->Release();
406                         r = MakeConnection(false);
407                         SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
408
409                         continue;
410                 }
411
412                 fd = __fds.back();
413                 __fds.pop_back();
414
415                 __pFdLock->Release();
416         }
417
418         return fd;
419 }
420
421 void
422 _IpcClient::ReleaseFd(int fd)
423 {
424         __pFdLock->Acquire();
425
426         __fds.push_back(fd);
427
428         __pFdLock->Release();
429 }
430
431 result
432 _IpcClient::SendAsync(IPC::Message* pMessage)
433 {
434         result r = E_SUCCESS;
435
436         int fd = -1;
437         char* pData = null;
438         int remain = 0;
439         int written = 0;
440
441         pData = (char*) pMessage->data();
442         remain = pMessage->size();
443
444         fd = AcquireFd();
445         SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
446
447         while (remain > 0)
448         {
449                 written = write(fd, (char*) pData, remain);
450                 remain -= written;
451                 pData += written;
452         }
453
454         ReleaseFd(fd);
455
456         return r;
457 }
458
459 result
460 _IpcClient::SendSync(IPC::Message* pMessage)
461 {
462         result r = E_SUCCESS;
463
464         int messageId = 0;
465         int fd = -1;
466
467         char* pData = null;
468         int remain = 0;
469         int written = 0;
470         int readSize = 0;
471         char buffer[1024];
472         char* pEndOfMessage = null;
473
474         std::string message;
475
476         struct pollfd pfd;
477
478         IPC::Message* pReply = null;
479         MessageReplyDeserializer* pReplyDeserializer = null;
480         IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
481         SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
482
483         messageId = SyncMessage::GetMessageId(*pSyncMessage);
484
485         fd = AcquireFd();
486         SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
487
488         pData = (char*) pSyncMessage->data();
489         remain = pSyncMessage->size();
490
491         while (remain > 0)
492         {
493                 written = write(fd, (char*) pData, remain);
494                 remain -= written;
495                 pData += written;
496         }
497
498         // Wait reply
499         pfd.fd = fd;
500         pfd.events = POLLIN | POLLRDHUP;
501         pfd.revents = 0;
502
503         while (true)
504         {
505                 poll(&pfd, 1, -1);
506
507                 if (pfd.revents & POLLRDHUP)
508                 {
509                         return E_SYSTEM;
510                 }
511
512                 if (pfd.revents & POLLIN)
513                 {
514                         readSize = read(fd, buffer, 1024);
515                 }
516
517                 message.append(buffer, readSize);
518
519                 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
520                 if (pEndOfMessage)
521                 {
522                         pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
523                         SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
524                         break;
525                 }
526         }
527
528         pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
529         pReplyDeserializer->SerializeOutputParameters(*pReply);
530
531         delete pReply;
532         delete pReplyDeserializer;
533
534         ReleaseFd(fd);
535
536         return r;
537 }
538
539 result
540 _IpcClient::Send(IPC::Message* pMessage)
541 {
542         result r = E_SUCCESS;
543
544         SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
545
546         if (pMessage->is_sync())
547         {
548                 r = SendSync(pMessage);
549         }
550         else
551         {
552                 r = SendAsync(pMessage);
553         }
554
555         return r;
556 }
557
558 result
559 _IpcClient::SendRequest(IPC::Message* pMessage)
560 {
561         return Send(pMessage);
562 }
563
564 result
565 _IpcClient::SendRequest(const IPC::Message& message)
566 {
567         result r = E_SUCCESS;
568
569         SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
570
571         if (message.is_sync())
572         {
573                 r = SendSync(const_cast<IPC::Message*>(&message));
574         }
575         else
576         {
577                 r = SendAsync(const_cast<IPC::Message*>(&message));
578         }
579
580         return r;
581 }
582
583 } } //Tizen::Io