Add an error check in Ipc
[platform/framework/native/appfw.git] / src / io / FIo_IpcClient.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
3 //
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
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
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.
15 //
16
17 /**
18  * @file        FIo_IpcClient.cpp
19  * @brief       This is the implementation file for the _IpcClient class.
20  *
21  */
22
23 #include <stdio.h>
24 #include <errno.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <poll.h>
32 #include <pthread.h>
33 #include <fcntl.h>
34
35 #include <iostream>
36 #include <queue>
37 #include <map>
38
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"
46
47 using namespace IPC;
48 using namespace std;
49 using namespace Tizen::App;
50 using namespace Tizen::App::Package;
51 using namespace Tizen::Base;
52 using namespace Tizen::Base::Runtime;
53
54 namespace Tizen { namespace Io
55 {
56
57 _IpcClient::_IpcClient(void)
58         : __pReverseSource(null)
59         , __fdCount(0)
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         char appId[256];
138 };
139
140 result
141 _IpcClient::MakeConnection(bool forReverse)
142 {
143         result r = E_SUCCESS;
144
145         struct sockaddr_un server;
146         socklen_t serverLen = 0;
147         int client = -1;
148         int ret = 0;
149         int retry = 0;
150         HelloMessage helloMessage = {0, 0};
151         std::string socketName;
152         char* pSocketName = null;
153         size_t socketNameLength = 0;
154         int flags = 0;
155
156         helloMessage.pid = getpid();
157         if (forReverse)
158         {
159                 helloMessage.reverse = 1;
160         }
161         else
162         {
163                 helloMessage.reverse = 0;
164         }
165
166         pSocketName = _StringConverter::CopyToCharArrayN(__name);
167         SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
168
169         socketName.append("/tmp/");
170         socketName.append(pSocketName);
171
172         delete[] pSocketName;
173
174         socketNameLength = socketName.size() + 1;
175         SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long.");
176
177         if (__fdCount == 0)
178         {
179                 // Set an appId
180                 String appId = _AppInfo::GetApplicationId();
181                 int length = (appId.GetLength() + 1) * sizeof(wchar_t);
182                 if (length > 255)
183                 {
184                         length = 255;
185                 }
186
187                 SysTryReturnResult(NID_IO, appId.GetLength() > 0, E_SYSTEM, "AppId dose not exist.");
188
189                 memcpy(helloMessage.appId, appId.GetPointer(), length);
190         }
191
192         client = socket(AF_UNIX, SOCK_STREAM, 0);
193         SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno));
194
195         flags = fcntl(client, F_GETFL, 0);
196         ret = fcntl(client, F_SETFL, flags | O_NONBLOCK);
197         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
198                                            errno, strerror(errno));
199
200         bzero(&server, sizeof(server));
201         server.sun_family = AF_UNIX;
202         strncpy(server.sun_path, socketName.c_str(), socketNameLength);
203         serverLen = sizeof(server);
204
205         // Retry if the server is not ready
206         retry = 5;
207         while (retry > 0)
208         {
209                 ret = connect(client, (struct sockaddr*) &server, serverLen);
210                 if (ret < 0 && errno == ENOENT)
211                 {
212                         SysLog(NID_IO, "The server is not ready. %d", retry);
213
214                         usleep(1000 * 1000);
215
216                         --retry;
217                 }
218                 else
219                 {
220                         break;
221                 }
222         }
223
224         if (ret < 0)
225         {
226                 SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
227                                    socketName.c_str(), strerror(errno));
228
229                 fd_set rset;
230                 fd_set wset;
231                 struct timeval timeout;
232                 int length = 0;
233                 int error = 0;
234                 socklen_t socketLength = 0;
235
236                 FD_ZERO(&rset);
237                 FD_SET(client, &rset);
238                 wset = rset;
239                 timeout.tv_sec = 10;
240                 timeout.tv_usec = 0;
241
242                 while (true)
243                 {
244                         ret = select(client+1, &rset, &wset, NULL, &timeout);
245                         if (ret < 0)
246                         {
247                                 SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
248
249                                 continue;
250                         }
251                         else if (ret == 0)
252                         {
253                                 r = E_TIMEOUT;
254                                 SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout.");
255                                 goto CATCH;
256                         }
257                         else
258                         {
259                                 break;
260                         }
261                 }
262
263                 if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset))
264                 {
265                         length = sizeof(error);
266                         ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength);
267                         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s",
268                                            socketName.c_str(), strerror(errno));
269                 }
270                 else
271                 {
272                         r = E_SYSTEM;
273                         SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error.");
274                         goto CATCH;
275                 }
276         }
277
278         ret = fcntl(client, F_SETFL, flags);
279         SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).",
280                                            errno, strerror(errno));
281
282         write(client, &helloMessage, sizeof(helloMessage));
283
284         if (forReverse)
285         {
286                 GError* pGError = null;
287                 GSource* pGSource = null;
288                 ;
289                 GIOChannel* pChannel = g_io_channel_unix_new(client);
290                 GMainContext* pGMainContext = g_main_context_default();
291
292                 g_io_channel_set_encoding(pChannel, null, &pGError);
293                 g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError);
294                 g_io_channel_set_close_on_unref(pChannel, TRUE);
295
296                 pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
297                 g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null);
298                 g_source_attach(pGSource, pGMainContext);
299
300                 g_io_channel_unref(pChannel);
301                 __pReverseSource = pGSource;
302         }
303         else
304         {
305                 ++__fdCount;
306
307                 ReleaseFd(client);
308         }
309
310         return r;
311
312 CATCH:
313         if (client != -1)
314         {
315                 close(client);
316         }
317
318         return r;
319 }
320
321 gboolean
322 _IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data)
323 {
324
325         _IpcClient* pIpcClient = (_IpcClient*) data;
326
327         return pIpcClient->HandleReceivedMessage(source, condition);
328 }
329
330 gboolean
331 _IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition)
332 {
333         GError* pGError = null;
334         GIOStatus status;
335         IPC::Message* pMessage = null;
336
337         if (condition & G_IO_HUP)
338         {
339                 SysLog(NID_IO, "G_IO_HUP, the connection is closed.");
340
341                 g_source_destroy(__pReverseSource);
342                 g_source_unref(__pReverseSource);
343                 __pReverseSource = null;
344
345                 if (__pListener)
346                 {
347                         __pListener->OnIpcServerDisconnected(*this);
348                 }
349
350                 return FALSE;
351         }
352         else if (condition & G_IO_IN)
353         {
354                 gsize readSize = 0;
355                 const char* pStart = null;
356                 const char* pEnd = null;
357                 const char* pEndOfMessage = null;
358
359                 while (true)
360                 {
361                         pGError = null;
362                         status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError);
363                         if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
364                         {
365                                 if (status == G_IO_STATUS_EOF)
366                                 {
367                                         SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed.");
368                                 }
369                                 else
370                                 {
371                                         SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. ");
372                                 }
373
374                                 pGError = null;
375
376                                 g_io_channel_shutdown(source, FALSE, &pGError);
377
378                                 g_source_destroy(__pReverseSource);
379                                 g_source_unref(__pReverseSource);
380                                 __pReverseSource = null;
381
382                                 if (__pListener)
383                                 {
384                                         __pListener->OnIpcServerDisconnected(*this);
385                                 }
386
387                                 return FALSE;
388                         }
389
390                         if (readSize == 0)
391                         {
392                                 break;
393                         }
394
395                         if (__pending.empty())
396                         {
397                                 pStart = __messageBuffer;
398                                 pEnd = pStart + readSize;
399                         }
400                         else
401                         {
402                                 __pending.append(__messageBuffer, readSize);
403                                 pStart = __pending.data();
404                                 pEnd = pStart + __pending.size();
405                         }
406
407                         while (true)
408                         {
409                                 pEndOfMessage = IPC::Message::FindNext(pStart, pEnd);
410                                 if (pEndOfMessage == null)
411                                 {
412                                         __pending.assign(pStart, pEnd - pStart);
413                                         break;
414                                 }
415
416                                 pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart);
417                                 SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
418
419                                 if (__pListener)
420                                 {
421                                         __pListener->OnIpcResponseReceived(*this, *pMessage);
422                                 }
423
424                                 delete pMessage;
425
426                                 pStart = pEndOfMessage;
427                         }
428                 }
429         }
430         else
431         {
432                 // empty statement.
433         }
434
435         return TRUE;
436 }
437
438 int
439 _IpcClient::AcquireFd(void)
440 {
441         result r = E_SUCCESS;
442         int fd = -1;
443
444         while (fd == -1)
445         {
446                 __pFdLock->Acquire();
447                 if (__fds.size() == 0)
448                 {
449                         __pFdLock->Release();
450                         r = MakeConnection(false);
451                         SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r));
452
453                         continue;
454                 }
455
456                 fd = __fds.back();
457                 __fds.pop_back();
458
459                 __pFdLock->Release();
460         }
461
462         return fd;
463 }
464
465 void
466 _IpcClient::ReleaseFd(int fd)
467 {
468         __pFdLock->Acquire();
469
470         __fds.push_back(fd);
471
472         __pFdLock->Release();
473 }
474
475 result
476 _IpcClient::SendAsync(IPC::Message* pMessage)
477 {
478         result r = E_SUCCESS;
479
480         int fd = -1;
481         char* pData = null;
482         int remain = 0;
483         int written = 0;
484
485         pData = (char*) pMessage->data();
486         remain = pMessage->size();
487
488         fd = AcquireFd();
489         SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
490
491         while (remain > 0)
492         {
493                 written = write(fd, (char*) pData, remain);
494                 if (written < 0)
495                 {
496                         SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
497
498                         ReleaseFd(fd);
499                         return E_SYSTEM;
500                 }
501
502                 remain -= written;
503                 pData += written;
504         }
505
506         ReleaseFd(fd);
507
508         return r;
509 }
510
511 result
512 _IpcClient::SendSync(IPC::Message* pMessage)
513 {
514         result r = E_SUCCESS;
515
516         int messageId = 0;
517         int fd = -1;
518
519         char* pData = null;
520         int remain = 0;
521         int written = 0;
522         int readSize = 0;
523         char buffer[1024];
524         char* pEndOfMessage = null;
525
526         std::string message;
527
528         IPC::Message* pReply = null;
529         MessageReplyDeserializer* pReplyDeserializer = null;
530         IPC::SyncMessage* pSyncMessage = dynamic_cast <IPC::SyncMessage*>(pMessage);
531         SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message.");
532
533         messageId = SyncMessage::GetMessageId(*pSyncMessage);
534
535         fd = AcquireFd();
536         SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd.");
537
538         pData = (char*) pSyncMessage->data();
539         remain = pSyncMessage->size();
540
541         while (remain > 0)
542         {
543                 written = write(fd, (char*) pData, remain);
544                 if (written < 0)
545                 {
546                         SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send a request: %d, %s", errno, strerror(errno));
547
548                         ReleaseFd(fd);
549                         return E_SYSTEM;
550                 }
551
552                 remain -= written;
553                 pData += written;
554         }
555
556         // Wait reply
557         struct pollfd pfd;
558
559         pfd.fd = fd;
560         pfd.events = POLLIN | POLLRDHUP;
561         pfd.revents = 0;
562
563         int ret = 0;
564
565         while (true)
566         {
567                 ret = poll(&pfd, 1, -1);
568                 if (ret < 0)
569                 {
570                         if (errno == EINTR)
571                         {
572                                 continue;
573                         }
574
575                         SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to poll (%d, %s).", errno, strerror(errno));
576                         return E_SYSTEM;
577                 }
578
579                 if (pfd.revents & POLLRDHUP)
580                 {
581                         SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] POLLRDHUP");
582
583                         ReleaseFd(fd);
584                         return E_SYSTEM;
585                 }
586
587                 if (pfd.revents & POLLIN)
588                 {
589                         readSize = read(fd, buffer, 1024);
590                 }
591
592                 if (readSize > 0)
593                 {
594                         message.append(buffer, readSize);
595                 }
596
597                 pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size());
598                 if (pEndOfMessage)
599                 {
600                         pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data());
601                         SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
602                         break;
603                 }
604         }
605
606         pReplyDeserializer = pSyncMessage->GetReplyDeserializer();
607         pReplyDeserializer->SerializeOutputParameters(*pReply);
608
609         delete pReply;
610         delete pReplyDeserializer;
611
612         ReleaseFd(fd);
613
614         return r;
615 }
616
617 result
618 _IpcClient::Send(IPC::Message* pMessage)
619 {
620         result r = E_SUCCESS;
621
622         SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
623
624         if (pMessage->is_sync())
625         {
626                 r = SendSync(pMessage);
627         }
628         else
629         {
630                 r = SendAsync(pMessage);
631         }
632
633         return r;
634 }
635
636 result
637 _IpcClient::SendRequest(IPC::Message* pMessage)
638 {
639         return Send(pMessage);
640 }
641
642 result
643 _IpcClient::SendRequest(const IPC::Message& message)
644 {
645         result r = E_SUCCESS;
646
647         SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n");
648
649         if (message.is_sync())
650         {
651                 r = SendSync(const_cast<IPC::Message*>(&message));
652         }
653         else
654         {
655                 r = SendAsync(const_cast<IPC::Message*>(&message));
656         }
657
658         return r;
659 }
660
661 } } //Tizen::Io