6e939f271d72ba3aab7969717ffc23e03e46d548
[bpt/emacs.git] / src / filelock.c
1 /* Lock files for editing.
2 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2013 Free Software
3 Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include <config.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <signal.h>
25 #include <stdio.h>
26
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30
31 #include <sys/file.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34
35 #ifdef __FreeBSD__
36 #include <sys/sysctl.h>
37 #endif /* __FreeBSD__ */
38
39 #include <errno.h>
40
41 #include <c-ctype.h>
42
43 #include "lisp.h"
44 #include "character.h"
45 #include "buffer.h"
46 #include "coding.h"
47 #include "systime.h"
48 #ifdef WINDOWSNT
49 #include <share.h>
50 #include <sys/socket.h> /* for fcntl */
51 #include "w32.h" /* for dostounix_filename */
52 #endif
53
54 #ifdef CLASH_DETECTION
55
56 #ifdef HAVE_UTMP_H
57 #include <utmp.h>
58 #endif
59
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
66 #ifndef WTMP_FILE
67 #define WTMP_FILE "/var/log/wtmp"
68 #endif
69
70 /* Normally use a symbolic link to represent a lock.
71 The strategy: to lock a file FN, create a symlink .#FN in FN's
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.
77
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
85 environment, it seems such stale locks arise fairly infrequently, and
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
92 files to be useful on old systems lacking symlinks, nowadays
93 virtually all such systems are probably single-user anyway, so it
94 didn't seem worth the complication.
95
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.
99
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.
103
104 --karl@cs.umb.edu/karl@hq.ileaf.com.
105
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. */
121
122 \f
123 /* Return the time of the last system boot. */
124
125 static time_t boot_time;
126 static bool boot_time_initialized;
127
128 #ifdef BOOT_TIME
129 static void get_boot_time_1 (const char *, bool);
130 #endif
131
132 static time_t
133 get_boot_time (void)
134 {
135 #if defined (BOOT_TIME)
136 int counter;
137 #endif
138
139 if (boot_time_initialized)
140 return boot_time;
141 boot_time_initialized = 1;
142
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) */
160
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
171 #if defined (BOOT_TIME)
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
188 /* Try to get boot time from the current wtmp file. */
189 get_boot_time_1 (WTMP_FILE, 1);
190
191 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
192 for (counter = 0; counter < 20 && ! boot_time; counter++)
193 {
194 char cmd_string[sizeof WTMP_FILE ".19.gz"];
195 Lisp_Object tempname, filename;
196 bool delete_flag = 0;
197
198 filename = Qnil;
199
200 tempname = make_formatted_string
201 (cmd_string, "%s.%d", WTMP_FILE, counter);
202 if (! NILP (Ffile_exists_p (tempname)))
203 filename = tempname;
204 else
205 {
206 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
207 WTMP_FILE, counter);
208 if (! NILP (Ffile_exists_p (tempname)))
209 {
210 Lisp_Object args[6];
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. */
217 filename = Fexpand_file_name (build_string ("wt"),
218 Vtemporary_file_directory);
219 filename = make_temp_name (filename, 1);
220 args[0] = build_string ("gzip");
221 args[1] = Qnil;
222 args[2] = list2 (QCfile, filename);
223 args[3] = Qnil;
224 args[4] = build_string ("-cd");
225 args[5] = tempname;
226 Fcall_process (6, args);
227 delete_flag = 1;
228 }
229 }
230
231 if (! NILP (filename))
232 {
233 get_boot_time_1 (SSDATA (filename), 1);
234 if (delete_flag)
235 unlink (SSDATA (filename));
236 }
237 }
238
239 return boot_time;
240 #else
241 return 0;
242 #endif
243 }
244
245 #ifdef BOOT_TIME
246 /* Try to get the boot time from wtmp file FILENAME.
247 This succeeds if that file contains a reboot record.
248
249 If FILENAME is zero, use the same file as before;
250 if no FILENAME has ever been specified, this is the utmp file.
251 Use the newest reboot record if NEWEST,
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
256 void
257 get_boot_time_1 (const char *filename, bool newest)
258 {
259 struct utmp ut, *utp;
260 int desc;
261
262 if (filename)
263 {
264 /* On some versions of IRIX, opening a nonexistent file name
265 is likely to crash in the utmp routines. */
266 desc = emacs_open (filename, O_RDONLY, 0);
267 if (desc < 0)
268 return;
269
270 emacs_close (desc);
271
272 utmpname (filename);
273 }
274
275 setutent ();
276
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)
286 {
287 boot_time = utp->ut_time;
288 if (! newest)
289 break;
290 }
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 }
297 endutent ();
298 }
299 #endif /* BOOT_TIME */
300 \f
301 /* An arbitrary limit on lock contents length. 8 K should be plenty
302 big enough in practice. */
303 enum { MAX_LFINFO = 8 * 1024 };
304
305 /* Here is the structure that stores information about a lock. */
306
307 typedef struct
308 {
309 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
310 points to the end of USER. */
311 char *at, *dot, *colon;
312
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;
320
321 /* Write the name of the lock file for FNAME into LOCKNAME. Length
322 will be that of FNAME plus two more for the leading ".#", plus one
323 for the null. */
324 #define MAKE_LOCK_NAME(lockname, fname) \
325 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
326 fill_in_lock_file_name (lockname, fname))
327
328 static void
329 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
330 {
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] = '#';
337 strcpy (lockfile + dirlen + 2, base);
338 }
339
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. */
345 enum { 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. */
350 static int
351 rename_lock_file (char const *old, char const *new, bool force)
352 {
353 #ifdef WINDOWSNT
354 return sys_rename_replace (old, new, force);
355 #else
356 if (! force)
357 {
358 struct stat st;
359
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
384 /* Create the lock file FILE with contents CONTENTS. Return 0 if
385 successful, an errno value on failure. If FORCE, remove any
386 existing FILE if necessary. */
387
388 static int
389 create_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;
397 #else
398 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
399 #endif
400
401 if (err == EEXIST && force)
402 {
403 unlink (lfname);
404 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
405 }
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;
415 bool need_fchmod;
416 mode_t world_readable = S_IRUSR | S_IRGRP | S_IROTH;
417 memcpy (nonce, lfname, lfdirlen);
418 strcpy (nonce + lfdirlen, nonce_base);
419
420 #if HAVE_MKOSTEMP
421 /* Prefer mkostemp to mkstemp, as it avoids a window where FD is
422 temporarily open without close-on-exec. */
423 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
424 need_fchmod = 1;
425 #elif HAVE_MKSTEMP
426 /* Prefer mkstemp to mktemp, as it avoids a race between
427 mktemp and emacs_open. */
428 fd = mkstemp (nonce);
429 need_fchmod = 1;
430 #else
431 mktemp (nonce);
432 fd = emacs_open (nonce, O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
433 world_readable);
434 need_fchmod = 0;
435 #endif
436
437 if (fd < 0)
438 err = errno;
439 else
440 {
441 ptrdiff_t lock_info_len;
442 #if ! HAVE_MKOSTEMP
443 fcntl (fd, F_SETFD, FD_CLOEXEC);
444 #endif
445 lock_info_len = strlen (lock_info_str);
446 err = 0;
447 if (emacs_write (fd, lock_info_str, lock_info_len) != lock_info_len
448 || (need_fchmod && fchmod (fd, world_readable) != 0))
449 err = errno;
450 /* There is no need to call fsync here, as the contents of
451 the lock file need not survive system crashes. */
452 if (emacs_close (fd) != 0)
453 err = errno;
454 if (!err && rename_lock_file (nonce, lfname, force) != 0)
455 err = errno;
456 if (err)
457 unlink (nonce);
458 }
459
460 SAFE_FREE ();
461 }
462
463 return err;
464 }
465
466 /* Lock the lock file named LFNAME.
467 If FORCE, do so even if it is already locked.
468 Return 0 if successful, an error number on failure. */
469
470 static int
471 lock_file_1 (char *lfname, bool force)
472 {
473 /* Call this first because it can GC. */
474 printmax_t boot = get_boot_time ();
475
476 Lisp_Object luser_name = Fuser_login_name (Qnil);
477 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
478 Lisp_Object lhost_name = Fsystem_name ();
479 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
480 char lock_info_str[MAX_LFINFO + 1];
481 printmax_t pid = getpid ();
482
483 if (sizeof lock_info_str
484 <= snprintf (lock_info_str, sizeof lock_info_str,
485 boot ? "%s@%s.%"pMd":%"pMd : "%s@%s.%"pMd,
486 user_name, host_name, pid, boot))
487 return ENAMETOOLONG;
488
489 return create_lock_file (lfname, lock_info_str, force);
490 }
491
492 /* Return true if times A and B are no more than one second apart. */
493
494 static bool
495 within_one_second (time_t a, time_t b)
496 {
497 return (a - b >= -1 && a - b <= 1);
498 }
499 \f
500 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
501 #ifndef ELOOP
502 # define ELOOP (-1)
503 #endif
504
505 /* Read the data for the lock file LFNAME into LFINFO. Read at most
506 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
507 (setting errno) on error. */
508
509 static ptrdiff_t
510 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
511 {
512 ptrdiff_t nbytes;
513
514 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
515 && errno == EINVAL)
516 {
517 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
518 if (0 <= fd)
519 {
520 ptrdiff_t read_bytes = emacs_read (fd, lfinfo, MAX_LFINFO + 1);
521 int read_errno = errno;
522 if (emacs_close (fd) != 0)
523 return -1;
524 errno = read_errno;
525 return read_bytes;
526 }
527
528 if (errno != ELOOP)
529 return -1;
530
531 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
532 The former must have been removed and replaced by the latter.
533 Try again. */
534 QUIT;
535 }
536
537 return nbytes;
538 }
539
540 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
541 1 if another process owns it (and set OWNER (if non-null) to info),
542 2 if the current process owns it,
543 or -1 if something is wrong with the locking mechanism. */
544
545 static int
546 current_lock_owner (lock_info_type *owner, char *lfname)
547 {
548 int ret;
549 lock_info_type local_owner;
550 ptrdiff_t lfinfolen;
551 intmax_t pid, boot_time;
552 char *at, *dot, *lfinfo_end;
553
554 /* Even if the caller doesn't want the owner info, we still have to
555 read it to determine return value. */
556 if (!owner)
557 owner = &local_owner;
558
559 /* If nonexistent lock file, all is well; otherwise, got strange error. */
560 lfinfolen = read_lock_data (lfname, owner->user);
561 if (lfinfolen < 0)
562 return errno == ENOENT ? 0 : -1;
563 if (MAX_LFINFO < lfinfolen)
564 return -1;
565 owner->user[lfinfolen] = 0;
566
567 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
568 /* The USER is everything before the last @. */
569 owner->at = at = memrchr (owner->user, '@', lfinfolen);
570 if (!at)
571 return -1;
572 owner->dot = dot = strrchr (at, '.');
573 if (!dot)
574 return -1;
575
576 /* The PID is everything from the last `.' to the `:'. */
577 if (! c_isdigit (dot[1]))
578 return -1;
579 errno = 0;
580 pid = strtoimax (dot + 1, &owner->colon, 10);
581 if (errno == ERANGE)
582 pid = -1;
583
584 /* After the `:', if there is one, comes the boot time. */
585 switch (owner->colon[0])
586 {
587 case 0:
588 boot_time = 0;
589 lfinfo_end = owner->colon;
590 break;
591
592 case ':':
593 if (! c_isdigit (owner->colon[1]))
594 return -1;
595 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
596 break;
597
598 default:
599 return -1;
600 }
601 if (lfinfo_end != owner->user + lfinfolen)
602 return -1;
603
604 /* On current host? */
605 if (STRINGP (Vsystem_name)
606 && dot - (at + 1) == SBYTES (Vsystem_name)
607 && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
608 {
609 if (pid == getpid ())
610 ret = 2; /* We own it. */
611 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
612 && (kill (pid, 0) >= 0 || errno == EPERM)
613 && (boot_time == 0
614 || (boot_time <= TYPE_MAXIMUM (time_t)
615 && within_one_second (boot_time, get_boot_time ()))))
616 ret = 1; /* An existing process on this machine owns it. */
617 /* The owner process is dead or has a strange pid, so try to
618 zap the lockfile. */
619 else
620 return unlink (lfname);
621 }
622 else
623 { /* If we wanted to support the check for stale locks on remote machines,
624 here's where we'd do it. */
625 ret = 1;
626 }
627
628 return ret;
629 }
630
631 \f
632 /* Lock the lock named LFNAME if possible.
633 Return 0 in that case.
634 Return positive if some other process owns the lock, and info about
635 that process in CLASHER.
636 Return -1 if cannot lock for any other reason. */
637
638 static int
639 lock_if_free (lock_info_type *clasher, char *lfname)
640 {
641 int err;
642 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
643 {
644 switch (current_lock_owner (clasher, lfname))
645 {
646 case 2:
647 return 0; /* We ourselves locked it. */
648 case 1:
649 return 1; /* Someone else has it. */
650 case -1:
651 return -1; /* current_lock_owner returned strange error. */
652 }
653
654 /* We deleted a stale lock; try again to lock the file. */
655 }
656
657 return err ? -1 : 0;
658 }
659
660 /* lock_file locks file FN,
661 meaning it serves notice on the world that you intend to edit that file.
662 This should be done only when about to modify a file-visiting
663 buffer previously unmodified.
664 Do not (normally) call this for a buffer already modified,
665 as either the file is already locked, or the user has already
666 decided to go ahead without locking.
667
668 When this returns, either the lock is locked for us,
669 or lock creation failed,
670 or the user has said to go ahead without locking.
671
672 If the file is locked by someone else, this calls
673 ask-user-about-lock (a Lisp function) with two arguments,
674 the file name and info about the user who did the locking.
675 This function can signal an error, or return t meaning
676 take away the lock, or return nil meaning ignore the lock. */
677
678 void
679 lock_file (Lisp_Object fn)
680 {
681 Lisp_Object orig_fn, encoded_fn;
682 char *lfname;
683 lock_info_type lock_info;
684 struct gcpro gcpro1;
685 USE_SAFE_ALLOCA;
686
687 /* Don't do locking if the user has opted out. */
688 if (! create_lockfiles)
689 return;
690
691 /* Don't do locking while dumping Emacs.
692 Uncompressing wtmp files uses call-process, which does not work
693 in an uninitialized Emacs. */
694 if (! NILP (Vpurify_flag))
695 return;
696
697 orig_fn = fn;
698 GCPRO1 (fn);
699 fn = Fexpand_file_name (fn, Qnil);
700 #ifdef WINDOWSNT
701 /* Ensure we have only '/' separators, to avoid problems with
702 looking (inside fill_in_lock_file_name) for backslashes in file
703 names encoded by some DBCS codepage. */
704 dostounix_filename (SSDATA (fn), 1);
705 #endif
706 encoded_fn = ENCODE_FILE (fn);
707
708 /* Create the name of the lock-file for file fn */
709 MAKE_LOCK_NAME (lfname, encoded_fn);
710
711 /* See if this file is visited and has changed on disk since it was
712 visited. */
713 {
714 register Lisp_Object subject_buf;
715
716 subject_buf = get_truename_buffer (orig_fn);
717
718 if (!NILP (subject_buf)
719 && NILP (Fverify_visited_file_modtime (subject_buf))
720 && !NILP (Ffile_exists_p (fn)))
721 call1 (intern ("ask-user-about-supersession-threat"), fn);
722
723 }
724
725 /* Try to lock the lock. */
726 if (0 < lock_if_free (&lock_info, lfname))
727 {
728 /* Someone else has the lock. Consider breaking it. */
729 Lisp_Object attack;
730 char *dot = lock_info.dot;
731 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
732 static char const replacement[] = " (pid ";
733 int replacementlen = sizeof replacement - 1;
734 memmove (dot + replacementlen, dot + 1, pidlen);
735 strcpy (dot + replacementlen + pidlen, ")");
736 memcpy (dot, replacement, replacementlen);
737 attack = call2 (intern ("ask-user-about-lock"), fn,
738 build_string (lock_info.user));
739 /* Take the lock if the user said so. */
740 if (!NILP (attack))
741 lock_file_1 (lfname, 1);
742 }
743
744 UNGCPRO;
745 SAFE_FREE ();
746 }
747
748 void
749 unlock_file (Lisp_Object fn)
750 {
751 char *lfname;
752 USE_SAFE_ALLOCA;
753
754 fn = Fexpand_file_name (fn, Qnil);
755 fn = ENCODE_FILE (fn);
756
757 MAKE_LOCK_NAME (lfname, fn);
758
759 if (current_lock_owner (0, lfname) == 2)
760 unlink (lfname);
761
762 SAFE_FREE ();
763 }
764
765 void
766 unlock_all_files (void)
767 {
768 register Lisp_Object tail;
769 register struct buffer *b;
770
771 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
772 {
773 b = XBUFFER (XCDR (XCAR (tail)));
774 if (STRINGP (BVAR (b, file_truename)) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
775 {
776 unlock_file (BVAR (b, file_truename));
777 }
778 }
779 }
780 \f
781 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
782 0, 1, 0,
783 doc: /* Lock FILE, if current buffer is modified.
784 FILE defaults to current buffer's visited file,
785 or else nothing is done if current buffer isn't visiting a file. */)
786 (Lisp_Object file)
787 {
788 if (NILP (file))
789 file = BVAR (current_buffer, file_truename);
790 else
791 CHECK_STRING (file);
792 if (SAVE_MODIFF < MODIFF
793 && !NILP (file))
794 lock_file (file);
795 return Qnil;
796 }
797
798 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
799 0, 0, 0,
800 doc: /* Unlock the file visited in the current buffer.
801 If the buffer is not modified, this does nothing because the file
802 should not be locked in that case. */)
803 (void)
804 {
805 if (SAVE_MODIFF < MODIFF
806 && STRINGP (BVAR (current_buffer, file_truename)))
807 unlock_file (BVAR (current_buffer, file_truename));
808 return Qnil;
809 }
810
811 /* Unlock the file visited in buffer BUFFER. */
812
813 void
814 unlock_buffer (struct buffer *buffer)
815 {
816 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
817 && STRINGP (BVAR (buffer, file_truename)))
818 unlock_file (BVAR (buffer, file_truename));
819 }
820
821 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
822 doc: /* Return a value indicating whether FILENAME is locked.
823 The value is nil if the FILENAME is not locked,
824 t if it is locked by you, else a string saying which user has locked it. */)
825 (Lisp_Object filename)
826 {
827 Lisp_Object ret;
828 char *lfname;
829 int owner;
830 lock_info_type locker;
831 USE_SAFE_ALLOCA;
832
833 filename = Fexpand_file_name (filename, Qnil);
834
835 MAKE_LOCK_NAME (lfname, filename);
836
837 owner = current_lock_owner (&locker, lfname);
838 if (owner <= 0)
839 ret = Qnil;
840 else if (owner == 2)
841 ret = Qt;
842 else
843 ret = make_string (locker.user, locker.at - locker.user);
844
845 SAFE_FREE ();
846 return ret;
847 }
848
849 #endif /* CLASH_DETECTION */
850
851 void
852 syms_of_filelock (void)
853 {
854 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
855 doc: /* The directory for writing temporary files. */);
856 Vtemporary_file_directory = Qnil;
857
858 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
859 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
860 create_lockfiles = 1;
861
862 #ifdef CLASH_DETECTION
863 defsubr (&Sunlock_buffer);
864 defsubr (&Slock_buffer);
865 defsubr (&Sfile_locked_p);
866 #endif
867 }