• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.8.5 API Reference
  • KDE Home
  • Contact Us
 

KDECore

  • kdecore
  • io
kdirwatch.cpp
Go to the documentation of this file.
1 /* This file is part of the KDE libraries
2  Copyright (C) 1998 Sven Radej <sven@lisa.exp.univie.ac.at>
3  Copyright (C) 2006 Dirk Mueller <mueller@kde.org>
4  Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com>
5  Copyright (C) 2008 Rafal Rzepecki <divided.mind@gmail.com>
6  Copyright (C) 2010 David Faure <faure@kde.org>
7 
8  This library is free software; you can redistribute it and/or
9  modify it under the terms of the GNU Library General Public
10  License version 2 as published by the Free Software Foundation.
11 
12  This library is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Library General Public License for more details.
16 
17  You should have received a copy of the GNU Library General Public License
18  along with this library; see the file COPYING.LIB. If not, write to
19  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20  Boston, MA 02110-1301, USA.
21 */
22 
23 
24 // CHANGES:
25 // Jul 30, 2008 - Don't follow symlinks when recursing to avoid loops (Rafal)
26 // Aug 6, 2007 - KDirWatch::WatchModes support complete, flags work fine also
27 // when using FAMD (Flavio Castelli)
28 // Aug 3, 2007 - Handled KDirWatch::WatchModes flags when using inotify, now
29 // recursive and file monitoring modes are implemented (Flavio Castelli)
30 // Jul 30, 2007 - Substituted addEntry boolean params with KDirWatch::WatchModes
31 // flag (Flavio Castelli)
32 // Oct 4, 2005 - Inotify support (Dirk Mueller)
33 // Februar 2002 - Add file watching and remote mount check for STAT
34 // Mar 30, 2001 - Native support for Linux dir change notification.
35 // Jan 28, 2000 - Usage of FAM service on IRIX (Josef.Weidendorfer@in.tum.de)
36 // May 24. 1998 - List of times introduced, and some bugs are fixed. (sven)
37 // May 23. 1998 - Removed static pointer - you can have more instances.
38 // It was Needed for KRegistry. KDirWatch now emits signals and doesn't
39 // call (or need) KFM. No more URL's - just plain paths. (sven)
40 // Mar 29. 1998 - added docs, stop/restart for particular Dirs and
41 // deep copies for list of dirs. (sven)
42 // Mar 28. 1998 - Created. (sven)
43 
44 #include "kdirwatch.h"
45 #include "kdirwatch_p.h"
46 #include "kfilesystemtype_p.h"
47 
48 #include <io/config-kdirwatch.h>
49 #include <config.h>
50 
51 #include <sys/stat.h>
52 #include <assert.h>
53 #include <errno.h>
54 #include <QtCore/QDir>
55 #include <QtCore/QFile>
56 #include <QtCore/QSocketNotifier>
57 #include <QtCore/QTimer>
58 #include <QtCore/QCoreApplication>
59 
60 #include <ksharedconfig.h>
61 #include <kdebug.h>
62 #include <kconfig.h>
63 #include <kglobal.h>
64 #include <kde_file.h>
65 #include <kconfiggroup.h>
66 
67 #include <stdlib.h>
68 #include <string.h>
69 
70 // debug
71 #include <sys/ioctl.h>
72 
73 
74 #include <sys/utsname.h>
75 
76 // set this to true for much more verbose debug output
77 static const bool s_verboseDebug = false;
78 
79 // The KDirWatchPrivate instance is refcounted, and deleted by the last KDirWatch instance
80 static KDirWatchPrivate* dwp_self = 0;
81 static KDirWatchPrivate* createPrivate() {
82  if (!dwp_self)
83  dwp_self = new KDirWatchPrivate;
84  return dwp_self;
85 }
86 
87 // Convert a string into a watch Method
88 static KDirWatch::Method methodFromString(const QString& method) {
89  if (method == QLatin1String("Fam")) {
90  return KDirWatch::FAM;
91  } else if (method == QLatin1String("Stat")) {
92  return KDirWatch::Stat;
93  } else if (method == QLatin1String("QFSWatch")) {
94  return KDirWatch::QFSWatch;
95  } else {
96 #ifdef Q_OS_LINUX
97  // inotify supports delete+recreate+modify, which QFSWatch doesn't support
98  return KDirWatch::INotify;
99 #else
100  return KDirWatch::QFSWatch;
101 #endif
102  }
103 }
104 
105 #ifndef NDEBUG
106 static const char* methodToString(KDirWatch::Method method)
107 {
108  switch (method) {
109  case KDirWatch::FAM:
110  return "Fam";
111  case KDirWatch::INotify:
112  return "INotify";
113  case KDirWatch::DNotify:
114  return "DNotify";
115  case KDirWatch::Stat:
116  return "Stat";
117  case KDirWatch::QFSWatch:
118  return "QFSWatch";
119  default:
120  return "ERROR!";
121  }
122 }
123 #endif
124 
125 //
126 // Class KDirWatchPrivate (singleton)
127 //
128 
129 /* All entries (files/directories) to be watched in the
130  * application (coming from multiple KDirWatch instances)
131  * are registered in a single KDirWatchPrivate instance.
132  *
133  * At the moment, the following methods for file watching
134  * are supported:
135  * - Polling: All files to be watched are polled regularly
136  * using stat (more precise: QFileInfo.lastModified()).
137  * The polling frequency is determined from global kconfig
138  * settings, defaulting to 500 ms for local directories
139  * and 5000 ms for remote mounts
140  * - FAM (File Alternation Monitor): first used on IRIX, SGI
141  * has ported this method to LINUX. It uses a kernel part
142  * (IMON, sending change events to /dev/imon) and a user
143  * level damon (fam), to which applications connect for
144  * notification of file changes. For NFS, the fam damon
145  * on the NFS server machine is used; if IMON is not built
146  * into the kernel, fam uses polling for local files.
147  * - INOTIFY: In LINUX 2.6.13, inode change notification was
148  * introduced. You're now able to watch arbitrary inode's
149  * for changes, and even get notification when they're
150  * unmounted.
151  */
152 
153 KDirWatchPrivate::KDirWatchPrivate()
154  : timer(),
155  freq( 3600000 ), // 1 hour as upper bound
156  statEntries( 0 ),
157  m_ref( 0 ),
158  delayRemove( false ),
159  rescan_all( false ),
160  rescan_timer()
161 {
162  timer.setObjectName(QLatin1String("KDirWatchPrivate::timer"));
163  connect (&timer, SIGNAL(timeout()), this, SLOT(slotRescan()));
164 
165  KConfigGroup config(KGlobal::config(), "DirWatch");
166  m_nfsPollInterval = config.readEntry("NFSPollInterval", 5000);
167  m_PollInterval = config.readEntry("PollInterval", 500);
168 
169  QString method = config.readEntry("PreferredMethod", "inotify");
170  m_preferredMethod = methodFromString(method);
171 
172  // The nfs method defaults to the normal (local) method
173  m_nfsPreferredMethod = methodFromString(config.readEntry("nfsPreferredMethod", "Fam"));
174 
175  QList<QByteArray> availableMethods;
176 
177  availableMethods << "Stat";
178 
179  // used for FAM and inotify
180  rescan_timer.setObjectName(QString::fromLatin1("KDirWatchPrivate::rescan_timer"));
181  rescan_timer.setSingleShot( true );
182  connect(&rescan_timer, SIGNAL(timeout()), this, SLOT(slotRescan()));
183 
184 #ifdef HAVE_FAM
185  // It's possible that FAM server can't be started
186  if (FAMOpen(&fc) ==0) {
187  availableMethods << "FAM";
188  use_fam=true;
189  sn = new QSocketNotifier( FAMCONNECTION_GETFD(&fc),
190  QSocketNotifier::Read, this);
191  connect( sn, SIGNAL(activated(int)),
192  this, SLOT(famEventReceived()) );
193  }
194  else {
195  kDebug(7001) << "Can't use FAM (fam daemon not running?)";
196  use_fam=false;
197  }
198 #endif
199 
200 #ifdef HAVE_SYS_INOTIFY_H
201  supports_inotify = true;
202 
203  m_inotify_fd = inotify_init();
204 
205  if ( m_inotify_fd <= 0 ) {
206  kDebug(7001) << "Can't use Inotify, kernel doesn't support it";
207  supports_inotify = false;
208  }
209 
210  {
211  struct utsname uts;
212  int major, minor, patch;
213  if (uname(&uts) < 0) {
214  supports_inotify = false;
215  kDebug(7001) << "Unable to get uname";
216  } else if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
217  supports_inotify = false;
218  kDebug(7001) << "The version is malformed: " << uts.release;
219  } else if(major == 2 && minor == 6) { // If it is 2.6 check further...
220  if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &patch) != 3) {
221  supports_inotify = false;
222  kDebug() << "Detected 2.6 kernel but can't know more: " << uts.release;
223  } else if (major * 1000000 + minor * 1000 + patch < 2006014 ){
224  supports_inotify = false;
225  kDebug(7001) << "Can't use INotify, Linux kernel too old " << uts.release;
226  }
227  }
228  }
229 
230  kDebug(7001) << "INotify available: " << supports_inotify;
231  if ( supports_inotify ) {
232  availableMethods << "INotify";
233  fcntl(m_inotify_fd, F_SETFD, FD_CLOEXEC);
234 
235  mSn = new QSocketNotifier( m_inotify_fd, QSocketNotifier::Read, this );
236  connect( mSn, SIGNAL(activated(int)),
237  this, SLOT(inotifyEventReceived()) );
238  }
239 #endif
240 #ifdef HAVE_QFILESYSTEMWATCHER
241  availableMethods << "QFileSystemWatcher";
242  fsWatcher = 0;
243 #endif
244 #ifndef NDEBUG
245  kDebug(7001) << "Available methods: " << availableMethods << "preferred=" << methodToString(m_preferredMethod);
246 #endif
247 }
248 
249 // This is called on app exit (when K_GLOBAL_STATIC deletes KDirWatch::self)
250 KDirWatchPrivate::~KDirWatchPrivate()
251 {
252  timer.stop();
253 
254  /* remove all entries being watched */
255  removeEntries(0);
256 
257 #ifdef HAVE_FAM
258  if (use_fam) {
259  FAMClose(&fc);
260  }
261 #endif
262 #ifdef HAVE_SYS_INOTIFY_H
263  if ( supports_inotify )
264  ::close( m_inotify_fd );
265 #endif
266 #ifdef HAVE_QFILESYSTEMWATCHER
267  delete fsWatcher;
268 #endif
269 }
270 
271 void KDirWatchPrivate::inotifyEventReceived()
272 {
273  //kDebug(7001);
274 #ifdef HAVE_SYS_INOTIFY_H
275  if ( !supports_inotify )
276  return;
277 
278  int pending = -1;
279  int offsetStartRead = 0; // where we read into buffer
280  char buf[8192];
281  assert( m_inotify_fd > -1 );
282  ioctl( m_inotify_fd, FIONREAD, &pending );
283 
284  while ( pending > 0 ) {
285 
286  const int bytesToRead = qMin( pending, (int)sizeof( buf ) - offsetStartRead );
287 
288  int bytesAvailable = read( m_inotify_fd, &buf[offsetStartRead], bytesToRead );
289  pending -= bytesAvailable;
290  bytesAvailable += offsetStartRead;
291  offsetStartRead = 0;
292 
293  int offsetCurrent = 0;
294  while ( bytesAvailable >= (int)sizeof( struct inotify_event ) ) {
295  const struct inotify_event * const event = (struct inotify_event *) &buf[offsetCurrent];
296  const int eventSize = sizeof( struct inotify_event ) + event->len;
297  if ( bytesAvailable < eventSize ) {
298  break;
299  }
300 
301  bytesAvailable -= eventSize;
302  offsetCurrent += eventSize;
303 
304  QString path;
305  QByteArray cpath(event->name, event->len);
306  if(event->len)
307  path = QFile::decodeName ( cpath );
308 
309  if ( path.length() && isNoisyFile( cpath ) )
310  continue;
311 
312  // now we're in deep trouble of finding the
313  // associated entries
314  // for now, we suck and iterate
315  for ( EntryMap::Iterator it = m_mapEntries.begin();
316  it != m_mapEntries.end(); ) {
317  Entry* e = &( *it );
318  ++it;
319  if ( e->wd == event->wd ) {
320  e->dirty = true;
321 
322  //if (s_verboseDebug) {
323  // kDebug(7001) << "got event" << "0x"+QString::number(event->mask, 16) << "for" << e->path;
324  //}
325 
326  if( event->mask & IN_DELETE_SELF) {
327  if (s_verboseDebug) {
328  kDebug(7001) << "-->got deleteself signal for" << e->path;
329  }
330  e->m_status = NonExistent;
331  e->wd = -1;
332  e->m_ctime = invalid_ctime;
333  emitEvent(e, Deleted, e->path);
334  // Add entry to parent dir to notice if the entry gets recreated
335  addEntry(0, e->parentDirectory(), e, true /*isDir*/);
336  }
337  if ( event->mask & IN_IGNORED ) {
338  // Causes bug #207361 with kernels 2.6.31 and 2.6.32!
339  //e->wd = -1;
340  }
341  if ( event->mask & (IN_CREATE|IN_MOVED_TO) ) {
342  const QString tpath = e->path + QLatin1Char('/') + path;
343  Entry* sub_entry = e->findSubEntry(tpath);
344 
345  if (s_verboseDebug) {
346  kDebug(7001) << "-->got CREATE signal for" << (tpath) << "sub_entry=" << sub_entry;
347  kDebug(7001) << *e;
348  }
349 
350  // The code below is very similar to the one in checkFAMEvent...
351  if (sub_entry) {
352  // We were waiting for this new file/dir to be created
353  sub_entry->dirty = true;
354  rescan_timer.start(0); // process this asap, to start watching that dir
355  } else if (e->isDir && !e->m_clients.empty()) {
356  bool isDir = false;
357  const QList<Client *> clients = e->clientsForFileOrDir(tpath, &isDir);
358  Q_FOREACH(Client *client, clients) {
359  // See discussion in addEntry for why we don't addEntry for individual
360  // files in WatchFiles mode with inotify.
361  if (isDir) {
362  addEntry(client->instance, tpath, 0, isDir,
363  isDir ? client->m_watchModes : KDirWatch::WatchDirOnly);
364  }
365  }
366  if (!clients.isEmpty()) {
367  emitEvent(e, Created, tpath);
368  kDebug(7001).nospace() << clients.count() << " instance(s) monitoring the new "
369  << (isDir ? "dir " : "file ") << tpath;
370  }
371  e->m_pendingFileChanges.append(e->path);
372  if (!rescan_timer.isActive())
373  rescan_timer.start(m_PollInterval); // singleshot
374  }
375  }
376  if (event->mask & (IN_DELETE|IN_MOVED_FROM)) {
377  const QString tpath = e->path + QLatin1Char('/') + path;
378  if (s_verboseDebug) {
379  kDebug(7001) << "-->got DELETE signal for" << tpath;
380  }
381  if ((e->isDir) && (!e->m_clients.empty())) {
382  Client* client = 0;
383  // A file in this directory has been removed. It wasn't an explicitly
384  // watched file as it would have its own watch descriptor, so
385  // no addEntry/ removeEntry bookkeeping should be required. Emit
386  // the event immediately if any clients are interested.
387  KDE_struct_stat stat_buf;
388  // Unlike clientsForFileOrDir, the stat can fail here (item deleted),
389  // so in that case we'll just take both kinds of clients and emit Deleted.
390  KDirWatch::WatchModes flag = KDirWatch::WatchSubDirs | KDirWatch::WatchFiles;
391  if (KDE::stat(tpath, &stat_buf) == 0) {
392  bool isDir = S_ISDIR(stat_buf.st_mode);
393  flag = isDir ? KDirWatch::WatchSubDirs : KDirWatch::WatchFiles;
394  }
395  int counter = 0;
396  Q_FOREACH(client, e->m_clients) { // krazy:exclude=foreach
397  if (client->m_watchModes & flag) {
398  counter++;
399  }
400  }
401  if (counter != 0) {
402  emitEvent(e, Deleted, tpath);
403  }
404  }
405  }
406  if (event->mask & (IN_MODIFY|IN_ATTRIB)) {
407  if ((e->isDir) && (!e->m_clients.empty())) {
408  const QString tpath = e->path + QLatin1Char('/') + path;
409  if (s_verboseDebug) {
410  kDebug(7001) << "-->got MODIFY signal for" << (tpath);
411  }
412  // A file in this directory has been changed. No
413  // addEntry/ removeEntry bookkeeping should be required.
414  // Add the path to the list of pending file changes if
415  // there are any interested clients.
416  //KDE_struct_stat stat_buf;
417  //QByteArray tpath = QFile::encodeName(e->path+'/'+path);
418  //KDE_stat(tpath, &stat_buf);
419  //bool isDir = S_ISDIR(stat_buf.st_mode);
420 
421  // The API doc is somewhat vague as to whether we should emit
422  // dirty() for implicitly watched files when WatchFiles has
423  // not been specified - we'll assume they are always interested,
424  // regardless.
425  // Don't worry about duplicates for the time
426  // being; this is handled in slotRescan.
427  e->m_pendingFileChanges.append(tpath);
428  }
429  }
430 
431  if (!rescan_timer.isActive())
432  rescan_timer.start(m_PollInterval); // singleshot
433 
434  break;
435  }
436  }
437  }
438  if (bytesAvailable > 0) {
439  // copy partial event to beginning of buffer
440  memmove(buf, &buf[offsetCurrent], bytesAvailable);
441  offsetStartRead = bytesAvailable;
442  }
443  }
444 #endif
445 }
446 
447 /* In FAM mode, only entries which are marked dirty are scanned.
448  * We first need to mark all yet nonexistent, but possible created
449  * entries as dirty...
450  */
451 void KDirWatchPrivate::Entry::propagate_dirty()
452 {
453  foreach(Entry *sub_entry, m_entries)
454  {
455  if (!sub_entry->dirty)
456  {
457  sub_entry->dirty = true;
458  sub_entry->propagate_dirty();
459  }
460  }
461 }
462 
463 
464 /* A KDirWatch instance is interested in getting events for
465  * this file/Dir entry.
466  */
467 void KDirWatchPrivate::Entry::addClient(KDirWatch* instance,
468  KDirWatch::WatchModes watchModes)
469 {
470  if (instance == 0)
471  return;
472 
473  foreach(Client* client, m_clients) {
474  if (client->instance == instance) {
475  client->count++;
476  client->m_watchModes = watchModes;
477  return;
478  }
479  }
480 
481  Client* client = new Client;
482  client->instance = instance;
483  client->count = 1;
484  client->watchingStopped = instance->isStopped();
485  client->pending = NoChange;
486  client->m_watchModes = watchModes;
487 
488  m_clients.append(client);
489 }
490 
491 void KDirWatchPrivate::Entry::removeClient(KDirWatch* instance)
492 {
493  QList<Client *>::iterator it = m_clients.begin();
494  const QList<Client *>::iterator end = m_clients.end();
495  for ( ; it != end ; ++it ) {
496  Client* client = *it;
497  if (client->instance == instance) {
498  client->count--;
499  if (client->count == 0) {
500  m_clients.erase(it);
501  delete client;
502  }
503  return;
504  }
505  }
506 }
507 
508 /* get number of clients */
509 int KDirWatchPrivate::Entry::clientCount() const
510 {
511  int clients = 0;
512  foreach(Client* client, m_clients)
513  clients += client->count;
514 
515  return clients;
516 }
517 
518 QString KDirWatchPrivate::Entry::parentDirectory() const
519 {
520  return QDir::cleanPath(path + QLatin1String("/.."));
521 }
522 
523 QList<KDirWatchPrivate::Client *> KDirWatchPrivate::Entry::clientsForFileOrDir(const QString& tpath, bool* isDir) const
524 {
525  QList<Client *> ret;
526  KDE_struct_stat stat_buf;
527  if (KDE::stat(tpath, &stat_buf) == 0) {
528  *isDir = S_ISDIR(stat_buf.st_mode);
529  const KDirWatch::WatchModes flag =
530  *isDir ? KDirWatch::WatchSubDirs : KDirWatch::WatchFiles;
531  Q_FOREACH(Client *client, this->m_clients) {
532  if (client->m_watchModes & flag) {
533  ret.append(client);
534  }
535  }
536  } else {
537  // Happens frequently, e.g. ERROR: couldn't stat "/home/dfaure/.viminfo.tmp"
538  //kDebug(7001) << "ERROR: couldn't stat" << tpath;
539  }
540  // If KDE_stat fails then isDir is not set, but ret is empty anyway
541  // so isDir won't be used.
542  return ret;
543 }
544 
545 QDebug operator<<(QDebug debug, const KDirWatchPrivate::Entry &entry)
546 {
547  debug.nospace() << "[ Entry for " << entry.path << ", " << (entry.isDir ? "dir" : "file");
548  if (entry.m_status == KDirWatchPrivate::NonExistent)
549  debug << ", non-existent";
550  debug << ", using " << ((entry.m_mode == KDirWatchPrivate::FAMMode) ? "FAM" :
551  (entry.m_mode == KDirWatchPrivate::INotifyMode) ? "INotify" :
552  (entry.m_mode == KDirWatchPrivate::DNotifyMode) ? "DNotify" :
553  (entry.m_mode == KDirWatchPrivate::QFSWatchMode) ? "QFSWatch" :
554  (entry.m_mode == KDirWatchPrivate::StatMode) ? "Stat" : "Unknown Method");
555 #ifdef HAVE_SYS_INOTIFY_H
556  if (entry.m_mode == KDirWatchPrivate::INotifyMode)
557  debug << " inotify_wd=" << entry.wd;
558 #endif
559  debug << ", has " << entry.m_clients.count() << " clients";
560  debug.space();
561  if (!entry.m_entries.isEmpty()) {
562  debug << ", nonexistent subentries:";
563  Q_FOREACH(KDirWatchPrivate::Entry* subEntry, entry.m_entries)
564  debug << subEntry << subEntry->path;
565  }
566  debug << ']';
567  return debug;
568 }
569 
570 KDirWatchPrivate::Entry* KDirWatchPrivate::entry(const QString& _path)
571 {
572 // we only support absolute paths
573  if (_path.isEmpty() || QDir::isRelativePath(_path)) {
574  return 0;
575  }
576 
577  QString path (_path);
578 
579  if ( path.length() > 1 && path.endsWith( QLatin1Char( '/' ) ) )
580  path.truncate( path.length() - 1 );
581 
582  EntryMap::Iterator it = m_mapEntries.find( path );
583  if ( it == m_mapEntries.end() )
584  return 0;
585  else
586  return &(*it);
587 }
588 
589 // set polling frequency for a entry and adjust global freq if needed
590 void KDirWatchPrivate::useFreq(Entry* e, int newFreq)
591 {
592  e->freq = newFreq;
593 
594  // a reasonable frequency for the global polling timer
595  if (e->freq < freq) {
596  freq = e->freq;
597  if (timer.isActive()) timer.start(freq);
598  kDebug(7001) << "Global Poll Freq is now" << freq << "msec";
599  }
600 }
601 
602 
603 #if defined(HAVE_FAM)
604 // setup FAM notification, returns false if not possible
605 bool KDirWatchPrivate::useFAM(Entry* e)
606 {
607  if (!use_fam) return false;
608 
609  // handle FAM events to avoid deadlock
610  // (FAM sends back all files in a directory when monitoring)
611  famEventReceived();
612 
613  e->m_mode = FAMMode;
614  e->dirty = false;
615 
616  if (e->isDir) {
617  if (e->m_status == NonExistent) {
618  // If the directory does not exist we watch the parent directory
619  addEntry(0, e->parentDirectory(), e, true);
620  }
621  else {
622  int res =FAMMonitorDirectory(&fc, QFile::encodeName(e->path),
623  &(e->fr), e);
624  if (res<0) {
625  e->m_mode = UnknownMode;
626  use_fam=false;
627  delete sn; sn = 0;
628  return false;
629  }
630  kDebug(7001).nospace() << " Setup FAM (Req " << FAMREQUEST_GETREQNUM(&(e->fr))
631  << ") for " << e->path;
632  }
633  }
634  else {
635  if (e->m_status == NonExistent) {
636  // If the file does not exist we watch the directory
637  addEntry(0, QFileInfo(e->path).absolutePath(), e, true);
638  }
639  else {
640  int res = FAMMonitorFile(&fc, QFile::encodeName(e->path),
641  &(e->fr), e);
642  if (res<0) {
643  e->m_mode = UnknownMode;
644  use_fam=false;
645  delete sn; sn = 0;
646  return false;
647  }
648 
649  kDebug(7001).nospace() << " Setup FAM (Req " << FAMREQUEST_GETREQNUM(&(e->fr))
650  << ") for " << e->path;
651  }
652  }
653 
654  // handle FAM events to avoid deadlock
655  // (FAM sends back all files in a directory when monitoring)
656  famEventReceived();
657 
658  return true;
659 }
660 #endif
661 
662 #ifdef HAVE_SYS_INOTIFY_H
663 // setup INotify notification, returns false if not possible
664 bool KDirWatchPrivate::useINotify( Entry* e )
665 {
666  //kDebug (7001) << "trying to use inotify for monitoring";
667 
668  e->wd = -1;
669  e->dirty = false;
670 
671  if (!supports_inotify) return false;
672 
673  e->m_mode = INotifyMode;
674 
675  if ( e->m_status == NonExistent ) {
676  addEntry(0, e->parentDirectory(), e, true);
677  return true;
678  }
679 
680  // May as well register for almost everything - it's free!
681  int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW|IN_MOVED_FROM|IN_MODIFY|IN_ATTRIB;
682 
683  if ( ( e->wd = inotify_add_watch( m_inotify_fd,
684  QFile::encodeName( e->path ), mask) ) >= 0)
685  {
686  if (s_verboseDebug) {
687  kDebug(7001) << "inotify successfully used for monitoring" << e->path << "wd=" << e->wd;
688  }
689  return true;
690  }
691 
692  kDebug(7001) << "inotify failed for monitoring" << e->path << ":" << strerror(errno);
693  return false;
694 }
695 #endif
696 #ifdef HAVE_QFILESYSTEMWATCHER
697 bool KDirWatchPrivate::useQFSWatch(Entry* e)
698 {
699  e->m_mode = QFSWatchMode;
700  e->dirty = false;
701 
702  if ( e->m_status == NonExistent ) {
703  addEntry(0, e->parentDirectory(), e, true /*isDir*/);
704  return true;
705  }
706 
707  kDebug(7001) << "fsWatcher->addPath" << e->path;
708  if (!fsWatcher) {
709  fsWatcher = new KFileSystemWatcher();
710  connect(fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(fswEventReceived(QString)));
711  connect(fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(fswEventReceived(QString)));
712  }
713  fsWatcher->addPath( e->path );
714  return true;
715 }
716 #endif
717 
718 bool KDirWatchPrivate::useStat(Entry* e)
719 {
720  if (KFileSystemType::fileSystemType(e->path) == KFileSystemType::Nfs) // TODO: or Smbfs?
721  useFreq(e, m_nfsPollInterval);
722  else
723  useFreq(e, m_PollInterval);
724 
725  if (e->m_mode != StatMode) {
726  e->m_mode = StatMode;
727  statEntries++;
728 
729  if ( statEntries == 1 ) {
730  // if this was first STAT entry (=timer was stopped)
731  timer.start(freq); // then start the timer
732  kDebug(7001) << " Started Polling Timer, freq " << freq;
733  }
734  }
735 
736  kDebug(7001) << " Setup Stat (freq " << e->freq << ") for " << e->path;
737 
738  return true;
739 }
740 
741 
742 /* If <instance> !=0, this KDirWatch instance wants to watch at <_path>,
743  * providing in <isDir> the type of the entry to be watched.
744  * Sometimes, entries are dependant on each other: if <sub_entry> !=0,
745  * this entry needs another entry to watch himself (when notExistent).
746  */
747 void KDirWatchPrivate::addEntry(KDirWatch* instance, const QString& _path,
748  Entry* sub_entry, bool isDir, KDirWatch::WatchModes watchModes)
749 {
750  QString path (_path);
751  if (path.isEmpty()
752 #ifndef Q_WS_WIN
753  || path == QLatin1String("/dev")
754  || (path.startsWith(QLatin1String("/dev/")) && !path.startsWith(QLatin1String("/dev/.")))
755 #endif
756  )
757  return; // Don't even go there.
758 
759  if ( path.length() > 1 && path.endsWith( QLatin1Char( '/' ) ) )
760  path.truncate( path.length() - 1 );
761 
762  EntryMap::Iterator it = m_mapEntries.find( path );
763  if ( it != m_mapEntries.end() )
764  {
765  if (sub_entry) {
766  (*it).m_entries.append(sub_entry);
767  if (s_verboseDebug) {
768  kDebug(7001) << "Added already watched Entry" << path
769  << "(for" << sub_entry->path << ")";
770  }
771 #ifdef HAVE_SYS_INOTIFY_H
772  Entry* e = &(*it);
773  if( (e->m_mode == INotifyMode) && (e->wd >= 0) ) {
774  int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW;
775  if(!e->isDir)
776  mask |= IN_MODIFY|IN_ATTRIB;
777  else
778  mask |= IN_ONLYDIR;
779 
780  inotify_rm_watch (m_inotify_fd, e->wd);
781  e->wd = inotify_add_watch( m_inotify_fd, QFile::encodeName( e->path ),
782  mask);
783  //Q_ASSERT(e->wd >= 0); // fails in KDirListerTest::testDeleteCurrentDir
784  }
785 #endif
786  }
787  else {
788  (*it).addClient(instance, watchModes);
789  if (s_verboseDebug) {
790  kDebug(7001) << "Added already watched Entry" << path
791  << "(now" << (*it).clientCount() << "clients)"
792  << QString::fromLatin1("[%1]").arg(instance->objectName());
793  }
794  }
795  return;
796  }
797 
798  // we have a new path to watch
799 
800  KDE_struct_stat stat_buf;
801  bool exists = (KDE::stat(path, &stat_buf) == 0);
802 
803  EntryMap::iterator newIt = m_mapEntries.insert( path, Entry() );
804  // the insert does a copy, so we have to use <e> now
805  Entry* e = &(*newIt);
806 
807  if (exists) {
808  e->isDir = S_ISDIR(stat_buf.st_mode);
809 
810  if (e->isDir && !isDir) {
811  KDE::lstat(path, &stat_buf);
812  if (S_ISLNK(stat_buf.st_mode))
813  // if it's a symlink, don't follow it
814  e->isDir = false;
815  else
816  qWarning() << "KDirWatch:" << path << "is a directory. Use addDir!";
817  } else if (!e->isDir && isDir)
818  qWarning("KDirWatch: %s is a file. Use addFile!", qPrintable(path));
819 
820  if (!e->isDir && ( watchModes != KDirWatch::WatchDirOnly)) {
821  qWarning() << "KDirWatch:" << path << "is a file. You can't use recursive or "
822  "watchFiles options";
823  watchModes = KDirWatch::WatchDirOnly;
824  }
825 
826 #ifdef Q_OS_WIN
827  // ctime is the 'creation time' on windows - use mtime instead
828  e->m_ctime = stat_buf.st_mtime;
829 #else
830  e->m_ctime = stat_buf.st_ctime;
831 #endif
832  e->m_status = Normal;
833  e->m_nlink = stat_buf.st_nlink;
834  e->m_ino = stat_buf.st_ino;
835  }
836  else {
837  e->isDir = isDir;
838  e->m_ctime = invalid_ctime;
839  e->m_status = NonExistent;
840  e->m_nlink = 0;
841  e->m_ino = 0;
842  }
843 
844  e->path = path;
845  if (sub_entry)
846  e->m_entries.append(sub_entry);
847  else
848  e->addClient(instance, watchModes);
849 
850  kDebug(7001).nospace() << "Added " << (e->isDir ? "Dir " : "File ") << path
851  << (e->m_status == NonExistent ? " NotExisting" : "")
852  << " for " << (sub_entry ? sub_entry->path : QString())
853  << " [" << (instance ? instance->objectName() : QString()) << "]";
854 
855  // now setup the notification method
856  e->m_mode = UnknownMode;
857  e->msecLeft = 0;
858 
859  if ( isNoisyFile( QFile::encodeName( path ) ) )
860  return;
861 
862  if (exists && e->isDir && (watchModes != KDirWatch::WatchDirOnly)) {
863  QFlags<QDir::Filter> filters = QDir::NoDotAndDotDot;
864 
865  if ((watchModes & KDirWatch::WatchSubDirs) &&
866  (watchModes & KDirWatch::WatchFiles)) {
867  filters |= (QDir::Dirs|QDir::Files);
868  } else if (watchModes & KDirWatch::WatchSubDirs) {
869  filters |= QDir::Dirs;
870  } else if (watchModes & KDirWatch::WatchFiles) {
871  filters |= QDir::Files;
872  }
873 
874 #if defined(HAVE_SYS_INOTIFY_H)
875  if (e->m_mode == INotifyMode || (e->m_mode == UnknownMode && m_preferredMethod == KDirWatch::INotify) )
876  {
877  //kDebug(7001) << "Ignoring WatchFiles directive - this is implicit with inotify";
878  // Placing a watch on individual files is redundant with inotify
879  // (inotify gives us WatchFiles functionality "for free") and indeed
880  // actively harmful, so prevent it. WatchSubDirs is necessary, though.
881  filters &= ~QDir::Files;
882  }
883 #endif
884 
885  QDir basedir (e->path);
886  const QFileInfoList contents = basedir.entryInfoList(filters);
887  for (QFileInfoList::const_iterator iter = contents.constBegin();
888  iter != contents.constEnd(); ++iter)
889  {
890  const QFileInfo &fileInfo = *iter;
891  // treat symlinks as files--don't follow them.
892  bool isDir = fileInfo.isDir() && !fileInfo.isSymLink();
893 
894  addEntry (instance, fileInfo.absoluteFilePath(), 0, isDir,
895  isDir ? watchModes : KDirWatch::WatchDirOnly);
896  }
897  }
898 
899  addWatch(e);
900 }
901 
902 void KDirWatchPrivate::addWatch(Entry* e)
903 {
904  // If the watch is on a network filesystem use the nfsPreferredMethod as the
905  // default, otherwise use preferredMethod as the default, if the methods are
906  // the same we can skip the mountpoint check
907 
908  // This allows to configure a different method for NFS mounts, since inotify
909  // cannot detect changes made by other machines. However as a default inotify
910  // is fine, since the most common case is a NFS-mounted home, where all changes
911  // are made locally. #177892.
912  KDirWatch::Method preferredMethod = m_preferredMethod;
913  if (m_nfsPreferredMethod != m_preferredMethod) {
914  if (KFileSystemType::fileSystemType(e->path) == KFileSystemType::Nfs) {
915  preferredMethod = m_nfsPreferredMethod;
916  }
917  }
918 
919  // Try the appropriate preferred method from the config first
920  bool entryAdded = false;
921  switch (preferredMethod) {
922 #if defined(HAVE_FAM)
923  case KDirWatch::FAM: entryAdded = useFAM(e); break;
924 #endif
925 #if defined(HAVE_SYS_INOTIFY_H)
926  case KDirWatch::INotify: entryAdded = useINotify(e); break;
927 #endif
928 #if defined(HAVE_QFILESYSTEMWATCHER)
929  case KDirWatch::QFSWatch: entryAdded = useQFSWatch(e); break;
930 #endif
931  case KDirWatch::Stat: entryAdded = useStat(e); break;
932  default: break;
933  }
934 
935  // Failing that try in order INotify, FAM, QFSWatch, Stat
936  if (!entryAdded) {
937 #if defined(HAVE_SYS_INOTIFY_H)
938  if (useINotify(e)) return;
939 #endif
940 #if defined(HAVE_FAM)
941  if (useFAM(e)) return;
942 #endif
943 #if defined(HAVE_QFILESYSTEMWATCHER)
944  if (useQFSWatch(e)) return;
945 #endif
946  useStat(e);
947  }
948 }
949 
950 void KDirWatchPrivate::removeWatch(Entry* e)
951 {
952 #ifdef HAVE_FAM
953  if (e->m_mode == FAMMode) {
954  FAMCancelMonitor(&fc, &(e->fr) );
955  kDebug(7001).nospace() << "Cancelled FAM (Req " << FAMREQUEST_GETREQNUM(&(e->fr))
956  << ") for " << e->path;
957  }
958 #endif
959 #ifdef HAVE_SYS_INOTIFY_H
960  if (e->m_mode == INotifyMode) {
961  (void) inotify_rm_watch( m_inotify_fd, e->wd );
962  if (s_verboseDebug) {
963  kDebug(7001).nospace() << "Cancelled INotify (fd " << m_inotify_fd << ", "
964  << e->wd << ") for " << e->path;
965  }
966  }
967 #endif
968 #ifdef HAVE_QFILESYSTEMWATCHER
969  if (e->m_mode == QFSWatchMode && fsWatcher) {
970  if (s_verboseDebug)
971  kDebug(7001) << "fsWatcher->removePath" << e->path;
972  fsWatcher->removePath(e->path);
973  }
974 #endif
975 }
976 
977 void KDirWatchPrivate::removeEntry(KDirWatch* instance,
978  const QString& _path,
979  Entry* sub_entry)
980 {
981  if (s_verboseDebug) {
982  kDebug(7001) << "path=" << _path << "sub_entry:" << sub_entry;
983  }
984  Entry* e = entry(_path);
985  if (!e) {
986  kWarning(7001) << "doesn't know" << _path;
987  return;
988  }
989 
990  removeEntry(instance, e, sub_entry);
991 }
992 
993 void KDirWatchPrivate::removeEntry(KDirWatch* instance,
994  Entry* e,
995  Entry* sub_entry)
996 {
997  removeList.remove(e);
998 
999  if (sub_entry)
1000  e->m_entries.removeAll(sub_entry);
1001  else
1002  e->removeClient(instance);
1003 
1004  if (e->m_clients.count() || e->m_entries.count())
1005  return;
1006 
1007  if (delayRemove) {
1008  removeList.insert(e);
1009  // now e->isValid() is false
1010  return;
1011  }
1012 
1013  if ( e->m_status == Normal) {
1014  removeWatch(e);
1015  } else {
1016  // Removed a NonExistent entry - we just remove it from the parent
1017  if (e->isDir)
1018  removeEntry(0, e->parentDirectory(), e);
1019  else
1020  removeEntry(0, QFileInfo(e->path).absolutePath(), e);
1021  }
1022 
1023  if (e->m_mode == StatMode) {
1024  statEntries--;
1025  if ( statEntries == 0 ) {
1026  timer.stop(); // stop timer if lists are empty
1027  kDebug(7001) << " Stopped Polling Timer";
1028  }
1029  }
1030 
1031  if (s_verboseDebug) {
1032  kDebug(7001).nospace() << "Removed " << (e->isDir ? "Dir ":"File ") << e->path
1033  << " for " << (sub_entry ? sub_entry->path : QString())
1034  << " [" << (instance ? instance->objectName() : QString()) << "]";
1035  }
1036  m_mapEntries.remove( e->path ); // <e> not valid any more
1037 }
1038 
1039 
1040 /* Called from KDirWatch destructor:
1041  * remove <instance> as client from all entries
1042  */
1043 void KDirWatchPrivate::removeEntries( KDirWatch* instance )
1044 {
1045  int minfreq = 3600000;
1046 
1047  QStringList pathList;
1048  // put all entries where instance is a client in list
1049  EntryMap::Iterator it = m_mapEntries.begin();
1050  for( ; it != m_mapEntries.end(); ++it ) {
1051  Client* c = 0;
1052  foreach(Client* client, (*it).m_clients) {
1053  if (client->instance == instance) {
1054  c = client;
1055  break;
1056  }
1057  }
1058  if (c) {
1059  c->count = 1; // forces deletion of instance as client
1060  pathList.append((*it).path);
1061  }
1062  else if ( (*it).m_mode == StatMode && (*it).freq < minfreq )
1063  minfreq = (*it).freq;
1064  }
1065 
1066  foreach(const QString &path, pathList)
1067  removeEntry(instance, path, 0);
1068 
1069  if (minfreq > freq) {
1070  // we can decrease the global polling frequency
1071  freq = minfreq;
1072  if (timer.isActive()) timer.start(freq);
1073  kDebug(7001) << "Poll Freq now" << freq << "msec";
1074  }
1075 }
1076 
1077 // instance ==0: stop scanning for all instances
1078 bool KDirWatchPrivate::stopEntryScan( KDirWatch* instance, Entry* e)
1079 {
1080  int stillWatching = 0;
1081  foreach(Client* client, e->m_clients) {
1082  if (!instance || instance == client->instance)
1083  client->watchingStopped = true;
1084  else if (!client->watchingStopped)
1085  stillWatching += client->count;
1086  }
1087 
1088  kDebug(7001) << (instance ? instance->objectName() : QString::fromLatin1("all"))
1089  << "stopped scanning" << e->path << "(now"
1090  << stillWatching << "watchers)";
1091 
1092  if (stillWatching == 0) {
1093  // if nobody is interested, we don't watch
1094  if ( e->m_mode != INotifyMode ) {
1095  e->m_ctime = invalid_ctime; // invalid
1096  e->m_status = NonExistent;
1097  }
1098  // e->m_status = Normal;
1099  }
1100  return true;
1101 }
1102 
1103 // instance ==0: start scanning for all instances
1104 bool KDirWatchPrivate::restartEntryScan( KDirWatch* instance, Entry* e,
1105  bool notify)
1106 {
1107  int wasWatching = 0, newWatching = 0;
1108  foreach(Client* client, e->m_clients) {
1109  if (!client->watchingStopped)
1110  wasWatching += client->count;
1111  else if (!instance || instance == client->instance) {
1112  client->watchingStopped = false;
1113  newWatching += client->count;
1114  }
1115  }
1116  if (newWatching == 0)
1117  return false;
1118 
1119  kDebug(7001) << (instance ? instance->objectName() : QString::fromLatin1("all"))
1120  << "restarted scanning" << e->path
1121  << "(now" << wasWatching+newWatching << "watchers)";
1122 
1123  // restart watching and emit pending events
1124 
1125  int ev = NoChange;
1126  if (wasWatching == 0) {
1127  if (!notify) {
1128  KDE_struct_stat stat_buf;
1129  bool exists = (KDE::stat(e->path, &stat_buf) == 0);
1130  if (exists) {
1131 #ifdef Q_OS_WIN
1132  // ctime is the 'creation time' on windows - use mtime instead
1133  e->m_ctime = stat_buf.st_mtime;
1134 #else
1135  e->m_ctime = stat_buf.st_ctime;
1136 #endif
1137  e->m_status = Normal;
1138  if (s_verboseDebug) {
1139  kDebug(7001) << "Setting status to Normal for" << e << e->path;
1140  }
1141  e->m_nlink = stat_buf.st_nlink;
1142  e->m_ino = stat_buf.st_ino;
1143 
1144  // Same as in scanEntry: ensure no subentry in parent dir
1145  removeEntry(0, e->parentDirectory(), e);
1146  }
1147  else {
1148  e->m_ctime = invalid_ctime;
1149  e->m_status = NonExistent;
1150  e->m_nlink = 0;
1151  if (s_verboseDebug) {
1152  kDebug(7001) << "Setting status to NonExistent for" << e << e->path;
1153  }
1154  }
1155  }
1156  e->msecLeft = 0;
1157  ev = scanEntry(e);
1158  }
1159  emitEvent(e,ev);
1160 
1161  return true;
1162 }
1163 
1164 // instance ==0: stop scanning for all instances
1165 void KDirWatchPrivate::stopScan(KDirWatch* instance)
1166 {
1167  EntryMap::Iterator it = m_mapEntries.begin();
1168  for( ; it != m_mapEntries.end(); ++it )
1169  stopEntryScan(instance, &(*it));
1170 }
1171 
1172 
1173 void KDirWatchPrivate::startScan(KDirWatch* instance,
1174  bool notify, bool skippedToo )
1175 {
1176  if (!notify)
1177  resetList(instance,skippedToo);
1178 
1179  EntryMap::Iterator it = m_mapEntries.begin();
1180  for( ; it != m_mapEntries.end(); ++it )
1181  restartEntryScan(instance, &(*it), notify);
1182 
1183  // timer should still be running when in polling mode
1184 }
1185 
1186 
1187 // clear all pending events, also from stopped
1188 void KDirWatchPrivate::resetList( KDirWatch* /*instance*/, bool skippedToo )
1189 {
1190  EntryMap::Iterator it = m_mapEntries.begin();
1191  for( ; it != m_mapEntries.end(); ++it ) {
1192 
1193  foreach(Client* client, (*it).m_clients) {
1194  if (!client->watchingStopped || skippedToo)
1195  client->pending = NoChange;
1196  }
1197  }
1198 }
1199 
1200 // Return event happened on <e>
1201 //
1202 int KDirWatchPrivate::scanEntry(Entry* e)
1203 {
1204  // Shouldn't happen: Ignore "unknown" notification method
1205  if (e->m_mode == UnknownMode) return NoChange;
1206 
1207  if (e->m_mode == FAMMode || e->m_mode == INotifyMode) {
1208  // we know nothing has changed, no need to stat
1209  if(!e->dirty) return NoChange;
1210  e->dirty = false;
1211  }
1212 
1213  if (e->m_mode == StatMode) {
1214  // only scan if timeout on entry timer happens;
1215  // e.g. when using 500msec global timer, a entry
1216  // with freq=5000 is only watched every 10th time
1217 
1218  e->msecLeft -= freq;
1219  if (e->msecLeft>0) return NoChange;
1220  e->msecLeft += e->freq;
1221  }
1222 
1223  KDE_struct_stat stat_buf;
1224  const bool exists = (KDE::stat(e->path, &stat_buf) == 0);
1225  if (exists) {
1226 
1227  if (e->m_status == NonExistent) {
1228  // ctime is the 'creation time' on windows, but with qMax
1229  // we get the latest change of any kind, on any platform.
1230  e->m_ctime = qMax(stat_buf.st_ctime, stat_buf.st_mtime);
1231  e->m_status = Normal;
1232  e->m_ino = stat_buf.st_ino;
1233  if (s_verboseDebug) {
1234  kDebug(7001) << "Setting status to Normal for just created" << e << e->path;
1235  }
1236  // We need to make sure the entry isn't listed in its parent's subentries... (#222974, testMoveTo)
1237  removeEntry(0, e->parentDirectory(), e);
1238 
1239  return Created;
1240  }
1241 
1242 #if 1 // for debugging the if() below
1243  if (s_verboseDebug) {
1244  struct tm* tmp = localtime(&e->m_ctime);
1245  char outstr[200];
1246  strftime(outstr, sizeof(outstr), "%T", tmp);
1247  kDebug(7001) << "e->m_ctime=" << e->m_ctime << outstr
1248  << "stat_buf.st_ctime=" << stat_buf.st_ctime
1249  << "e->m_nlink=" << e->m_nlink
1250  << "stat_buf.st_nlink=" << stat_buf.st_nlink
1251  << "e->m_ino=" << e->m_ino
1252  << "stat_buf.st_ino=" << stat_buf.st_ino;
1253  }
1254 #endif
1255 
1256  if ( ((e->m_ctime != invalid_ctime) &&
1257  (qMax(stat_buf.st_ctime, stat_buf.st_mtime) != e->m_ctime ||
1258  stat_buf.st_ino != e->m_ino ||
1259  stat_buf.st_nlink != nlink_t(e->m_nlink)))
1260 #ifdef Q_OS_WIN
1261  // we trust QFSW to get it right, the ctime comparisons above
1262  // fail for example when adding files to directories on Windows
1263  // which doesn't change the mtime of the directory
1264  || e->m_mode == QFSWatchMode
1265 #endif
1266  ) {
1267  e->m_ctime = qMax(stat_buf.st_ctime, stat_buf.st_mtime);
1268  e->m_nlink = stat_buf.st_nlink;
1269  if (e->m_ino != stat_buf.st_ino) {
1270  // The file got deleted and recreated. We need to watch it again.
1271  removeWatch(e);
1272  addWatch(e);
1273  }
1274  e->m_ino = stat_buf.st_ino;
1275  return Changed;
1276  }
1277 
1278  return NoChange;
1279  }
1280 
1281  // dir/file doesn't exist
1282 
1283  e->m_nlink = 0;
1284  e->m_ino = 0;
1285  e->m_status = NonExistent;
1286 
1287  if (e->m_ctime == invalid_ctime) {
1288  return NoChange;
1289  }
1290 
1291  e->m_ctime = invalid_ctime;
1292  return Deleted;
1293 }
1294 
1295 /* Notify all interested KDirWatch instances about a given event on an entry
1296  * and stored pending events. When watching is stopped, the event is
1297  * added to the pending events.
1298  */
1299 void KDirWatchPrivate::emitEvent(const Entry* e, int event, const QString &fileName)
1300 {
1301  QString path (e->path);
1302  if (!fileName.isEmpty()) {
1303  if (!QDir::isRelativePath(fileName))
1304  path = fileName;
1305  else {
1306 #ifdef Q_OS_UNIX
1307  path += QLatin1Char('/') + fileName;
1308 #elif defined(Q_WS_WIN)
1309  //current drive is passed instead of /
1310  path += QDir::currentPath().left(2) + QLatin1Char('/') + fileName;
1311 #endif
1312  }
1313  }
1314 
1315  if (s_verboseDebug) {
1316  kDebug(7001) << event << path << e->m_clients.count() << "clients";
1317  }
1318 
1319  foreach(Client* c, e->m_clients)
1320  {
1321  if (c->instance==0 || c->count==0) continue;
1322 
1323  if (c->watchingStopped) {
1324  // add event to pending...
1325  if (event == Changed)
1326  c->pending |= event;
1327  else if (event == Created || event == Deleted)
1328  c->pending = event;
1329  continue;
1330  }
1331  // not stopped
1332  if (event == NoChange || event == Changed)
1333  event |= c->pending;
1334  c->pending = NoChange;
1335  if (event == NoChange) continue;
1336 
1337  // Emit the signals delayed, to avoid unexpected re-entrancy from the slots (#220153)
1338 
1339  if (event & Deleted) {
1340  QMetaObject::invokeMethod(c->instance, "setDeleted", Qt::QueuedConnection, Q_ARG(QString, path));
1341  // emit only Deleted event...
1342  continue;
1343  }
1344 
1345  if (event & Created) {
1346  QMetaObject::invokeMethod(c->instance, "setCreated", Qt::QueuedConnection, Q_ARG(QString, path));
1347  // possible emit Change event after creation
1348  }
1349 
1350  if (event & Changed) {
1351  QMetaObject::invokeMethod(c->instance, "setDirty", Qt::QueuedConnection, Q_ARG(QString, path));
1352  }
1353  }
1354 }
1355 
1356 // Remove entries which were marked to be removed
1357 void KDirWatchPrivate::slotRemoveDelayed()
1358 {
1359  delayRemove = false;
1360  // Removing an entry could also take care of removing its parent
1361  // (e.g. in FAM or inotify mode), which would remove other entries in removeList,
1362  // so don't use foreach or iterators here...
1363  while (!removeList.isEmpty()) {
1364  Entry* entry = *removeList.begin();
1365  removeEntry(0, entry, 0); // this will remove entry from removeList
1366  }
1367 }
1368 
1369 /* Scan all entries to be watched for changes. This is done regularly
1370  * when polling. FAM and inotify use a single-shot timer to call this slot delayed.
1371  */
1372 void KDirWatchPrivate::slotRescan()
1373 {
1374  if (s_verboseDebug)
1375  kDebug(7001);
1376 
1377  EntryMap::Iterator it;
1378 
1379  // People can do very long things in the slot connected to dirty(),
1380  // like showing a message box. We don't want to keep polling during
1381  // that time, otherwise the value of 'delayRemove' will be reset.
1382  // ### TODO: now the emitEvent delays emission, this can be cleaned up
1383  bool timerRunning = timer.isActive();
1384  if ( timerRunning )
1385  timer.stop();
1386 
1387  // We delay deletions of entries this way.
1388  // removeDir(), when called in slotDirty(), can cause a crash otherwise
1389  // ### TODO: now the emitEvent delays emission, this can be cleaned up
1390  delayRemove = true;
1391 
1392  if (rescan_all)
1393  {
1394  // mark all as dirty
1395  it = m_mapEntries.begin();
1396  for( ; it != m_mapEntries.end(); ++it )
1397  (*it).dirty = true;
1398  rescan_all = false;
1399  }
1400  else
1401  {
1402  // progate dirty flag to dependant entries (e.g. file watches)
1403  it = m_mapEntries.begin();
1404  for( ; it != m_mapEntries.end(); ++it )
1405  if (((*it).m_mode == INotifyMode || (*it).m_mode == QFSWatchMode) && (*it).dirty )
1406  (*it).propagate_dirty();
1407  }
1408 
1409 #ifdef HAVE_SYS_INOTIFY_H
1410  QList<Entry*> cList;
1411 #endif
1412 
1413  it = m_mapEntries.begin();
1414  for( ; it != m_mapEntries.end(); ++it ) {
1415  // we don't check invalid entries (i.e. remove delayed)
1416  Entry* entry = &(*it);
1417  if (!entry->isValid()) continue;
1418 
1419  const int ev = scanEntry(entry);
1420  if (s_verboseDebug)
1421  kDebug(7001) << "scanEntry for" << entry->path << "says" << ev;
1422 
1423  switch(entry->m_mode) {
1424 #ifdef HAVE_SYS_INOTIFY_H
1425  case INotifyMode:
1426  if ( ev == Deleted ) {
1427  if (s_verboseDebug)
1428  kDebug(7001) << "scanEntry says" << entry->path << "was deleted";
1429  addEntry(0, entry->parentDirectory(), entry, true);
1430  } else if (ev == Created) {
1431  if (s_verboseDebug)
1432  kDebug(7001) << "scanEntry says" << entry->path << "was created. wd=" << entry->wd;
1433  if (entry->wd < 0) {
1434  cList.append(entry);
1435  addWatch(entry);
1436  }
1437  }
1438  break;
1439 #endif
1440  case FAMMode:
1441  case QFSWatchMode:
1442  if (ev == Created) {
1443  addWatch(entry);
1444  }
1445  break;
1446  default:
1447  // dunno about StatMode...
1448  break;
1449  }
1450 
1451 #ifdef HAVE_SYS_INOTIFY_H
1452  if (entry->isDir) {
1453  // Report and clear the the list of files that have changed in this directory.
1454  // Remove duplicates by changing to set and back again:
1455  // we don't really care about preserving the order of the
1456  // original changes.
1457  QStringList pendingFileChanges = entry->m_pendingFileChanges;
1458  pendingFileChanges.removeDuplicates();
1459  Q_FOREACH(const QString &changedFilename, pendingFileChanges) {
1460  if (s_verboseDebug) {
1461  kDebug(7001) << "processing pending file change for" << changedFilename;
1462  }
1463  emitEvent(entry, Changed, changedFilename);
1464  }
1465  entry->m_pendingFileChanges.clear();
1466  }
1467 #endif
1468 
1469  if ( ev != NoChange ) {
1470  emitEvent(entry, ev);
1471  }
1472  }
1473 
1474  if ( timerRunning )
1475  timer.start(freq);
1476 
1477 #ifdef HAVE_SYS_INOTIFY_H
1478  // Remove watch of parent of new created directories
1479  Q_FOREACH(Entry* e, cList)
1480  removeEntry(0, e->parentDirectory(), e);
1481 #endif
1482 
1483  QTimer::singleShot(0, this, SLOT(slotRemoveDelayed()));
1484 }
1485 
1486 bool KDirWatchPrivate::isNoisyFile( const char * filename )
1487 {
1488  // $HOME/.X.err grows with debug output, so don't notify change
1489  if ( *filename == '.') {
1490  if (strncmp(filename, ".X.err", 6) == 0) return true;
1491  if (strncmp(filename, ".xsession-errors", 16) == 0) return true;
1492  // fontconfig updates the cache on every KDE app start
1493  // (inclusive kio_thumbnail slaves)
1494  if (strncmp(filename, ".fonts.cache", 12) == 0) return true;
1495  }
1496 
1497  return false;
1498 }
1499 
1500 #ifdef HAVE_FAM
1501 void KDirWatchPrivate::famEventReceived()
1502 {
1503  static FAMEvent fe;
1504 
1505  delayRemove = true;
1506 
1507  //kDebug(7001) << "Fam event received";
1508 
1509  while(use_fam && FAMPending(&fc)) {
1510  if (FAMNextEvent(&fc, &fe) == -1) {
1511  kWarning(7001) << "FAM connection problem, switching to polling.";
1512  use_fam = false;
1513  delete sn; sn = 0;
1514 
1515  // Replace all FAMMode entries with INotify/Stat
1516  EntryMap::Iterator it = m_mapEntries.begin();
1517  for( ; it != m_mapEntries.end(); ++it )
1518  if ((*it).m_mode == FAMMode && (*it).m_clients.count()>0) {
1519  Entry* e = &(*it);
1520  addWatch(e);
1521  }
1522  }
1523  else
1524  checkFAMEvent(&fe);
1525  }
1526 
1527  QTimer::singleShot(0, this, SLOT(slotRemoveDelayed()));
1528 }
1529 
1530 void KDirWatchPrivate::checkFAMEvent(FAMEvent* fe)
1531 {
1532  //kDebug(7001);
1533 
1534  // Don't be too verbose ;-)
1535  if ((fe->code == FAMExists) ||
1536  (fe->code == FAMEndExist) ||
1537  (fe->code == FAMAcknowledge)) return;
1538 
1539  if ( isNoisyFile( fe->filename ) )
1540  return;
1541 
1542  Entry* e = 0;
1543  EntryMap::Iterator it = m_mapEntries.begin();
1544  for( ; it != m_mapEntries.end(); ++it )
1545  if (FAMREQUEST_GETREQNUM(&( (*it).fr )) ==
1546  FAMREQUEST_GETREQNUM(&(fe->fr)) ) {
1547  e = &(*it);
1548  break;
1549  }
1550 
1551  // Entry* e = static_cast<Entry*>(fe->userdata);
1552 
1553  if (s_verboseDebug) { // don't enable this except when debugging, see #88538
1554  kDebug(7001) << "Processing FAM event ("
1555  << ((fe->code == FAMChanged) ? "FAMChanged" :
1556  (fe->code == FAMDeleted) ? "FAMDeleted" :
1557  (fe->code == FAMStartExecuting) ? "FAMStartExecuting" :
1558  (fe->code == FAMStopExecuting) ? "FAMStopExecuting" :
1559  (fe->code == FAMCreated) ? "FAMCreated" :
1560  (fe->code == FAMMoved) ? "FAMMoved" :
1561  (fe->code == FAMAcknowledge) ? "FAMAcknowledge" :
1562  (fe->code == FAMExists) ? "FAMExists" :
1563  (fe->code == FAMEndExist) ? "FAMEndExist" : "Unknown Code")
1564  << ", " << fe->filename
1565  << ", Req " << FAMREQUEST_GETREQNUM(&(fe->fr)) << ") e=" << e;
1566  }
1567 
1568  if (!e) {
1569  // this happens e.g. for FAMAcknowledge after deleting a dir...
1570  // kDebug(7001) << "No entry for FAM event ?!";
1571  return;
1572  }
1573 
1574  if (e->m_status == NonExistent) {
1575  kDebug(7001) << "FAM event for nonExistent entry " << e->path;
1576  return;
1577  }
1578 
1579  // Delayed handling. This rechecks changes with own stat calls.
1580  e->dirty = true;
1581  if (!rescan_timer.isActive())
1582  rescan_timer.start(m_PollInterval); // singleshot
1583 
1584  // needed FAM control actions on FAM events
1585  switch (fe->code) {
1586  case FAMDeleted:
1587  // fe->filename is an absolute path when a watched file-or-dir is deleted
1588  if (!QDir::isRelativePath(QFile::decodeName(fe->filename))) {
1589  FAMCancelMonitor(&fc, &(e->fr) ); // needed ?
1590  kDebug(7001) << "Cancelled FAMReq"
1591  << FAMREQUEST_GETREQNUM(&(e->fr))
1592  << "for" << e->path;
1593  e->m_status = NonExistent;
1594  e->m_ctime = invalid_ctime;
1595  emitEvent(e, Deleted, e->path);
1596  // Add entry to parent dir to notice if the entry gets recreated
1597  addEntry(0, e->parentDirectory(), e, true /*isDir*/);
1598  } else {
1599  // A file in this directory has been removed, and wasn't explicitly watched.
1600  // We could still inform clients, like inotify does? But stat can't.
1601  // For now we just marked e dirty and slotRescan will emit the dir as dirty.
1602  //kDebug(7001) << "Got FAMDeleted for" << QFile::decodeName(fe->filename) << "in" << e->path << ". Absolute path -> NOOP!";
1603  }
1604  break;
1605 
1606  case FAMCreated: {
1607  // check for creation of a directory we have to watch
1608  QString tpath(e->path + QLatin1Char('/') + QFile::decodeName(fe->filename));
1609 
1610  // This code is very similar to the one in inotifyEventReceived...
1611  Entry* sub_entry = e->findSubEntry(tpath);
1612  if (sub_entry /*&& sub_entry->isDir*/) {
1613  // We were waiting for this new file/dir to be created
1614  emitEvent(sub_entry, Created);
1615  sub_entry->dirty = true;
1616  rescan_timer.start(0); // process this asap, to start watching that dir
1617  } else if (e->isDir && !e->m_clients.empty()) {
1618  bool isDir = false;
1619  const QList<Client *> clients = e->clientsForFileOrDir(tpath, &isDir);
1620  Q_FOREACH(Client *client, clients) {
1621  addEntry (client->instance, tpath, 0, isDir,
1622  isDir ? client->m_watchModes : KDirWatch::WatchDirOnly);
1623  }
1624 
1625  if (!clients.isEmpty()) {
1626  emitEvent(e, Created, tpath);
1627 
1628  kDebug(7001).nospace() << clients.count() << " instance(s) monitoring the new "
1629  << (isDir ? "dir " : "file ") << tpath;
1630  }
1631  }
1632  }
1633  break;
1634  default:
1635  break;
1636  }
1637 }
1638 #else
1639 void KDirWatchPrivate::famEventReceived()
1640 {
1641  kWarning (7001) << "Fam event received but FAM is not supported";
1642 }
1643 #endif
1644 
1645 
1646 void KDirWatchPrivate::statistics()
1647 {
1648  EntryMap::Iterator it;
1649 
1650  kDebug(7001) << "Entries watched:";
1651  if (m_mapEntries.count()==0) {
1652  kDebug(7001) << " None.";
1653  }
1654  else {
1655  it = m_mapEntries.begin();
1656  for( ; it != m_mapEntries.end(); ++it ) {
1657  Entry* e = &(*it);
1658  kDebug(7001) << " " << *e;
1659 
1660  foreach(Client* c, e->m_clients) {
1661  QByteArray pending;
1662  if (c->watchingStopped) {
1663  if (c->pending & Deleted) pending += "deleted ";
1664  if (c->pending & Created) pending += "created ";
1665  if (c->pending & Changed) pending += "changed ";
1666  if (!pending.isEmpty()) pending = " (pending: " + pending + ')';
1667  pending = ", stopped" + pending;
1668  }
1669  kDebug(7001) << " by " << c->instance->objectName()
1670  << " (" << c->count << " times)" << pending;
1671  }
1672  if (e->m_entries.count()>0) {
1673  kDebug(7001) << " dependent entries:";
1674  foreach(Entry *d, e->m_entries) {
1675  kDebug(7001) << " " << d << d->path << (d->m_status == NonExistent ? "NonExistent" : "EXISTS!!! ERROR!");
1676  if (s_verboseDebug) {
1677  Q_ASSERT(d->m_status == NonExistent); // it doesn't belong here otherwise
1678  }
1679  }
1680  }
1681  }
1682  }
1683 }
1684 
1685 #ifdef HAVE_QFILESYSTEMWATCHER
1686 // Slot for QFileSystemWatcher
1687 void KDirWatchPrivate::fswEventReceived(const QString &path)
1688 {
1689  if (s_verboseDebug)
1690  kDebug(7001) << path;
1691  EntryMap::Iterator it = m_mapEntries.find(path);
1692  if(it != m_mapEntries.end()) {
1693  Entry* e = &(*it);
1694  e->dirty = true;
1695  const int ev = scanEntry(e);
1696  if (s_verboseDebug)
1697  kDebug(7001) << "scanEntry for" << e->path << "says" << ev;
1698  if (ev != NoChange)
1699  emitEvent(e, ev);
1700  if(ev == Deleted) {
1701  if (e->isDir)
1702  addEntry(0, e->parentDirectory(), e, true);
1703  else
1704  addEntry(0, QFileInfo(e->path).absolutePath(), e, true);
1705  } else if (ev == Created) {
1706  // We were waiting for it to appear; now watch it
1707  addWatch(e);
1708  } else if (e->isDir) {
1709  // Check if any file or dir was created under this directory, that we were waiting for
1710  Q_FOREACH(Entry* sub_entry, e->m_entries) {
1711  fswEventReceived(sub_entry->path); // recurse, to call scanEntry and see if something changed
1712  }
1713  }
1714  }
1715 }
1716 #else
1717 void KDirWatchPrivate::fswEventReceived(const QString &path)
1718 {
1719  Q_UNUSED(path);
1720  kWarning (7001) << "QFileSystemWatcher event received but QFileSystemWatcher is not supported";
1721 }
1722 #endif // HAVE_QFILESYSTEMWATCHER
1723 
1724 //
1725 // Class KDirWatch
1726 //
1727 
1728 K_GLOBAL_STATIC(KDirWatch, s_pKDirWatchSelf)
1729 KDirWatch* KDirWatch::self()
1730 {
1731  return s_pKDirWatchSelf;
1732 }
1733 
1734 // TODO KDE5: is this used anywhere?
1735 bool KDirWatch::exists()
1736 {
1737  return s_pKDirWatchSelf.exists();
1738 }
1739 
1740 static void cleanupQFSWatcher()
1741 {
1742  s_pKDirWatchSelf->deleteQFSWatcher();
1743 }
1744 
1745 KDirWatch::KDirWatch (QObject* parent)
1746  : QObject(parent), d(createPrivate())
1747 {
1748  static int nameCounter = 0;
1749 
1750  nameCounter++;
1751  setObjectName(QString::fromLatin1("KDirWatch-%1").arg(nameCounter) );
1752 
1753  d->ref();
1754 
1755  d->_isStopped = false;
1756 
1757  static bool cleanupRegistered = false;
1758  if (!cleanupRegistered) {
1759  cleanupRegistered = true;
1760  // Must delete QFileSystemWatcher before qApp is gone - bug 261541
1761  qAddPostRoutine(cleanupQFSWatcher);
1762  }
1763 }
1764 
1765 KDirWatch::~KDirWatch()
1766 {
1767  d->removeEntries(this);
1768  if ( d->deref() )
1769  {
1770  // delete it if it's the last one
1771  delete d;
1772  dwp_self = 0;
1773  }
1774 }
1775 
1776 void KDirWatch::addDir( const QString& _path, WatchModes watchModes)
1777 {
1778  if (d) d->addEntry(this, _path, 0, true, watchModes);
1779 }
1780 
1781 void KDirWatch::addFile( const QString& _path )
1782 {
1783  if ( !d )
1784  return;
1785 
1786  d->addEntry(this, _path, 0, false);
1787 }
1788 
1789 QDateTime KDirWatch::ctime( const QString &_path ) const
1790 {
1791  KDirWatchPrivate::Entry* e = d->entry(_path);
1792 
1793  if (!e)
1794  return QDateTime();
1795 
1796  return QDateTime::fromTime_t(e->m_ctime);
1797 }
1798 
1799 void KDirWatch::removeDir( const QString& _path )
1800 {
1801  if (d) d->removeEntry(this, _path, 0);
1802 }
1803 
1804 void KDirWatch::removeFile( const QString& _path )
1805 {
1806  if (d) d->removeEntry(this, _path, 0);
1807 }
1808 
1809 bool KDirWatch::stopDirScan( const QString& _path )
1810 {
1811  if (d) {
1812  KDirWatchPrivate::Entry *e = d->entry(_path);
1813  if (e && e->isDir) return d->stopEntryScan(this, e);
1814  }
1815  return false;
1816 }
1817 
1818 bool KDirWatch::restartDirScan( const QString& _path )
1819 {
1820  if (d) {
1821  KDirWatchPrivate::Entry *e = d->entry(_path);
1822  if (e && e->isDir)
1823  // restart without notifying pending events
1824  return d->restartEntryScan(this, e, false);
1825  }
1826  return false;
1827 }
1828 
1829 void KDirWatch::stopScan()
1830 {
1831  if (d) {
1832  d->stopScan(this);
1833  d->_isStopped = true;
1834  }
1835 }
1836 
1837 bool KDirWatch::isStopped()
1838 {
1839  return d->_isStopped;
1840 }
1841 
1842 void KDirWatch::startScan( bool notify, bool skippedToo )
1843 {
1844  if (d) {
1845  d->_isStopped = false;
1846  d->startScan(this, notify, skippedToo);
1847  }
1848 }
1849 
1850 
1851 bool KDirWatch::contains( const QString& _path ) const
1852 {
1853  KDirWatchPrivate::Entry* e = d->entry(_path);
1854  if (!e)
1855  return false;
1856 
1857  foreach(KDirWatchPrivate::Client* client, e->m_clients) {
1858  if (client->instance == this)
1859  return true;
1860  }
1861 
1862  return false;
1863 }
1864 
1865 void KDirWatch::deleteQFSWatcher()
1866 {
1867  delete d->fsWatcher;
1868  d->fsWatcher = 0;
1869 }
1870 
1871 void KDirWatch::statistics()
1872 {
1873  if (!dwp_self) {
1874  kDebug(7001) << "KDirWatch not used";
1875  return;
1876  }
1877  dwp_self->statistics();
1878 }
1879 
1880 
1881 void KDirWatch::setCreated( const QString & _file )
1882 {
1883  kDebug(7001) << objectName() << "emitting created" << _file;
1884  emit created( _file );
1885 }
1886 
1887 void KDirWatch::setDirty( const QString & _file )
1888 {
1889  //kDebug(7001) << objectName() << "emitting dirty" << _file;
1890  emit dirty( _file );
1891 }
1892 
1893 void KDirWatch::setDeleted( const QString & _file )
1894 {
1895  kDebug(7001) << objectName() << "emitting deleted" << _file;
1896  emit deleted( _file );
1897 }
1898 
1899 KDirWatch::Method KDirWatch::internalMethod()
1900 {
1901  return d->m_preferredMethod;
1902 }
1903 
1904 
1905 #include "kdirwatch.moc"
1906 #include "kdirwatch_p.moc"
1907 
1908 //sven
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Fri Dec 7 2012 15:57:19 by doxygen 1.8.1 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.

KDECore

Skip menu "KDECore"
  • Main Page
  • Namespace List
  • Namespace Members
  • Alphabetical List
  • Class List
  • Class Hierarchy
  • Class Members
  • File List
  • File Members
  • Modules
  • Related Pages

kdelibs-4.8.5 API Reference

Skip menu "kdelibs-4.8.5 API Reference"
  • DNSSD
  • Interfaces
  •   KHexEdit
  •   KMediaPlayer
  •   KSpeech
  •   KTextEditor
  • kconf_update
  • KDE3Support
  •   KUnitTest
  • KDECore
  • KDED
  • KDEsu
  • KDEUI
  • KDEWebKit
  • KDocTools
  • KFile
  • KHTML
  • KImgIO
  • KInit
  • kio
  • KIOSlave
  • KJS
  •   KJS-API
  •   WTF
  • kjsembed
  • KNewStuff
  • KParts
  • KPty
  • Kross
  • KUnitConversion
  • KUtils
  • Nepomuk
  • Plasma
  • Solid
  • Sonnet
  • ThreadWeaver
Report problems with this website to our bug tracking system.
Contact the specific authors with questions and comments about the page contents.

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. | Legal