]> git.saurik.com Git - wxWidgets.git/blob - src/unix/snglinst.cpp
correcting border drawing for clientareaorigin in notebooks etc.
[wxWidgets.git] / src / unix / snglinst.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: unix/snglinst.cpp
3 // Purpose: implements wxSingleInstanceChecker class for Unix using
4 // lock files with fcntl(2) or flock(2)
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 09.06.01
8 // RCS-ID: $Id$
9 // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // License: wxWindows licence
11 ///////////////////////////////////////////////////////////////////////////////
12
13 // ============================================================================
14 // declarations
15 // ============================================================================
16
17 // ----------------------------------------------------------------------------
18 // headers
19 // ----------------------------------------------------------------------------
20
21 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
22 #pragma implementation "snglinst.h"
23 #endif
24
25 // For compilers that support precompilation, includes "wx.h".
26 #include "wx/wxprec.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #if wxUSE_SNGLINST_CHECKER
33
34 #ifndef WX_PRECOMP
35 #include "wx/string.h"
36 #include "wx/log.h"
37 #include "wx/intl.h"
38 #endif //WX_PRECOMP
39
40 #include "wx/file.h"
41 #include "wx/utils.h" // wxGetHomeDir()
42
43 #include "wx/snglinst.h"
44
45 #include <unistd.h>
46 #include <sys/types.h>
47 #include <sys/stat.h> // for S_I[RW]USR
48 #include <signal.h> // for kill()
49 #include <errno.h>
50
51 #ifdef HAVE_FCNTL
52 #include <fcntl.h>
53 #elif defined(HAVE_FLOCK)
54 #include <sys/file.h>
55 #else
56 // normally, wxUSE_SNGLINST_CHECKER must have been reset by configure
57 #error "wxSingleInstanceChecker can't be compiled on this platform"
58 #endif // fcntl()/flock()
59
60 // ----------------------------------------------------------------------------
61 // constants
62 // ----------------------------------------------------------------------------
63
64 // argument of wxLockFile()
65 enum LockOperation
66 {
67 LOCK,
68 UNLOCK
69 };
70
71 // return value of CreateLockFile()
72 enum LockResult
73 {
74 LOCK_ERROR = -1,
75 LOCK_EXISTS,
76 LOCK_CREATED
77 };
78
79 // ----------------------------------------------------------------------------
80 // private functions: (exclusively) lock/unlock the file
81 // ----------------------------------------------------------------------------
82
83 #ifdef HAVE_FCNTL
84
85 static int wxLockFile(int fd, LockOperation lock)
86 {
87 // init the flock parameter struct
88 struct flock fl;
89 fl.l_type = lock == LOCK ? F_WRLCK : F_UNLCK;
90
91 // lock the entire file
92 fl.l_whence =
93 fl.l_start =
94 fl.l_len = 0;
95
96 // is this needed?
97 fl.l_pid = getpid();
98
99 return fcntl(fd, F_SETLK, &fl);
100 }
101
102 #else // HAVE_FLOCK
103
104 static int wxLockFile(int fd, LockOperation lock)
105 {
106 return flock(fd, lock == LOCK ? LOCK_EX | LOCK_NB : LOCK_UN);
107 }
108
109 #endif // fcntl()/flock()
110
111 // ----------------------------------------------------------------------------
112 // wxSingleInstanceCheckerImpl: the real implementation class
113 // ----------------------------------------------------------------------------
114
115 class wxSingleInstanceCheckerImpl
116 {
117 public:
118 wxSingleInstanceCheckerImpl()
119 {
120 m_fdLock = -1;
121 m_pidLocker = 0;
122 }
123
124 bool Create(const wxString& name);
125
126 pid_t GetLockerPID() const { return m_pidLocker; }
127
128 ~wxSingleInstanceCheckerImpl() { Unlock(); }
129
130 private:
131 // try to create and lock the file
132 LockResult CreateLockFile();
133
134 // unlock and remove the lock file
135 void Unlock();
136
137 // the descriptor of our lock file, -1 if none
138 int m_fdLock;
139
140 // pid of the process owning the lock file
141 pid_t m_pidLocker;
142
143 // the name of the lock file
144 wxString m_nameLock;
145 };
146
147 // ============================================================================
148 // wxSingleInstanceCheckerImpl implementation
149 // ============================================================================
150
151 LockResult wxSingleInstanceCheckerImpl::CreateLockFile()
152 {
153 // try to open the file
154 m_fdLock = open(m_nameLock.fn_str(),
155 O_WRONLY | O_CREAT | O_EXCL,
156 S_IRUSR | S_IWUSR);
157
158 if ( m_fdLock != -1 )
159 {
160 // try to lock it
161 if ( wxLockFile(m_fdLock, LOCK) == 0 )
162 {
163 // fine, we have the exclusive lock to the file, write our PID
164 // into it
165 m_pidLocker = getpid();
166
167 // use char here, not wxChar!
168 char buf[256]; // enough for any PID size
169 int len = sprintf(buf, "%d", (int)m_pidLocker) + 1;
170
171 if ( write(m_fdLock, buf, len) != len )
172 {
173 wxLogSysError(_("Failed to write to lock file '%s'"),
174 m_nameLock.c_str());
175
176 Unlock();
177
178 return LOCK_ERROR;
179 }
180
181 fsync(m_fdLock);
182
183 // change file's permission so that only this user can access it:
184 if ( chmod(m_nameLock.fn_str(), S_IRUSR | S_IWUSR) != 0 )
185 {
186 wxLogSysError(_("Failed to set permissions on lock file '%s'"),
187 m_nameLock.c_str());
188
189 Unlock();
190
191 return LOCK_ERROR;
192 }
193
194 return LOCK_CREATED;
195 }
196 else // failure: see what exactly happened
197 {
198 close(m_fdLock);
199 m_fdLock = -1;
200
201 if ( errno != EACCES && errno != EAGAIN )
202 {
203 wxLogSysError(_("Failed to lock the lock file '%s'"),
204 m_nameLock.c_str());
205
206 unlink(m_nameLock.fn_str());
207
208 return LOCK_ERROR;
209 }
210 //else: couldn't lock because the lock is held by another process:
211 // this might have happened because of a race condition:
212 // maybe another instance opened and locked the file between
213 // our calls to open() and flock(), so don't give an error
214 }
215 }
216
217 // we didn't create and lock the file
218 return LOCK_EXISTS;
219 }
220
221 bool wxSingleInstanceCheckerImpl::Create(const wxString& name)
222 {
223 m_nameLock = name;
224
225 switch ( CreateLockFile() )
226 {
227 case LOCK_EXISTS:
228 // there is a lock file, check below if it is still valid
229 break;
230
231 case LOCK_CREATED:
232 // nothing more to do
233 return TRUE;
234
235 case LOCK_ERROR:
236 // oops...
237 return FALSE;
238 }
239
240 // Check if the file is owned by current user and has 0600 permissions.
241 // If it doesn't, it's a fake file, possibly meant as a DoS attack, and
242 // so we refuse to touch it:
243 wxStructStat stats;
244 if ( wxStat(name, &stats) != 0 )
245 {
246 wxLogSysError(_("Failed to inspect the lock file '%s'"), name.c_str());
247 return false;
248 }
249 if ( stats.st_uid != getuid() )
250 {
251 wxLogError(_("Lock file '%s' has incorrect owner."), name.c_str());
252 return false;
253 }
254 if ( stats.st_mode != (S_IFREG | S_IRUSR | S_IWUSR) )
255 {
256 wxLogError(_("Lock file '%s' has incorrect permissions."), name.c_str());
257 return false;
258 }
259
260 // try to open the file for reading and get the PID of the process
261 // which has it
262 wxFile file(name, wxFile::read);
263 if ( !file.IsOpened() )
264 {
265 // well, this is really weird - file doesn't exist and we can't
266 // create it
267 //
268 // normally, this just means that we don't have write access to
269 // the directory where we try to create it, so return failure,
270 // even it might also be a rare case of a race condition when
271 // another process managed to open and lock the file and terminate
272 // (erasing it) before we got here, but this should happen so
273 // rarely in practice that we don't care
274 wxLogError(_("Failed to access lock file."));
275
276 return FALSE;
277 }
278
279 char buf[256];
280 off_t count = file.Read(buf, WXSIZEOF(buf));
281 if ( count == wxInvalidOffset )
282 {
283 wxLogError(_("Failed to read PID from lock file."));
284 }
285 else
286 {
287 if ( sscanf(buf, "%d", (int *)&m_pidLocker) == 1 )
288 {
289 if ( kill(m_pidLocker, 0) != 0 )
290 {
291 if ( unlink(name.fn_str()) != 0 )
292 {
293 wxLogError(_("Failed to remove stale lock file '%s'."),
294 name.c_str());
295
296 // return TRUE in this case for now...
297 }
298 else
299 {
300 wxLogMessage(_("Deleted stale lock file '%s'."),
301 name.c_str());
302
303 // retry now
304 (void)CreateLockFile();
305 }
306 }
307 //else: the other process is running
308 }
309 else
310 {
311 wxLogWarning(_("Invalid lock file '%s'."), name.c_str());
312 }
313 }
314
315 // return TRUE if we could get the PID of the process owning the lock file
316 // (whether it is still running or not), FALSE otherwise as it is
317 // unexpected
318 return m_pidLocker != 0;
319 }
320
321 void wxSingleInstanceCheckerImpl::Unlock()
322 {
323 if ( m_fdLock != -1 )
324 {
325 if ( unlink(m_nameLock.fn_str()) != 0 )
326 {
327 wxLogSysError(_("Failed to remove lock file '%s'"),
328 m_nameLock.c_str());
329 }
330
331 if ( wxLockFile(m_fdLock, UNLOCK) != 0 )
332 {
333 wxLogSysError(_("Failed to unlock lock file '%s'"),
334 m_nameLock.c_str());
335 }
336
337 if ( close(m_fdLock) != 0 )
338 {
339 wxLogSysError(_("Failed to close lock file '%s'"),
340 m_nameLock.c_str());
341 }
342 }
343
344 m_pidLocker = 0;
345 }
346
347 // ============================================================================
348 // wxSingleInstanceChecker implementation
349 // ============================================================================
350
351 bool wxSingleInstanceChecker::Create(const wxString& name,
352 const wxString& path)
353 {
354 wxASSERT_MSG( !m_impl,
355 _T("calling wxSingleInstanceChecker::Create() twice?") );
356
357 // must have the file name to create a lock file
358 wxASSERT_MSG( !name.empty(), _T("lock file name can't be empty") );
359
360 m_impl = new wxSingleInstanceCheckerImpl;
361
362 wxString fullname = path;
363 if ( fullname.empty() )
364 {
365 fullname = wxGetHomeDir();
366 }
367
368 if ( fullname.Last() != _T('/') )
369 {
370 fullname += _T('/');
371 }
372
373 fullname << name;
374
375 return m_impl->Create(fullname);
376 }
377
378 bool wxSingleInstanceChecker::IsAnotherRunning() const
379 {
380 wxCHECK_MSG( m_impl, FALSE, _T("must call Create() first") );
381
382 // if another instance is running, it must own the lock file - otherwise
383 // we have it and the locker PID is ours one
384 return m_impl->GetLockerPID() != getpid();
385 }
386
387 wxSingleInstanceChecker::~wxSingleInstanceChecker()
388 {
389 delete m_impl;
390 }
391
392 #endif // wxUSE_SNGLINST_CHECKER
393