1// Copyright (C) 2013 David Faure <faure+bluesystems@kde.org>
2// Copyright (C) 2017 Intel Corporation.
3// Copyright (C) 2016 The Qt Company Ltd.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5
6#include "private/qlockfile_p.h"
7
8#include "QtCore/qtemporaryfile.h"
9#include "QtCore/qfileinfo.h"
10#include "QtCore/qdebug.h"
11#include "QtCore/qdatetime.h"
12#include "QtCore/qfileinfo.h"
13#include "QtCore/qcache.h"
14#include "QtCore/qglobalstatic.h"
15#include "QtCore/qmutex.h"
16
17#include "private/qcore_unix_p.h" // qt_safe_open
18#include "private/qabstractfileengine_p.h"
19#include "private/qfilesystementry_p.h"
20#include "private/qtemporaryfile_p.h"
21
22#if !defined(Q_OS_INTEGRITY)
23#include <sys/file.h> // flock
24#endif
25
26#if defined(Q_OS_RTEMS)
27// flock() does not work in these OSes and produce warnings when we try to use
28# undef LOCK_EX
29# undef LOCK_NB
30#endif
31
32#include <sys/types.h> // kill
33#include <signal.h> // kill
34#include <unistd.h> // gethostname
35
36#if defined(Q_OS_MACOS)
37# include <libproc.h>
38#elif defined(Q_OS_LINUX)
39# include <unistd.h>
40# include <cstdio>
41#elif defined(Q_OS_HAIKU)
42# include <kernel/OS.h>
43#elif defined(Q_OS_BSD4) && !defined(QT_PLATFORM_UIKIT)
44# include <sys/cdefs.h>
45# include <sys/param.h>
46# include <sys/sysctl.h>
47# if !defined(Q_OS_NETBSD)
48# include <sys/user.h>
49# endif
50#endif
51
52QT_BEGIN_NAMESPACE
53
54// ### merge into qt_safe_write?
55static qint64 qt_write_loop(int fd, const char *data, qint64 len)
56{
57 qint64 pos = 0;
58 while (pos < len) {
59 const qint64 ret = qt_safe_write(fd, data: data + pos, len: len - pos);
60 if (ret == -1) // e.g. partition full
61 return pos;
62 pos += ret;
63 }
64 return pos;
65}
66
67/*
68 * Details about file locking on Unix.
69 *
70 * There are three types of advisory locks on Unix systems:
71 * 1) POSIX process-wide locks using fcntl(F_SETLK)
72 * 2) BSD flock(2) system call
73 * 3) Linux-specific file descriptor locks using fcntl(F_OFD_SETLK)
74 * There's also a mandatory locking feature by POSIX, which is deprecated on
75 * Linux and users are advised not to use it.
76 *
77 * The first problem is that the POSIX API is braindead. POSIX.1-2008 says:
78 *
79 * All locks associated with a file for a given process shall be removed when
80 * a file descriptor for that file is closed by that process or the process
81 * holding that file descriptor terminates.
82 *
83 * The Linux manpage is clearer:
84 *
85 * * If a process closes _any_ file descriptor referring to a file, then all
86 * of the process's locks on that file are released, regardless of the file
87 * descriptor(s) on which the locks were obtained. This is bad: [...]
88 *
89 * * The threads in a process share locks. In other words, a multithreaded
90 * program can't use record locking to ensure that threads don't
91 * simultaneously access the same region of a file.
92 *
93 * So in order to use POSIX locks, we'd need a global mutex that stays locked
94 * while the QLockFile is locked. For that reason, Qt does not use POSIX
95 * advisory locks anymore.
96 *
97 * The next problem is that POSIX leaves undefined the relationship between
98 * locks with fcntl(), flock() and lockf(). In some systems (like the BSDs),
99 * all three use the same record set, while on others (like Linux) the locks
100 * are independent, except if locking over NFS mounts, in which case they're
101 * actually the same. Therefore, it's a very bad idea to mix them in the same
102 * process.
103 *
104 * We therefore use only flock(2), except on Android.
105 *
106 * Android Compatibility:
107 * Some versions of Android have known issues where flock does not function correctly. 
108 * As a result, on Android, we use POSIX fcntl(F_SETLK) to handle file locking.
109 * fcntl is better integrated with Android’s underlying system, avoiding
110 * the limitations of flock.
111 */
112
113static bool setNativeLocks(int fd)
114{
115#if defined(Q_OS_ANDROID)
116 struct flock fl;
117 fl.l_type = F_WRLCK;
118 fl.l_whence = SEEK_SET;
119 fl.l_start = 0;
120 fl.l_len = 0;
121 if (fcntl(fd, F_SETLK, &fl) == -1)
122 return false;
123#elif defined(LOCK_EX) && defined(LOCK_NB)
124 if (flock(fd: fd, LOCK_EX | LOCK_NB) == -1) // other threads, and other processes on a local fs
125 return false;
126#else
127 Q_UNUSED(fd);
128#endif
129 return true;
130}
131
132QLockFile::LockError QLockFilePrivate::tryLock_sys()
133{
134 const QByteArray lockFileName = QFile::encodeName(fileName);
135 const int fd = qt_safe_open(pathname: lockFileName.constData(), O_RDWR | O_CREAT | O_EXCL, mode: 0666);
136 if (fd < 0) {
137 switch (errno) {
138 case EEXIST:
139 return QLockFile::LockFailedError;
140 case EACCES:
141 case EROFS:
142 return QLockFile::PermissionError;
143 default:
144 return QLockFile::UnknownError;
145 }
146 }
147 // Ensure nobody else can delete the file while we have it
148 if (!setNativeLocks(fd)) {
149 const int errnoSaved = errno;
150 qWarning() << "setNativeLocks failed:" << qt_error_string(errorCode: errnoSaved);
151 }
152
153 QByteArray fileData = lockFileContents();
154 if (qt_write_loop(fd, data: fileData.constData(), len: fileData.size()) < fileData.size()) {
155 qt_safe_close(fd);
156 if (!QFile::remove(fileName))
157 qWarning(msg: "QLockFile: Could not remove our own lock file %ls.", qUtf16Printable(fileName));
158 return QLockFile::UnknownError; // partition full
159 }
160
161 // We hold the lock, continue.
162 fileHandle = fd;
163
164 // Sync to disk if possible. Ignore errors (e.g. not supported).
165#if defined(_POSIX_SYNCHRONIZED_IO) && _POSIX_SYNCHRONIZED_IO > 0
166 fdatasync(fildes: fileHandle);
167#else
168 fsync(fileHandle);
169#endif
170
171 return QLockFile::NoError;
172}
173
174bool QLockFilePrivate::removeStaleLock()
175{
176 const QByteArray lockFileName = QFile::encodeName(fileName);
177 const int fd = qt_safe_open(pathname: lockFileName.constData(), O_WRONLY, mode: 0666);
178 if (fd < 0) // gone already?
179 return false;
180 bool success = setNativeLocks(fd) && (::unlink(name: lockFileName) == 0);
181 close(fd: fd);
182 return success;
183}
184
185bool QLockFilePrivate::isProcessRunning(qint64 pid, const QString &appname)
186{
187 if (::kill(pid: pid_t(pid), sig: 0) == -1 && errno == ESRCH)
188 return false; // PID doesn't exist anymore
189
190 const QString processName = processNameByPid(pid);
191 if (!processName.isEmpty()) {
192 QFileInfo fi(appname);
193 if (fi.isSymLink())
194 fi.setFile(fi.symLinkTarget());
195 if (processName != fi.fileName())
196 return false; // PID got reused by a different application.
197 }
198
199 return true;
200}
201
202QString QLockFilePrivate::processNameByPid(qint64 pid)
203{
204#if defined(Q_OS_MACOS)
205 char name[1024];
206 proc_name(pid, name, sizeof(name) / sizeof(char));
207 return QFile::decodeName(name);
208#elif defined(Q_OS_LINUX)
209 if (!qt_haveLinuxProcfs())
210 return QString();
211
212 char exePath[64];
213 sprintf(s: exePath, format: "/proc/%lld/exe", pid);
214
215 QByteArray buf = qt_readlink(path: exePath);
216 if (buf.isEmpty()) {
217 // The pid is gone. Return some invalid process name to fail the test.
218 return QStringLiteral("/ERROR/");
219 }
220
221 // remove the " (deleted)" suffix, if any
222 static const char deleted[] = " (deleted)";
223 if (buf.endsWith(bv: deleted))
224 buf.chop(n: strlen(s: deleted));
225
226 return QFileSystemEntry(buf, QFileSystemEntry::FromNativePath()).fileName();
227#elif defined(Q_OS_HAIKU)
228 thread_info info;
229 if (get_thread_info(pid, &info) != B_OK)
230 return QString();
231 return QFile::decodeName(info.name);
232#elif defined(Q_OS_BSD4) && !defined(QT_PLATFORM_UIKIT)
233# if defined(Q_OS_NETBSD)
234 struct kinfo_proc2 kp;
235 int mib[6] = { CTL_KERN, KERN_PROC2, KERN_PROC_PID, (int)pid, sizeof(struct kinfo_proc2), 1 };
236# elif defined(Q_OS_OPENBSD)
237 struct kinfo_proc kp;
238 int mib[6] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid, sizeof(struct kinfo_proc), 1 };
239# else
240 struct kinfo_proc kp;
241 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)pid };
242# endif
243 size_t len = sizeof(kp);
244 u_int mib_len = sizeof(mib)/sizeof(u_int);
245
246 if (sysctl(mib, mib_len, &kp, &len, NULL, 0) < 0)
247 return QString();
248
249# if defined(Q_OS_OPENBSD) || defined(Q_OS_NETBSD)
250 if (kp.p_pid != pid)
251 return QString();
252 QString name = QFile::decodeName(kp.p_comm);
253# else
254 if (kp.ki_pid != pid)
255 return QString();
256 QString name = QFile::decodeName(kp.ki_comm);
257# endif
258 return name;
259#elif defined(Q_OS_QNX)
260 char exePath[PATH_MAX];
261 sprintf(exePath, "/proc/%lld/exefile", pid);
262
263 int fd = qt_safe_open(exePath, O_RDONLY);
264 if (fd == -1)
265 return QString();
266
267 QT_STATBUF sbuf;
268 if (QT_FSTAT(fd, &sbuf) == -1) {
269 qt_safe_close(fd);
270 return QString();
271 }
272
273 QByteArray buffer(sbuf.st_size, Qt::Uninitialized);
274 buffer.resize(qt_safe_read(fd, buffer.data(), sbuf.st_size - 1));
275 if (buffer.isEmpty()) {
276 // The pid is gone. Return some invalid process name to fail the test.
277 return QStringLiteral("/ERROR/");
278 }
279 return QFileSystemEntry(buffer, QFileSystemEntry::FromNativePath()).fileName();
280#else
281 Q_UNUSED(pid);
282 return QString();
283#endif
284}
285
286void QLockFile::unlock()
287{
288 Q_D(QLockFile);
289 if (!d->isLocked)
290 return;
291 close(fd: d->fileHandle);
292 d->fileHandle = -1;
293 if (!QFile::remove(fileName: d->fileName)) {
294 qWarning() << "Could not remove our own lock file" << d->fileName << "maybe permissions changed meanwhile?";
295 // This is bad because other users of this lock file will now have to wait for the stale-lock-timeout...
296 }
297 d->lockError = QLockFile::NoError;
298 d->isLocked = false;
299}
300
301QT_END_NAMESPACE
302

source code of qtbase/src/corelib/io/qlockfile_unix.cpp