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

KDECore

  • kdecore
  • io
klockfile_unix.cpp
Go to the documentation of this file.
1 /*
2  This file is part of the KDE libraries
3  Copyright (c) 2004 Waldo Bastian <bastian@kde.org>
4  Copyright (c) 2011 David Faure <faure@kde.org>
5 
6  This library is free software; you can redistribute it and/or
7  modify it under the terms of the GNU Library General Public
8  License version 2 as published by the Free Software Foundation.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Library General Public License for more details.
14 
15  You should have received a copy of the GNU Library General Public License
16  along with this library; see the file COPYING.LIB. If not, write to
17  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  Boston, MA 02110-1301, USA.
19 */
20 
21 #include "klockfile.h"
22 
23 #include <config.h>
24 
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_STAT_H
27 #include <sys/stat.h>
28 #endif
29 #ifdef HAVE_SYS_TIME_H
30 #include <sys/time.h>
31 #endif
32 #include <signal.h>
33 #include <errno.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 
37 #include <QtCore/QDate>
38 #include <QtCore/QFile>
39 #include <QTextStream>
40 
41 #include "krandom.h"
42 #include "kglobal.h"
43 #include "kcomponentdata.h"
44 #include "ktemporaryfile.h"
45 #include "kde_file.h"
46 #include "kfilesystemtype_p.h"
47 
48 #include <unistd.h>
49 #include <fcntl.h>
50 
51 // Related reading:
52 // http://www.spinnaker.de/linux/nfs-locking.html
53 // http://en.wikipedia.org/wiki/File_locking
54 // http://apenwarr.ca/log/?m=201012
55 
56 // Related source code:
57 // * lockfile-create, from the lockfile-progs package, uses the link() trick from lockFileWithLink
58 // below, so it works over NFS but fails on FAT32 too.
59 // * the flock program, which uses flock(LOCK_EX), works on local filesystems (including FAT32),
60 // but not NFS.
61 // Note about flock: don't unlink, it creates a race. http://world.std.com/~swmcd/steven/tech/flock.html
62 
63 // fcntl(F_SETLK) is not a good solution.
64 // It locks other processes but locking out other threads must be done by hand,
65 // and worse, it unlocks when just reading the file in the same process (!).
66 // See the apenwarr.ca article above.
67 
68 // open(O_EXCL) seems to be the best solution for local files (on all filesystems),
69 // it only fails over NFS (at least with old NFS servers).
70 // See http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=144
71 
72 // Conclusion: we use O_EXCL by default, and the link() trick over NFS.
73 
74 class KLockFile::Private
75 {
76 public:
77  Private(const KComponentData &c)
78  : staleTime(30), // 30 seconds
79  isLocked(false),
80  linkCountSupport(true),
81  mustCloseFd(false),
82  m_pid(-1),
83  m_componentData(c)
84  {
85  }
86 
87  // The main method
88  KLockFile::LockResult lockFile(KDE_struct_stat &st_buf);
89 
90  // Two different implementations
91  KLockFile::LockResult lockFileOExcl(KDE_struct_stat &st_buf);
92  KLockFile::LockResult lockFileWithLink(KDE_struct_stat &st_buf);
93 
94  KLockFile::LockResult deleteStaleLock();
95  KLockFile::LockResult deleteStaleLockWithLink();
96 
97  void writeIntoLockFile(QFile& file, const KComponentData& componentData);
98  void readLockFile();
99  bool isNfs() const;
100 
101  QFile m_file;
102  QString m_fileName;
103  int staleTime;
104  bool isLocked;
105  bool linkCountSupport;
106  bool mustCloseFd;
107  QTime staleTimer;
108  KDE_struct_stat statBuf;
109  int m_pid;
110  QString m_hostname;
111  QString m_componentName;
112  KComponentData m_componentData;
113 };
114 
115 
116 KLockFile::KLockFile(const QString &file, const KComponentData &componentData)
117  : d(new Private(componentData))
118 {
119  d->m_fileName = file;
120 }
121 
122 KLockFile::~KLockFile()
123 {
124  unlock();
125  delete d;
126 }
127 
128 int
129 KLockFile::staleTime() const
130 {
131  return d->staleTime;
132 }
133 
134 
135 void
136 KLockFile::setStaleTime(int _staleTime)
137 {
138  d->staleTime = _staleTime;
139 }
140 
141 static bool operator==( const KDE_struct_stat &st_buf1,
142  const KDE_struct_stat &st_buf2)
143 {
144 #define FIELD_EQ(what) (st_buf1.what == st_buf2.what)
145  return FIELD_EQ(st_dev) && FIELD_EQ(st_ino) &&
146  FIELD_EQ(st_uid) && FIELD_EQ(st_gid) && FIELD_EQ(st_nlink);
147 #undef FIELD_EQ
148 }
149 
150 static bool operator!=( const KDE_struct_stat& st_buf1,
151  const KDE_struct_stat& st_buf2 )
152 {
153  return !(st_buf1 == st_buf2);
154 }
155 
156 static bool testLinkCountSupport(const QByteArray &fileName)
157 {
158  KDE_struct_stat st_buf;
159  int result = -1;
160  // Check if hardlinks raise the link count at all?
161  if(!::link( fileName, QByteArray(fileName+".test") )) {
162  result = KDE_lstat( fileName, &st_buf );
163  ::unlink( QByteArray(fileName+".test") );
164  }
165  return (result < 0 || ((result == 0) && (st_buf.st_nlink == 2)));
166 }
167 
168 void KLockFile::Private::writeIntoLockFile(QFile& file, const KComponentData& componentData)
169 {
170  file.setPermissions(QFile::ReadUser|QFile::WriteUser|QFile::ReadGroup|QFile::ReadOther);
171 
172  char hostname[256];
173  hostname[0] = 0;
174  gethostname(hostname, 255);
175  hostname[255] = 0;
176  m_hostname = QString::fromLocal8Bit(hostname);
177  m_componentName = componentData.componentName();
178 
179  QTextStream stream(&file);
180  m_pid = getpid();
181 
182  stream << QString::number(m_pid) << endl
183  << m_componentName << endl
184  << m_hostname << endl;
185  stream.flush();
186 }
187 
188 void KLockFile::Private::readLockFile()
189 {
190  m_pid = -1;
191  m_hostname.clear();
192  m_componentName.clear();
193 
194  QFile file(m_fileName);
195  if (file.open(QIODevice::ReadOnly))
196  {
197  QTextStream ts(&file);
198  if (!ts.atEnd())
199  m_pid = ts.readLine().toInt();
200  if (!ts.atEnd())
201  m_componentName = ts.readLine();
202  if (!ts.atEnd())
203  m_hostname = ts.readLine();
204  }
205 }
206 
207 KLockFile::LockResult KLockFile::Private::lockFileWithLink(KDE_struct_stat &st_buf)
208 {
209  const QByteArray lockFileName = QFile::encodeName( m_fileName );
210  int result = KDE_lstat( lockFileName, &st_buf );
211  if (result == 0) {
212  return KLockFile::LockFail;
213  }
214 
215  KTemporaryFile uniqueFile(m_componentData);
216  uniqueFile.setFileTemplate(m_fileName);
217  if (!uniqueFile.open())
218  return KLockFile::LockError;
219 
220  writeIntoLockFile(uniqueFile, m_componentData);
221 
222  QByteArray uniqueName = QFile::encodeName( uniqueFile.fileName() );
223 
224  // Create lock file
225  result = ::link( uniqueName, lockFileName );
226  if (result != 0)
227  return KLockFile::LockError;
228 
229  if (!linkCountSupport)
230  return KLockFile::LockOK;
231 
232  KDE_struct_stat st_buf2;
233  result = KDE_lstat( uniqueName, &st_buf2 );
234  if (result != 0)
235  return KLockFile::LockError;
236 
237  result = KDE_lstat( lockFileName, &st_buf );
238  if (result != 0)
239  return KLockFile::LockError;
240 
241  if (st_buf != st_buf2 || S_ISLNK(st_buf.st_mode) || S_ISLNK(st_buf2.st_mode))
242  {
243  // SMBFS supports hardlinks by copying the file, as a result the above test will always fail
244  // cifs increases link count artifically but the inodes are still different
245  if ((st_buf2.st_nlink > 1 ||
246  ((st_buf.st_nlink == 1) && (st_buf2.st_nlink == 1))) && (st_buf.st_ino != st_buf2.st_ino))
247  {
248  linkCountSupport = testLinkCountSupport(uniqueName);
249  if (!linkCountSupport)
250  return KLockFile::LockOK; // Link count support is missing... assume everything is OK.
251  }
252  return KLockFile::LockFail;
253  }
254 
255  return KLockFile::LockOK;
256 }
257 
258 bool KLockFile::Private::isNfs() const
259 {
260  const KFileSystemType::Type fsType = KFileSystemType::fileSystemType(m_fileName);
261  return fsType == KFileSystemType::Nfs;
262 }
263 
264 KLockFile::LockResult KLockFile::Private::lockFile(KDE_struct_stat &st_buf)
265 {
266  if (isNfs()) {
267  return lockFileWithLink(st_buf);
268  }
269 
270  return lockFileOExcl(st_buf);
271 }
272 
273 KLockFile::LockResult KLockFile::Private::lockFileOExcl(KDE_struct_stat &st_buf)
274 {
275  const QByteArray lockFileName = QFile::encodeName( m_fileName );
276 
277  int fd = KDE_open(lockFileName.constData(), O_WRONLY | O_CREAT | O_EXCL, 0644);
278  if (fd < 0) {
279  if (errno == EEXIST) {
280  // File already exists
281  return LockFail;
282  } else {
283  return LockError;
284  }
285  }
286  // We hold the lock, continue.
287  if (!m_file.open(fd, QIODevice::WriteOnly)) {
288  return LockError;
289  }
290  mustCloseFd = true;
291  writeIntoLockFile(m_file, m_componentData);
292 
293  // stat to get the modification time
294  const int result = KDE_lstat(QFile::encodeName(m_fileName), &st_buf);
295  if (result != 0)
296  return KLockFile::LockError;
297  return KLockFile::LockOK;
298 }
299 
300 KLockFile::LockResult KLockFile::Private::deleteStaleLock()
301 {
302  if (isNfs())
303  return deleteStaleLockWithLink();
304 
305  // I see no way to prevent the race condition here, where we could
306  // delete a new lock file that another process just got after we
307  // decided the old one was too stale for us too.
308  qWarning("WARNING: deleting stale lockfile %s", qPrintable(m_fileName));
309  QFile::remove(m_fileName);
310  return LockOK;
311 }
312 
313 KLockFile::LockResult KLockFile::Private::deleteStaleLockWithLink()
314 {
315  // This is dangerous, we could be deleting a new lock instead of
316  // the old stale one, let's be very careful
317 
318  // Create temp file
319  KTemporaryFile *ktmpFile = new KTemporaryFile(m_componentData);
320  ktmpFile->setFileTemplate(m_fileName);
321  if (!ktmpFile->open()) {
322  delete ktmpFile;
323  return KLockFile::LockError;
324  }
325 
326  const QByteArray lckFile = QFile::encodeName(m_fileName);
327  const QByteArray tmpFile = QFile::encodeName(ktmpFile->fileName());
328  delete ktmpFile;
329 
330  // link to lock file
331  if (::link(lckFile, tmpFile) != 0)
332  return KLockFile::LockFail; // Try again later
333 
334  // check if link count increased with exactly one
335  // and if the lock file still matches
336  KDE_struct_stat st_buf1;
337  KDE_struct_stat st_buf2;
338  memcpy(&st_buf1, &statBuf, sizeof(KDE_struct_stat));
339  st_buf1.st_nlink++;
340  if ((KDE_lstat(tmpFile, &st_buf2) == 0) && st_buf1 == st_buf2)
341  {
342  if ((KDE_lstat(lckFile, &st_buf2) == 0) && st_buf1 == st_buf2)
343  {
344  // - - if yes, delete lock file, delete temp file, retry lock
345  qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
346  ::unlink(lckFile);
347  ::unlink(tmpFile);
348  return KLockFile::LockOK;
349  }
350  }
351 
352  // SMBFS supports hardlinks by copying the file, as a result the above test will always fail
353  if (linkCountSupport)
354  {
355  linkCountSupport = testLinkCountSupport(tmpFile);
356  }
357 
358  if (!linkCountSupport)
359  {
360  // Without support for link counts we will have a little race condition
361  qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
362  ::unlink(tmpFile);
363  if (::unlink(lckFile) < 0) {
364  qWarning("WARNING: Problem deleting stale lockfile %s: %s", lckFile.data(),
365  strerror(errno));
366  return KLockFile::LockFail;
367  }
368  return KLockFile::LockOK;
369  }
370 
371  // Failed to delete stale lock file
372  qWarning("WARNING: Problem deleting stale lockfile %s", lckFile.data());
373  ::unlink(tmpFile);
374  return KLockFile::LockFail;
375 }
376 
377 
378 KLockFile::LockResult KLockFile::lock(LockFlags options)
379 {
380  if (d->isLocked)
381  return KLockFile::LockOK;
382 
383  KLockFile::LockResult result;
384  int hardErrors = 5;
385  int n = 5;
386  while(true)
387  {
388  KDE_struct_stat st_buf;
389  // Try to create the lock file
390  result = d->lockFile(st_buf);
391 
392  if (result == KLockFile::LockOK)
393  {
394  d->staleTimer = QTime();
395  break;
396  }
397  else if (result == KLockFile::LockError)
398  {
399  d->staleTimer = QTime();
400  if (--hardErrors == 0)
401  {
402  break;
403  }
404  }
405  else // KLockFile::Fail -- there is already such a file present (e.g. left by a crashed app)
406  {
407  if (!d->staleTimer.isNull() && d->statBuf != st_buf)
408  d->staleTimer = QTime();
409 
410  if (d->staleTimer.isNull())
411  {
412  memcpy(&(d->statBuf), &st_buf, sizeof(KDE_struct_stat));
413  d->staleTimer.start();
414 
415  d->readLockFile();
416  }
417 
418  bool isStale = false;
419  if ((d->m_pid > 0) && !d->m_hostname.isEmpty())
420  {
421  // Check if hostname is us
422  char hostname[256];
423  hostname[0] = 0;
424  gethostname(hostname, 255);
425  hostname[255] = 0;
426 
427  if (d->m_hostname == QLatin1String(hostname))
428  {
429  // Check if pid still exists
430  int res = ::kill(d->m_pid, 0);
431  if ((res == -1) && (errno == ESRCH))
432  isStale = true; // pid does not exist
433  }
434  }
435  if (d->staleTimer.elapsed() > (d->staleTime*1000))
436  isStale = true;
437 
438  if (isStale)
439  {
440  if ((options & ForceFlag) == 0)
441  return KLockFile::LockStale;
442 
443  result = d->deleteStaleLock();
444 
445  if (result == KLockFile::LockOK)
446  {
447  // Lock deletion successful
448  d->staleTimer = QTime();
449  continue; // Now try to get the new lock
450  }
451  else if (result != KLockFile::LockFail)
452  {
453  return result;
454  }
455  }
456  }
457 
458  if (options & NoBlockFlag)
459  break;
460 
461  struct timeval tv;
462  tv.tv_sec = 0;
463  tv.tv_usec = n*((KRandom::random() % 200)+100);
464  if (n < 2000)
465  n = n * 2;
466 
467  select(0, 0, 0, 0, &tv);
468  }
469  if (result == LockOK)
470  d->isLocked = true;
471  return result;
472 }
473 
474 bool KLockFile::isLocked() const
475 {
476  return d->isLocked;
477 }
478 
479 void KLockFile::unlock()
480 {
481  if (d->isLocked)
482  {
483  ::unlink(QFile::encodeName(d->m_fileName));
484  if (d->mustCloseFd) {
485  close(d->m_file.handle());
486  d->mustCloseFd = false;
487  }
488  d->m_file.close();
489  d->m_pid = -1;
490  d->isLocked = false;
491  }
492 }
493 
494 bool KLockFile::getLockInfo(int &pid, QString &hostname, QString &appname)
495 {
496  if (d->m_pid == -1)
497  return false;
498  pid = d->m_pid;
499  hostname = d->m_hostname;
500  appname = d->m_componentName;
501  return true;
502 }
This file is part of the KDE documentation.
Documentation copyright © 1996-2013 The KDE developers.
Generated on Thu Feb 21 2013 11:01:06 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