Merge from trunk.
[bpt/emacs.git] / src / filelock.c
CommitLineData
b97771fc 1/* Lock files for editing.
ab422c4d
PE
2 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2013 Free Software
3 Foundation, Inc.
8489eb67
RS
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
8489eb67 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
8489eb67
RS
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
8489eb67
RS
19
20
68c45bf0 21#include <config.h>
8489eb67
RS
22#include <sys/types.h>
23#include <sys/stat.h>
dfcf069d 24#include <signal.h>
2decc5a9 25#include <stdio.h>
bfb61299 26
5b9c0a1d 27#ifdef HAVE_PWD_H
8489eb67 28#include <pwd.h>
5b9c0a1d 29#endif
bfb61299 30
8489eb67 31#include <sys/file.h>
8489eb67 32#include <fcntl.h>
dfcf069d 33#include <unistd.h>
dfcf069d 34
f805a125 35#ifdef __FreeBSD__
f805a125
KH
36#include <sys/sysctl.h>
37#endif /* __FreeBSD__ */
38
e5ef3cdf 39#include <errno.h>
e5ef3cdf 40
70743157
PE
41#include <c-ctype.h>
42
8489eb67 43#include "lisp.h"
d2f6dae8 44#include "character.h"
e5560ff7 45#include "buffer.h"
f4a4528d 46#include "coding.h"
9177d978 47#include "systime.h"
343a2aef 48#ifdef WINDOWSNT
531e70ec 49#include <share.h>
1d442672 50#include <sys/socket.h> /* for fcntl */
343a2aef
EZ
51#include "w32.h" /* for dostounix_filename */
52#endif
8489eb67 53
8489eb67 54#ifdef CLASH_DETECTION
e788eecc 55
c6d09b8d 56#ifdef HAVE_UTMP_H
e788eecc 57#include <utmp.h>
c6d09b8d 58#endif
77e544a4 59
a48de9b2
PE
60/* A file whose last-modified time is just after the most recent boot.
61 Define this to be NULL to disable checking for this file. */
62#ifndef BOOT_TIME_FILE
63#define BOOT_TIME_FILE "/var/run/random-seed"
64#endif
65
77e544a4
RS
66#ifndef WTMP_FILE
67#define WTMP_FILE "/var/log/wtmp"
68#endif
177c0ea7 69
70743157 70/* Normally use a symbolic link to represent a lock.
b5029e23 71 The strategy: to lock a file FN, create a symlink .#FN in FN's
8dbbc384
RS
72 directory, with link data `user@host.pid'. This avoids a single
73 mount (== failure) point for lock files.
74
75 When the host in the lock data is the current host, we can check if
76 the pid is valid with kill.
177c0ea7 77
8dbbc384
RS
78 Otherwise, we could look at a separate file that maps hostnames to
79 reboot times to see if the remote pid can possibly be valid, since we
80 don't want Emacs to have to communicate via pipes or sockets or
81 whatever to other processes, either locally or remotely; rms says
82 that's too unreliable. Hence the separate file, which could
83 theoretically be updated by daemons running separately -- but this
84 whole idea is unimplemented; in practice, at least in our
1c4f857c 85 environment, it seems such stale locks arise fairly infrequently, and
8dbbc384
RS
86 Emacs' standard methods of dealing with clashes suffice.
87
88 We use symlinks instead of normal files because (1) they can be
89 stored more efficiently on the filesystem, since the kernel knows
90 they will be small, and (2) all the info about the lock can be read
91 in a single system call (readlink). Although we could use regular
1c4f857c 92 files to be useful on old systems lacking symlinks, nowadays
8dbbc384
RS
93 virtually all such systems are probably single-user anyway, so it
94 didn't seem worth the complication.
177c0ea7 95
8dbbc384
RS
96 Similarly, we don't worry about a possible 14-character limit on
97 file names, because those are all the same systems that don't have
98 symlinks.
177c0ea7 99
8dbbc384
RS
100 This is compatible with the locking scheme used by Interleaf (which
101 has contributed this implementation for Emacs), and was designed by
102 Ethan Jacobson, Kimbo Mundy, and others.
177c0ea7 103
b5029e23
PE
104 --karl@cs.umb.edu/karl@hq.ileaf.com.
105
70743157
PE
106 On some file systems, notably those of MS-Windows, symbolic links
107 do not work well, so instead of a symlink .#FN -> 'user@host.pid',
108 the lock is a regular file .#FN with contents 'user@host.pid'. To
109 establish a lock, a nonce file is created and then renamed to .#FN.
110 On MS-Windows this renaming is atomic unless the lock is forcibly
111 acquired. On other systems the renaming is atomic if the lock is
112 forcibly acquired; if not, the renaming is done via hard links,
113 which is good enough for lock-file purposes.
114
115 To summarize, race conditions can occur with either:
116
117 * Forced locks on MS-Windows systems.
118
119 * Non-forced locks on non-MS-Windows systems that support neither
120 hard nor symbolic links. */
8489eb67 121
8dbbc384 122\f
15e88d21
RS
123/* Return the time of the last system boot. */
124
125static time_t boot_time;
f75d7a91 126static bool boot_time_initialized;
15e88d21 127
2f2500ef 128#ifdef BOOT_TIME
f75d7a91 129static void get_boot_time_1 (const char *, bool);
2f2500ef
DL
130#endif
131
15e88d21 132static time_t
971de7fb 133get_boot_time (void)
15e88d21 134{
9d2818d6 135#if defined (BOOT_TIME)
9177d978 136 int counter;
2decc5a9 137#endif
15e88d21 138
b97771fc 139 if (boot_time_initialized)
15e88d21 140 return boot_time;
b97771fc 141 boot_time_initialized = 1;
15e88d21 142
f805a125
KH
143#if defined (CTL_KERN) && defined (KERN_BOOTTIME)
144 {
145 int mib[2];
146 size_t size;
147 struct timeval boottime_val;
148
149 mib[0] = CTL_KERN;
150 mib[1] = KERN_BOOTTIME;
151 size = sizeof (boottime_val);
152
153 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
154 {
155 boot_time = boottime_val.tv_sec;
156 return boot_time;
157 }
158 }
159#endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
9177d978 160
a48de9b2
PE
161 if (BOOT_TIME_FILE)
162 {
163 struct stat st;
164 if (stat (BOOT_TIME_FILE, &st) == 0)
165 {
166 boot_time = st.st_mtime;
167 return boot_time;
168 }
169 }
170
9d2818d6 171#if defined (BOOT_TIME)
b97771fc
RS
172#ifndef CANNOT_DUMP
173 /* The utmp routines maintain static state.
174 Don't touch that state unless we are initialized,
175 since it might not survive dumping. */
176 if (! initialized)
177 return boot_time;
178#endif /* not CANNOT_DUMP */
179
180 /* Try to get boot time from utmp before wtmp,
181 since utmp is typically much smaller than wtmp.
182 Passing a null pointer causes get_boot_time_1
183 to inspect the default file, namely utmp. */
7d652d97 184 get_boot_time_1 (0, 0);
b97771fc
RS
185 if (boot_time)
186 return boot_time;
187
9177d978 188 /* Try to get boot time from the current wtmp file. */
b97771fc 189 get_boot_time_1 (WTMP_FILE, 1);
9177d978
RS
190
191 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
b97771fc 192 for (counter = 0; counter < 20 && ! boot_time; counter++)
9177d978 193 {
882f0d81 194 char cmd_string[sizeof WTMP_FILE ".19.gz"];
9177d978 195 Lisp_Object tempname, filename;
f75d7a91 196 bool delete_flag = 0;
9177d978
RS
197
198 filename = Qnil;
199
a8290ec3
DA
200 tempname = make_formatted_string
201 (cmd_string, "%s.%d", WTMP_FILE, counter);
29a2adb0 202 if (! NILP (Ffile_exists_p (tempname)))
9177d978
RS
203 filename = tempname;
204 else
205 {
a8290ec3
DA
206 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
207 WTMP_FILE, counter);
9177d978
RS
208 if (! NILP (Ffile_exists_p (tempname)))
209 {
210 Lisp_Object args[6];
f1d367aa
GM
211
212 /* The utmp functions on mescaline.gnu.org accept only
213 file names up to 8 characters long. Choose a 2
214 character long prefix, and call make_temp_file with
215 second arg non-zero, so that it will add not more
216 than 6 characters to the prefix. */
882f0d81 217 filename = Fexpand_file_name (build_string ("wt"),
5f8d6a10 218 Vtemporary_file_directory);
882f0d81
PE
219 filename = make_temp_name (filename, 1);
220 args[0] = build_string ("gzip");
9177d978 221 args[1] = Qnil;
882f0d81 222 args[2] = list2 (QCfile, filename);
9177d978 223 args[3] = Qnil;
882f0d81
PE
224 args[4] = build_string ("-cd");
225 args[5] = tempname;
9177d978 226 Fcall_process (6, args);
9177d978
RS
227 delete_flag = 1;
228 }
229 }
230
231 if (! NILP (filename))
232 {
42a5b22f 233 get_boot_time_1 (SSDATA (filename), 1);
9177d978 234 if (delete_flag)
42a5b22f 235 unlink (SSDATA (filename));
9177d978
RS
236 }
237 }
238
239 return boot_time;
240#else
241 return 0;
242#endif
243}
244
e9f22ced 245#ifdef BOOT_TIME
9177d978
RS
246/* Try to get the boot time from wtmp file FILENAME.
247 This succeeds if that file contains a reboot record.
9177d978 248
b97771fc
RS
249 If FILENAME is zero, use the same file as before;
250 if no FILENAME has ever been specified, this is the utmp file.
f75d7a91 251 Use the newest reboot record if NEWEST,
b97771fc
RS
252 the first reboot record otherwise.
253 Ignore all reboot records on or before BOOT_TIME.
254 Success is indicated by setting BOOT_TIME to a larger value. */
255
2f2500ef 256void
f75d7a91 257get_boot_time_1 (const char *filename, bool newest)
9177d978
RS
258{
259 struct utmp ut, *utp;
77e544a4 260
b97771fc
RS
261 if (filename)
262 {
263 /* On some versions of IRIX, opening a nonexistent file name
264 is likely to crash in the utmp routines. */
5e679a2c 265 if (faccessat (AT_FDCWD, filename, R_OK, AT_EACCESS) != 0)
b97771fc
RS
266 return;
267
b97771fc
RS
268 utmpname (filename);
269 }
9177d978 270
c321b190 271 setutent ();
b97771fc 272
c321b190
RS
273 while (1)
274 {
275 /* Find the next reboot record. */
276 ut.ut_type = BOOT_TIME;
277 utp = getutid (&ut);
278 if (! utp)
279 break;
280 /* Compare reboot times and use the newest one. */
281 if (utp->ut_time > boot_time)
b97771fc
RS
282 {
283 boot_time = utp->ut_time;
284 if (! newest)
285 break;
286 }
c321b190
RS
287 /* Advance on element in the file
288 so that getutid won't repeat the same one. */
289 utp = getutent ();
290 if (! utp)
291 break;
292 }
15e88d21 293 endutent ();
15e88d21 294}
e9f22ced 295#endif /* BOOT_TIME */
15e88d21 296\f
70743157
PE
297/* An arbitrary limit on lock contents length. 8 K should be plenty
298 big enough in practice. */
299enum { MAX_LFINFO = 8 * 1024 };
300
8dbbc384 301/* Here is the structure that stores information about a lock. */
32676c08 302
8dbbc384
RS
303typedef struct
304{
70743157
PE
305 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
306 points to the end of USER. */
307 char *at, *dot, *colon;
e31fbc7a 308
70743157
PE
309 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
310 appended. This memory is used as a lock file contents buffer, so
311 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
312 may be appended to the USER@HOST while generating a diagnostic,
313 so make room for its extra bytes (as opposed to ".NNNN") too. */
314 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
315} lock_info_type;
e31fbc7a 316
b5029e23 317/* Write the name of the lock file for FNAME into LOCKNAME. Length
70743157
PE
318 will be that of FNAME plus two more for the leading ".#", plus one
319 for the null. */
b5029e23 320#define MAKE_LOCK_NAME(lockname, fname) \
70743157 321 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
b5029e23
PE
322 fill_in_lock_file_name (lockname, fname))
323
8dbbc384 324static void
b5029e23 325fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
e31fbc7a 326{
b5029e23
PE
327 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
328 char *base = last_slash + 1;
329 ptrdiff_t dirlen = base - SSDATA (fn);
330 memcpy (lockfile, SSDATA (fn), dirlen);
331 lockfile[dirlen] = '.';
332 lockfile[dirlen + 1] = '#';
70743157 333 strcpy (lockfile + dirlen + 2, base);
8dbbc384 334}
e31fbc7a 335
70743157
PE
336/* For some reason Linux kernels return EPERM on file systems that do
337 not support hard or symbolic links. This symbol documents the quirk.
338 There is no way to tell whether a symlink call fails due to
339 permissions issues or because links are not supported, but luckily
340 the lock file code should work either way. */
341enum { LINKS_MIGHT_NOT_WORK = EPERM };
342
343/* Rename OLD to NEW. If FORCE, replace any existing NEW.
344 It is OK if there are temporarily two hard links to OLD.
345 Return 0 if successful, -1 (setting errno) otherwise. */
343a2aef 346static int
70743157 347rename_lock_file (char const *old, char const *new, bool force)
343a2aef 348{
343a2aef 349#ifdef WINDOWSNT
70743157
PE
350 return sys_rename_replace (old, new, force);
351#else
352 if (! force)
353 {
354 struct stat st;
343a2aef 355
70743157
PE
356 if (link (old, new) == 0)
357 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
358 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
359 return -1;
360
361 /* 'link' does not work on this file system. This can occur on
362 a GNU/Linux host mounting a FAT32 file system. Fall back on
363 'rename' after checking that NEW does not exist. There is a
364 potential race condition since some other process may create
365 NEW immediately after the existence check, but it's the best
366 we can portably do here. */
367 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
368 {
369 errno = EEXIST;
370 return -1;
371 }
372 if (errno != ENOENT)
373 return -1;
374 }
375
376 return rename (old, new);
377#endif
378}
379
1b6006a5 380/* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
70743157 381 successful, an errno value on failure. If FORCE, remove any
1b6006a5 382 existing LFNAME if necessary. */
70743157
PE
383
384static int
385create_lock_file (char *lfname, char *lock_info_str, bool force)
386{
387#ifdef WINDOWSNT
388 /* Symlinks are supported only by later versions of Windows, and
389 creating them is a privileged operation that often triggers
390 User Account Control elevation prompts. Avoid the problem by
391 pretending that 'symlink' does not work. */
392 int err = ENOSYS;
343a2aef 393#else
70743157
PE
394 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
395#endif
396
397 if (err == EEXIST && force)
343a2aef
EZ
398 {
399 unlink (lfname);
70743157 400 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
343a2aef 401 }
70743157
PE
402
403 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
404 {
405 static char const nonce_base[] = ".#-emacsXXXXXX";
406 char *last_slash = strrchr (lfname, '/');
407 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
408 USE_SAFE_ALLOCA;
409 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
410 int fd;
70743157
PE
411 memcpy (nonce, lfname, lfdirlen);
412 strcpy (nonce + lfdirlen, nonce_base);
413
067428c1 414 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
70743157
PE
415 if (fd < 0)
416 err = errno;
417 else
418 {
067428c1 419 ptrdiff_t lock_info_len;
e0fdb694
PE
420 if (! O_CLOEXEC)
421 fcntl (fd, F_SETFD, FD_CLOEXEC);
067428c1 422 lock_info_len = strlen (lock_info_str);
70743157 423 err = 0;
3f5bef16
PE
424 /* Use 'write', not 'emacs_write', as garbage collection
425 might signal an error, which would leak FD. */
426 if (write (fd, lock_info_str, lock_info_len) != lock_info_len
5c97beae 427 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
70743157 428 err = errno;
cbee2131
PE
429 /* There is no need to call fsync here, as the contents of
430 the lock file need not survive system crashes. */
70743157
PE
431 if (emacs_close (fd) != 0)
432 err = errno;
433 if (!err && rename_lock_file (nonce, lfname, force) != 0)
434 err = errno;
435 if (err)
436 unlink (nonce);
437 }
438
439 SAFE_FREE ();
440 }
441
343a2aef
EZ
442 return err;
443}
444
8dbbc384 445/* Lock the lock file named LFNAME.
f75d7a91 446 If FORCE, do so even if it is already locked.
70743157 447 Return 0 if successful, an error number on failure. */
e31fbc7a 448
70743157 449static int
f75d7a91 450lock_file_1 (char *lfname, bool force)
8dbbc384 451{
4ba93ac0 452 /* Call this first because it can GC. */
98c6f1e3
PE
453 printmax_t boot = get_boot_time ();
454
455 Lisp_Object luser_name = Fuser_login_name (Qnil);
456 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
457 Lisp_Object lhost_name = Fsystem_name ();
458 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
70743157 459 char lock_info_str[MAX_LFINFO + 1];
98c6f1e3 460 printmax_t pid = getpid ();
8dbbc384 461
8762e524
JD
462 if (boot)
463 {
464 if (sizeof lock_info_str
465 <= snprintf (lock_info_str, sizeof lock_info_str,
466 "%s@%s.%"pMd":%"pMd,
467 user_name, host_name, pid, boot))
468 return ENAMETOOLONG;
469 }
470 else if (sizeof lock_info_str
471 <= snprintf (lock_info_str, sizeof lock_info_str,
472 "%s@%s.%"pMd,
473 user_name, host_name, pid))
70743157 474 return ENAMETOOLONG;
e31fbc7a 475
70743157 476 return create_lock_file (lfname, lock_info_str, force);
8dbbc384 477}
e31fbc7a 478
f75d7a91 479/* Return true if times A and B are no more than one second apart. */
32676c08 480
f75d7a91 481static bool
971de7fb 482within_one_second (time_t a, time_t b)
9177d978
RS
483{
484 return (a - b >= -1 && a - b <= 1);
485}
8dbbc384 486\f
70743157
PE
487/* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
488#ifndef ELOOP
489# define ELOOP (-1)
490#endif
343a2aef 491
70743157
PE
492/* Read the data for the lock file LFNAME into LFINFO. Read at most
493 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
494 (setting errno) on error. */
343a2aef 495
70743157
PE
496static ptrdiff_t
497read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
498{
499 ptrdiff_t nbytes;
343a2aef 500
70743157
PE
501 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
502 && errno == EINVAL)
343a2aef 503 {
70743157
PE
504 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
505 if (0 <= fd)
506 {
5e679a2c
PE
507 /* Use read, not emacs_read, since FD isn't unwind-protected. */
508 ptrdiff_t read_bytes = read (fd, lfinfo, MAX_LFINFO + 1);
70743157
PE
509 int read_errno = errno;
510 if (emacs_close (fd) != 0)
511 return -1;
512 errno = read_errno;
513 return read_bytes;
514 }
515
516 if (errno != ELOOP)
517 return -1;
518
519 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
520 The former must have been removed and replaced by the latter.
521 Try again. */
522 QUIT;
343a2aef 523 }
70743157
PE
524
525 return nbytes;
343a2aef
EZ
526}
527
8dbbc384
RS
528/* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
529 1 if another process owns it (and set OWNER (if non-null) to info),
530 2 if the current process owns it,
531 or -1 if something is wrong with the locking mechanism. */
e31fbc7a 532
8dbbc384 533static int
971de7fb 534current_lock_owner (lock_info_type *owner, char *lfname)
32676c08 535{
d1fdcab7 536 int ret;
882f0d81 537 lock_info_type local_owner;
70743157
PE
538 ptrdiff_t lfinfolen;
539 intmax_t pid, boot_time;
540 char *at, *dot, *lfinfo_end;
177c0ea7 541
8dbbc384 542 /* Even if the caller doesn't want the owner info, we still have to
882f0d81 543 read it to determine return value. */
8dbbc384 544 if (!owner)
882f0d81 545 owner = &local_owner;
177c0ea7 546
70743157
PE
547 /* If nonexistent lock file, all is well; otherwise, got strange error. */
548 lfinfolen = read_lock_data (lfname, owner->user);
549 if (lfinfolen < 0)
550 return errno == ENOENT ? 0 : -1;
551 if (MAX_LFINFO < lfinfolen)
552 return -1;
553 owner->user[lfinfolen] = 0;
554
15e88d21 555 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
50624218 556 /* The USER is everything before the last @. */
70743157
PE
557 owner->at = at = memrchr (owner->user, '@', lfinfolen);
558 if (!at)
559 return -1;
560 owner->dot = dot = strrchr (at, '.');
561 if (!dot)
8654f9d7 562 return -1;
177c0ea7 563
15e88d21 564 /* The PID is everything from the last `.' to the `:'. */
70743157
PE
565 if (! c_isdigit (dot[1]))
566 return -1;
882f0d81 567 errno = 0;
70743157
PE
568 pid = strtoimax (dot + 1, &owner->colon, 10);
569 if (errno == ERANGE)
570 pid = -1;
882f0d81 571
15e88d21 572 /* After the `:', if there is one, comes the boot time. */
70743157 573 switch (owner->colon[0])
882f0d81 574 {
70743157
PE
575 case 0:
576 boot_time = 0;
577 lfinfo_end = owner->colon;
578 break;
579
580 case ':':
581 if (! c_isdigit (owner->colon[1]))
582 return -1;
583 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
584 break;
585
586 default:
587 return -1;
882f0d81 588 }
70743157
PE
589 if (lfinfo_end != owner->user + lfinfolen)
590 return -1;
177c0ea7 591
8dbbc384 592 /* On current host? */
70743157
PE
593 if (STRINGP (Vsystem_name)
594 && dot - (at + 1) == SBYTES (Vsystem_name)
595 && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
32676c08 596 {
70743157 597 if (pid == getpid ())
8dbbc384 598 ret = 2; /* We own it. */
70743157
PE
599 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
600 && (kill (pid, 0) >= 0 || errno == EPERM)
601 && (boot_time == 0
602 || (boot_time <= TYPE_MAXIMUM (time_t)
603 && within_one_second (boot_time, get_boot_time ()))))
8dbbc384 604 ret = 1; /* An existing process on this machine owns it. */
70743157 605 /* The owner process is dead or has a strange pid, so try to
8dbbc384 606 zap the lockfile. */
72dcef0e 607 else
70743157 608 return unlink (lfname);
32676c08 609 }
8dbbc384
RS
610 else
611 { /* If we wanted to support the check for stale locks on remote machines,
612 here's where we'd do it. */
613 ret = 1;
614 }
177c0ea7 615
8dbbc384 616 return ret;
32676c08
JB
617}
618
8dbbc384
RS
619\f
620/* Lock the lock named LFNAME if possible.
621 Return 0 in that case.
622 Return positive if some other process owns the lock, and info about
623 that process in CLASHER.
624 Return -1 if cannot lock for any other reason. */
8489eb67 625
8dbbc384 626static int
70743157 627lock_if_free (lock_info_type *clasher, char *lfname)
8dbbc384 628{
70743157
PE
629 int err;
630 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
8dbbc384 631 {
70743157
PE
632 switch (current_lock_owner (clasher, lfname))
633 {
634 case 2:
635 return 0; /* We ourselves locked it. */
636 case 1:
637 return 1; /* Someone else has it. */
638 case -1:
639 return -1; /* current_lock_owner returned strange error. */
640 }
8dbbc384 641
cfc01fa7 642 /* We deleted a stale lock; try again to lock the file. */
8dbbc384 643 }
70743157
PE
644
645 return err ? -1 : 0;
8489eb67
RS
646}
647
8dbbc384 648/* lock_file locks file FN,
8489eb67
RS
649 meaning it serves notice on the world that you intend to edit that file.
650 This should be done only when about to modify a file-visiting
651 buffer previously unmodified.
8dbbc384 652 Do not (normally) call this for a buffer already modified,
8489eb67
RS
653 as either the file is already locked, or the user has already
654 decided to go ahead without locking.
655
8dbbc384 656 When this returns, either the lock is locked for us,
b5029e23 657 or lock creation failed,
8489eb67
RS
658 or the user has said to go ahead without locking.
659
8dbbc384 660 If the file is locked by someone else, this calls
8489eb67 661 ask-user-about-lock (a Lisp function) with two arguments,
8dbbc384 662 the file name and info about the user who did the locking.
8489eb67
RS
663 This function can signal an error, or return t meaning
664 take away the lock, or return nil meaning ignore the lock. */
665
8489eb67 666void
971de7fb 667lock_file (Lisp_Object fn)
8489eb67 668{
2db41375
PE
669 Lisp_Object orig_fn, encoded_fn;
670 char *lfname;
8dbbc384 671 lock_info_type lock_info;
3edc33a4 672 struct gcpro gcpro1;
b5cd1905 673 USE_SAFE_ALLOCA;
8489eb67 674
836d29b3
DA
675 /* Don't do locking if the user has opted out. */
676 if (! create_lockfiles)
677 return;
678
33bae690
RS
679 /* Don't do locking while dumping Emacs.
680 Uncompressing wtmp files uses call-process, which does not work
681 in an uninitialized Emacs. */
682 if (! NILP (Vpurify_flag))
683 return;
684
5383bc6d 685 orig_fn = fn;
8af8a9ca 686 GCPRO1 (fn);
1e89de84 687 fn = Fexpand_file_name (fn, Qnil);
343a2aef
EZ
688#ifdef WINDOWSNT
689 /* Ensure we have only '/' separators, to avoid problems with
690 looking (inside fill_in_lock_file_name) for backslashes in file
691 names encoded by some DBCS codepage. */
1fd201bb 692 dostounix_filename (SSDATA (fn));
343a2aef 693#endif
f4a4528d 694 encoded_fn = ENCODE_FILE (fn);
1e89de84 695
8dbbc384 696 /* Create the name of the lock-file for file fn */
f4a4528d 697 MAKE_LOCK_NAME (lfname, encoded_fn);
8489eb67 698
32676c08
JB
699 /* See if this file is visited and has changed on disk since it was
700 visited. */
8489eb67 701 {
a57bc488 702 register Lisp_Object subject_buf;
3036594f 703
5383bc6d 704 subject_buf = get_truename_buffer (orig_fn);
3036594f 705
265a9e55
JB
706 if (!NILP (subject_buf)
707 && NILP (Fverify_visited_file_modtime (subject_buf))
708 && !NILP (Ffile_exists_p (fn)))
8489eb67 709 call1 (intern ("ask-user-about-supersession-threat"), fn);
3036594f 710
8489eb67 711 }
8489eb67 712
2db41375
PE
713 /* Try to lock the lock. */
714 if (0 < lock_if_free (&lock_info, lfname))
8489eb67 715 {
2db41375 716 /* Someone else has the lock. Consider breaking it. */
2db41375 717 Lisp_Object attack;
70743157
PE
718 char *dot = lock_info.dot;
719 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
720 static char const replacement[] = " (pid ";
721 int replacementlen = sizeof replacement - 1;
722 memmove (dot + replacementlen, dot + 1, pidlen);
723 strcpy (dot + replacementlen + pidlen, ")");
724 memcpy (dot, replacement, replacementlen);
725 attack = call2 (intern ("ask-user-about-lock"), fn,
726 build_string (lock_info.user));
2db41375
PE
727 /* Take the lock if the user said so. */
728 if (!NILP (attack))
729 lock_file_1 (lfname, 1);
8489eb67 730 }
2db41375
PE
731
732 UNGCPRO;
733 SAFE_FREE ();
8489eb67
RS
734}
735
8489eb67 736void
b5029e23 737unlock_file (Lisp_Object fn)
8489eb67 738{
b5029e23
PE
739 char *lfname;
740 USE_SAFE_ALLOCA;
8489eb67 741
1e89de84 742 fn = Fexpand_file_name (fn, Qnil);
88eace34 743 fn = ENCODE_FILE (fn);
1e89de84 744
7b92975f 745 MAKE_LOCK_NAME (lfname, fn);
8489eb67 746
8dbbc384 747 if (current_lock_owner (0, lfname) == 2)
8489eb67 748 unlink (lfname);
b5029e23
PE
749
750 SAFE_FREE ();
8489eb67
RS
751}
752
753void
971de7fb 754unlock_all_files (void)
8489eb67 755{
8f3a2c26 756 register Lisp_Object tail, buf;
8489eb67
RS
757 register struct buffer *b;
758
8f3a2c26 759 FOR_EACH_LIVE_BUFFER (tail, buf)
8489eb67 760 {
8f3a2c26
DA
761 b = XBUFFER (buf);
762 if (STRINGP (BVAR (b, file_truename))
763 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
764 unlock_file (BVAR (b, file_truename));
8489eb67
RS
765 }
766}
8489eb67
RS
767\f
768DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
335c5470
PJ
769 0, 1, 0,
770 doc: /* Lock FILE, if current buffer is modified.
771FILE defaults to current buffer's visited file,
772or else nothing is done if current buffer isn't visiting a file. */)
5842a27b 773 (Lisp_Object file)
8489eb67 774{
e9319ef2 775 if (NILP (file))
4b4deea2 776 file = BVAR (current_buffer, file_truename);
8489eb67 777 else
b7826503 778 CHECK_STRING (file);
6a140159 779 if (SAVE_MODIFF < MODIFF
e9319ef2
EN
780 && !NILP (file))
781 lock_file (file);
177c0ea7 782 return Qnil;
8489eb67
RS
783}
784
a7ca3326 785DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
335c5470 786 0, 0, 0,
3bfb8921
RS
787 doc: /* Unlock the file visited in the current buffer.
788If the buffer is not modified, this does nothing because the file
789should not be locked in that case. */)
5842a27b 790 (void)
8489eb67 791{
6a140159 792 if (SAVE_MODIFF < MODIFF
4b4deea2
TT
793 && STRINGP (BVAR (current_buffer, file_truename)))
794 unlock_file (BVAR (current_buffer, file_truename));
8489eb67
RS
795 return Qnil;
796}
797
8489eb67
RS
798/* Unlock the file visited in buffer BUFFER. */
799
d07e0802 800void
971de7fb 801unlock_buffer (struct buffer *buffer)
8489eb67 802{
6a140159 803 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
4b4deea2
TT
804 && STRINGP (BVAR (buffer, file_truename)))
805 unlock_file (BVAR (buffer, file_truename));
8489eb67
RS
806}
807
8105cbf7 808DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
3bfb8921
RS
809 doc: /* Return a value indicating whether FILENAME is locked.
810The value is nil if the FILENAME is not locked,
811t if it is locked by you, else a string saying which user has locked it. */)
5842a27b 812 (Lisp_Object filename)
8489eb67 813{
8dbbc384 814 Lisp_Object ret;
b5029e23 815 char *lfname;
8489eb67 816 int owner;
8dbbc384 817 lock_info_type locker;
b5029e23 818 USE_SAFE_ALLOCA;
8489eb67 819
e9319ef2 820 filename = Fexpand_file_name (filename, Qnil);
8489eb67 821
e9319ef2 822 MAKE_LOCK_NAME (lfname, filename);
8489eb67 823
8dbbc384 824 owner = current_lock_owner (&locker, lfname);
8489eb67 825 if (owner <= 0)
8dbbc384
RS
826 ret = Qnil;
827 else if (owner == 2)
828 ret = Qt;
829 else
70743157 830 ret = make_string (locker.user, locker.at - locker.user);
8dbbc384 831
b5029e23 832 SAFE_FREE ();
8dbbc384 833 return ret;
8489eb67 834}
a3fd58aa 835
ffe75e6b
EZ
836#endif /* CLASH_DETECTION */
837
dfcf069d 838void
971de7fb 839syms_of_filelock (void)
8489eb67 840{
29208e82 841 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
335c5470 842 doc: /* The directory for writing temporary files. */);
5f8d6a10
RS
843 Vtemporary_file_directory = Qnil;
844
836d29b3
DA
845 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
846 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
847 create_lockfiles = 1;
848
ffe75e6b 849#ifdef CLASH_DETECTION
8489eb67
RS
850 defsubr (&Sunlock_buffer);
851 defsubr (&Slock_buffer);
852 defsubr (&Sfile_locked_p);
ffe75e6b 853#endif
8489eb67 854}