• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.10.1 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  (void)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  if (KDE::lstat(path, &stat_buf) == 0) {
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  }
818  } else if (!e->isDir && isDir)
819  qWarning("KDirWatch: %s is a file. Use addFile!", qPrintable(path));
820 
821  if (!e->isDir && ( watchModes != KDirWatch::WatchDirOnly)) {
822  qWarning() << "KDirWatch:" << path << "is a file. You can't use recursive or "
823  "watchFiles options";
824  watchModes = KDirWatch::WatchDirOnly;
825  }
826 
827 #ifdef Q_OS_WIN
828  // ctime is the 'creation time' on windows - use mtime instead
829  e->m_ctime = stat_buf.st_mtime;
830 #else
831  e->m_ctime = stat_buf.st_ctime;
832 #endif
833  e->m_status = Normal;
834  e->m_nlink = stat_buf.st_nlink;
835  e->m_ino = stat_buf.st_ino;
836  }
837  else {
838  e->isDir = isDir;
839  e->m_ctime = invalid_ctime;
840  e->m_status = NonExistent;
841  e->m_nlink = 0;
842  e->m_ino = 0;
843  }
844 
845  e->path = path;
846  if (sub_entry)
847  e->m_entries.append(sub_entry);
848  else
849  e->addClient(instance, watchModes);
850 
851  kDebug(7001).nospace() << "Added " << (e->isDir ? "Dir " : "File ") << path
852  << (e->m_status == NonExistent ? " NotExisting" : "")
853  << " for " << (sub_entry ? sub_entry->path : QString())
854  << " [" << (instance ? instance->objectName() : QString()) << "]";
855 
856  // now setup the notification method
857  e->m_mode = UnknownMode;
858  e->msecLeft = 0;
859 
860  if ( isNoisyFile( QFile::encodeName( path ) ) )
861  return;
862 
863  if (exists && e->isDir && (watchModes != KDirWatch::WatchDirOnly)) {
864  QFlags<QDir::Filter> filters = QDir::NoDotAndDotDot;
865 
866  if ((watchModes & KDirWatch::WatchSubDirs) &&
867  (watchModes & KDirWatch::WatchFiles)) {
868  filters |= (QDir::Dirs|QDir::Files);
869  } else if (watchModes & KDirWatch::WatchSubDirs) {
870  filters |= QDir::Dirs;
871  } else if (watchModes & KDirWatch::WatchFiles) {
872  filters |= QDir::Files;
873  }
874 
875 #if defined(HAVE_SYS_INOTIFY_H)
876  if (e->m_mode == INotifyMode || (e->m_mode == UnknownMode && m_preferredMethod == KDirWatch::INotify) )
877  {
878  //kDebug(7001) << "Ignoring WatchFiles directive - this is implicit with inotify";
879  // Placing a watch on individual files is redundant with inotify
880  // (inotify gives us WatchFiles functionality "for free") and indeed
881  // actively harmful, so prevent it. WatchSubDirs is necessary, though.
882  filters &= ~QDir::Files;
883  }
884 #endif
885 
886  QDir basedir (e->path);
887  const QFileInfoList contents = basedir.entryInfoList(filters);
888  for (QFileInfoList::const_iterator iter = contents.constBegin();
889  iter != contents.constEnd(); ++iter)
890  {
891  const QFileInfo &fileInfo = *iter;
892  // treat symlinks as files--don't follow them.
893  bool isDir = fileInfo.isDir() && !fileInfo.isSymLink();
894 
895  addEntry (instance, fileInfo.absoluteFilePath(), 0, isDir,
896  isDir ? watchModes : KDirWatch::WatchDirOnly);
897  }
898  }
899 
900  addWatch(e);
901 }
902 
903 void KDirWatchPrivate::addWatch(Entry* e)
904 {
905  // If the watch is on a network filesystem use the nfsPreferredMethod as the
906  // default, otherwise use preferredMethod as the default, if the methods are
907  // the same we can skip the mountpoint check
908 
909  // This allows to configure a different method for NFS mounts, since inotify
910  // cannot detect changes made by other machines. However as a default inotify
911  // is fine, since the most common case is a NFS-mounted home, where all changes
912  // are made locally. #177892.
913  KDirWatch::Method preferredMethod = m_preferredMethod;
914  if (m_nfsPreferredMethod != m_preferredMethod) {
915  if (KFileSystemType::fileSystemType(e->path) == KFileSystemType::Nfs) {
916  preferredMethod = m_nfsPreferredMethod;
917  }
918  }
919 
920  // Try the appropriate preferred method from the config first
921  bool entryAdded = false;
922  switch (preferredMethod) {
923 #if defined(HAVE_FAM)
924  case KDirWatch::FAM: entryAdded = useFAM(e); break;
925 #endif
926 #if defined(HAVE_SYS_INOTIFY_H)
927  case KDirWatch::INotify: entryAdded = useINotify(e); break;
928 #endif
929 #if defined(HAVE_QFILESYSTEMWATCHER)
930  case KDirWatch::QFSWatch: entryAdded = useQFSWatch(e); break;
931 #endif
932  case KDirWatch::Stat: entryAdded = useStat(e); break;
933  default: break;
934  }
935 
936  // Failing that try in order INotify, FAM, QFSWatch, Stat
937  if (!entryAdded) {
938 #if defined(HAVE_SYS_INOTIFY_H)
939  if (useINotify(e)) return;
940 #endif
941 #if defined(HAVE_FAM)
942  if (useFAM(e)) return;
943 #endif
944 #if defined(HAVE_QFILESYSTEMWATCHER)
945  if (useQFSWatch(e)) return;
946 #endif
947  useStat(e);
948  }
949 }
950 
951 void KDirWatchPrivate::removeWatch(Entry* e)
952 {
953 #ifdef HAVE_FAM
954  if (e->m_mode == FAMMode) {
955  FAMCancelMonitor(&fc, &(e->fr) );
956  kDebug(7001).nospace() << "Cancelled FAM (Req " << FAMREQUEST_GETREQNUM(&(e->fr))
957  << ") for " << e->path;
958  }
959 #endif
960 #ifdef HAVE_SYS_INOTIFY_H
961  if (e->m_mode == INotifyMode) {
962  (void) inotify_rm_watch( m_inotify_fd, e->wd );
963  if (s_verboseDebug) {
964  kDebug(7001).nospace() << "Cancelled INotify (fd " << m_inotify_fd << ", "
965  << e->wd << ") for " << e->path;
966  }
967  }
968 #endif
969 #ifdef HAVE_QFILESYSTEMWATCHER
970  if (e->m_mode == QFSWatchMode && fsWatcher) {
971  if (s_verboseDebug)
972  kDebug(7001) << "fsWatcher->removePath" << e->path;
973  fsWatcher->removePath(e->path);
974  }
975 #endif
976 }
977 
978 void KDirWatchPrivate::removeEntry(KDirWatch* instance,
979  const QString& _path,
980  Entry* sub_entry)
981 {
982  if (s_verboseDebug) {
983  kDebug(7001) << "path=" << _path << "sub_entry:" << sub_entry;
984  }
985  Entry* e = entry(_path);
986  if (!e) {
987  kWarning(7001) << "doesn't know" << _path;
988  return;
989  }
990 
991  removeEntry(instance, e, sub_entry);
992 }
993 
994 void KDirWatchPrivate::removeEntry(KDirWatch* instance,
995  Entry* e,
996  Entry* sub_entry)
997 {
998  removeList.remove(e);
999 
1000  if (sub_entry)
1001  e->m_entries.removeAll(sub_entry);
1002  else
1003  e->removeClient(instance);
1004 
1005  if (e->m_clients.count() || e->m_entries.count())
1006  return;
1007 
1008  if (delayRemove) {
1009  removeList.insert(e);
1010  // now e->isValid() is false
1011  return;
1012  }
1013 
1014  if ( e->m_status == Normal) {
1015  removeWatch(e);
1016  } else {
1017  // Removed a NonExistent entry - we just remove it from the parent
1018  if (e->isDir)
1019  removeEntry(0, e->parentDirectory(), e);
1020  else
1021  removeEntry(0, QFileInfo(e->path).absolutePath(), e);
1022  }
1023 
1024  if (e->m_mode == StatMode) {
1025  statEntries--;
1026  if ( statEntries == 0 ) {
1027  timer.stop(); // stop timer if lists are empty
1028  kDebug(7001) << " Stopped Polling Timer";
1029  }
1030  }
1031 
1032  if (s_verboseDebug) {
1033  kDebug(7001).nospace() << "Removed " << (e->isDir ? "Dir ":"File ") << e->path
1034  << " for " << (sub_entry ? sub_entry->path : QString())
1035  << " [" << (instance ? instance->objectName() : QString()) << "]";
1036  }
1037  m_mapEntries.remove( e->path ); // <e> not valid any more
1038 }
1039 
1040 
1041 /* Called from KDirWatch destructor:
1042  * remove <instance> as client from all entries
1043  */
1044 void KDirWatchPrivate::removeEntries( KDirWatch* instance )
1045 {
1046  int minfreq = 3600000;
1047 
1048  QStringList pathList;
1049  // put all entries where instance is a client in list
1050  EntryMap::Iterator it = m_mapEntries.begin();
1051  for( ; it != m_mapEntries.end(); ++it ) {
1052  Client* c = 0;
1053  foreach(Client* client, (*it).m_clients) {
1054  if (client->instance == instance) {
1055  c = client;
1056  break;
1057  }
1058  }
1059  if (c) {
1060  c->count = 1; // forces deletion of instance as client
1061  pathList.append((*it).path);
1062  }
1063  else if ( (*it).m_mode == StatMode && (*it).freq < minfreq )
1064  minfreq = (*it).freq;
1065  }
1066 
1067  foreach(const QString &path, pathList)
1068  removeEntry(instance, path, 0);
1069 
1070  if (minfreq > freq) {
1071  // we can decrease the global polling frequency
1072  freq = minfreq;
1073  if (timer.isActive()) timer.start(freq);
1074  kDebug(7001) << "Poll Freq now" << freq << "msec";
1075  }
1076 }
1077 
1078 // instance ==0: stop scanning for all instances
1079 bool KDirWatchPrivate::stopEntryScan( KDirWatch* instance, Entry* e)
1080 {
1081  int stillWatching = 0;
1082  foreach(Client* client, e->m_clients) {
1083  if (!instance || instance == client->instance)
1084  client->watchingStopped = true;
1085  else if (!client->watchingStopped)
1086  stillWatching += client->count;
1087  }
1088 
1089  kDebug(7001) << (instance ? instance->objectName() : QString::fromLatin1("all"))
1090  << "stopped scanning" << e->path << "(now"
1091  << stillWatching << "watchers)";
1092 
1093  if (stillWatching == 0) {
1094  // if nobody is interested, we don't watch
1095  if ( e->m_mode != INotifyMode ) {
1096  e->m_ctime = invalid_ctime; // invalid
1097  e->m_status = NonExistent;
1098  }
1099  // e->m_status = Normal;
1100  }
1101  return true;
1102 }
1103 
1104 // instance ==0: start scanning for all instances
1105 bool KDirWatchPrivate::restartEntryScan( KDirWatch* instance, Entry* e,
1106  bool notify)
1107 {
1108  int wasWatching = 0, newWatching = 0;
1109  foreach(Client* client, e->m_clients) {
1110  if (!client->watchingStopped)
1111  wasWatching += client->count;
1112  else if (!instance || instance == client->instance) {
1113  client->watchingStopped = false;
1114  newWatching += client->count;
1115  }
1116  }
1117  if (newWatching == 0)
1118  return false;
1119 
1120  kDebug(7001) << (instance ? instance->objectName() : QString::fromLatin1("all"))
1121  << "restarted scanning" << e->path
1122  << "(now" << wasWatching+newWatching << "watchers)";
1123 
1124  // restart watching and emit pending events
1125 
1126  int ev = NoChange;
1127  if (wasWatching == 0) {
1128  if (!notify) {
1129  KDE_struct_stat stat_buf;
1130  bool exists = (KDE::stat(e->path, &stat_buf) == 0);
1131  if (exists) {
1132 #ifdef Q_OS_WIN
1133  // ctime is the 'creation time' on windows - use mtime instead
1134  e->m_ctime = stat_buf.st_mtime;
1135 #else
1136  e->m_ctime = stat_buf.st_ctime;
1137 #endif
1138  e->m_status = Normal;
1139  if (s_verboseDebug) {
1140  kDebug(7001) << "Setting status to Normal for" << e << e->path;
1141  }
1142  e->m_nlink = stat_buf.st_nlink;
1143  e->m_ino = stat_buf.st_ino;
1144 
1145  // Same as in scanEntry: ensure no subentry in parent dir
1146  removeEntry(0, e->parentDirectory(), e);
1147  }
1148  else {
1149  e->m_ctime = invalid_ctime;
1150  e->m_status = NonExistent;
1151  e->m_nlink = 0;
1152  if (s_verboseDebug) {
1153  kDebug(7001) << "Setting status to NonExistent for" << e << e->path;
1154  }
1155  }
1156  }
1157  e->msecLeft = 0;
1158  ev = scanEntry(e);
1159  }
1160  emitEvent(e,ev);
1161 
1162  return true;
1163 }
1164 
1165 // instance ==0: stop scanning for all instances
1166 void KDirWatchPrivate::stopScan(KDirWatch* instance)
1167 {
1168  EntryMap::Iterator it = m_mapEntries.begin();
1169  for( ; it != m_mapEntries.end(); ++it )
1170  stopEntryScan(instance, &(*it));
1171 }
1172 
1173 
1174 void KDirWatchPrivate::startScan(KDirWatch* instance,
1175  bool notify, bool skippedToo )
1176 {
1177  if (!notify)
1178  resetList(instance,skippedToo);
1179 
1180  EntryMap::Iterator it = m_mapEntries.begin();
1181  for( ; it != m_mapEntries.end(); ++it )
1182  restartEntryScan(instance, &(*it), notify);
1183 
1184  // timer should still be running when in polling mode
1185 }
1186 
1187 
1188 // clear all pending events, also from stopped
1189 void KDirWatchPrivate::resetList( KDirWatch* /*instance*/, bool skippedToo )
1190 {
1191  EntryMap::Iterator it = m_mapEntries.begin();
1192  for( ; it != m_mapEntries.end(); ++it ) {
1193 
1194  foreach(Client* client, (*it).m_clients) {
1195  if (!client->watchingStopped || skippedToo)
1196  client->pending = NoChange;
1197  }
1198  }
1199 }
1200 
1201 // Return event happened on <e>
1202 //
1203 int KDirWatchPrivate::scanEntry(Entry* e)
1204 {
1205  // Shouldn't happen: Ignore "unknown" notification method
1206  if (e->m_mode == UnknownMode) return NoChange;
1207 
1208  if (e->m_mode == FAMMode || e->m_mode == INotifyMode) {
1209  // we know nothing has changed, no need to stat
1210  if(!e->dirty) return NoChange;
1211  e->dirty = false;
1212  }
1213 
1214  if (e->m_mode == StatMode) {
1215  // only scan if timeout on entry timer happens;
1216  // e.g. when using 500msec global timer, a entry
1217  // with freq=5000 is only watched every 10th time
1218 
1219  e->msecLeft -= freq;
1220  if (e->msecLeft>0) return NoChange;
1221  e->msecLeft += e->freq;
1222  }
1223 
1224  KDE_struct_stat stat_buf;
1225  const bool exists = (KDE::stat(e->path, &stat_buf) == 0);
1226  if (exists) {
1227 
1228  if (e->m_status == NonExistent) {
1229  // ctime is the 'creation time' on windows, but with qMax
1230  // we get the latest change of any kind, on any platform.
1231  e->m_ctime = qMax(stat_buf.st_ctime, stat_buf.st_mtime);
1232  e->m_status = Normal;
1233  e->m_ino = stat_buf.st_ino;
1234  if (s_verboseDebug) {
1235  kDebug(7001) << "Setting status to Normal for just created" << e << e->path;
1236  }
1237  // We need to make sure the entry isn't listed in its parent's subentries... (#222974, testMoveTo)
1238  removeEntry(0, e->parentDirectory(), e);
1239 
1240  return Created;
1241  }
1242 
1243 #if 1 // for debugging the if() below
1244  if (s_verboseDebug) {
1245  struct tm* tmp = localtime(&e->m_ctime);
1246  char outstr[200];
1247  strftime(outstr, sizeof(outstr), "%T", tmp);
1248  kDebug(7001) << "e->m_ctime=" << e->m_ctime << outstr
1249  << "stat_buf.st_ctime=" << stat_buf.st_ctime
1250  << "e->m_nlink=" << e->m_nlink
1251  << "stat_buf.st_nlink=" << stat_buf.st_nlink
1252  << "e->m_ino=" << e->m_ino
1253  << "stat_buf.st_ino=" << stat_buf.st_ino;
1254  }
1255 #endif
1256 
1257  if ( ((e->m_ctime != invalid_ctime) &&
1258  (qMax(stat_buf.st_ctime, stat_buf.st_mtime) != e->m_ctime ||
1259  stat_buf.st_ino != e->m_ino ||
1260  stat_buf.st_nlink != nlink_t(e->m_nlink)))
1261 #ifdef Q_OS_WIN
1262  // we trust QFSW to get it right, the ctime comparisons above
1263  // fail for example when adding files to directories on Windows
1264  // which doesn't change the mtime of the directory
1265  || e->m_mode == QFSWatchMode
1266 #endif
1267  ) {
1268  e->m_ctime = qMax(stat_buf.st_ctime, stat_buf.st_mtime);
1269  e->m_nlink = stat_buf.st_nlink;
1270  if (e->m_ino != stat_buf.st_ino) {
1271  // The file got deleted and recreated. We need to watch it again.
1272  removeWatch(e);
1273  addWatch(e);
1274  }
1275  e->m_ino = stat_buf.st_ino;
1276  return Changed;
1277  }
1278 
1279  return NoChange;
1280  }
1281 
1282  // dir/file doesn't exist
1283 
1284  e->m_nlink = 0;
1285  e->m_ino = 0;
1286  e->m_status = NonExistent;
1287 
1288  if (e->m_ctime == invalid_ctime) {
1289  return NoChange;
1290  }
1291 
1292  e->m_ctime = invalid_ctime;
1293  return Deleted;
1294 }
1295 
1296 /* Notify all interested KDirWatch instances about a given event on an entry
1297  * and stored pending events. When watching is stopped, the event is
1298  * added to the pending events.
1299  */
1300 void KDirWatchPrivate::emitEvent(const Entry* e, int event, const QString &fileName)
1301 {
1302  QString path (e->path);
1303  if (!fileName.isEmpty()) {
1304  if (!QDir::isRelativePath(fileName))
1305  path = fileName;
1306  else {
1307 #ifdef Q_OS_UNIX
1308  path += QLatin1Char('/') + fileName;
1309 #elif defined(Q_WS_WIN)
1310  //current drive is passed instead of /
1311  path += QDir::currentPath().left(2) + QLatin1Char('/') + fileName;
1312 #endif
1313  }
1314  }
1315 
1316  if (s_verboseDebug) {
1317  kDebug(7001) << event << path << e->m_clients.count() << "clients";
1318  }
1319 
1320  foreach(Client* c, e->m_clients)
1321  {
1322  if (c->instance==0 || c->count==0) continue;
1323 
1324  if (c->watchingStopped) {
1325  // add event to pending...
1326  if (event == Changed)
1327  c->pending |= event;
1328  else if (event == Created || event == Deleted)
1329  c->pending = event;
1330  continue;
1331  }
1332  // not stopped
1333  if (event == NoChange || event == Changed)
1334  event |= c->pending;
1335  c->pending = NoChange;
1336  if (event == NoChange) continue;
1337 
1338  // Emit the signals delayed, to avoid unexpected re-entrancy from the slots (#220153)
1339 
1340  if (event & Deleted) {
1341  QMetaObject::invokeMethod(c->instance, "setDeleted", Qt::QueuedConnection, Q_ARG(QString, path));
1342  // emit only Deleted event...
1343  continue;
1344  }
1345 
1346  if (event & Created) {
1347  QMetaObject::invokeMethod(c->instance, "setCreated", Qt::QueuedConnection, Q_ARG(QString, path));
1348  // possible emit Change event after creation
1349  }
1350 
1351  if (event & Changed) {
1352  QMetaObject::invokeMethod(c->instance, "setDirty", Qt::QueuedConnection, Q_ARG(QString, path));
1353  }
1354  }
1355 }
1356 
1357 // Remove entries which were marked to be removed
1358 void KDirWatchPrivate::slotRemoveDelayed()
1359 {
1360  delayRemove = false;
1361  // Removing an entry could also take care of removing its parent
1362  // (e.g. in FAM or inotify mode), which would remove other entries in removeList,
1363  // so don't use foreach or iterators here...
1364  while (!removeList.isEmpty()) {
1365  Entry* entry = *removeList.begin();
1366  removeEntry(0, entry, 0); // this will remove entry from removeList
1367  }
1368 }
1369 
1370 /* Scan all entries to be watched for changes. This is done regularly
1371  * when polling. FAM and inotify use a single-shot timer to call this slot delayed.
1372  */
1373 void KDirWatchPrivate::slotRescan()
1374 {
1375  if (s_verboseDebug)
1376  kDebug(7001);
1377 
1378  EntryMap::Iterator it;
1379 
1380  // People can do very long things in the slot connected to dirty(),
1381  // like showing a message box. We don't want to keep polling during
1382  // that time, otherwise the value of 'delayRemove' will be reset.
1383  // ### TODO: now the emitEvent delays emission, this can be cleaned up
1384  bool timerRunning = timer.isActive();
1385  if ( timerRunning )
1386  timer.stop();
1387 
1388  // We delay deletions of entries this way.
1389  // removeDir(), when called in slotDirty(), can cause a crash otherwise
1390  // ### TODO: now the emitEvent delays emission, this can be cleaned up
1391  delayRemove = true;
1392 
1393  if (rescan_all)
1394  {
1395  // mark all as dirty
1396  it = m_mapEntries.begin();
1397  for( ; it != m_mapEntries.end(); ++it )
1398  (*it).dirty = true;
1399  rescan_all = false;
1400  }
1401  else
1402  {
1403  // progate dirty flag to dependant entries (e.g. file watches)
1404  it = m_mapEntries.begin();
1405  for( ; it != m_mapEntries.end(); ++it )
1406  if (((*it).m_mode == INotifyMode || (*it).m_mode == QFSWatchMode) && (*it).dirty )
1407  (*it).propagate_dirty();
1408  }
1409 
1410 #ifdef HAVE_SYS_INOTIFY_H
1411  QList<Entry*> cList;
1412 #endif
1413 
1414  it = m_mapEntries.begin();
1415  for( ; it != m_mapEntries.end(); ++it ) {
1416  // we don't check invalid entries (i.e. remove delayed)
1417  Entry* entry = &(*it);
1418  if (!entry->isValid()) continue;
1419 
1420  const int ev = scanEntry(entry);
1421  if (s_verboseDebug)
1422  kDebug(7001) << "scanEntry for" << entry->path << "says" << ev;
1423 
1424  switch(entry->m_mode) {
1425 #ifdef HAVE_SYS_INOTIFY_H
1426  case INotifyMode:
1427  if ( ev == Deleted ) {
1428  if (s_verboseDebug)
1429  kDebug(7001) << "scanEntry says" << entry->path << "was deleted";
1430  addEntry(0, entry->parentDirectory(), entry, true);
1431  } else if (ev == Created) {
1432  if (s_verboseDebug)
1433  kDebug(7001) << "scanEntry says" << entry->path << "was created. wd=" << entry->wd;
1434  if (entry->wd < 0) {
1435  cList.append(entry);
1436  addWatch(entry);
1437  }
1438  }
1439  break;
1440 #endif
1441  case FAMMode:
1442  case QFSWatchMode:
1443  if (ev == Created) {
1444  addWatch(entry);
1445  }
1446  break;
1447  default:
1448  // dunno about StatMode...
1449  break;
1450  }
1451 
1452 #ifdef HAVE_SYS_INOTIFY_H
1453  if (entry->isDir) {
1454  // Report and clear the the list of files that have changed in this directory.
1455  // Remove duplicates by changing to set and back again:
1456  // we don't really care about preserving the order of the
1457  // original changes.
1458  QStringList pendingFileChanges = entry->m_pendingFileChanges;
1459  pendingFileChanges.removeDuplicates();
1460  Q_FOREACH(const QString &changedFilename, pendingFileChanges) {
1461  if (s_verboseDebug) {
1462  kDebug(7001) << "processing pending file change for" << changedFilename;
1463  }
1464  emitEvent(entry, Changed, changedFilename);
1465  }
1466  entry->m_pendingFileChanges.clear();
1467  }
1468 #endif
1469 
1470  if ( ev != NoChange ) {
1471  emitEvent(entry, ev);
1472  }
1473  }
1474 
1475  if ( timerRunning )
1476  timer.start(freq);
1477 
1478 #ifdef HAVE_SYS_INOTIFY_H
1479  // Remove watch of parent of new created directories
1480  Q_FOREACH(Entry* e, cList)
1481  removeEntry(0, e->parentDirectory(), e);
1482 #endif
1483 
1484  QTimer::singleShot(0, this, SLOT(slotRemoveDelayed()));
1485 }
1486 
1487 bool KDirWatchPrivate::isNoisyFile( const char * filename )
1488 {
1489  // $HOME/.X.err grows with debug output, so don't notify change
1490  if ( *filename == '.') {
1491  if (strncmp(filename, ".X.err", 6) == 0) return true;
1492  if (strncmp(filename, ".xsession-errors", 16) == 0) return true;
1493  // fontconfig updates the cache on every KDE app start
1494  // (inclusive kio_thumbnail slaves)
1495  if (strncmp(filename, ".fonts.cache", 12) == 0) return true;
1496  }
1497 
1498  return false;
1499 }
1500 
1501 #ifdef HAVE_FAM
1502 void KDirWatchPrivate::famEventReceived()
1503 {
1504  static FAMEvent fe;
1505 
1506  delayRemove = true;
1507 
1508  //kDebug(7001) << "Fam event received";
1509 
1510  while(use_fam && FAMPending(&fc)) {
1511  if (FAMNextEvent(&fc, &fe) == -1) {
1512  kWarning(7001) << "FAM connection problem, switching to polling.";
1513  use_fam = false;
1514  delete sn; sn = 0;
1515 
1516  // Replace all FAMMode entries with INotify/Stat
1517  EntryMap::Iterator it = m_mapEntries.begin();
1518  for( ; it != m_mapEntries.end(); ++it )
1519  if ((*it).m_mode == FAMMode && (*it).m_clients.count()>0) {
1520  Entry* e = &(*it);
1521  addWatch(e);
1522  }
1523  }
1524  else
1525  checkFAMEvent(&fe);
1526  }
1527 
1528  QTimer::singleShot(0, this, SLOT(slotRemoveDelayed()));
1529 }
1530 
1531 void KDirWatchPrivate::checkFAMEvent(FAMEvent* fe)
1532 {
1533  //kDebug(7001);
1534 
1535  // Don't be too verbose ;-)
1536  if ((fe->code == FAMExists) ||
1537  (fe->code == FAMEndExist) ||
1538  (fe->code == FAMAcknowledge)) return;
1539 
1540  if ( isNoisyFile( fe->filename ) )
1541  return;
1542 
1543  Entry* e = 0;
1544  EntryMap::Iterator it = m_mapEntries.begin();
1545  for( ; it != m_mapEntries.end(); ++it )
1546  if (FAMREQUEST_GETREQNUM(&( (*it).fr )) ==
1547  FAMREQUEST_GETREQNUM(&(fe->fr)) ) {
1548  e = &(*it);
1549  break;
1550  }
1551 
1552  // Entry* e = static_cast<Entry*>(fe->userdata);
1553 
1554  if (s_verboseDebug) { // don't enable this except when debugging, see #88538
1555  kDebug(7001) << "Processing FAM event ("
1556  << ((fe->code == FAMChanged) ? "FAMChanged" :
1557  (fe->code == FAMDeleted) ? "FAMDeleted" :
1558  (fe->code == FAMStartExecuting) ? "FAMStartExecuting" :
1559  (fe->code == FAMStopExecuting) ? "FAMStopExecuting" :
1560  (fe->code == FAMCreated) ? "FAMCreated" :
1561  (fe->code == FAMMoved) ? "FAMMoved" :
1562  (fe->code == FAMAcknowledge) ? "FAMAcknowledge" :
1563  (fe->code == FAMExists) ? "FAMExists" :
1564  (fe->code == FAMEndExist) ? "FAMEndExist" : "Unknown Code")
1565  << ", " << fe->filename
1566  << ", Req " << FAMREQUEST_GETREQNUM(&(fe->fr)) << ") e=" << e;
1567  }
1568 
1569  if (!e) {
1570  // this happens e.g. for FAMAcknowledge after deleting a dir...
1571  // kDebug(7001) << "No entry for FAM event ?!";
1572  return;
1573  }
1574 
1575  if (e->m_status == NonExistent) {
1576  kDebug(7001) << "FAM event for nonExistent entry " << e->path;
1577  return;
1578  }
1579 
1580  // Delayed handling. This rechecks changes with own stat calls.
1581  e->dirty = true;
1582  if (!rescan_timer.isActive())
1583  rescan_timer.start(m_PollInterval); // singleshot
1584 
1585  // needed FAM control actions on FAM events
1586  switch (fe->code) {
1587  case FAMDeleted:
1588  // fe->filename is an absolute path when a watched file-or-dir is deleted
1589  if (!QDir::isRelativePath(QFile::decodeName(fe->filename))) {
1590  FAMCancelMonitor(&fc, &(e->fr) ); // needed ?
1591  kDebug(7001) << "Cancelled FAMReq"
1592  << FAMREQUEST_GETREQNUM(&(e->fr))
1593  << "for" << e->path;
1594  e->m_status = NonExistent;
1595  e->m_ctime = invalid_ctime;
1596  emitEvent(e, Deleted, e->path);
1597  // Add entry to parent dir to notice if the entry gets recreated
1598  addEntry(0, e->parentDirectory(), e, true /*isDir*/);
1599  } else {
1600  // A file in this directory has been removed, and wasn't explicitly watched.
1601  // We could still inform clients, like inotify does? But stat can't.
1602  // For now we just marked e dirty and slotRescan will emit the dir as dirty.
1603  //kDebug(7001) << "Got FAMDeleted for" << QFile::decodeName(fe->filename) << "in" << e->path << ". Absolute path -> NOOP!";
1604  }
1605  break;
1606 
1607  case FAMCreated: {
1608  // check for creation of a directory we have to watch
1609  QString tpath(e->path + QLatin1Char('/') + QFile::decodeName(fe->filename));
1610 
1611  // This code is very similar to the one in inotifyEventReceived...
1612  Entry* sub_entry = e->findSubEntry(tpath);
1613  if (sub_entry /*&& sub_entry->isDir*/) {
1614  // We were waiting for this new file/dir to be created
1615  emitEvent(sub_entry, Created);
1616  sub_entry->dirty = true;
1617  rescan_timer.start(0); // process this asap, to start watching that dir
1618  } else if (e->isDir && !e->m_clients.empty()) {
1619  bool isDir = false;
1620  const QList<Client *> clients = e->clientsForFileOrDir(tpath, &isDir);
1621  Q_FOREACH(Client *client, clients) {
1622  addEntry (client->instance, tpath, 0, isDir,
1623  isDir ? client->m_watchModes : KDirWatch::WatchDirOnly);
1624  }
1625 
1626  if (!clients.isEmpty()) {
1627  emitEvent(e, Created, tpath);
1628 
1629  kDebug(7001).nospace() << clients.count() << " instance(s) monitoring the new "
1630  << (isDir ? "dir " : "file ") << tpath;
1631  }
1632  }
1633  }
1634  break;
1635  default:
1636  break;
1637  }
1638 }
1639 #else
1640 void KDirWatchPrivate::famEventReceived()
1641 {
1642  kWarning (7001) << "Fam event received but FAM is not supported";
1643 }
1644 #endif
1645 
1646 
1647 void KDirWatchPrivate::statistics()
1648 {
1649  EntryMap::Iterator it;
1650 
1651  kDebug(7001) << "Entries watched:";
1652  if (m_mapEntries.count()==0) {
1653  kDebug(7001) << " None.";
1654  }
1655  else {
1656  it = m_mapEntries.begin();
1657  for( ; it != m_mapEntries.end(); ++it ) {
1658  Entry* e = &(*it);
1659  kDebug(7001) << " " << *e;
1660 
1661  foreach(Client* c, e->m_clients) {
1662  QByteArray pending;
1663  if (c->watchingStopped) {
1664  if (c->pending & Deleted) pending += "deleted ";
1665  if (c->pending & Created) pending += "created ";
1666  if (c->pending & Changed) pending += "changed ";
1667  if (!pending.isEmpty()) pending = " (pending: " + pending + ')';
1668  pending = ", stopped" + pending;
1669  }
1670  kDebug(7001) << " by " << c->instance->objectName()
1671  << " (" << c->count << " times)" << pending;
1672  }
1673  if (e->m_entries.count()>0) {
1674  kDebug(7001) << " dependent entries:";
1675  foreach(Entry *d, e->m_entries) {
1676  kDebug(7001) << " " << d << d->path << (d->m_status == NonExistent ? "NonExistent" : "EXISTS!!! ERROR!");
1677  if (s_verboseDebug) {
1678  Q_ASSERT(d->m_status == NonExistent); // it doesn't belong here otherwise
1679  }
1680  }
1681  }
1682  }
1683  }
1684 }
1685 
1686 #ifdef HAVE_QFILESYSTEMWATCHER
1687 // Slot for QFileSystemWatcher
1688 void KDirWatchPrivate::fswEventReceived(const QString &path)
1689 {
1690  if (s_verboseDebug)
1691  kDebug(7001) << path;
1692  EntryMap::Iterator it = m_mapEntries.find(path);
1693  if(it != m_mapEntries.end()) {
1694  Entry* e = &(*it);
1695  e->dirty = true;
1696  const int ev = scanEntry(e);
1697  if (s_verboseDebug)
1698  kDebug(7001) << "scanEntry for" << e->path << "says" << ev;
1699  if (ev != NoChange)
1700  emitEvent(e, ev);
1701  if(ev == Deleted) {
1702  if (e->isDir)
1703  addEntry(0, e->parentDirectory(), e, true);
1704  else
1705  addEntry(0, QFileInfo(e->path).absolutePath(), e, true);
1706  } else if (ev == Created) {
1707  // We were waiting for it to appear; now watch it
1708  addWatch(e);
1709  } else if (e->isDir) {
1710  // Check if any file or dir was created under this directory, that we were waiting for
1711  Q_FOREACH(Entry* sub_entry, e->m_entries) {
1712  fswEventReceived(sub_entry->path); // recurse, to call scanEntry and see if something changed
1713  }
1714  }
1715  }
1716 }
1717 #else
1718 void KDirWatchPrivate::fswEventReceived(const QString &path)
1719 {
1720  Q_UNUSED(path);
1721  kWarning (7001) << "QFileSystemWatcher event received but QFileSystemWatcher is not supported";
1722 }
1723 #endif // HAVE_QFILESYSTEMWATCHER
1724 
1725 //
1726 // Class KDirWatch
1727 //
1728 
1729 K_GLOBAL_STATIC(KDirWatch, s_pKDirWatchSelf)
1730 KDirWatch* KDirWatch::self()
1731 {
1732  return s_pKDirWatchSelf;
1733 }
1734 
1735 // TODO KDE5: is this used anywhere?
1736 bool KDirWatch::exists()
1737 {
1738  return s_pKDirWatchSelf.exists();
1739 }
1740 
1741 static void cleanupQFSWatcher()
1742 {
1743  s_pKDirWatchSelf->deleteQFSWatcher();
1744 }
1745 
1746 KDirWatch::KDirWatch (QObject* parent)
1747  : QObject(parent), d(createPrivate())
1748 {
1749  static int nameCounter = 0;
1750 
1751  nameCounter++;
1752  setObjectName(QString::fromLatin1("KDirWatch-%1").arg(nameCounter) );
1753 
1754  d->ref();
1755 
1756  d->_isStopped = false;
1757 
1758  static bool cleanupRegistered = false;
1759  if (!cleanupRegistered) {
1760  cleanupRegistered = true;
1761  // Must delete QFileSystemWatcher before qApp is gone - bug 261541
1762  qAddPostRoutine(cleanupQFSWatcher);
1763  }
1764 }
1765 
1766 KDirWatch::~KDirWatch()
1767 {
1768  d->removeEntries(this);
1769  if ( d->deref() )
1770  {
1771  // delete it if it's the last one
1772  delete d;
1773  dwp_self = 0;
1774  }
1775 }
1776 
1777 void KDirWatch::addDir( const QString& _path, WatchModes watchModes)
1778 {
1779  if (d) d->addEntry(this, _path, 0, true, watchModes);
1780 }
1781 
1782 void KDirWatch::addFile( const QString& _path )
1783 {
1784  if ( !d )
1785  return;
1786 
1787  d->addEntry(this, _path, 0, false);
1788 }
1789 
1790 QDateTime KDirWatch::ctime( const QString &_path ) const
1791 {
1792  KDirWatchPrivate::Entry* e = d->entry(_path);
1793 
1794  if (!e)
1795  return QDateTime();
1796 
1797  return QDateTime::fromTime_t(e->m_ctime);
1798 }
1799 
1800 void KDirWatch::removeDir( const QString& _path )
1801 {
1802  if (d) d->removeEntry(this, _path, 0);
1803 }
1804 
1805 void KDirWatch::removeFile( const QString& _path )
1806 {
1807  if (d) d->removeEntry(this, _path, 0);
1808 }
1809 
1810 bool KDirWatch::stopDirScan( const QString& _path )
1811 {
1812  if (d) {
1813  KDirWatchPrivate::Entry *e = d->entry(_path);
1814  if (e && e->isDir) return d->stopEntryScan(this, e);
1815  }
1816  return false;
1817 }
1818 
1819 bool KDirWatch::restartDirScan( const QString& _path )
1820 {
1821  if (d) {
1822  KDirWatchPrivate::Entry *e = d->entry(_path);
1823  if (e && e->isDir)
1824  // restart without notifying pending events
1825  return d->restartEntryScan(this, e, false);
1826  }
1827  return false;
1828 }
1829 
1830 void KDirWatch::stopScan()
1831 {
1832  if (d) {
1833  d->stopScan(this);
1834  d->_isStopped = true;
1835  }
1836 }
1837 
1838 bool KDirWatch::isStopped()
1839 {
1840  return d->_isStopped;
1841 }
1842 
1843 void KDirWatch::startScan( bool notify, bool skippedToo )
1844 {
1845  if (d) {
1846  d->_isStopped = false;
1847  d->startScan(this, notify, skippedToo);
1848  }
1849 }
1850 
1851 
1852 bool KDirWatch::contains( const QString& _path ) const
1853 {
1854  KDirWatchPrivate::Entry* e = d->entry(_path);
1855  if (!e)
1856  return false;
1857 
1858  foreach(KDirWatchPrivate::Client* client, e->m_clients) {
1859  if (client->instance == this)
1860  return true;
1861  }
1862 
1863  return false;
1864 }
1865 
1866 void KDirWatch::deleteQFSWatcher()
1867 {
1868  delete d->fsWatcher;
1869  d->fsWatcher = 0;
1870 }
1871 
1872 void KDirWatch::statistics()
1873 {
1874  if (!dwp_self) {
1875  kDebug(7001) << "KDirWatch not used";
1876  return;
1877  }
1878  dwp_self->statistics();
1879 }
1880 
1881 
1882 void KDirWatch::setCreated( const QString & _file )
1883 {
1884  kDebug(7001) << objectName() << "emitting created" << _file;
1885  emit created( _file );
1886 }
1887 
1888 void KDirWatch::setDirty( const QString & _file )
1889 {
1890  //kDebug(7001) << objectName() << "emitting dirty" << _file;
1891  emit dirty( _file );
1892 }
1893 
1894 void KDirWatch::setDeleted( const QString & _file )
1895 {
1896  kDebug(7001) << objectName() << "emitting deleted" << _file;
1897  emit deleted( _file );
1898 }
1899 
1900 KDirWatch::Method KDirWatch::internalMethod()
1901 {
1902  return d->m_preferredMethod;
1903 }
1904 
1905 
1906 #include "kdirwatch.moc"
1907 #include "kdirwatch_p.moc"
1908 
1909 //sven
This file is part of the KDE documentation.
Documentation copyright © 1996-2013 The KDE developers.
Generated on Wed Mar 20 2013 07:14:35 by doxygen 1.8.3.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.10.1 API Reference

Skip menu "kdelibs-4.10.1 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