Log invalid inotify() events without a valid watch descriptor.
[wxWidgets.git] / src / unix / fswatcher_inotify.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/fswatcher_inotify.cpp
3 // Purpose: inotify-based wxFileSystemWatcher implementation
4 // Author: Bartosz Bekier
5 // Created: 2009-05-26
6 // RCS-ID: $Id$
7 // Copyright: (c) 2009 Bartosz Bekier <bartosz.bekier@gmail.com>
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 #if wxUSE_FSWATCHER
19
20 #include "wx/fswatcher.h"
21
22 #ifdef wxHAS_INOTIFY
23
24 #include <sys/inotify.h>
25 #include <unistd.h>
26 #include "wx/private/fswatcher.h"
27
28 // ============================================================================
29 // wxFSWatcherImpl implementation & helper wxFSWSourceHandler implementation
30 // ============================================================================
31
32 // inotify watch descriptor => wxFSWatchEntry* map
33 WX_DECLARE_HASH_MAP(int, wxFSWatchEntry*, wxIntegerHash, wxIntegerEqual,
34 wxFSWatchEntryDescriptors);
35
36 // inotify event cookie => inotify_event* map
37 WX_DECLARE_HASH_MAP(int, inotify_event*, wxIntegerHash, wxIntegerEqual,
38 wxInotifyCookies);
39
40 /**
41 * Helper class encapsulating inotify mechanism
42 */
43 class wxFSWatcherImplUnix : public wxFSWatcherImpl
44 {
45 public:
46 wxFSWatcherImplUnix(wxFileSystemWatcherBase* watcher) :
47 wxFSWatcherImpl(watcher),
48 m_source(NULL),
49 m_ifd(-1)
50 {
51 m_handler = new wxFSWSourceHandler(this);
52 }
53
54 ~wxFSWatcherImplUnix()
55 {
56 // we close inotify only if initialized before
57 if (IsOk())
58 {
59 Close();
60 }
61
62 delete m_handler;
63 }
64
65 bool Init()
66 {
67 wxCHECK_MSG( !IsOk(), false, "Inotify already initialized" );
68
69 wxEventLoopBase *loop = wxEventLoopBase::GetActive();
70 wxCHECK_MSG( loop, false, "File system watcher needs an event loop" );
71
72 m_ifd = inotify_init();
73 if ( m_ifd == -1 )
74 {
75 wxLogSysError( _("Unable to create inotify instance") );
76 return false;
77 }
78
79 m_source = loop->AddSourceForFD
80 (
81 m_ifd,
82 m_handler,
83 wxEVENT_SOURCE_INPUT | wxEVENT_SOURCE_EXCEPTION
84 );
85
86 return m_source != NULL;
87 }
88
89 void Close()
90 {
91 wxCHECK_RET( IsOk(),
92 "Inotify not initialized or invalid inotify descriptor" );
93
94 wxDELETE(m_source);
95
96 if ( close(m_ifd) != 0 )
97 {
98 wxLogSysError( _("Unable to close inotify instance") );
99 }
100 }
101
102 virtual bool DoAdd(wxSharedPtr<wxFSWatchEntryUnix> watch)
103 {
104 wxCHECK_MSG( IsOk(), false,
105 "Inotify not initialized or invalid inotify descriptor" );
106
107 int wd = DoAddInotify(watch.get());
108 if (wd == -1)
109 {
110 wxLogSysError( _("Unable to add inotify watch") );
111 return false;
112 }
113
114 wxFSWatchEntryDescriptors::value_type val(wd, watch.get());
115 if (!m_watchMap.insert(val).second)
116 {
117 wxFAIL_MSG( wxString::Format( "Path %s is already watched",
118 watch->GetPath()) );
119 return false;
120 }
121
122 return true;
123 }
124
125 virtual bool DoRemove(wxSharedPtr<wxFSWatchEntryUnix> watch)
126 {
127 wxCHECK_MSG( IsOk(), false,
128 "Inotify not initialized or invalid inotify descriptor" );
129
130 int ret = DoRemoveInotify(watch.get());
131 if (ret == -1)
132 {
133 wxLogSysError( _("Unable to remove inotify watch") );
134 return false;
135 }
136
137 if (m_watchMap.erase(watch->GetWatchDescriptor()) != 1)
138 {
139 wxFAIL_MSG( wxString::Format("Path %s is not watched",
140 watch->GetPath()) );
141 }
142 // Cache the wd in case any events arrive late
143 m_staleDescriptors.Add(watch->GetWatchDescriptor());
144
145 watch->SetWatchDescriptor(-1);
146 return true;
147 }
148
149 virtual bool RemoveAll()
150 {
151 wxFSWatchEntries::iterator it = m_watches.begin();
152 for ( ; it != m_watches.end(); ++it )
153 {
154 (void) DoRemove(it->second);
155 }
156 m_watches.clear();
157 return true;
158 }
159
160 int ReadEvents()
161 {
162 wxCHECK_MSG( IsOk(), -1,
163 "Inotify not initialized or invalid inotify descriptor" );
164
165 // read events
166 // TODO differentiate depending on params
167 char buf[128 * sizeof(inotify_event)];
168 int left = ReadEventsToBuf(buf, sizeof(buf));
169 if (left == -1)
170 return -1;
171
172 // left > 0, we have events
173 char* memory = buf;
174 int event_count = 0;
175 while (left > 0) // OPT checking 'memory' would suffice
176 {
177 event_count++;
178 inotify_event* e = (inotify_event*)memory;
179
180 // process one inotify_event
181 ProcessNativeEvent(*e);
182
183 int offset = sizeof(inotify_event) + e->len;
184 left -= offset;
185 memory += offset;
186 }
187
188 // take care of unmatched renames
189 ProcessRenames();
190
191 wxLogTrace(wxTRACE_FSWATCHER, "We had %d native events", event_count);
192 return event_count;
193 }
194
195 bool IsOk() const
196 {
197 return m_source != NULL;
198 }
199
200 protected:
201 int DoAddInotify(wxFSWatchEntry* watch)
202 {
203 int flags = Watcher2NativeFlags(watch->GetFlags());
204 int wd = inotify_add_watch(m_ifd, watch->GetPath().fn_str(), flags);
205 // finally we can set watch descriptor
206 watch->SetWatchDescriptor(wd);
207 return wd;
208 }
209
210 int DoRemoveInotify(wxFSWatchEntry* watch)
211 {
212 return inotify_rm_watch(m_ifd, watch->GetWatchDescriptor());
213 }
214
215 void ProcessNativeEvent(const inotify_event& inevt)
216 {
217 wxLogTrace(wxTRACE_FSWATCHER, InotifyEventToString(inevt));
218
219 // after removing inotify watch we get IN_IGNORED for it, but the watch
220 // will be already removed from our list at that time
221 if (inevt.mask & IN_IGNORED)
222 {
223 // It is now safe to remove it from the stale descriptors too, we
224 // won't get any more events for it.
225 // However if we're here because a dir that we're still watching
226 // has just been deleted, its wd won't be on this list
227 const int pos = m_staleDescriptors.Index(inevt.wd);
228 if ( pos != wxNOT_FOUND )
229 {
230 m_staleDescriptors.RemoveAt(static_cast<size_t>(pos));
231 wxLogTrace(wxTRACE_FSWATCHER,
232 "Removed wd %i from the stale-wd cache", inevt.wd);
233 }
234 return;
235 }
236
237 // get watch entry for this event
238 wxFSWatchEntryDescriptors::iterator it = m_watchMap.find(inevt.wd);
239
240 // wd will be -1 for IN_Q_OVERFLOW, which would trigger the wxFAIL_MSG
241 if (inevt.wd != -1)
242 {
243 if (it == m_watchMap.end())
244 {
245 // It's not in the map; check if was recently removed from it.
246 if (m_staleDescriptors.Index(inevt.wd) != wxNOT_FOUND)
247 {
248 wxLogTrace(wxTRACE_FSWATCHER,
249 "Got an event for stale wd %i", inevt.wd);
250 }
251 else
252 {
253 wxFAIL_MSG("Event for unknown watch descriptor.");
254 }
255
256 // In any case, don't process this event: it's either for an
257 // already removed entry, or for a completely unknown one.
258 return;
259 }
260 }
261
262 int nativeFlags = inevt.mask;
263 int flags = Native2WatcherFlags(nativeFlags);
264
265 // check out for error/warning condition
266 if (flags & wxFSW_EVENT_WARNING || flags & wxFSW_EVENT_ERROR)
267 {
268 wxString errMsg = GetErrorDescription(nativeFlags);
269 wxFileSystemWatcherEvent event(flags, errMsg);
270 SendEvent(event);
271 return;
272 }
273
274 if (inevt.wd == -1)
275 {
276 // Although this is not supposed to happen, we seem to be getting
277 // occasional IN_ACCESS/IN_MODIFY events without valid watch value.
278 wxFileSystemWatcherEvent
279 event
280 (
281 wxFSW_EVENT_WARNING,
282 wxString::Format
283 (
284 _("Invalid inotify event for \"%s\""),
285 inevt.len ? inevt.name : ""
286 )
287 );
288 SendEvent(event);
289 return;
290 }
291
292 wxFSWatchEntry& watch = *(it->second);
293
294 // Now IN_UNMOUNT. We must do so here, as it's not in the watch flags
295 if (nativeFlags & IN_UNMOUNT)
296 {
297 wxFileName path = GetEventPath(watch, inevt);
298 wxFileSystemWatcherEvent event(wxFSW_EVENT_UNMOUNT, path, path);
299 SendEvent(event);
300 }
301 // filter out ignored events and those not asked for.
302 // we never filter out warnings or exceptions
303 else if ((flags == 0) || !(flags & watch.GetFlags()))
304 {
305 return;
306 }
307
308 // Creation
309 // We need do something here only if the original watch was recursive;
310 // we don't watch a child dir itself inside a non-tree watch.
311 // We watch only dirs explicitly, so we don't want file IN_CREATEs.
312 // Distinguish by whether nativeFlags contain IN_ISDIR
313 else if ((nativeFlags & IN_CREATE) &&
314 (watch.GetType() == wxFSWPath_Tree) && (inevt.mask & IN_ISDIR))
315 {
316 wxFileName fn = GetEventPath(watch, inevt);
317 // Though it's a dir, fn treats it as a file. So:
318 fn.AssignDir(fn.GetFullPath());
319
320 if (m_watcher->AddAny(fn, wxFSW_EVENT_ALL,
321 wxFSWPath_Tree, watch.GetFilespec()))
322 {
323 // Tell the owner, in case it's interested
324 // If there's a filespec, assume he's not
325 if (watch.GetFilespec().empty())
326 {
327 wxFileSystemWatcherEvent event(flags, fn, fn);
328 SendEvent(event);
329 }
330 }
331 }
332
333 // Deletion
334 // We watch only dirs explicitly, so we don't want file IN_DELETEs.
335 // We obviously can't check using DirExists() as the object has been
336 // deleted; and nativeFlags here doesn't contain IN_ISDIR, even for
337 // a dir. Fortunately IN_DELETE_SELF doesn't happen for files. We need
338 // to do something here only inside a tree watch, or if it's the parent
339 // dir that's deleted. Otherwise let the parent dir cope
340 else if ((nativeFlags & IN_DELETE_SELF) &&
341 ((watch.GetType() == wxFSWPath_Dir) ||
342 (watch.GetType() == wxFSWPath_Tree)))
343 {
344 // We must remove the deleted directory from the map, so that
345 // DoRemoveInotify() isn't called on it in the future. Don't assert
346 // if the wd isn't found: repeated IN_DELETE_SELFs can occur
347 wxFileName fn = GetEventPath(watch, inevt);
348 wxString path(fn.GetPathWithSep());
349
350 if (m_watchMap.erase(inevt.wd) == 1)
351 {
352 // Delete from wxFileSystemWatcher
353 wxDynamicCast(m_watcher, wxInotifyFileSystemWatcher)->
354 OnDirDeleted(path);
355
356 // Now remove from our local list of watched items
357 wxFSWatchEntries::iterator wit =
358 m_watches.find(path);
359 if (wit != m_watches.end())
360 {
361 m_watches.erase(wit);
362 }
363
364 // Cache the wd in case any events arrive late
365 m_staleDescriptors.Add(inevt.wd);
366 }
367
368 // Tell the owner, in case it's interested
369 // If there's a filespec, assume he's not
370 if (watch.GetFilespec().empty())
371 {
372 wxFileSystemWatcherEvent event(flags, fn, fn);
373 SendEvent(event);
374 }
375 }
376
377 // renames
378 else if (nativeFlags & IN_MOVE)
379 {
380 wxInotifyCookies::iterator it2 = m_cookies.find(inevt.cookie);
381 if ( it2 == m_cookies.end() )
382 {
383 int size = sizeof(inevt) + inevt.len;
384 inotify_event* e = (inotify_event*) operator new (size);
385 memcpy(e, &inevt, size);
386
387 wxInotifyCookies::value_type val(e->cookie, e);
388 m_cookies.insert(val);
389 }
390 else
391 {
392 inotify_event& oldinevt = *(it2->second);
393
394 // Tell the owner, in case it's interested
395 // If there's a filespec, assume he's not
396 if ( watch.GetFilespec().empty() )
397 {
398 wxFileSystemWatcherEvent event(flags);
399 if ( inevt.mask & IN_MOVED_FROM )
400 {
401 event.SetPath(GetEventPath(watch, inevt));
402 event.SetNewPath(GetEventPath(watch, oldinevt));
403 }
404 else
405 {
406 event.SetPath(GetEventPath(watch, oldinevt));
407 event.SetNewPath(GetEventPath(watch, inevt));
408 }
409 SendEvent(event);
410 }
411
412 m_cookies.erase(it2);
413 delete &oldinevt;
414 }
415 }
416 // every other kind of event
417 else
418 {
419 wxFileName path = GetEventPath(watch, inevt);
420 // For files, check that it matches any filespec
421 if ( MatchesFilespec(path, watch.GetFilespec()) )
422 {
423 wxFileSystemWatcherEvent event(flags, path, path);
424 SendEvent(event);
425 }
426 }
427 }
428
429 void ProcessRenames()
430 {
431 wxInotifyCookies::iterator it = m_cookies.begin();
432 while ( it != m_cookies.end() )
433 {
434 inotify_event& inevt = *(it->second);
435
436 wxLogTrace(wxTRACE_FSWATCHER, "Processing pending rename events");
437 wxLogTrace(wxTRACE_FSWATCHER, InotifyEventToString(inevt));
438
439 // get watch entry for this event
440 wxFSWatchEntryDescriptors::iterator wit = m_watchMap.find(inevt.wd);
441 wxCHECK_RET(wit != m_watchMap.end(),
442 "Watch descriptor not present in the watch map!");
443
444 // Tell the owner, in case it's interested
445 // If there's a filespec, assume he's not
446 wxFSWatchEntry& watch = *(wit->second);
447 if ( watch.GetFilespec().empty() )
448 {
449 int flags = Native2WatcherFlags(inevt.mask);
450 wxFileName path = GetEventPath(watch, inevt);
451 {
452 wxFileSystemWatcherEvent event(flags, path, path);
453 SendEvent(event);
454 }
455 }
456
457 m_cookies.erase(it);
458 delete &inevt;
459 it = m_cookies.begin();
460 }
461 }
462
463 void SendEvent(wxFileSystemWatcherEvent& evt)
464 {
465 wxLogTrace(wxTRACE_FSWATCHER, evt.ToString());
466 m_watcher->GetOwner()->ProcessEvent(evt);
467 }
468
469 int ReadEventsToBuf(char* buf, int size)
470 {
471 wxCHECK_MSG( IsOk(), false,
472 "Inotify not initialized or invalid inotify descriptor" );
473
474 memset(buf, 0, size);
475 ssize_t left = read(m_ifd, buf, size);
476 if (left == -1)
477 {
478 wxLogSysError(_("Unable to read from inotify descriptor"));
479 return -1;
480 }
481 else if (left == 0)
482 {
483 wxLogWarning(_("EOF while reading from inotify descriptor"));
484 return -1;
485 }
486
487 return left;
488 }
489
490 static wxString InotifyEventToString(const inotify_event& inevt)
491 {
492 wxString mask = (inevt.mask & IN_ISDIR) ?
493 wxString::Format("IS_DIR | %u", inevt.mask & ~IN_ISDIR) :
494 wxString::Format("%u", inevt.mask);
495 const char* name = "";
496 if (inevt.len)
497 name = inevt.name;
498 return wxString::Format("Event: wd=%d, mask=%s, cookie=%u, len=%u, "
499 "name=%s", inevt.wd, mask, inevt.cookie,
500 inevt.len, name);
501 }
502
503 static wxFileName GetEventPath(const wxFSWatchEntry& watch,
504 const inotify_event& inevt)
505 {
506 // only when dir is watched, we have non-empty e.name
507 wxFileName path = watch.GetPath();
508 if (path.IsDir() && inevt.len)
509 {
510 path = wxFileName(path.GetPath(), inevt.name);
511 }
512 return path;
513 }
514
515 static int Watcher2NativeFlags(int flags)
516 {
517 // Start with the standard case of wanting all events
518 if (flags == wxFSW_EVENT_ALL)
519 {
520 return IN_ALL_EVENTS;
521 }
522
523 static const int flag_mapping[][2] = {
524 { wxFSW_EVENT_ACCESS, IN_ACCESS },
525 { wxFSW_EVENT_MODIFY, IN_MODIFY },
526 { wxFSW_EVENT_ATTRIB, IN_ATTRIB },
527 { wxFSW_EVENT_RENAME, IN_MOVE },
528 { wxFSW_EVENT_CREATE, IN_CREATE },
529 { wxFSW_EVENT_DELETE, IN_DELETE|IN_DELETE_SELF|IN_MOVE_SELF },
530 { wxFSW_EVENT_UNMOUNT, IN_UNMOUNT }
531 // wxFSW_EVENT_ERROR/WARNING make no sense here
532 };
533
534 int native_flags = 0;
535 for ( unsigned int i=0; i < WXSIZEOF(flag_mapping); ++i)
536 {
537 if (flags & flag_mapping[i][0])
538 native_flags |= flag_mapping[i][1];
539 }
540
541 return native_flags;
542 }
543
544 static int Native2WatcherFlags(int flags)
545 {
546 static const int flag_mapping[][2] = {
547 { IN_ACCESS, wxFSW_EVENT_ACCESS }, // generated during read!
548 { IN_MODIFY, wxFSW_EVENT_MODIFY },
549 { IN_ATTRIB, wxFSW_EVENT_ATTRIB },
550 { IN_CLOSE_WRITE, 0 },
551 { IN_CLOSE_NOWRITE, 0 },
552 { IN_OPEN, 0 },
553 { IN_MOVED_FROM, wxFSW_EVENT_RENAME },
554 { IN_MOVED_TO, wxFSW_EVENT_RENAME },
555 { IN_CREATE, wxFSW_EVENT_CREATE },
556 { IN_DELETE, wxFSW_EVENT_DELETE },
557 { IN_DELETE_SELF, wxFSW_EVENT_DELETE },
558 { IN_MOVE_SELF, wxFSW_EVENT_DELETE },
559
560 { IN_UNMOUNT, wxFSW_EVENT_UNMOUNT},
561 { IN_Q_OVERFLOW, wxFSW_EVENT_WARNING},
562
563 // ignored, because this is generated mainly by watcher::Remove()
564 { IN_IGNORED, 0 }
565 };
566
567 unsigned int i=0;
568 for ( ; i < WXSIZEOF(flag_mapping); ++i) {
569 // in this mapping multiple flags at once don't happen
570 if (flags & flag_mapping[i][0])
571 return flag_mapping[i][1];
572 }
573
574 // never reached
575 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flags));
576 return -1;
577 }
578
579 /**
580 * Returns error description for specified inotify mask
581 */
582 static const wxString GetErrorDescription(int flag)
583 {
584 switch ( flag )
585 {
586 case IN_Q_OVERFLOW:
587 return _("Event queue overflowed");
588 }
589
590 // never reached
591 wxFAIL_MSG(wxString::Format("Unknown inotify event mask %u", flag));
592 return wxEmptyString;
593 }
594
595 wxFSWSourceHandler* m_handler; // handler for inotify event source
596 wxFSWatchEntryDescriptors m_watchMap; // inotify wd=>wxFSWatchEntry* map
597 wxArrayInt m_staleDescriptors; // stores recently-removed watches
598 wxInotifyCookies m_cookies; // map to track renames
599 wxEventLoopSource* m_source; // our event loop source
600
601 // file descriptor created by inotify_init()
602 int m_ifd;
603 };
604
605
606 // ============================================================================
607 // wxFSWSourceHandler implementation
608 // ============================================================================
609
610 // once we get signaled to read, actuall event reading occurs
611 void wxFSWSourceHandler::OnReadWaiting()
612 {
613 wxLogTrace(wxTRACE_FSWATCHER, "--- OnReadWaiting ---");
614 m_service->ReadEvents();
615 }
616
617 void wxFSWSourceHandler::OnWriteWaiting()
618 {
619 wxFAIL_MSG("We never write to inotify descriptor.");
620 }
621
622 void wxFSWSourceHandler::OnExceptionWaiting()
623 {
624 wxFAIL_MSG("We never receive exceptions on inotify descriptor.");
625 }
626
627
628 // ============================================================================
629 // wxInotifyFileSystemWatcher implementation
630 // ============================================================================
631
632 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher()
633 : wxFileSystemWatcherBase()
634 {
635 Init();
636 }
637
638 wxInotifyFileSystemWatcher::wxInotifyFileSystemWatcher(const wxFileName& path,
639 int events)
640 : wxFileSystemWatcherBase()
641 {
642 if (!Init())
643 {
644 if (m_service)
645 delete m_service;
646 return;
647 }
648
649 Add(path, events);
650 }
651
652 wxInotifyFileSystemWatcher::~wxInotifyFileSystemWatcher()
653 {
654 }
655
656 bool wxInotifyFileSystemWatcher::Init()
657 {
658 m_service = new wxFSWatcherImplUnix(this);
659 return m_service->Init();
660 }
661
662 void wxInotifyFileSystemWatcher::OnDirDeleted(const wxString& path)
663 {
664 if (!path.empty())
665 {
666 wxFSWatchInfoMap::iterator it = m_watches.find(path);
667 wxCHECK_RET(it != m_watches.end(),
668 wxString::Format("Path '%s' is not watched", path));
669
670 // path has been deleted, so we must forget it whatever its refcount
671 m_watches.erase(it);
672 }
673 }
674
675 #endif // wxHAS_INOTIFY
676
677 #endif // wxUSE_FSWATCHER