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