* themes/tsdh-dark-theme.el (tsdh-dark): Add some more faces.
[emacs.git] / src / filelock.c
blobf17d3182eab1fa520c3b2a773a2c8bd5074d0f26
1 /* Lock files for editing.
2 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2013 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
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.
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.
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/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <signal.h>
25 #include <stdio.h>
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
31 #include <sys/file.h>
32 #include <fcntl.h>
33 #include <unistd.h>
35 #ifdef __FreeBSD__
36 #include <sys/sysctl.h>
37 #endif /* __FreeBSD__ */
39 #include <errno.h>
41 #include <c-ctype.h>
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 "w32.h" /* for dostounix_filename */
51 #endif
53 #ifdef CLASH_DETECTION
55 #ifdef HAVE_UTMP_H
56 #include <utmp.h>
57 #endif
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
65 #ifndef WTMP_FILE
66 #define WTMP_FILE "/var/log/wtmp"
67 #endif
69 /* Normally use a symbolic link to represent a lock.
70 The strategy: to lock a file FN, create a symlink .#FN in FN's
71 directory, with link data `user@host.pid'. This avoids a single
72 mount (== failure) point for lock files.
74 When the host in the lock data is the current host, we can check if
75 the pid is valid with kill.
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
84 environment, it seems such stale locks arise fairly infrequently, and
85 Emacs' standard methods of dealing with clashes suffice.
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
91 files to be useful on old systems lacking symlinks, nowadays
92 virtually all such systems are probably single-user anyway, so it
93 didn't seem worth the complication.
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.
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.
103 --karl@cs.umb.edu/karl@hq.ileaf.com.
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.
114 To summarize, race conditions can occur with either:
116 * Forced locks on MS-Windows systems.
118 * Non-forced locks on non-MS-Windows systems that support neither
119 hard nor symbolic links. */
122 /* Return the time of the last system boot. */
124 static time_t boot_time;
125 static bool boot_time_initialized;
127 #ifdef BOOT_TIME
128 static void get_boot_time_1 (const char *, bool);
129 #endif
131 static time_t
132 get_boot_time (void)
134 #if defined (BOOT_TIME)
135 int counter;
136 #endif
138 if (boot_time_initialized)
139 return boot_time;
140 boot_time_initialized = 1;
142 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
144 int mib[2];
145 size_t size;
146 struct timeval boottime_val;
148 mib[0] = CTL_KERN;
149 mib[1] = KERN_BOOTTIME;
150 size = sizeof (boottime_val);
152 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
154 boot_time = boottime_val.tv_sec;
155 return boot_time;
158 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
160 if (BOOT_TIME_FILE)
162 struct stat st;
163 if (stat (BOOT_TIME_FILE, &st) == 0)
165 boot_time = st.st_mtime;
166 return boot_time;
170 #if defined (BOOT_TIME)
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 */
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;
187 /* Try to get boot time from the current wtmp file. */
188 get_boot_time_1 (WTMP_FILE, 1);
190 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
191 for (counter = 0; counter < 20 && ! boot_time; counter++)
193 char cmd_string[sizeof WTMP_FILE ".19.gz"];
194 Lisp_Object tempname, filename;
195 bool delete_flag = 0;
197 filename = Qnil;
199 tempname = make_formatted_string
200 (cmd_string, "%s.%d", WTMP_FILE, counter);
201 if (! NILP (Ffile_exists_p (tempname)))
202 filename = tempname;
203 else
205 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
206 WTMP_FILE, counter);
207 if (! NILP (Ffile_exists_p (tempname)))
209 Lisp_Object args[6];
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. */
216 filename = Fexpand_file_name (build_string ("wt"),
217 Vtemporary_file_directory);
218 filename = make_temp_name (filename, 1);
219 args[0] = build_string ("gzip");
220 args[1] = Qnil;
221 args[2] = list2 (QCfile, filename);
222 args[3] = Qnil;
223 args[4] = build_string ("-cd");
224 args[5] = tempname;
225 Fcall_process (6, args);
226 delete_flag = 1;
230 if (! NILP (filename))
232 get_boot_time_1 (SSDATA (filename), 1);
233 if (delete_flag)
234 unlink (SSDATA (filename));
238 return boot_time;
239 #else
240 return 0;
241 #endif
244 #ifdef BOOT_TIME
245 /* Try to get the boot time from wtmp file FILENAME.
246 This succeeds if that file contains a reboot record.
248 If FILENAME is zero, use the same file as before;
249 if no FILENAME has ever been specified, this is the utmp file.
250 Use the newest reboot record if NEWEST,
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. */
255 void
256 get_boot_time_1 (const char *filename, bool newest)
258 struct utmp ut, *utp;
259 int desc;
261 if (filename)
263 /* On some versions of IRIX, opening a nonexistent file name
264 is likely to crash in the utmp routines. */
265 desc = emacs_open (filename, O_RDONLY, 0);
266 if (desc < 0)
267 return;
269 emacs_close (desc);
271 utmpname (filename);
274 setutent ();
276 while (1)
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)
286 boot_time = utp->ut_time;
287 if (! newest)
288 break;
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;
296 endutent ();
298 #endif /* BOOT_TIME */
300 /* An arbitrary limit on lock contents length. 8 K should be plenty
301 big enough in practice. */
302 enum { MAX_LFINFO = 8 * 1024 };
304 /* Here is the structure that stores information about a lock. */
306 typedef struct
308 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
309 points to the end of USER. */
310 char *at, *dot, *colon;
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;
320 /* Write the name of the lock file for FNAME into LOCKNAME. Length
321 will be that of FNAME plus two more for the leading ".#", plus one
322 for the null. */
323 #define MAKE_LOCK_NAME(lockname, fname) \
324 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
325 fill_in_lock_file_name (lockname, fname))
327 static void
328 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
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] = '#';
336 strcpy (lockfile + dirlen + 2, base);
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. */
344 enum { LINKS_MIGHT_NOT_WORK = EPERM };
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. */
349 static int
350 rename_lock_file (char const *old, char const *new, bool force)
352 #ifdef WINDOWSNT
353 return sys_rename_replace (old, new, force);
354 #else
355 if (! force)
357 struct stat st;
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;
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)
372 errno = EEXIST;
373 return -1;
375 if (errno != ENOENT)
376 return -1;
379 return rename (old, new);
380 #endif
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. */
387 static int
388 create_lock_file (char *lfname, char *lock_info_str, bool force)
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;
396 #else
397 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
398 #endif
400 if (err == EEXIST && force)
402 unlink (lfname);
403 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
406 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
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);
419 #if HAVE_MKSTEMP
420 /* Prefer mkstemp if available, as it avoids a race between
421 mktemp and emacs_open. */
422 fd = mkstemp (nonce);
423 need_fchmod = 1;
424 #else
425 mktemp (nonce);
426 fd = emacs_open (nonce, O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
427 world_readable);
428 need_fchmod = 0;
429 #endif
431 if (fd < 0)
432 err = errno;
433 else
435 ptrdiff_t lock_info_len = strlen (lock_info_str);
436 err = 0;
437 if (emacs_write (fd, lock_info_str, lock_info_len) != lock_info_len
438 || (need_fchmod && fchmod (fd, world_readable) != 0))
439 err = errno;
440 else
441 while (fsync (fd) != 0)
442 if (errno != EINTR)
444 if (errno != EINVAL)
445 err = errno;
446 break;
448 if (emacs_close (fd) != 0)
449 err = errno;
450 if (!err && rename_lock_file (nonce, lfname, force) != 0)
451 err = errno;
452 if (err)
453 unlink (nonce);
456 SAFE_FREE ();
459 return err;
462 /* Lock the lock file named LFNAME.
463 If FORCE, do so even if it is already locked.
464 Return 0 if successful, an error number on failure. */
466 static int
467 lock_file_1 (char *lfname, bool force)
469 /* Call this first because it can GC. */
470 printmax_t boot = get_boot_time ();
472 Lisp_Object luser_name = Fuser_login_name (Qnil);
473 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
474 Lisp_Object lhost_name = Fsystem_name ();
475 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
476 char lock_info_str[MAX_LFINFO + 1];
477 printmax_t pid = getpid ();
479 if (sizeof lock_info_str
480 <= snprintf (lock_info_str, sizeof lock_info_str,
481 boot ? "%s@%s.%"pMd":%"pMd : "%s@%s.%"pMd,
482 user_name, host_name, pid, boot))
483 return ENAMETOOLONG;
485 return create_lock_file (lfname, lock_info_str, force);
488 /* Return true if times A and B are no more than one second apart. */
490 static bool
491 within_one_second (time_t a, time_t b)
493 return (a - b >= -1 && a - b <= 1);
496 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
497 #ifndef ELOOP
498 # define ELOOP (-1)
499 #endif
501 /* Read the data for the lock file LFNAME into LFINFO. Read at most
502 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
503 (setting errno) on error. */
505 static ptrdiff_t
506 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
508 ptrdiff_t nbytes;
510 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
511 && errno == EINVAL)
513 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
514 if (0 <= fd)
516 ptrdiff_t read_bytes = emacs_read (fd, lfinfo, MAX_LFINFO + 1);
517 int read_errno = errno;
518 if (emacs_close (fd) != 0)
519 return -1;
520 errno = read_errno;
521 return read_bytes;
524 if (errno != ELOOP)
525 return -1;
527 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
528 The former must have been removed and replaced by the latter.
529 Try again. */
530 QUIT;
533 return nbytes;
536 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
537 1 if another process owns it (and set OWNER (if non-null) to info),
538 2 if the current process owns it,
539 or -1 if something is wrong with the locking mechanism. */
541 static int
542 current_lock_owner (lock_info_type *owner, char *lfname)
544 int ret;
545 lock_info_type local_owner;
546 ptrdiff_t lfinfolen;
547 intmax_t pid, boot_time;
548 char *at, *dot, *lfinfo_end;
550 /* Even if the caller doesn't want the owner info, we still have to
551 read it to determine return value. */
552 if (!owner)
553 owner = &local_owner;
555 /* If nonexistent lock file, all is well; otherwise, got strange error. */
556 lfinfolen = read_lock_data (lfname, owner->user);
557 if (lfinfolen < 0)
558 return errno == ENOENT ? 0 : -1;
559 if (MAX_LFINFO < lfinfolen)
560 return -1;
561 owner->user[lfinfolen] = 0;
563 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
564 /* The USER is everything before the last @. */
565 owner->at = at = memrchr (owner->user, '@', lfinfolen);
566 if (!at)
567 return -1;
568 owner->dot = dot = strrchr (at, '.');
569 if (!dot)
570 return -1;
572 /* The PID is everything from the last `.' to the `:'. */
573 if (! c_isdigit (dot[1]))
574 return -1;
575 errno = 0;
576 pid = strtoimax (dot + 1, &owner->colon, 10);
577 if (errno == ERANGE)
578 pid = -1;
580 /* After the `:', if there is one, comes the boot time. */
581 switch (owner->colon[0])
583 case 0:
584 boot_time = 0;
585 lfinfo_end = owner->colon;
586 break;
588 case ':':
589 if (! c_isdigit (owner->colon[1]))
590 return -1;
591 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
592 break;
594 default:
595 return -1;
597 if (lfinfo_end != owner->user + lfinfolen)
598 return -1;
600 /* On current host? */
601 if (STRINGP (Vsystem_name)
602 && dot - (at + 1) == SBYTES (Vsystem_name)
603 && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
605 if (pid == getpid ())
606 ret = 2; /* We own it. */
607 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
608 && (kill (pid, 0) >= 0 || errno == EPERM)
609 && (boot_time == 0
610 || (boot_time <= TYPE_MAXIMUM (time_t)
611 && within_one_second (boot_time, get_boot_time ()))))
612 ret = 1; /* An existing process on this machine owns it. */
613 /* The owner process is dead or has a strange pid, so try to
614 zap the lockfile. */
615 else
616 return unlink (lfname);
618 else
619 { /* If we wanted to support the check for stale locks on remote machines,
620 here's where we'd do it. */
621 ret = 1;
624 return ret;
628 /* Lock the lock named LFNAME if possible.
629 Return 0 in that case.
630 Return positive if some other process owns the lock, and info about
631 that process in CLASHER.
632 Return -1 if cannot lock for any other reason. */
634 static int
635 lock_if_free (lock_info_type *clasher, char *lfname)
637 int err;
638 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
640 switch (current_lock_owner (clasher, lfname))
642 case 2:
643 return 0; /* We ourselves locked it. */
644 case 1:
645 return 1; /* Someone else has it. */
646 case -1:
647 return -1; /* current_lock_owner returned strange error. */
650 /* We deleted a stale lock; try again to lock the file. */
653 return err ? -1 : 0;
656 /* lock_file locks file FN,
657 meaning it serves notice on the world that you intend to edit that file.
658 This should be done only when about to modify a file-visiting
659 buffer previously unmodified.
660 Do not (normally) call this for a buffer already modified,
661 as either the file is already locked, or the user has already
662 decided to go ahead without locking.
664 When this returns, either the lock is locked for us,
665 or lock creation failed,
666 or the user has said to go ahead without locking.
668 If the file is locked by someone else, this calls
669 ask-user-about-lock (a Lisp function) with two arguments,
670 the file name and info about the user who did the locking.
671 This function can signal an error, or return t meaning
672 take away the lock, or return nil meaning ignore the lock. */
674 void
675 lock_file (Lisp_Object fn)
677 Lisp_Object orig_fn, encoded_fn;
678 char *lfname;
679 lock_info_type lock_info;
680 struct gcpro gcpro1;
681 USE_SAFE_ALLOCA;
683 /* Don't do locking if the user has opted out. */
684 if (! create_lockfiles)
685 return;
687 /* Don't do locking while dumping Emacs.
688 Uncompressing wtmp files uses call-process, which does not work
689 in an uninitialized Emacs. */
690 if (! NILP (Vpurify_flag))
691 return;
693 orig_fn = fn;
694 GCPRO1 (fn);
695 fn = Fexpand_file_name (fn, Qnil);
696 #ifdef WINDOWSNT
697 /* Ensure we have only '/' separators, to avoid problems with
698 looking (inside fill_in_lock_file_name) for backslashes in file
699 names encoded by some DBCS codepage. */
700 dostounix_filename (SSDATA (fn), 1);
701 #endif
702 encoded_fn = ENCODE_FILE (fn);
704 /* Create the name of the lock-file for file fn */
705 MAKE_LOCK_NAME (lfname, encoded_fn);
707 /* See if this file is visited and has changed on disk since it was
708 visited. */
710 register Lisp_Object subject_buf;
712 subject_buf = get_truename_buffer (orig_fn);
714 if (!NILP (subject_buf)
715 && NILP (Fverify_visited_file_modtime (subject_buf))
716 && !NILP (Ffile_exists_p (fn)))
717 call1 (intern ("ask-user-about-supersession-threat"), fn);
721 /* Try to lock the lock. */
722 if (0 < lock_if_free (&lock_info, lfname))
724 /* Someone else has the lock. Consider breaking it. */
725 Lisp_Object attack;
726 char *dot = lock_info.dot;
727 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
728 static char const replacement[] = " (pid ";
729 int replacementlen = sizeof replacement - 1;
730 memmove (dot + replacementlen, dot + 1, pidlen);
731 strcpy (dot + replacementlen + pidlen, ")");
732 memcpy (dot, replacement, replacementlen);
733 attack = call2 (intern ("ask-user-about-lock"), fn,
734 build_string (lock_info.user));
735 /* Take the lock if the user said so. */
736 if (!NILP (attack))
737 lock_file_1 (lfname, 1);
740 UNGCPRO;
741 SAFE_FREE ();
744 void
745 unlock_file (Lisp_Object fn)
747 char *lfname;
748 USE_SAFE_ALLOCA;
750 fn = Fexpand_file_name (fn, Qnil);
751 fn = ENCODE_FILE (fn);
753 MAKE_LOCK_NAME (lfname, fn);
755 if (current_lock_owner (0, lfname) == 2)
756 unlink (lfname);
758 SAFE_FREE ();
761 void
762 unlock_all_files (void)
764 register Lisp_Object tail;
765 register struct buffer *b;
767 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
769 b = XBUFFER (XCDR (XCAR (tail)));
770 if (STRINGP (BVAR (b, file_truename)) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
772 unlock_file (BVAR (b, file_truename));
777 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
778 0, 1, 0,
779 doc: /* Lock FILE, if current buffer is modified.
780 FILE defaults to current buffer's visited file,
781 or else nothing is done if current buffer isn't visiting a file. */)
782 (Lisp_Object file)
784 if (NILP (file))
785 file = BVAR (current_buffer, file_truename);
786 else
787 CHECK_STRING (file);
788 if (SAVE_MODIFF < MODIFF
789 && !NILP (file))
790 lock_file (file);
791 return Qnil;
794 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
795 0, 0, 0,
796 doc: /* Unlock the file visited in the current buffer.
797 If the buffer is not modified, this does nothing because the file
798 should not be locked in that case. */)
799 (void)
801 if (SAVE_MODIFF < MODIFF
802 && STRINGP (BVAR (current_buffer, file_truename)))
803 unlock_file (BVAR (current_buffer, file_truename));
804 return Qnil;
807 /* Unlock the file visited in buffer BUFFER. */
809 void
810 unlock_buffer (struct buffer *buffer)
812 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
813 && STRINGP (BVAR (buffer, file_truename)))
814 unlock_file (BVAR (buffer, file_truename));
817 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
818 doc: /* Return a value indicating whether FILENAME is locked.
819 The value is nil if the FILENAME is not locked,
820 t if it is locked by you, else a string saying which user has locked it. */)
821 (Lisp_Object filename)
823 Lisp_Object ret;
824 char *lfname;
825 int owner;
826 lock_info_type locker;
827 USE_SAFE_ALLOCA;
829 filename = Fexpand_file_name (filename, Qnil);
831 MAKE_LOCK_NAME (lfname, filename);
833 owner = current_lock_owner (&locker, lfname);
834 if (owner <= 0)
835 ret = Qnil;
836 else if (owner == 2)
837 ret = Qt;
838 else
839 ret = make_string (locker.user, locker.at - locker.user);
841 SAFE_FREE ();
842 return ret;
845 #endif /* CLASH_DETECTION */
847 void
848 syms_of_filelock (void)
850 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
851 doc: /* The directory for writing temporary files. */);
852 Vtemporary_file_directory = Qnil;
854 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
855 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
856 create_lockfiles = 1;
858 #ifdef CLASH_DETECTION
859 defsubr (&Sunlock_buffer);
860 defsubr (&Slock_buffer);
861 defsubr (&Sfile_locked_p);
862 #endif