Document reserved keys
[emacs.git] / src / filelock.c
blobf2dc723407698031366ea63f60ac2dd7cf38dacc
1 /* Lock files for editing.
3 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2018 Free Software
4 Foundation, Inc.
6 Author: Richard King
7 (according to authors.el)
9 This file is part of GNU Emacs.
11 GNU Emacs is free software: you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or (at
14 your option) any later version.
16 GNU Emacs is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
25 #include <config.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
32 #ifdef HAVE_PWD_H
33 #include <pwd.h>
34 #endif
36 #include <sys/file.h>
37 #include <fcntl.h>
38 #include <unistd.h>
40 #ifdef __FreeBSD__
41 #include <sys/sysctl.h>
42 #endif /* __FreeBSD__ */
44 #include <errno.h>
46 #include <c-ctype.h>
48 #include "lisp.h"
49 #include "buffer.h"
50 #include "coding.h"
51 #ifdef WINDOWSNT
52 #include <share.h>
53 #include <sys/socket.h> /* for fcntl */
54 #include "w32.h" /* for dostounix_filename */
55 #endif
57 #ifndef MSDOS
59 #ifdef HAVE_UTMP_H
60 #include <utmp.h>
61 #endif
63 /* A file whose last-modified time is just after the most recent boot.
64 Define this to be NULL to disable checking for this file. */
65 #ifndef BOOT_TIME_FILE
66 #define BOOT_TIME_FILE "/var/run/random-seed"
67 #endif
69 #if !defined WTMP_FILE && !defined WINDOWSNT
70 #define WTMP_FILE "/var/log/wtmp"
71 #endif
73 /* Normally use a symbolic link to represent a lock.
74 The strategy: to lock a file FN, create a symlink .#FN in FN's
75 directory, with link data USER@HOST.PID:BOOT. This avoids a single
76 mount (== failure) point for lock files. The :BOOT is omitted if
77 the boot time is not available.
79 When the host in the lock data is the current host, we can check if
80 the pid is valid with kill.
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
89 environment, it seems such stale locks arise fairly infrequently, and
90 Emacs' standard methods of dealing with clashes suffice.
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
96 files to be useful on old systems lacking symlinks, nowadays
97 virtually all such systems are probably single-user anyway, so it
98 didn't seem worth the complication.
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.
104 This is compatible with the locking scheme used by Interleaf (which
105 has contributed this implementation for Emacs), and was designed by
106 Karl Berry, Ethan Jacobson, Kimbo Mundy, and others.
108 On some file systems, notably those of MS-Windows, symbolic links
109 do not work well, so instead of a symlink .#FN -> USER@HOST.PID:BOOT,
110 the lock is a regular file .#FN with contents USER@HOST.PID:BOOT. To
111 establish a lock, a nonce file is created and then renamed to .#FN.
112 On MS-Windows this renaming is atomic unless the lock is forcibly
113 acquired. On other systems the renaming is atomic if the lock is
114 forcibly acquired; if not, the renaming is done via hard links,
115 which is good enough for lock-file purposes.
117 To summarize, race conditions can occur with either:
119 * Forced locks on MS-Windows systems.
121 * Non-forced locks on non-MS-Windows systems that support neither
122 hard nor symbolic links. */
125 /* Return the time of the last system boot. */
127 static time_t boot_time;
128 static bool boot_time_initialized;
130 #ifdef BOOT_TIME
131 static void get_boot_time_1 (const char *, bool);
132 #endif
134 static time_t
135 get_boot_time (void)
137 #if defined (BOOT_TIME)
138 int counter;
139 #endif
141 if (boot_time_initialized)
142 return boot_time;
143 boot_time_initialized = 1;
145 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
147 int mib[2];
148 size_t size;
149 struct timeval boottime_val;
151 mib[0] = CTL_KERN;
152 mib[1] = KERN_BOOTTIME;
153 size = sizeof (boottime_val);
155 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
157 boot_time = boottime_val.tv_sec;
158 return boot_time;
161 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
163 if (BOOT_TIME_FILE)
165 struct stat st;
166 if (stat (BOOT_TIME_FILE, &st) == 0)
168 boot_time = st.st_mtime;
169 return boot_time;
173 #if defined (BOOT_TIME)
174 #ifndef CANNOT_DUMP
175 /* The utmp routines maintain static state.
176 Don't touch that state unless we are initialized,
177 since it might not survive dumping. */
178 if (! initialized)
179 return boot_time;
180 #endif /* not CANNOT_DUMP */
182 /* Try to get boot time from utmp before wtmp,
183 since utmp is typically much smaller than wtmp.
184 Passing a null pointer causes get_boot_time_1
185 to inspect the default file, namely utmp. */
186 get_boot_time_1 (0, 0);
187 if (boot_time)
188 return boot_time;
190 /* Try to get boot time from the current wtmp file. */
191 get_boot_time_1 (WTMP_FILE, 1);
193 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
194 for (counter = 0; counter < 20 && ! boot_time; counter++)
196 Lisp_Object filename = Qnil;
197 bool delete_flag = false;
198 char cmd_string[sizeof WTMP_FILE ".19.gz"];
199 AUTO_STRING_WITH_LEN (tempname, cmd_string,
200 sprintf (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 /* The utmp functions on older systems accept only file
210 names up to 8 bytes long. Choose a 2 byte prefix, so
211 the 6-byte suffix does not make the name too long. */
212 filename = Fmake_temp_file_internal (build_string ("wt"), Qnil,
213 empty_unibyte_string, Qnil);
214 CALLN (Fcall_process, build_string ("gzip"), Qnil,
215 list2 (QCfile, filename), Qnil,
216 build_string ("-cd"), tempname);
217 delete_flag = true;
221 if (! NILP (filename))
223 get_boot_time_1 (SSDATA (filename), 1);
224 if (delete_flag)
225 unlink (SSDATA (filename));
229 return boot_time;
230 #else
231 return 0;
232 #endif
235 #ifdef BOOT_TIME
236 /* Try to get the boot time from wtmp file FILENAME.
237 This succeeds if that file contains a reboot record.
239 If FILENAME is zero, use the same file as before;
240 if no FILENAME has ever been specified, this is the utmp file.
241 Use the newest reboot record if NEWEST,
242 the first reboot record otherwise.
243 Ignore all reboot records on or before BOOT_TIME.
244 Success is indicated by setting BOOT_TIME to a larger value. */
246 void
247 get_boot_time_1 (const char *filename, bool newest)
249 struct utmp ut, *utp;
251 if (filename)
252 utmpname (filename);
254 setutent ();
256 while (1)
258 /* Find the next reboot record. */
259 ut.ut_type = BOOT_TIME;
260 utp = getutid (&ut);
261 if (! utp)
262 break;
263 /* Compare reboot times and use the newest one. */
264 if (utp->ut_time > boot_time)
266 boot_time = utp->ut_time;
267 if (! newest)
268 break;
270 /* Advance on element in the file
271 so that getutid won't repeat the same one. */
272 utp = getutent ();
273 if (! utp)
274 break;
276 endutent ();
278 #endif /* BOOT_TIME */
280 /* An arbitrary limit on lock contents length. 8 K should be plenty
281 big enough in practice. */
282 enum { MAX_LFINFO = 8 * 1024 };
284 /* Here is the structure that stores information about a lock. */
286 typedef struct
288 /* Location of '@', '.', and ':' (or equivalent) in USER. If there's
289 no colon or equivalent, COLON points to the end of USER. */
290 char *at, *dot, *colon;
292 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
293 appended. This memory is used as a lock file contents buffer, so
294 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
295 may be appended to the USER@HOST while generating a diagnostic,
296 so make room for its extra bytes (as opposed to ".NNNN") too. */
297 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
298 } lock_info_type;
300 /* Write the name of the lock file for FNAME into LOCKNAME. Length
301 will be that of FNAME plus two more for the leading ".#", plus one
302 for the null. */
303 #define MAKE_LOCK_NAME(lockname, fname) \
304 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
305 fill_in_lock_file_name (lockname, fname))
307 static void
308 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
310 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
311 char *base = last_slash + 1;
312 ptrdiff_t dirlen = base - SSDATA (fn);
313 memcpy (lockfile, SSDATA (fn), dirlen);
314 lockfile[dirlen] = '.';
315 lockfile[dirlen + 1] = '#';
316 strcpy (lockfile + dirlen + 2, base);
319 /* For some reason Linux kernels return EPERM on file systems that do
320 not support hard or symbolic links. This symbol documents the quirk.
321 There is no way to tell whether a symlink call fails due to
322 permissions issues or because links are not supported, but luckily
323 the lock file code should work either way. */
324 enum { LINKS_MIGHT_NOT_WORK = EPERM };
326 /* Rename OLD to NEW. If FORCE, replace any existing NEW.
327 It is OK if there are temporarily two hard links to OLD.
328 Return 0 if successful, -1 (setting errno) otherwise. */
329 static int
330 rename_lock_file (char const *old, char const *new, bool force)
332 #ifdef WINDOWSNT
333 return sys_rename_replace (old, new, force);
334 #else
335 if (! force)
337 struct stat st;
339 int r = renameat_noreplace (AT_FDCWD, old, AT_FDCWD, new);
340 if (! (r < 0 && errno == ENOSYS))
341 return r;
342 if (link (old, new) == 0)
343 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
344 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
345 return -1;
347 /* 'link' does not work on this file system. This can occur on
348 a GNU/Linux host mounting a FAT32 file system. Fall back on
349 'rename' after checking that NEW does not exist. There is a
350 potential race condition since some other process may create
351 NEW immediately after the existence check, but it's the best
352 we can portably do here. */
353 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
355 errno = EEXIST;
356 return -1;
358 if (errno != ENOENT)
359 return -1;
362 return rename (old, new);
363 #endif
366 /* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
367 successful, an errno value on failure. If FORCE, remove any
368 existing LFNAME if necessary. */
370 static int
371 create_lock_file (char *lfname, char *lock_info_str, bool force)
373 #ifdef WINDOWSNT
374 /* Symlinks are supported only by later versions of Windows, and
375 creating them is a privileged operation that often triggers
376 User Account Control elevation prompts. Avoid the problem by
377 pretending that 'symlink' does not work. */
378 int err = ENOSYS;
379 #else
380 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
381 #endif
383 if (err == EEXIST && force)
385 unlink (lfname);
386 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
389 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
391 static char const nonce_base[] = ".#-emacsXXXXXX";
392 char *last_slash = strrchr (lfname, '/');
393 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
394 USE_SAFE_ALLOCA;
395 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
396 int fd;
397 memcpy (nonce, lfname, lfdirlen);
398 strcpy (nonce + lfdirlen, nonce_base);
400 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
401 if (fd < 0)
402 err = errno;
403 else
405 ptrdiff_t lock_info_len;
406 lock_info_len = strlen (lock_info_str);
407 err = 0;
408 if (emacs_write (fd, lock_info_str, lock_info_len) != lock_info_len
409 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
410 err = errno;
411 /* There is no need to call fsync here, as the contents of
412 the lock file need not survive system crashes. */
413 if (emacs_close (fd) != 0)
414 err = errno;
415 if (!err && rename_lock_file (nonce, lfname, force) != 0)
416 err = errno;
417 if (err)
418 unlink (nonce);
421 SAFE_FREE ();
424 return err;
427 /* Lock the lock file named LFNAME.
428 If FORCE, do so even if it is already locked.
429 Return 0 if successful, an error number on failure. */
431 static int
432 lock_file_1 (char *lfname, bool force)
434 /* Call this first because it can GC. */
435 printmax_t boot = get_boot_time ();
437 Lisp_Object luser_name = Fuser_login_name (Qnil);
438 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
439 Lisp_Object lhost_name = Fsystem_name ();
440 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
441 char lock_info_str[MAX_LFINFO + 1];
442 printmax_t pid = getpid ();
444 if (boot)
446 if (sizeof lock_info_str
447 <= snprintf (lock_info_str, sizeof lock_info_str,
448 "%s@%s.%"pMd":%"pMd,
449 user_name, host_name, pid, boot))
450 return ENAMETOOLONG;
452 else if (sizeof lock_info_str
453 <= snprintf (lock_info_str, sizeof lock_info_str,
454 "%s@%s.%"pMd,
455 user_name, host_name, pid))
456 return ENAMETOOLONG;
458 return create_lock_file (lfname, lock_info_str, force);
461 /* Return true if times A and B are no more than one second apart. */
463 static bool
464 within_one_second (time_t a, time_t b)
466 return (a - b >= -1 && a - b <= 1);
469 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
470 #ifndef ELOOP
471 # define ELOOP (-1)
472 #endif
474 /* Read the data for the lock file LFNAME into LFINFO. Read at most
475 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
476 (setting errno) on error. */
478 static ptrdiff_t
479 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
481 ptrdiff_t nbytes;
483 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
484 && errno == EINVAL)
486 int fd = emacs_open (lfname, O_RDONLY | O_NOFOLLOW, 0);
487 if (0 <= fd)
489 ptrdiff_t read_bytes = emacs_read (fd, lfinfo, MAX_LFINFO + 1);
490 int read_errno = errno;
491 if (emacs_close (fd) != 0)
492 return -1;
493 errno = read_errno;
494 return read_bytes;
497 if (errno != ELOOP)
498 return -1;
500 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
501 The former must have been removed and replaced by the latter.
502 Try again. */
503 maybe_quit ();
506 return nbytes;
509 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
510 1 if another process owns it (and set OWNER (if non-null) to info),
511 2 if the current process owns it,
512 or -1 if something is wrong with the locking mechanism. */
514 static int
515 current_lock_owner (lock_info_type *owner, char *lfname)
517 int ret;
518 lock_info_type local_owner;
519 ptrdiff_t lfinfolen;
520 intmax_t pid, boot_time;
521 char *at, *dot, *lfinfo_end;
523 /* Even if the caller doesn't want the owner info, we still have to
524 read it to determine return value. */
525 if (!owner)
526 owner = &local_owner;
528 /* If nonexistent lock file, all is well; otherwise, got strange error. */
529 lfinfolen = read_lock_data (lfname, owner->user);
530 if (lfinfolen < 0)
531 return errno == ENOENT ? 0 : -1;
532 if (MAX_LFINFO < lfinfolen)
533 return -1;
534 owner->user[lfinfolen] = 0;
536 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
537 /* The USER is everything before the last @. */
538 owner->at = at = memrchr (owner->user, '@', lfinfolen);
539 if (!at)
540 return -1;
541 owner->dot = dot = strrchr (at, '.');
542 if (!dot)
543 return -1;
545 /* The PID is everything from the last '.' to the ':' or equivalent. */
546 if (! c_isdigit (dot[1]))
547 return -1;
548 errno = 0;
549 pid = strtoimax (dot + 1, &owner->colon, 10);
550 if (errno == ERANGE)
551 pid = -1;
553 /* After the ':' or equivalent, if there is one, comes the boot time. */
554 char *boot = owner->colon + 1;
555 switch (owner->colon[0])
557 case 0:
558 boot_time = 0;
559 lfinfo_end = owner->colon;
560 break;
562 case '\357':
563 /* Treat "\357\200\242" (U+F022 in UTF-8) as if it were ":" (Bug#24656).
564 This works around a bug in the Linux CIFS kernel client, which can
565 mistakenly transliterate ':' to U+F022 in symlink contents.
566 See <https://bugzilla.redhat.com/show_bug.cgi?id=1384153>. */
567 if (! (boot[0] == '\200' && boot[1] == '\242'))
568 return -1;
569 boot += 2;
570 FALLTHROUGH;
571 case ':':
572 if (! c_isdigit (boot[0]))
573 return -1;
574 boot_time = strtoimax (boot, &lfinfo_end, 10);
575 break;
577 default:
578 return -1;
580 if (lfinfo_end != owner->user + lfinfolen)
581 return -1;
583 /* On current host? */
584 Lisp_Object system_name = Fsystem_name ();
585 if (STRINGP (system_name)
586 && dot - (at + 1) == SBYTES (system_name)
587 && memcmp (at + 1, SSDATA (system_name), SBYTES (system_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 USE_SAFE_ALLOCA;
666 /* Don't do locking while dumping Emacs.
667 Uncompressing wtmp files uses call-process, which does not work
668 in an uninitialized Emacs. */
669 if (! NILP (Vpurify_flag))
670 return;
672 orig_fn = fn;
673 fn = Fexpand_file_name (fn, Qnil);
674 #ifdef WINDOWSNT
675 /* Ensure we have only '/' separators, to avoid problems with
676 looking (inside fill_in_lock_file_name) for backslashes in file
677 names encoded by some DBCS codepage. */
678 dostounix_filename (SSDATA (fn));
679 #endif
680 encoded_fn = ENCODE_FILE (fn);
682 /* See if this file is visited and has changed on disk since it was
683 visited. */
685 register Lisp_Object subject_buf;
687 subject_buf = get_truename_buffer (orig_fn);
689 if (!NILP (subject_buf)
690 && NILP (Fverify_visited_file_modtime (subject_buf))
691 && !NILP (Ffile_exists_p (fn)))
692 call1 (intern ("userlock--ask-user-about-supersession-threat"), fn);
696 /* Don't do locking if the user has opted out. */
697 if (create_lockfiles)
700 /* Create the name of the lock-file for file fn */
701 MAKE_LOCK_NAME (lfname, encoded_fn);
703 /* Try to lock the lock. */
704 if (0 < lock_if_free (&lock_info, lfname))
706 /* Someone else has the lock. Consider breaking it. */
707 Lisp_Object attack;
708 char *dot = lock_info.dot;
709 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
710 static char const replacement[] = " (pid ";
711 int replacementlen = sizeof replacement - 1;
712 memmove (dot + replacementlen, dot + 1, pidlen);
713 strcpy (dot + replacementlen + pidlen, ")");
714 memcpy (dot, replacement, replacementlen);
715 attack = call2 (intern ("ask-user-about-lock"), fn,
716 build_string (lock_info.user));
717 /* Take the lock if the user said so. */
718 if (!NILP (attack))
719 lock_file_1 (lfname, 1);
721 SAFE_FREE ();
725 void
726 unlock_file (Lisp_Object fn)
728 char *lfname;
729 USE_SAFE_ALLOCA;
731 fn = Fexpand_file_name (fn, Qnil);
732 fn = ENCODE_FILE (fn);
734 MAKE_LOCK_NAME (lfname, fn);
736 if (current_lock_owner (0, lfname) == 2)
737 unlink (lfname);
739 SAFE_FREE ();
742 #else /* MSDOS */
743 void
744 lock_file (Lisp_Object fn)
748 void
749 unlock_file (Lisp_Object fn)
753 #endif /* MSDOS */
755 void
756 unlock_all_files (void)
758 register Lisp_Object tail, buf;
759 register struct buffer *b;
761 FOR_EACH_LIVE_BUFFER (tail, buf)
763 b = XBUFFER (buf);
764 if (STRINGP (BVAR (b, file_truename))
765 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
766 unlock_file (BVAR (b, file_truename));
770 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
771 0, 1, 0,
772 doc: /* Lock FILE, if current buffer is modified.
773 FILE defaults to current buffer's visited file,
774 or else nothing is done if current buffer isn't visiting a file.
776 If the option `create-lockfiles' is nil, this does nothing. */)
777 (Lisp_Object file)
779 if (NILP (file))
780 file = BVAR (current_buffer, file_truename);
781 else
782 CHECK_STRING (file);
783 if (SAVE_MODIFF < MODIFF
784 && !NILP (file))
785 lock_file (file);
786 return Qnil;
789 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
790 0, 0, 0,
791 doc: /* Unlock the file visited in the current buffer.
792 If the buffer is not modified, this does nothing because the file
793 should not be locked in that case. */)
794 (void)
796 if (SAVE_MODIFF < MODIFF
797 && STRINGP (BVAR (current_buffer, file_truename)))
798 unlock_file (BVAR (current_buffer, file_truename));
799 return Qnil;
802 /* Unlock the file visited in buffer BUFFER. */
804 void
805 unlock_buffer (struct buffer *buffer)
807 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
808 && STRINGP (BVAR (buffer, file_truename)))
809 unlock_file (BVAR (buffer, file_truename));
812 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
813 doc: /* Return a value indicating whether FILENAME is locked.
814 The value is nil if the FILENAME is not locked,
815 t if it is locked by you, else a string saying which user has locked it. */)
816 (Lisp_Object filename)
818 #ifdef MSDOS
819 return Qnil;
820 #else
821 Lisp_Object ret;
822 char *lfname;
823 int owner;
824 lock_info_type locker;
825 USE_SAFE_ALLOCA;
827 filename = Fexpand_file_name (filename, Qnil);
829 MAKE_LOCK_NAME (lfname, filename);
831 owner = current_lock_owner (&locker, lfname);
832 if (owner <= 0)
833 ret = Qnil;
834 else if (owner == 2)
835 ret = Qt;
836 else
837 ret = make_string (locker.user, locker.at - locker.user);
839 SAFE_FREE ();
840 return ret;
841 #endif
844 void
845 syms_of_filelock (void)
847 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
848 doc: /* The directory for writing temporary files. */);
849 Vtemporary_file_directory = Qnil;
851 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
852 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
853 create_lockfiles = 1;
855 defsubr (&Sunlock_buffer);
856 defsubr (&Slock_buffer);
857 defsubr (&Sfile_locked_p);