* process.c (allocate_pty) [PTY_OPEN]: Set fd's FD_CLOEXEC flag.
[emacs.git] / src / filelock.c
blobdf72eff5950e6f11ec477c809199fb1a63b77f7a
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 <sys/socket.h> /* for fcntl */
51 #include "w32.h" /* for dostounix_filename */
52 #endif
54 #ifdef CLASH_DETECTION
56 #ifdef HAVE_UTMP_H
57 #include <utmp.h>
58 #endif
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
66 #ifndef WTMP_FILE
67 #define WTMP_FILE "/var/log/wtmp"
68 #endif
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.
75 When the host in the lock data is the current host, we can check if
76 the pid is valid with kill.
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.
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.
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.
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.
104 --karl@cs.umb.edu/karl@hq.ileaf.com.
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.
115 To summarize, race conditions can occur with either:
117 * Forced locks on MS-Windows systems.
119 * Non-forced locks on non-MS-Windows systems that support neither
120 hard nor symbolic links. */
123 /* Return the time of the last system boot. */
125 static time_t boot_time;
126 static bool boot_time_initialized;
128 #ifdef BOOT_TIME
129 static void get_boot_time_1 (const char *, bool);
130 #endif
132 static time_t
133 get_boot_time (void)
135 #if defined (BOOT_TIME)
136 int counter;
137 #endif
139 if (boot_time_initialized)
140 return boot_time;
141 boot_time_initialized = 1;
143 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
145 int mib[2];
146 size_t size;
147 struct timeval boottime_val;
149 mib[0] = CTL_KERN;
150 mib[1] = KERN_BOOTTIME;
151 size = sizeof (boottime_val);
153 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
155 boot_time = boottime_val.tv_sec;
156 return boot_time;
159 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
161 if (BOOT_TIME_FILE)
163 struct stat st;
164 if (stat (BOOT_TIME_FILE, &st) == 0)
166 boot_time = st.st_mtime;
167 return boot_time;
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 */
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 (0, 0);
185 if (boot_time)
186 return boot_time;
188 /* Try to get boot time from the current wtmp file. */
189 get_boot_time_1 (WTMP_FILE, 1);
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++)
194 char cmd_string[sizeof WTMP_FILE ".19.gz"];
195 Lisp_Object tempname, filename;
196 bool delete_flag = 0;
198 filename = Qnil;
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
206 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
207 WTMP_FILE, counter);
208 if (! NILP (Ffile_exists_p (tempname)))
210 Lisp_Object args[6];
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;
231 if (! NILP (filename))
233 get_boot_time_1 (SSDATA (filename), 1);
234 if (delete_flag)
235 unlink (SSDATA (filename));
239 return boot_time;
240 #else
241 return 0;
242 #endif
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.
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. */
256 void
257 get_boot_time_1 (const char *filename, bool newest)
259 struct utmp ut, *utp;
261 if (filename)
263 /* On some versions of IRIX, opening a nonexistent file name
264 is likely to crash in the utmp routines. */
265 if (faccessat (AT_FDCWD, filename, R_OK, AT_EACCESS) != 0)
266 return;
268 utmpname (filename);
271 setutent ();
273 while (1)
275 /* Find the next reboot record. */
276 ut.ut_type = BOOT_TIME;
277 utp = getutid (&ut);
278 if (! utp)
279 break;
280 /* Compare reboot times and use the newest one. */
281 if (utp->ut_time > boot_time)
283 boot_time = utp->ut_time;
284 if (! newest)
285 break;
287 /* Advance on element in the file
288 so that getutid won't repeat the same one. */
289 utp = getutent ();
290 if (! utp)
291 break;
293 endutent ();
295 #endif /* BOOT_TIME */
297 /* An arbitrary limit on lock contents length. 8 K should be plenty
298 big enough in practice. */
299 enum { MAX_LFINFO = 8 * 1024 };
301 /* Here is the structure that stores information about a lock. */
303 typedef struct
305 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
306 points to the end of USER. */
307 char *at, *dot, *colon;
309 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
310 appended. This memory is used as a lock file contents buffer, so
311 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
312 may be appended to the USER@HOST while generating a diagnostic,
313 so make room for its extra bytes (as opposed to ".NNNN") too. */
314 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
315 } lock_info_type;
317 /* Write the name of the lock file for FNAME into LOCKNAME. Length
318 will be that of FNAME plus two more for the leading ".#", plus one
319 for the null. */
320 #define MAKE_LOCK_NAME(lockname, fname) \
321 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
322 fill_in_lock_file_name (lockname, fname))
324 static void
325 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
327 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
328 char *base = last_slash + 1;
329 ptrdiff_t dirlen = base - SSDATA (fn);
330 memcpy (lockfile, SSDATA (fn), dirlen);
331 lockfile[dirlen] = '.';
332 lockfile[dirlen + 1] = '#';
333 strcpy (lockfile + dirlen + 2, base);
336 /* For some reason Linux kernels return EPERM on file systems that do
337 not support hard or symbolic links. This symbol documents the quirk.
338 There is no way to tell whether a symlink call fails due to
339 permissions issues or because links are not supported, but luckily
340 the lock file code should work either way. */
341 enum { LINKS_MIGHT_NOT_WORK = EPERM };
343 /* Rename OLD to NEW. If FORCE, replace any existing NEW.
344 It is OK if there are temporarily two hard links to OLD.
345 Return 0 if successful, -1 (setting errno) otherwise. */
346 static int
347 rename_lock_file (char const *old, char const *new, bool force)
349 #ifdef WINDOWSNT
350 return sys_rename_replace (old, new, force);
351 #else
352 if (! force)
354 struct stat st;
356 if (link (old, new) == 0)
357 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
358 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
359 return -1;
361 /* 'link' does not work on this file system. This can occur on
362 a GNU/Linux host mounting a FAT32 file system. Fall back on
363 'rename' after checking that NEW does not exist. There is a
364 potential race condition since some other process may create
365 NEW immediately after the existence check, but it's the best
366 we can portably do here. */
367 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
369 errno = EEXIST;
370 return -1;
372 if (errno != ENOENT)
373 return -1;
376 return rename (old, new);
377 #endif
380 /* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
381 successful, an errno value on failure. If FORCE, remove any
382 existing LFNAME if necessary. */
384 static int
385 create_lock_file (char *lfname, char *lock_info_str, bool force)
387 #ifdef WINDOWSNT
388 /* Symlinks are supported only by later versions of Windows, and
389 creating them is a privileged operation that often triggers
390 User Account Control elevation prompts. Avoid the problem by
391 pretending that 'symlink' does not work. */
392 int err = ENOSYS;
393 #else
394 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
395 #endif
397 if (err == EEXIST && force)
399 unlink (lfname);
400 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
403 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
405 static char const nonce_base[] = ".#-emacsXXXXXX";
406 char *last_slash = strrchr (lfname, '/');
407 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
408 USE_SAFE_ALLOCA;
409 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
410 int fd;
411 memcpy (nonce, lfname, lfdirlen);
412 strcpy (nonce + lfdirlen, nonce_base);
414 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
415 if (fd < 0)
416 err = errno;
417 else
419 ptrdiff_t lock_info_len;
420 if (! O_CLOEXEC)
421 fcntl (fd, F_SETFD, FD_CLOEXEC);
422 lock_info_len = strlen (lock_info_str);
423 err = 0;
424 /* Use 'write', not 'emacs_write', as garbage collection
425 might signal an error, which would leak FD. */
426 if (write (fd, lock_info_str, lock_info_len) != lock_info_len
427 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
428 err = errno;
429 /* There is no need to call fsync here, as the contents of
430 the lock file need not survive system crashes. */
431 if (emacs_close (fd) != 0)
432 err = errno;
433 if (!err && rename_lock_file (nonce, lfname, force) != 0)
434 err = errno;
435 if (err)
436 unlink (nonce);
439 SAFE_FREE ();
442 return err;
445 /* Lock the lock file named LFNAME.
446 If FORCE, do so even if it is already locked.
447 Return 0 if successful, an error number on failure. */
449 static int
450 lock_file_1 (char *lfname, bool force)
452 /* Call this first because it can GC. */
453 printmax_t boot = get_boot_time ();
455 Lisp_Object luser_name = Fuser_login_name (Qnil);
456 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
457 Lisp_Object lhost_name = Fsystem_name ();
458 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
459 char lock_info_str[MAX_LFINFO + 1];
460 printmax_t pid = getpid ();
462 if (sizeof lock_info_str
463 <= snprintf (lock_info_str, sizeof lock_info_str,
464 boot ? "%s@%s.%"pMd":%"pMd : "%s@%s.%"pMd,
465 user_name, host_name, pid, boot))
466 return ENAMETOOLONG;
468 return create_lock_file (lfname, lock_info_str, force);
471 /* Return true if times A and B are no more than one second apart. */
473 static bool
474 within_one_second (time_t a, time_t b)
476 return (a - b >= -1 && a - b <= 1);
479 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
480 #ifndef ELOOP
481 # define ELOOP (-1)
482 #endif
484 /* Read the data for the lock file LFNAME into LFINFO. Read at most
485 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
486 (setting errno) on error. */
488 static ptrdiff_t
489 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
491 ptrdiff_t nbytes;
493 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
494 && errno == EINVAL)
496 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
497 if (0 <= fd)
499 /* Use read, not emacs_read, since FD isn't unwind-protected. */
500 ptrdiff_t read_bytes = read (fd, lfinfo, MAX_LFINFO + 1);
501 int read_errno = errno;
502 if (emacs_close (fd) != 0)
503 return -1;
504 errno = read_errno;
505 return read_bytes;
508 if (errno != ELOOP)
509 return -1;
511 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
512 The former must have been removed and replaced by the latter.
513 Try again. */
514 QUIT;
517 return nbytes;
520 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
521 1 if another process owns it (and set OWNER (if non-null) to info),
522 2 if the current process owns it,
523 or -1 if something is wrong with the locking mechanism. */
525 static int
526 current_lock_owner (lock_info_type *owner, char *lfname)
528 int ret;
529 lock_info_type local_owner;
530 ptrdiff_t lfinfolen;
531 intmax_t pid, boot_time;
532 char *at, *dot, *lfinfo_end;
534 /* Even if the caller doesn't want the owner info, we still have to
535 read it to determine return value. */
536 if (!owner)
537 owner = &local_owner;
539 /* If nonexistent lock file, all is well; otherwise, got strange error. */
540 lfinfolen = read_lock_data (lfname, owner->user);
541 if (lfinfolen < 0)
542 return errno == ENOENT ? 0 : -1;
543 if (MAX_LFINFO < lfinfolen)
544 return -1;
545 owner->user[lfinfolen] = 0;
547 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
548 /* The USER is everything before the last @. */
549 owner->at = at = memrchr (owner->user, '@', lfinfolen);
550 if (!at)
551 return -1;
552 owner->dot = dot = strrchr (at, '.');
553 if (!dot)
554 return -1;
556 /* The PID is everything from the last `.' to the `:'. */
557 if (! c_isdigit (dot[1]))
558 return -1;
559 errno = 0;
560 pid = strtoimax (dot + 1, &owner->colon, 10);
561 if (errno == ERANGE)
562 pid = -1;
564 /* After the `:', if there is one, comes the boot time. */
565 switch (owner->colon[0])
567 case 0:
568 boot_time = 0;
569 lfinfo_end = owner->colon;
570 break;
572 case ':':
573 if (! c_isdigit (owner->colon[1]))
574 return -1;
575 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
576 break;
578 default:
579 return -1;
581 if (lfinfo_end != owner->user + lfinfolen)
582 return -1;
584 /* On current host? */
585 if (STRINGP (Vsystem_name)
586 && dot - (at + 1) == SBYTES (Vsystem_name)
587 && memcmp (at + 1, SSDATA (Vsystem_name), SBYTES (Vsystem_name)) == 0)
589 if (pid == getpid ())
590 ret = 2; /* We own it. */
591 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
592 && (kill (pid, 0) >= 0 || errno == EPERM)
593 && (boot_time == 0
594 || (boot_time <= TYPE_MAXIMUM (time_t)
595 && within_one_second (boot_time, get_boot_time ()))))
596 ret = 1; /* An existing process on this machine owns it. */
597 /* The owner process is dead or has a strange pid, so try to
598 zap the lockfile. */
599 else
600 return unlink (lfname);
602 else
603 { /* If we wanted to support the check for stale locks on remote machines,
604 here's where we'd do it. */
605 ret = 1;
608 return ret;
612 /* Lock the lock named LFNAME if possible.
613 Return 0 in that case.
614 Return positive if some other process owns the lock, and info about
615 that process in CLASHER.
616 Return -1 if cannot lock for any other reason. */
618 static int
619 lock_if_free (lock_info_type *clasher, char *lfname)
621 int err;
622 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
624 switch (current_lock_owner (clasher, lfname))
626 case 2:
627 return 0; /* We ourselves locked it. */
628 case 1:
629 return 1; /* Someone else has it. */
630 case -1:
631 return -1; /* current_lock_owner returned strange error. */
634 /* We deleted a stale lock; try again to lock the file. */
637 return err ? -1 : 0;
640 /* lock_file locks file FN,
641 meaning it serves notice on the world that you intend to edit that file.
642 This should be done only when about to modify a file-visiting
643 buffer previously unmodified.
644 Do not (normally) call this for a buffer already modified,
645 as either the file is already locked, or the user has already
646 decided to go ahead without locking.
648 When this returns, either the lock is locked for us,
649 or lock creation failed,
650 or the user has said to go ahead without locking.
652 If the file is locked by someone else, this calls
653 ask-user-about-lock (a Lisp function) with two arguments,
654 the file name and info about the user who did the locking.
655 This function can signal an error, or return t meaning
656 take away the lock, or return nil meaning ignore the lock. */
658 void
659 lock_file (Lisp_Object fn)
661 Lisp_Object orig_fn, encoded_fn;
662 char *lfname;
663 lock_info_type lock_info;
664 struct gcpro gcpro1;
665 USE_SAFE_ALLOCA;
667 /* Don't do locking if the user has opted out. */
668 if (! create_lockfiles)
669 return;
671 /* Don't do locking while dumping Emacs.
672 Uncompressing wtmp files uses call-process, which does not work
673 in an uninitialized Emacs. */
674 if (! NILP (Vpurify_flag))
675 return;
677 orig_fn = fn;
678 GCPRO1 (fn);
679 fn = Fexpand_file_name (fn, Qnil);
680 #ifdef WINDOWSNT
681 /* Ensure we have only '/' separators, to avoid problems with
682 looking (inside fill_in_lock_file_name) for backslashes in file
683 names encoded by some DBCS codepage. */
684 dostounix_filename (SSDATA (fn), 1);
685 #endif
686 encoded_fn = ENCODE_FILE (fn);
688 /* Create the name of the lock-file for file fn */
689 MAKE_LOCK_NAME (lfname, encoded_fn);
691 /* See if this file is visited and has changed on disk since it was
692 visited. */
694 register Lisp_Object subject_buf;
696 subject_buf = get_truename_buffer (orig_fn);
698 if (!NILP (subject_buf)
699 && NILP (Fverify_visited_file_modtime (subject_buf))
700 && !NILP (Ffile_exists_p (fn)))
701 call1 (intern ("ask-user-about-supersession-threat"), fn);
705 /* Try to lock the lock. */
706 if (0 < lock_if_free (&lock_info, lfname))
708 /* Someone else has the lock. Consider breaking it. */
709 Lisp_Object attack;
710 char *dot = lock_info.dot;
711 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
712 static char const replacement[] = " (pid ";
713 int replacementlen = sizeof replacement - 1;
714 memmove (dot + replacementlen, dot + 1, pidlen);
715 strcpy (dot + replacementlen + pidlen, ")");
716 memcpy (dot, replacement, replacementlen);
717 attack = call2 (intern ("ask-user-about-lock"), fn,
718 build_string (lock_info.user));
719 /* Take the lock if the user said so. */
720 if (!NILP (attack))
721 lock_file_1 (lfname, 1);
724 UNGCPRO;
725 SAFE_FREE ();
728 void
729 unlock_file (Lisp_Object fn)
731 char *lfname;
732 USE_SAFE_ALLOCA;
734 fn = Fexpand_file_name (fn, Qnil);
735 fn = ENCODE_FILE (fn);
737 MAKE_LOCK_NAME (lfname, fn);
739 if (current_lock_owner (0, lfname) == 2)
740 unlink (lfname);
742 SAFE_FREE ();
745 void
746 unlock_all_files (void)
748 register Lisp_Object tail, buf;
749 register struct buffer *b;
751 FOR_EACH_LIVE_BUFFER (tail, buf)
753 b = XBUFFER (buf);
754 if (STRINGP (BVAR (b, file_truename))
755 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
756 unlock_file (BVAR (b, file_truename));
760 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
761 0, 1, 0,
762 doc: /* Lock FILE, if current buffer is modified.
763 FILE defaults to current buffer's visited file,
764 or else nothing is done if current buffer isn't visiting a file. */)
765 (Lisp_Object file)
767 if (NILP (file))
768 file = BVAR (current_buffer, file_truename);
769 else
770 CHECK_STRING (file);
771 if (SAVE_MODIFF < MODIFF
772 && !NILP (file))
773 lock_file (file);
774 return Qnil;
777 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
778 0, 0, 0,
779 doc: /* Unlock the file visited in the current buffer.
780 If the buffer is not modified, this does nothing because the file
781 should not be locked in that case. */)
782 (void)
784 if (SAVE_MODIFF < MODIFF
785 && STRINGP (BVAR (current_buffer, file_truename)))
786 unlock_file (BVAR (current_buffer, file_truename));
787 return Qnil;
790 /* Unlock the file visited in buffer BUFFER. */
792 void
793 unlock_buffer (struct buffer *buffer)
795 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
796 && STRINGP (BVAR (buffer, file_truename)))
797 unlock_file (BVAR (buffer, file_truename));
800 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
801 doc: /* Return a value indicating whether FILENAME is locked.
802 The value is nil if the FILENAME is not locked,
803 t if it is locked by you, else a string saying which user has locked it. */)
804 (Lisp_Object filename)
806 Lisp_Object ret;
807 char *lfname;
808 int owner;
809 lock_info_type locker;
810 USE_SAFE_ALLOCA;
812 filename = Fexpand_file_name (filename, Qnil);
814 MAKE_LOCK_NAME (lfname, filename);
816 owner = current_lock_owner (&locker, lfname);
817 if (owner <= 0)
818 ret = Qnil;
819 else if (owner == 2)
820 ret = Qt;
821 else
822 ret = make_string (locker.user, locker.at - locker.user);
824 SAFE_FREE ();
825 return ret;
828 #endif /* CLASH_DETECTION */
830 void
831 syms_of_filelock (void)
833 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
834 doc: /* The directory for writing temporary files. */);
835 Vtemporary_file_directory = Qnil;
837 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
838 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
839 create_lockfiles = 1;
841 #ifdef CLASH_DETECTION
842 defsubr (&Sunlock_buffer);
843 defsubr (&Slock_buffer);
844 defsubr (&Sfile_locked_p);
845 #endif