• Skip to content
  • Skip to link menu
  • KDE API Reference
  • kdelibs-4.9.4 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  KDE_lstat( lockFileName, &st_buf ); // caller wants stat buf details
282  return LockFail;
283  } else {
284  return LockError;
285  }
286  }
287  // We hold the lock, continue.
288  if (!m_file.open(fd, QIODevice::WriteOnly)) {
289  return LockError;
290  }
291  mustCloseFd = true;
292  writeIntoLockFile(m_file, m_componentData);
293 
294  // stat to get the modification time
295  const int result = KDE_lstat(QFile::encodeName(m_fileName), &st_buf);
296  if (result != 0)
297  return KLockFile::LockError;
298  return KLockFile::LockOK;
299 }
300 
301 KLockFile::LockResult KLockFile::Private::deleteStaleLock()
302 {
303  if (isNfs())
304  return deleteStaleLockWithLink();
305 
306  // I see no way to prevent the race condition here, where we could
307  // delete a new lock file that another process just got after we
308  // decided the old one was too stale for us too.
309  qWarning("WARNING: deleting stale lockfile %s", qPrintable(m_fileName));
310  QFile::remove(m_fileName);
311  return LockOK;
312 }
313 
314 KLockFile::LockResult KLockFile::Private::deleteStaleLockWithLink()
315 {
316  // This is dangerous, we could be deleting a new lock instead of
317  // the old stale one, let's be very careful
318 
319  // Create temp file
320  KTemporaryFile *ktmpFile = new KTemporaryFile(m_componentData);
321  ktmpFile->setFileTemplate(m_fileName);
322  if (!ktmpFile->open()) {
323  delete ktmpFile;
324  return KLockFile::LockError;
325  }
326 
327  const QByteArray lckFile = QFile::encodeName(m_fileName);
328  const QByteArray tmpFile = QFile::encodeName(ktmpFile->fileName());
329  delete ktmpFile;
330 
331  // link to lock file
332  if (::link(lckFile, tmpFile) != 0)
333  return KLockFile::LockFail; // Try again later
334 
335  // check if link count increased with exactly one
336  // and if the lock file still matches
337  KDE_struct_stat st_buf1;
338  KDE_struct_stat st_buf2;
339  memcpy(&st_buf1, &statBuf, sizeof(KDE_struct_stat));
340  st_buf1.st_nlink++;
341  if ((KDE_lstat(tmpFile, &st_buf2) == 0) && st_buf1 == st_buf2)
342  {
343  if ((KDE_lstat(lckFile, &st_buf2) == 0) && st_buf1 == st_buf2)
344  {
345  // - - if yes, delete lock file, delete temp file, retry lock
346  qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
347  ::unlink(lckFile);
348  ::unlink(tmpFile);
349  return KLockFile::LockOK;
350  }
351  }
352 
353  // SMBFS supports hardlinks by copying the file, as a result the above test will always fail
354  if (linkCountSupport)
355  {
356  linkCountSupport = testLinkCountSupport(tmpFile);
357  }
358 
359  if (!linkCountSupport)
360  {
361  // Without support for link counts we will have a little race condition
362  qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
363  ::unlink(tmpFile);
364  if (::unlink(lckFile) < 0) {
365  qWarning("WARNING: Problem deleting stale lockfile %s: %s", lckFile.data(),
366  strerror(errno));
367  return KLockFile::LockFail;
368  }
369  return KLockFile::LockOK;
370  }
371 
372  // Failed to delete stale lock file
373  qWarning("WARNING: Problem deleting stale lockfile %s", lckFile.data());
374  ::unlink(tmpFile);
375  return KLockFile::LockFail;
376 }
377 
378 
379 KLockFile::LockResult KLockFile::lock(LockFlags options)
380 {
381  if (d->isLocked)
382  return KLockFile::LockOK;
383 
384  KLockFile::LockResult result;
385  int hardErrors = 5;
386  int n = 5;
387  while(true)
388  {
389  KDE_struct_stat st_buf;
390  // Try to create the lock file
391  result = d->lockFile(st_buf);
392 
393  if (result == KLockFile::LockOK)
394  {
395  d->staleTimer = QTime();
396  break;
397  }
398  else if (result == KLockFile::LockError)
399  {
400  d->staleTimer = QTime();
401  if (--hardErrors == 0)
402  {
403  break;
404  }
405  }
406  else // KLockFile::Fail -- there is already such a file present (e.g. left by a crashed app)
407  {
408  if (!d->staleTimer.isNull() && d->statBuf != st_buf)
409  d->staleTimer = QTime();
410 
411  if (d->staleTimer.isNull())
412  {
413  memcpy(&(d->statBuf), &st_buf, sizeof(KDE_struct_stat));
414  d->staleTimer.start();
415 
416  d->readLockFile();
417  }
418 
419  bool isStale = false;
420  if ((d->m_pid > 0) && !d->m_hostname.isEmpty())
421  {
422  // Check if hostname is us
423  char hostname[256];
424  hostname[0] = 0;
425  gethostname(hostname, 255);
426  hostname[255] = 0;
427 
428  if (d->m_hostname == QLatin1String(hostname))
429  {
430  // Check if pid still exists
431  int res = ::kill(d->m_pid, 0);
432  if ((res == -1) && (errno == ESRCH))
433  isStale = true; // pid does not exist
434  }
435  }
436  if (d->staleTimer.elapsed() > (d->staleTime*1000))
437  isStale = true;
438 
439  if (isStale)
440  {
441  if ((options & ForceFlag) == 0)
442  return KLockFile::LockStale;
443 
444  result = d->deleteStaleLock();
445 
446  if (result == KLockFile::LockOK)
447  {
448  // Lock deletion successful
449  d->staleTimer = QTime();
450  continue; // Now try to get the new lock
451  }
452  else if (result != KLockFile::LockFail)
453  {
454  return result;
455  }
456  }
457  }
458 
459  if (options & NoBlockFlag)
460  break;
461 
462  struct timeval tv;
463  tv.tv_sec = 0;
464  tv.tv_usec = n*((KRandom::random() % 200)+100);
465  if (n < 2000)
466  n = n * 2;
467 
468  select(0, 0, 0, 0, &tv);
469  }
470  if (result == LockOK)
471  d->isLocked = true;
472  return result;
473 }
474 
475 bool KLockFile::isLocked() const
476 {
477  return d->isLocked;
478 }
479 
480 void KLockFile::unlock()
481 {
482  if (d->isLocked)
483  {
484  ::unlink(QFile::encodeName(d->m_fileName));
485  if (d->mustCloseFd) {
486  close(d->m_file.handle());
487  d->mustCloseFd = false;
488  }
489  d->m_file.close();
490  d->m_pid = -1;
491  d->isLocked = false;
492  }
493 }
494 
495 bool KLockFile::getLockInfo(int &pid, QString &hostname, QString &appname)
496 {
497  if (d->m_pid == -1)
498  return false;
499  pid = d->m_pid;
500  hostname = d->m_hostname;
501  appname = d->m_componentName;
502  return true;
503 }
This file is part of the KDE documentation.
Documentation copyright © 1996-2012 The KDE developers.
Generated on Mon Dec 10 2012 13:38:49 by doxygen 1.8.1.2 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.9.4 API Reference

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