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