Fix the boiler plate codes
[platform/framework/native/appfw.git] / src / io / FIo_FileEventManagerImpl.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_FileEventManager.cpp
19  * @brief       This is the implementation file for FileEventManager class.
20  */
21
22 #include <unistd.h>
23 #include <sys/inotify.h>
24 #include <errno.h>
25 #include <new>
26 #include <unique_ptr.h>
27
28 #include <FBaseInteger.h>
29 #include <FBaseString.h>
30 #include <FBaseSysLog.h>
31 #include <FBaseColAllElementsDeleter.h>
32 #include <FBaseRtIEventArg.h>
33 #include <FIoFile.h>
34 #include <FIoIFileEventListener.h>
35 #include <FIoFileEventManager.h>
36
37 #include <FBase_StringConverter.h>
38 #include <FBase_NativeError.h>
39 #include <FIo_FileEventManagerImpl.h>
40
41 #define INOTIFY_BUFFER_LEN      (1024*(sizeof(struct inotify_event) + 16))
42
43 using namespace std;
44 using namespace Tizen::Base;
45 using namespace Tizen::Base::Runtime;
46 using namespace Tizen::Base::Collection;
47
48 namespace Tizen { namespace Io
49 {
50
51 class _FileEventArg
52         : public IEventArg
53 {
54 public:
55         _FileEventArg(unsigned long event, String path, unsigned int eventId)
56                 : __event(event)
57                 , __path(path)
58                 , __eventId(eventId)
59         {
60         }
61         unsigned long __event;
62         String __path;
63         unsigned int __eventId;
64 };
65
66 class _FileEvent
67         : public Event
68 {
69 protected:
70         virtual void FireImpl(IEventListener& listener, const IEventArg& arg)
71         {
72                 IFileEventListener* pListener = dynamic_cast<IFileEventListener*> (&listener);
73                 if (pListener != null)
74                 {
75                         const _FileEventArg* pArg = dynamic_cast<const _FileEventArg*>(&arg);
76                         if (pArg != null)
77                         {
78                                 pListener->OnFileEventOccured(pArg->__event, pArg->__path, pArg->__eventId);
79                         }
80                 }
81         }
82 };
83
84 _FileEventManagerImpl::_FileEventManagerImpl(void)
85         : __pMonitorFileList(null)
86         , __pEvent(null)
87         , __inotifyFd(-1)
88         , __pGSource(null)
89         , __pGIOChannel(null)
90 {
91 }
92
93 _FileEventManagerImpl::~_FileEventManagerImpl(void)
94 {
95         if (__inotifyFd != -1)
96         {
97                 close(__inotifyFd);
98         }
99
100         if (__pGIOChannel != null)
101         {
102                 g_io_channel_unref(__pGIOChannel);
103         }
104
105         if (__pGSource != null)
106         {
107                 g_source_destroy(__pGSource);
108                 g_source_unref(__pGSource);
109         }
110
111         if (__pMonitorFileList != null)
112         {
113                 __pMonitorFileList->RemoveAll(true);
114                 delete __pMonitorFileList;
115         }
116
117         delete __pEvent;
118 }
119
120 gboolean
121 _FileEventManagerImpl::OnFileEventOccured(GIOChannel* source, GIOCondition condition, gpointer data)
122 {
123         _FileEventManagerImpl* pFileEventManagerImpl = (_FileEventManagerImpl*)data;
124
125         pFileEventManagerImpl->SendEvent();
126
127         return true;
128 }
129
130 result
131 _FileEventManagerImpl::SendEvent(void)
132 {
133         unsigned long iter = 0;
134         ssize_t length = 0;
135         char buffer[INOTIFY_BUFFER_LEN + 1] = {0,};
136
137         unsigned long event = 0;
138         String path;
139         unsigned int eventId = 0;
140         result r = E_IO;
141
142         SysTryReturnResult(NID_IO, __inotifyFd != -1, E_IO, "Failed to inotify.");
143
144         length = read(__inotifyFd, buffer, INOTIFY_BUFFER_LEN);
145         SysTryReturnResult(NID_IO, length < (long)INOTIFY_BUFFER_LEN, E_IO, "Read buffer has failed.");
146
147         while (iter < static_cast<unsigned long> (length))
148         {
149                 struct inotify_event* pEvent = (struct inotify_event*)&buffer[iter];
150                 SysTryReturnResult(NID_IO, pEvent != null, E_IO, "Event info not found.");
151                 event = (unsigned long)pEvent->mask;
152                 eventId = pEvent->cookie;
153
154                 if (pEvent->len)
155                 {
156                         path = pEvent->name;
157                 }
158                 else
159                 {
160                         path = GetRegisteredPath(pEvent->wd);
161                 }
162
163                 _FileEventArg* pEventArg= new (std::nothrow) _FileEventArg(event, path, eventId);
164                  if(pEventArg != null)
165                  {
166                         SysLog(NID_IO, "_FileEventManagerImpl::SendEvent Event Fire");
167                         __pEvent->Fire(*pEventArg);
168                         r = E_SUCCESS;
169                  }
170
171                 iter += sizeof(struct inotify_event) + pEvent->len;
172         }
173
174         return r;
175 }
176
177 result
178 _FileEventManagerImpl::Construct(IFileEventListener& listener)
179 {
180         GMainContext* pGContext = null;
181         result r = E_SUCCESS;
182         _FileEvent* pEvent = null;
183         __inotifyFd = inotify_init();
184
185         if (__inotifyFd == -1 && errno == EMFILE)
186         {
187                 SysLogException(NID_IO, E_MAX_EXCEEDED, "The number of opened files has exceeded the maximum limit.");
188                 return E_MAX_EXCEEDED;
189         }
190         SysTryReturnResult(NID_IO, __inotifyFd != -1, E_IO, "Failed to init inotify.");
191
192         unique_ptr<HashMap, AllElementsDeleter> pMonitorFileList(new (std::nothrow) HashMap());
193         SysTryCatch(NID_IO, pMonitorFileList != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create monitored file list.");
194
195         r = pMonitorFileList->Construct();
196         SysTryCatch(NID_IO, r == E_SUCCESS, , r, "[%s] Propagated.", GetErrorMessage(r));
197
198         pGContext = g_main_context_get_thread_default(); //get own gmain context except default thread
199
200         if (pGContext == null)
201         {
202                 pGContext = g_main_context_default(); //get gmain context from me (default)
203                 SysTryCatch(NID_IO, pGContext != null, r = E_IO, E_IO, "[E_IO] Failed to get glib context.");
204         }
205
206         __pEvent = new (std::nothrow) _FileEvent();
207         SysTryReturnResult(NID_IO, __pEvent != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
208
209         __pEvent->AddListener(listener);
210
211         __pGIOChannel = g_io_channel_unix_new(__inotifyFd); //fd wrapping
212         SysTryCatch(NID_IO, __pGIOChannel != null, r = E_IO, E_IO, "[E_IO] Failed to create glib channel.");
213
214         __pGSource = g_io_create_watch(__pGIOChannel, (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP));
215         SysTryCatch(NID_IO, __pGSource != null, r = E_IO, E_IO, "[E_IO] Failed to create glib watch.");
216
217         g_source_set_callback(__pGSource, (GSourceFunc)OnFileEventOccured, this, NULL);
218         g_source_attach(__pGSource, pGContext);
219
220         __pMonitorFileList = pMonitorFileList.release();
221
222         // fall thru
223 CATCH:
224         if (r != E_SUCCESS)
225         {
226                 if (__inotifyFd != -1)
227                 {
228                         close(__inotifyFd);
229                 }
230
231                 if (__pGIOChannel != null)
232                 {
233                         g_io_channel_unref(__pGIOChannel);
234                         __pGIOChannel = null;
235                 }
236
237                 if (__pGSource != null)
238                 {
239                         g_source_destroy(__pGSource);
240                         g_source_unref(__pGSource);
241                         __pGSource = null;
242                 }
243         }
244
245         return r;
246 }
247
248 result
249 _FileEventManagerImpl::AddPath(const String& path, unsigned long eventsToMonitor)
250 {
251         int monitoredFd = 0;
252         result r = E_SUCCESS;
253
254         SysTryReturnResult(NID_IO, File::IsFileExist(path) == true, E_FILE_NOT_FOUND,
255                         "path[%ls] dose not exist.", path.GetPointer());
256
257         SysLog(NID_IO, "path:%ls", path.GetPointer());
258
259         unique_ptr<char[]> pPath(_StringConverter::CopyToCharArrayN(path));
260         SysTryReturnResult(NID_IO, pPath != null, E_IO, "String covert is failed.");
261
262         monitoredFd = inotify_add_watch(__inotifyFd, pPath.get(), eventsToMonitor);
263
264         if (monitoredFd == -1)
265         {
266                 r = E_IO;
267                 switch (errno)
268                 {
269                 case EACCES:
270                         SysLogException(NID_IO, E_IO, "Read access to the given file[%s] is not permitted.", pPath.get());
271                         r = E_ILLEGAL_ACCESS;
272                         break;
273                 case EFAULT:
274                         SysLogException(NID_IO, E_IO, "The path[%s] points outside of the process's accessible address space.", pPath.get());
275                         r = E_ILLEGAL_ACCESS;
276                         break;
277                 case EBADF:
278                         SysLogException(NID_IO, E_IO, "The given file descriptor is not valid.");
279                         break;
280                 case EINVAL:
281                         SysLogException(NID_IO, E_INVALID_ARG, "The given event mask contains no valid events; or fd is not an inotify file descriptor.");
282                         r = E_INVALID_ARG;
283                         break;
284                 case ENOMEM:
285                         SysLogException(NID_IO, E_IO, "Insufficient kernel memory was available.");
286                         break;
287                 case ENOSPC:
288                         SysLogException(NID_IO, E_IO, "The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource");
289                         break;
290                 default:
291                         break;
292                 }
293
294                 return r;
295         }
296
297         unique_ptr<String> pMonitoredPath(new (std::nothrow) String(path));
298         unique_ptr<Integer> pMonitoredFd(new (std::nothrow) Integer(monitoredFd));
299         SysTryReturnResult(NID_IO, pMonitoredPath != null && pMonitoredFd != null, E_IO, "Failed to allocate memory");
300
301         SysTryReturnResult(NID_IO, __pMonitorFileList != null, E_IO, "Monitored file list is null");
302
303         r = __pMonitorFileList->Add(*pMonitoredPath.release(), *pMonitoredFd.release());
304         SysTryReturnResult(NID_IO, r == E_SUCCESS || r == E_OBJ_ALREADY_EXIST, E_IO, "Failed to add on monitored list.");
305
306         return r;
307 }
308
309 result
310 _FileEventManagerImpl::RemovePath(const String& path)
311 {
312         Integer* pMonitoredFd = null;
313
314         SysTryReturnResult(NID_IO, __pMonitorFileList != null, E_IO, "Monitored file list is null");
315
316         pMonitoredFd = (Integer*)__pMonitorFileList->GetValue(path);
317
318         SysTryReturnResult(NID_IO, pMonitoredFd != null, E_IO, "path[%ls] is not registered.", path.GetPointer());
319
320         SysTryReturnResult(NID_IO, inotify_rm_watch(__inotifyFd, pMonitoredFd->ToInt()) == 0,
321                                 E_IO, "path[%ls] is not registered.", path.GetPointer());
322
323         SysTryReturnResult(NID_IO, __pMonitorFileList->Remove(path, true) == E_SUCCESS,
324                                 E_IO, "path[%ls] is not registered.", path.GetPointer());
325         return E_SUCCESS;
326 }
327
328 String
329 _FileEventManagerImpl::GetRegisteredPath(int fd)
330 {
331         String* pRegisteredPath = null;
332         Integer* pRegisteredFD = null;
333
334         if (__pMonitorFileList == null)
335         {
336                 SysLog(NID_IO, "There is no path for fd:%d", fd);
337                 return "";
338         }
339
340         unique_ptr<IMapEnumerator> pEnumerator(__pMonitorFileList->GetMapEnumeratorN());
341         SysTryReturn(NID_IO, pEnumerator != null, L"", GetLastResult(), "[%s] Monitored file list is empty", GetErrorMessage(GetLastResult()));
342
343         while (pEnumerator && pEnumerator->MoveNext() == E_SUCCESS)
344         {
345                 pRegisteredPath = static_cast<String*> (pEnumerator->GetKey());
346                 pRegisteredFD = static_cast<Integer*> (pEnumerator->GetValue());
347
348                 if (fd == pRegisteredFD->ToInt())
349                 {
350                         SysLog(NID_IO, "Path is %ls", pRegisteredPath->GetPointer());
351                         return *pRegisteredPath;
352                 }
353
354         }
355
356         SysLog(NID_IO, "There is no path for fd:%d", fd);
357         return "";
358 }
359
360 _FileEventManagerImpl*
361 _FileEventManagerImpl::GetInstance(FileEventManager& fileEventManager)
362 {
363         return fileEventManager.__pFileEventManagerImpl;
364 }
365
366 const _FileEventManagerImpl*
367 _FileEventManagerImpl::GetInstance(const FileEventManager& fileEventManager)
368 {
369         return fileEventManager.__pFileEventManagerImpl;
370 }
371
372 }} // Tizen::Io
373