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