* filelock.c (create_lock_file) [!HAVE_MKOSTEMP && !HAVE_MKSTEMP]:
[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. */
184 get_boot_time_1 ((char *) 0, 0);
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
RS
260 int desc;
261
b97771fc
RS
262 if (filename)
263 {
264 /* On some versions of IRIX, opening a nonexistent file name
265 is likely to crash in the utmp routines. */
68c45bf0 266 desc = emacs_open (filename, O_RDONLY, 0);
b97771fc
RS
267 if (desc < 0)
268 return;
269
68c45bf0 270 emacs_close (desc);
b97771fc
RS
271
272 utmpname (filename);
273 }
9177d978 274
c321b190 275 setutent ();
b97771fc 276
c321b190
RS
277 while (1)
278 {
279 /* Find the next reboot record. */
280 ut.ut_type = BOOT_TIME;
281 utp = getutid (&ut);
282 if (! utp)
283 break;
284 /* Compare reboot times and use the newest one. */
285 if (utp->ut_time > boot_time)
b97771fc
RS
286 {
287 boot_time = utp->ut_time;
288 if (! newest)
289 break;
290 }
c321b190
RS
291 /* Advance on element in the file
292 so that getutid won't repeat the same one. */
293 utp = getutent ();
294 if (! utp)
295 break;
296 }
15e88d21 297 endutent ();
15e88d21 298}
e9f22ced 299#endif /* BOOT_TIME */
15e88d21 300\f
70743157
PE
301/* An arbitrary limit on lock contents length. 8 K should be plenty
302 big enough in practice. */
303enum { MAX_LFINFO = 8 * 1024 };
304
8dbbc384 305/* Here is the structure that stores information about a lock. */
32676c08 306
8dbbc384
RS
307typedef struct
308{
70743157
PE
309 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
310 points to the end of USER. */
311 char *at, *dot, *colon;
e31fbc7a 312
70743157
PE
313 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
314 appended. This memory is used as a lock file contents buffer, so
315 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
316 may be appended to the USER@HOST while generating a diagnostic,
317 so make room for its extra bytes (as opposed to ".NNNN") too. */
318 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
319} lock_info_type;
e31fbc7a 320
b5029e23 321/* Write the name of the lock file for FNAME into LOCKNAME. Length
70743157
PE
322 will be that of FNAME plus two more for the leading ".#", plus one
323 for the null. */
b5029e23 324#define MAKE_LOCK_NAME(lockname, fname) \
70743157 325 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
b5029e23
PE
326 fill_in_lock_file_name (lockname, fname))
327
8dbbc384 328static void
b5029e23 329fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
e31fbc7a 330{
b5029e23
PE
331 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
332 char *base = last_slash + 1;
333 ptrdiff_t dirlen = base - SSDATA (fn);
334 memcpy (lockfile, SSDATA (fn), dirlen);
335 lockfile[dirlen] = '.';
336 lockfile[dirlen + 1] = '#';
70743157 337 strcpy (lockfile + dirlen + 2, base);
8dbbc384 338}
e31fbc7a 339
70743157
PE
340/* For some reason Linux kernels return EPERM on file systems that do
341 not support hard or symbolic links. This symbol documents the quirk.
342 There is no way to tell whether a symlink call fails due to
343 permissions issues or because links are not supported, but luckily
344 the lock file code should work either way. */
345enum { LINKS_MIGHT_NOT_WORK = EPERM };
346
347/* Rename OLD to NEW. If FORCE, replace any existing NEW.
348 It is OK if there are temporarily two hard links to OLD.
349 Return 0 if successful, -1 (setting errno) otherwise. */
343a2aef 350static int
70743157 351rename_lock_file (char const *old, char const *new, bool force)
343a2aef 352{
343a2aef 353#ifdef WINDOWSNT
70743157
PE
354 return sys_rename_replace (old, new, force);
355#else
356 if (! force)
357 {
358 struct stat st;
343a2aef 359
70743157
PE
360 if (link (old, new) == 0)
361 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
362 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
363 return -1;
364
365 /* 'link' does not work on this file system. This can occur on
366 a GNU/Linux host mounting a FAT32 file system. Fall back on
367 'rename' after checking that NEW does not exist. There is a
368 potential race condition since some other process may create
369 NEW immediately after the existence check, but it's the best
370 we can portably do here. */
371 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
372 {
373 errno = EEXIST;
374 return -1;
375 }
376 if (errno != ENOENT)
377 return -1;
378 }
379
380 return rename (old, new);
381#endif
382}
383
1b6006a5 384/* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
70743157 385 successful, an errno value on failure. If FORCE, remove any
1b6006a5 386 existing LFNAME if necessary. */
70743157
PE
387
388static int
389create_lock_file (char *lfname, char *lock_info_str, bool force)
390{
391#ifdef WINDOWSNT
392 /* Symlinks are supported only by later versions of Windows, and
393 creating them is a privileged operation that often triggers
394 User Account Control elevation prompts. Avoid the problem by
395 pretending that 'symlink' does not work. */
396 int err = ENOSYS;
343a2aef 397#else
70743157
PE
398 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
399#endif
400
401 if (err == EEXIST && force)
343a2aef
EZ
402 {
403 unlink (lfname);
70743157 404 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
343a2aef 405 }
70743157
PE
406
407 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
408 {
409 static char const nonce_base[] = ".#-emacsXXXXXX";
410 char *last_slash = strrchr (lfname, '/');
411 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
412 USE_SAFE_ALLOCA;
413 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
414 int fd;
70743157
PE
415 memcpy (nonce, lfname, lfdirlen);
416 strcpy (nonce + lfdirlen, nonce_base);
417
067428c1
PE
418#if HAVE_MKOSTEMP
419 /* Prefer mkostemp to mkstemp, as it avoids a window where FD is
420 temporarily open without close-on-exec. */
421 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
067428c1
PE
422#elif HAVE_MKSTEMP
423 /* Prefer mkstemp to mktemp, as it avoids a race between
70743157
PE
424 mktemp and emacs_open. */
425 fd = mkstemp (nonce);
70743157
PE
426#else
427 mktemp (nonce);
428 fd = emacs_open (nonce, O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
5c97beae 429 S_IRUSR | S_IWUSR);
343a2aef
EZ
430#endif
431
70743157
PE
432 if (fd < 0)
433 err = errno;
434 else
435 {
067428c1
PE
436 ptrdiff_t lock_info_len;
437#if ! HAVE_MKOSTEMP
438 fcntl (fd, F_SETFD, FD_CLOEXEC);
439#endif
440 lock_info_len = strlen (lock_info_str);
70743157
PE
441 err = 0;
442 if (emacs_write (fd, lock_info_str, lock_info_len) != lock_info_len
5c97beae 443 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
70743157 444 err = errno;
cbee2131
PE
445 /* There is no need to call fsync here, as the contents of
446 the lock file need not survive system crashes. */
70743157
PE
447 if (emacs_close (fd) != 0)
448 err = errno;
449 if (!err && rename_lock_file (nonce, lfname, force) != 0)
450 err = errno;
451 if (err)
452 unlink (nonce);
453 }
454
455 SAFE_FREE ();
456 }
457
343a2aef
EZ
458 return err;
459}
460
8dbbc384 461/* Lock the lock file named LFNAME.
f75d7a91 462 If FORCE, do so even if it is already locked.
70743157 463 Return 0 if successful, an error number on failure. */
e31fbc7a 464
70743157 465static int
f75d7a91 466lock_file_1 (char *lfname, bool force)
8dbbc384 467{
4ba93ac0 468 /* Call this first because it can GC. */
98c6f1e3
PE
469 printmax_t boot = get_boot_time ();
470
471 Lisp_Object luser_name = Fuser_login_name (Qnil);
472 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
473 Lisp_Object lhost_name = Fsystem_name ();
474 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
70743157 475 char lock_info_str[MAX_LFINFO + 1];
98c6f1e3 476 printmax_t pid = getpid ();
8dbbc384 477
70743157
PE
478 if (sizeof lock_info_str
479 <= snprintf (lock_info_str, sizeof lock_info_str,
480 boot ? "%s@%s.%"pMd":%"pMd : "%s@%s.%"pMd,
481 user_name, host_name, pid, boot))
482 return ENAMETOOLONG;
e31fbc7a 483
70743157 484 return create_lock_file (lfname, lock_info_str, force);
8dbbc384 485}
e31fbc7a 486
f75d7a91 487/* Return true if times A and B are no more than one second apart. */
32676c08 488
f75d7a91 489static bool
971de7fb 490within_one_second (time_t a, time_t b)
9177d978
RS
491{
492 return (a - b >= -1 && a - b <= 1);
493}
8dbbc384 494\f
70743157
PE
495/* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
496#ifndef ELOOP
497# define ELOOP (-1)
498#endif
343a2aef 499
70743157
PE
500/* Read the data for the lock file LFNAME into LFINFO. Read at most
501 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
502 (setting errno) on error. */
343a2aef 503
70743157
PE
504static ptrdiff_t
505read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
506{
507 ptrdiff_t nbytes;
343a2aef 508
70743157
PE
509 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
510 && errno == EINVAL)
343a2aef 511 {
70743157
PE
512 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
513 if (0 <= fd)
514 {
515 ptrdiff_t read_bytes = emacs_read (fd, lfinfo, MAX_LFINFO + 1);
516 int read_errno = errno;
517 if (emacs_close (fd) != 0)
518 return -1;
519 errno = read_errno;
520 return read_bytes;
521 }
522
523 if (errno != ELOOP)
524 return -1;
525
526 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
527 The former must have been removed and replaced by the latter.
528 Try again. */
529 QUIT;
343a2aef 530 }
70743157
PE
531
532 return nbytes;
343a2aef
EZ
533}
534
8dbbc384
RS
535/* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
536 1 if another process owns it (and set OWNER (if non-null) to info),
537 2 if the current process owns it,
538 or -1 if something is wrong with the locking mechanism. */
e31fbc7a 539
8dbbc384 540static int
971de7fb 541current_lock_owner (lock_info_type *owner, char *lfname)
32676c08 542{
d1fdcab7 543 int ret;
882f0d81 544 lock_info_type local_owner;
70743157
PE
545 ptrdiff_t lfinfolen;
546 intmax_t pid, boot_time;
547 char *at, *dot, *lfinfo_end;
177c0ea7 548
8dbbc384 549 /* Even if the caller doesn't want the owner info, we still have to
882f0d81 550 read it to determine return value. */
8dbbc384 551 if (!owner)
882f0d81 552 owner = &local_owner;
177c0ea7 553
70743157
PE
554 /* If nonexistent lock file, all is well; otherwise, got strange error. */
555 lfinfolen = read_lock_data (lfname, owner->user);
556 if (lfinfolen < 0)
557 return errno == ENOENT ? 0 : -1;
558 if (MAX_LFINFO < lfinfolen)
559 return -1;
560 owner->user[lfinfolen] = 0;
561
15e88d21 562 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
50624218 563 /* The USER is everything before the last @. */
70743157
PE
564 owner->at = at = memrchr (owner->user, '@', lfinfolen);
565 if (!at)
566 return -1;
567 owner->dot = dot = strrchr (at, '.');
568 if (!dot)
8654f9d7 569 return -1;
177c0ea7 570
15e88d21 571 /* The PID is everything from the last `.' to the `:'. */
70743157
PE
572 if (! c_isdigit (dot[1]))
573 return -1;
882f0d81 574 errno = 0;
70743157
PE
575 pid = strtoimax (dot + 1, &owner->colon, 10);
576 if (errno == ERANGE)
577 pid = -1;
882f0d81 578
15e88d21 579 /* After the `:', if there is one, comes the boot time. */
70743157 580 switch (owner->colon[0])
882f0d81 581 {
70743157
PE
582 case 0:
583 boot_time = 0;
584 lfinfo_end = owner->colon;
585 break;
586
587 case ':':
588 if (! c_isdigit (owner->colon[1]))
589 return -1;
590 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
591 break;
592
593 default:
594 return -1;
882f0d81 595 }
70743157
PE
596 if (lfinfo_end != owner->user + lfinfolen)
597 return -1;
177c0ea7 598
8dbbc384 599 /* On current host? */
70743157
PE
600 if (STRINGP (Vsystem_name)
601 && dot - (at + 1) == SBYTES (Vsystem_name)
602 && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
32676c08 603 {
70743157 604 if (pid == getpid ())
8dbbc384 605 ret = 2; /* We own it. */
70743157
PE
606 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
607 && (kill (pid, 0) >= 0 || errno == EPERM)
608 && (boot_time == 0
609 || (boot_time <= TYPE_MAXIMUM (time_t)
610 && within_one_second (boot_time, get_boot_time ()))))
8dbbc384 611 ret = 1; /* An existing process on this machine owns it. */
70743157 612 /* The owner process is dead or has a strange pid, so try to
8dbbc384 613 zap the lockfile. */
72dcef0e 614 else
70743157 615 return unlink (lfname);
32676c08 616 }
8dbbc384
RS
617 else
618 { /* If we wanted to support the check for stale locks on remote machines,
619 here's where we'd do it. */
620 ret = 1;
621 }
177c0ea7 622
8dbbc384 623 return ret;
32676c08
JB
624}
625
8dbbc384
RS
626\f
627/* Lock the lock named LFNAME if possible.
628 Return 0 in that case.
629 Return positive if some other process owns the lock, and info about
630 that process in CLASHER.
631 Return -1 if cannot lock for any other reason. */
8489eb67 632
8dbbc384 633static int
70743157 634lock_if_free (lock_info_type *clasher, char *lfname)
8dbbc384 635{
70743157
PE
636 int err;
637 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
8dbbc384 638 {
70743157
PE
639 switch (current_lock_owner (clasher, lfname))
640 {
641 case 2:
642 return 0; /* We ourselves locked it. */
643 case 1:
644 return 1; /* Someone else has it. */
645 case -1:
646 return -1; /* current_lock_owner returned strange error. */
647 }
8dbbc384 648
cfc01fa7 649 /* We deleted a stale lock; try again to lock the file. */
8dbbc384 650 }
70743157
PE
651
652 return err ? -1 : 0;
8489eb67
RS
653}
654
8dbbc384 655/* lock_file locks file FN,
8489eb67
RS
656 meaning it serves notice on the world that you intend to edit that file.
657 This should be done only when about to modify a file-visiting
658 buffer previously unmodified.
8dbbc384 659 Do not (normally) call this for a buffer already modified,
8489eb67
RS
660 as either the file is already locked, or the user has already
661 decided to go ahead without locking.
662
8dbbc384 663 When this returns, either the lock is locked for us,
b5029e23 664 or lock creation failed,
8489eb67
RS
665 or the user has said to go ahead without locking.
666
8dbbc384 667 If the file is locked by someone else, this calls
8489eb67 668 ask-user-about-lock (a Lisp function) with two arguments,
8dbbc384 669 the file name and info about the user who did the locking.
8489eb67
RS
670 This function can signal an error, or return t meaning
671 take away the lock, or return nil meaning ignore the lock. */
672
8489eb67 673void
971de7fb 674lock_file (Lisp_Object fn)
8489eb67 675{
2db41375
PE
676 Lisp_Object orig_fn, encoded_fn;
677 char *lfname;
8dbbc384 678 lock_info_type lock_info;
3edc33a4 679 struct gcpro gcpro1;
b5cd1905 680 USE_SAFE_ALLOCA;
8489eb67 681
836d29b3
DA
682 /* Don't do locking if the user has opted out. */
683 if (! create_lockfiles)
684 return;
685
33bae690
RS
686 /* Don't do locking while dumping Emacs.
687 Uncompressing wtmp files uses call-process, which does not work
688 in an uninitialized Emacs. */
689 if (! NILP (Vpurify_flag))
690 return;
691
5383bc6d 692 orig_fn = fn;
8af8a9ca 693 GCPRO1 (fn);
1e89de84 694 fn = Fexpand_file_name (fn, Qnil);
343a2aef
EZ
695#ifdef WINDOWSNT
696 /* Ensure we have only '/' separators, to avoid problems with
697 looking (inside fill_in_lock_file_name) for backslashes in file
698 names encoded by some DBCS codepage. */
699 dostounix_filename (SSDATA (fn), 1);
700#endif
f4a4528d 701 encoded_fn = ENCODE_FILE (fn);
1e89de84 702
8dbbc384 703 /* Create the name of the lock-file for file fn */
f4a4528d 704 MAKE_LOCK_NAME (lfname, encoded_fn);
8489eb67 705
32676c08
JB
706 /* See if this file is visited and has changed on disk since it was
707 visited. */
8489eb67 708 {
a57bc488 709 register Lisp_Object subject_buf;
3036594f 710
5383bc6d 711 subject_buf = get_truename_buffer (orig_fn);
3036594f 712
265a9e55
JB
713 if (!NILP (subject_buf)
714 && NILP (Fverify_visited_file_modtime (subject_buf))
715 && !NILP (Ffile_exists_p (fn)))
8489eb67 716 call1 (intern ("ask-user-about-supersession-threat"), fn);
3036594f 717
8489eb67 718 }
8489eb67 719
2db41375
PE
720 /* Try to lock the lock. */
721 if (0 < lock_if_free (&lock_info, lfname))
8489eb67 722 {
2db41375 723 /* Someone else has the lock. Consider breaking it. */
2db41375 724 Lisp_Object attack;
70743157
PE
725 char *dot = lock_info.dot;
726 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
727 static char const replacement[] = " (pid ";
728 int replacementlen = sizeof replacement - 1;
729 memmove (dot + replacementlen, dot + 1, pidlen);
730 strcpy (dot + replacementlen + pidlen, ")");
731 memcpy (dot, replacement, replacementlen);
732 attack = call2 (intern ("ask-user-about-lock"), fn,
733 build_string (lock_info.user));
2db41375
PE
734 /* Take the lock if the user said so. */
735 if (!NILP (attack))
736 lock_file_1 (lfname, 1);
8489eb67 737 }
2db41375
PE
738
739 UNGCPRO;
740 SAFE_FREE ();
8489eb67
RS
741}
742
8489eb67 743void
b5029e23 744unlock_file (Lisp_Object fn)
8489eb67 745{
b5029e23
PE
746 char *lfname;
747 USE_SAFE_ALLOCA;
8489eb67 748
1e89de84 749 fn = Fexpand_file_name (fn, Qnil);
88eace34 750 fn = ENCODE_FILE (fn);
1e89de84 751
7b92975f 752 MAKE_LOCK_NAME (lfname, fn);
8489eb67 753
8dbbc384 754 if (current_lock_owner (0, lfname) == 2)
8489eb67 755 unlink (lfname);
b5029e23
PE
756
757 SAFE_FREE ();
8489eb67
RS
758}
759
760void
971de7fb 761unlock_all_files (void)
8489eb67
RS
762{
763 register Lisp_Object tail;
764 register struct buffer *b;
765
8e50cc2d 766 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
8489eb67 767 {
03699b14 768 b = XBUFFER (XCDR (XCAR (tail)));
4b4deea2 769 if (STRINGP (BVAR (b, file_truename)) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
1c343051 770 {
5e617bc2 771 unlock_file (BVAR (b, file_truename));
1c343051 772 }
8489eb67
RS
773 }
774}
8489eb67
RS
775\f
776DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
335c5470
PJ
777 0, 1, 0,
778 doc: /* Lock FILE, if current buffer is modified.
779FILE defaults to current buffer's visited file,
780or else nothing is done if current buffer isn't visiting a file. */)
5842a27b 781 (Lisp_Object file)
8489eb67 782{
e9319ef2 783 if (NILP (file))
4b4deea2 784 file = BVAR (current_buffer, file_truename);
8489eb67 785 else
b7826503 786 CHECK_STRING (file);
6a140159 787 if (SAVE_MODIFF < MODIFF
e9319ef2
EN
788 && !NILP (file))
789 lock_file (file);
177c0ea7 790 return Qnil;
8489eb67
RS
791}
792
a7ca3326 793DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
335c5470 794 0, 0, 0,
3bfb8921
RS
795 doc: /* Unlock the file visited in the current buffer.
796If the buffer is not modified, this does nothing because the file
797should not be locked in that case. */)
5842a27b 798 (void)
8489eb67 799{
6a140159 800 if (SAVE_MODIFF < MODIFF
4b4deea2
TT
801 && STRINGP (BVAR (current_buffer, file_truename)))
802 unlock_file (BVAR (current_buffer, file_truename));
8489eb67
RS
803 return Qnil;
804}
805
8489eb67
RS
806/* Unlock the file visited in buffer BUFFER. */
807
d07e0802 808void
971de7fb 809unlock_buffer (struct buffer *buffer)
8489eb67 810{
6a140159 811 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
4b4deea2
TT
812 && STRINGP (BVAR (buffer, file_truename)))
813 unlock_file (BVAR (buffer, file_truename));
8489eb67
RS
814}
815
8105cbf7 816DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
3bfb8921
RS
817 doc: /* Return a value indicating whether FILENAME is locked.
818The value is nil if the FILENAME is not locked,
819t if it is locked by you, else a string saying which user has locked it. */)
5842a27b 820 (Lisp_Object filename)
8489eb67 821{
8dbbc384 822 Lisp_Object ret;
b5029e23 823 char *lfname;
8489eb67 824 int owner;
8dbbc384 825 lock_info_type locker;
b5029e23 826 USE_SAFE_ALLOCA;
8489eb67 827
e9319ef2 828 filename = Fexpand_file_name (filename, Qnil);
8489eb67 829
e9319ef2 830 MAKE_LOCK_NAME (lfname, filename);
8489eb67 831
8dbbc384 832 owner = current_lock_owner (&locker, lfname);
8489eb67 833 if (owner <= 0)
8dbbc384
RS
834 ret = Qnil;
835 else if (owner == 2)
836 ret = Qt;
837 else
70743157 838 ret = make_string (locker.user, locker.at - locker.user);
8dbbc384 839
b5029e23 840 SAFE_FREE ();
8dbbc384 841 return ret;
8489eb67 842}
a3fd58aa 843
ffe75e6b
EZ
844#endif /* CLASH_DETECTION */
845
dfcf069d 846void
971de7fb 847syms_of_filelock (void)
8489eb67 848{
29208e82 849 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
335c5470 850 doc: /* The directory for writing temporary files. */);
5f8d6a10
RS
851 Vtemporary_file_directory = Qnil;
852
836d29b3
DA
853 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
854 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
855 create_lockfiles = 1;
856
ffe75e6b 857#ifdef CLASH_DETECTION
8489eb67
RS
858 defsubr (&Sunlock_buffer);
859 defsubr (&Slock_buffer);
860 defsubr (&Sfile_locked_p);
ffe75e6b 861#endif
8489eb67 862}