; Fix a typo in comment
[emacs.git] / src / filelock.c
blobc067f4c46788fd79fcd334464adf9a485f57fc9d
1 /* Lock files for editing.
3 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2017 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 <http://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>
31 #ifdef HAVE_PWD_H
32 #include <pwd.h>
33 #endif
35 #include <sys/file.h>
36 #include <fcntl.h>
37 #include <unistd.h>
39 #ifdef __FreeBSD__
40 #include <sys/sysctl.h>
41 #endif /* __FreeBSD__ */
43 #include <errno.h>
45 #include <c-ctype.h>
47 #include "lisp.h"
48 #include "buffer.h"
49 #include "coding.h"
50 #ifdef WINDOWSNT
51 #include <share.h>
52 #include <sys/socket.h> /* for fcntl */
53 #include "w32.h" /* for dostounix_filename */
54 #endif
56 #ifndef MSDOS
58 #ifdef HAVE_UTMP_H
59 #include <utmp.h>
60 #endif
62 /* A file whose last-modified time is just after the most recent boot.
63 Define this to be NULL to disable checking for this file. */
64 #ifndef BOOT_TIME_FILE
65 #define BOOT_TIME_FILE "/var/run/random-seed"
66 #endif
68 #ifndef WTMP_FILE
69 #define WTMP_FILE "/var/log/wtmp"
70 #endif
72 /* Normally use a symbolic link to represent a lock.
73 The strategy: to lock a file FN, create a symlink .#FN in FN's
74 directory, with link data USER@HOST.PID:BOOT. This avoids a single
75 mount (== failure) point for lock files. The :BOOT is omitted if
76 the boot time is not available.
78 When the host in the lock data is the current host, we can check if
79 the pid is valid with kill.
81 Otherwise, we could look at a separate file that maps hostnames to
82 reboot times to see if the remote pid can possibly be valid, since we
83 don't want Emacs to have to communicate via pipes or sockets or
84 whatever to other processes, either locally or remotely; rms says
85 that's too unreliable. Hence the separate file, which could
86 theoretically be updated by daemons running separately -- but this
87 whole idea is unimplemented; in practice, at least in our
88 environment, it seems such stale locks arise fairly infrequently, and
89 Emacs' standard methods of dealing with clashes suffice.
91 We use symlinks instead of normal files because (1) they can be
92 stored more efficiently on the filesystem, since the kernel knows
93 they will be small, and (2) all the info about the lock can be read
94 in a single system call (readlink). Although we could use regular
95 files to be useful on old systems lacking symlinks, nowadays
96 virtually all such systems are probably single-user anyway, so it
97 didn't seem worth the complication.
99 Similarly, we don't worry about a possible 14-character limit on
100 file names, because those are all the same systems that don't have
101 symlinks.
103 This is compatible with the locking scheme used by Interleaf (which
104 has contributed this implementation for Emacs), and was designed by
105 Karl Berry, Ethan Jacobson, Kimbo Mundy, and others.
107 On some file systems, notably those of MS-Windows, symbolic links
108 do not work well, so instead of a symlink .#FN -> USER@HOST.PID:BOOT,
109 the lock is a regular file .#FN with contents USER@HOST.PID:BOOT. To
110 establish a lock, a nonce file is created and then renamed to .#FN.
111 On MS-Windows this renaming is atomic unless the lock is forcibly
112 acquired. On other systems the renaming is atomic if the lock is
113 forcibly acquired; if not, the renaming is done via hard links,
114 which is good enough for lock-file purposes.
116 To summarize, race conditions can occur with either:
118 * Forced locks on MS-Windows systems.
120 * Non-forced locks on non-MS-Windows systems that support neither
121 hard nor symbolic links. */
124 /* Return the time of the last system boot. */
126 static time_t boot_time;
127 static bool boot_time_initialized;
129 #ifdef BOOT_TIME
130 static void get_boot_time_1 (const char *, bool);
131 #endif
133 static time_t
134 get_boot_time (void)
136 #if defined (BOOT_TIME)
137 int counter;
138 #endif
140 if (boot_time_initialized)
141 return boot_time;
142 boot_time_initialized = 1;
144 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
146 int mib[2];
147 size_t size;
148 struct timeval boottime_val;
150 mib[0] = CTL_KERN;
151 mib[1] = KERN_BOOTTIME;
152 size = sizeof (boottime_val);
154 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
156 boot_time = boottime_val.tv_sec;
157 return boot_time;
160 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
162 if (BOOT_TIME_FILE)
164 struct stat st;
165 if (stat (BOOT_TIME_FILE, &st) == 0)
167 boot_time = st.st_mtime;
168 return boot_time;
172 #if defined (BOOT_TIME)
173 #ifndef CANNOT_DUMP
174 /* The utmp routines maintain static state.
175 Don't touch that state unless we are initialized,
176 since it might not survive dumping. */
177 if (! initialized)
178 return boot_time;
179 #endif /* not CANNOT_DUMP */
181 /* Try to get boot time from utmp before wtmp,
182 since utmp is typically much smaller than wtmp.
183 Passing a null pointer causes get_boot_time_1
184 to inspect the default file, namely utmp. */
185 get_boot_time_1 (0, 0);
186 if (boot_time)
187 return boot_time;
189 /* Try to get boot time from the current wtmp file. */
190 get_boot_time_1 (WTMP_FILE, 1);
192 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
193 for (counter = 0; counter < 20 && ! boot_time; counter++)
195 char cmd_string[sizeof WTMP_FILE ".19.gz"];
196 Lisp_Object tempname, filename;
197 bool delete_flag = 0;
199 filename = Qnil;
201 tempname = make_formatted_string
202 (cmd_string, "%s.%d", WTMP_FILE, counter);
203 if (! NILP (Ffile_exists_p (tempname)))
204 filename = tempname;
205 else
207 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
208 WTMP_FILE, counter);
209 if (! NILP (Ffile_exists_p (tempname)))
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 CALLN (Fcall_process, build_string ("gzip"), Qnil,
220 list2 (QCfile, filename), Qnil,
221 build_string ("-cd"), tempname);
222 delete_flag = 1;
226 if (! NILP (filename))
228 get_boot_time_1 (SSDATA (filename), 1);
229 if (delete_flag)
230 unlink (SSDATA (filename));
234 return boot_time;
235 #else
236 return 0;
237 #endif
240 #ifdef BOOT_TIME
241 /* Try to get the boot time from wtmp file FILENAME.
242 This succeeds if that file contains a reboot record.
244 If FILENAME is zero, use the same file as before;
245 if no FILENAME has ever been specified, this is the utmp file.
246 Use the newest reboot record if NEWEST,
247 the first reboot record otherwise.
248 Ignore all reboot records on or before BOOT_TIME.
249 Success is indicated by setting BOOT_TIME to a larger value. */
251 void
252 get_boot_time_1 (const char *filename, bool newest)
254 struct utmp ut, *utp;
256 if (filename)
258 /* On some versions of IRIX, opening a nonexistent file name
259 is likely to crash in the utmp routines. */
260 if (faccessat (AT_FDCWD, filename, R_OK, AT_EACCESS) != 0)
261 return;
263 utmpname (filename);
266 setutent ();
268 while (1)
270 /* Find the next reboot record. */
271 ut.ut_type = BOOT_TIME;
272 utp = getutid (&ut);
273 if (! utp)
274 break;
275 /* Compare reboot times and use the newest one. */
276 if (utp->ut_time > boot_time)
278 boot_time = utp->ut_time;
279 if (! newest)
280 break;
282 /* Advance on element in the file
283 so that getutid won't repeat the same one. */
284 utp = getutent ();
285 if (! utp)
286 break;
288 endutent ();
290 #endif /* BOOT_TIME */
292 /* An arbitrary limit on lock contents length. 8 K should be plenty
293 big enough in practice. */
294 enum { MAX_LFINFO = 8 * 1024 };
296 /* Here is the structure that stores information about a lock. */
298 typedef struct
300 /* Location of '@', '.', and ':' (or equivalent) in USER. If there's
301 no colon or equivalent, COLON points to the end of USER. */
302 char *at, *dot, *colon;
304 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
305 appended. This memory is used as a lock file contents buffer, so
306 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
307 may be appended to the USER@HOST while generating a diagnostic,
308 so make room for its extra bytes (as opposed to ".NNNN") too. */
309 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
310 } lock_info_type;
312 /* Write the name of the lock file for FNAME into LOCKNAME. Length
313 will be that of FNAME plus two more for the leading ".#", plus one
314 for the null. */
315 #define MAKE_LOCK_NAME(lockname, fname) \
316 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
317 fill_in_lock_file_name (lockname, fname))
319 static void
320 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
322 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
323 char *base = last_slash + 1;
324 ptrdiff_t dirlen = base - SSDATA (fn);
325 memcpy (lockfile, SSDATA (fn), dirlen);
326 lockfile[dirlen] = '.';
327 lockfile[dirlen + 1] = '#';
328 strcpy (lockfile + dirlen + 2, base);
331 /* For some reason Linux kernels return EPERM on file systems that do
332 not support hard or symbolic links. This symbol documents the quirk.
333 There is no way to tell whether a symlink call fails due to
334 permissions issues or because links are not supported, but luckily
335 the lock file code should work either way. */
336 enum { LINKS_MIGHT_NOT_WORK = EPERM };
338 /* Rename OLD to NEW. If FORCE, replace any existing NEW.
339 It is OK if there are temporarily two hard links to OLD.
340 Return 0 if successful, -1 (setting errno) otherwise. */
341 static int
342 rename_lock_file (char const *old, char const *new, bool force)
344 #ifdef WINDOWSNT
345 return sys_rename_replace (old, new, force);
346 #else
347 if (! force)
349 struct stat st;
351 if (link (old, new) == 0)
352 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
353 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
354 return -1;
356 /* 'link' does not work on this file system. This can occur on
357 a GNU/Linux host mounting a FAT32 file system. Fall back on
358 'rename' after checking that NEW does not exist. There is a
359 potential race condition since some other process may create
360 NEW immediately after the existence check, but it's the best
361 we can portably do here. */
362 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
364 errno = EEXIST;
365 return -1;
367 if (errno != ENOENT)
368 return -1;
371 return rename (old, new);
372 #endif
375 /* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
376 successful, an errno value on failure. If FORCE, remove any
377 existing LFNAME if necessary. */
379 static int
380 create_lock_file (char *lfname, char *lock_info_str, bool force)
382 #ifdef WINDOWSNT
383 /* Symlinks are supported only by later versions of Windows, and
384 creating them is a privileged operation that often triggers
385 User Account Control elevation prompts. Avoid the problem by
386 pretending that 'symlink' does not work. */
387 int err = ENOSYS;
388 #else
389 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
390 #endif
392 if (err == EEXIST && force)
394 unlink (lfname);
395 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
398 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
400 static char const nonce_base[] = ".#-emacsXXXXXX";
401 char *last_slash = strrchr (lfname, '/');
402 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
403 USE_SAFE_ALLOCA;
404 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
405 int fd;
406 memcpy (nonce, lfname, lfdirlen);
407 strcpy (nonce + lfdirlen, nonce_base);
409 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
410 if (fd < 0)
411 err = errno;
412 else
414 ptrdiff_t lock_info_len;
415 if (! O_CLOEXEC)
416 fcntl (fd, F_SETFD, FD_CLOEXEC);
417 lock_info_len = strlen (lock_info_str);
418 err = 0;
419 /* Use 'write', not 'emacs_write', as garbage collection
420 might signal an error, which would leak FD. */
421 if (write (fd, lock_info_str, lock_info_len) != lock_info_len
422 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
423 err = errno;
424 /* There is no need to call fsync here, as the contents of
425 the lock file need not survive system crashes. */
426 if (emacs_close (fd) != 0)
427 err = errno;
428 if (!err && rename_lock_file (nonce, lfname, force) != 0)
429 err = errno;
430 if (err)
431 unlink (nonce);
434 SAFE_FREE ();
437 return err;
440 /* Lock the lock file named LFNAME.
441 If FORCE, do so even if it is already locked.
442 Return 0 if successful, an error number on failure. */
444 static int
445 lock_file_1 (char *lfname, bool force)
447 /* Call this first because it can GC. */
448 printmax_t boot = get_boot_time ();
450 Lisp_Object luser_name = Fuser_login_name (Qnil);
451 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
452 Lisp_Object lhost_name = Fsystem_name ();
453 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
454 char lock_info_str[MAX_LFINFO + 1];
455 printmax_t pid = getpid ();
457 if (boot)
459 if (sizeof lock_info_str
460 <= snprintf (lock_info_str, sizeof lock_info_str,
461 "%s@%s.%"pMd":%"pMd,
462 user_name, host_name, pid, boot))
463 return ENAMETOOLONG;
465 else if (sizeof lock_info_str
466 <= snprintf (lock_info_str, sizeof lock_info_str,
467 "%s@%s.%"pMd,
468 user_name, host_name, pid))
469 return ENAMETOOLONG;
471 return create_lock_file (lfname, lock_info_str, force);
474 /* Return true if times A and B are no more than one second apart. */
476 static bool
477 within_one_second (time_t a, time_t b)
479 return (a - b >= -1 && a - b <= 1);
482 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
483 #ifndef ELOOP
484 # define ELOOP (-1)
485 #endif
487 /* Read the data for the lock file LFNAME into LFINFO. Read at most
488 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
489 (setting errno) on error. */
491 static ptrdiff_t
492 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
494 ptrdiff_t nbytes;
496 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
497 && errno == EINVAL)
499 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
500 if (0 <= fd)
502 /* Use read, not emacs_read, since FD isn't unwind-protected. */
503 ptrdiff_t read_bytes = read (fd, lfinfo, MAX_LFINFO + 1);
504 int read_errno = errno;
505 if (emacs_close (fd) != 0)
506 return -1;
507 errno = read_errno;
508 return read_bytes;
511 if (errno != ELOOP)
512 return -1;
514 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
515 The former must have been removed and replaced by the latter.
516 Try again. */
517 QUIT;
520 return nbytes;
523 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
524 1 if another process owns it (and set OWNER (if non-null) to info),
525 2 if the current process owns it,
526 or -1 if something is wrong with the locking mechanism. */
528 static int
529 current_lock_owner (lock_info_type *owner, char *lfname)
531 int ret;
532 lock_info_type local_owner;
533 ptrdiff_t lfinfolen;
534 intmax_t pid, boot_time;
535 char *at, *dot, *lfinfo_end;
537 /* Even if the caller doesn't want the owner info, we still have to
538 read it to determine return value. */
539 if (!owner)
540 owner = &local_owner;
542 /* If nonexistent lock file, all is well; otherwise, got strange error. */
543 lfinfolen = read_lock_data (lfname, owner->user);
544 if (lfinfolen < 0)
545 return errno == ENOENT ? 0 : -1;
546 if (MAX_LFINFO < lfinfolen)
547 return -1;
548 owner->user[lfinfolen] = 0;
550 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
551 /* The USER is everything before the last @. */
552 owner->at = at = memrchr (owner->user, '@', lfinfolen);
553 if (!at)
554 return -1;
555 owner->dot = dot = strrchr (at, '.');
556 if (!dot)
557 return -1;
559 /* The PID is everything from the last '.' to the ':' or equivalent. */
560 if (! c_isdigit (dot[1]))
561 return -1;
562 errno = 0;
563 pid = strtoimax (dot + 1, &owner->colon, 10);
564 if (errno == ERANGE)
565 pid = -1;
567 /* After the ':' or equivalent, if there is one, comes the boot time. */
568 char *boot = owner->colon + 1;
569 switch (owner->colon[0])
571 case 0:
572 boot_time = 0;
573 lfinfo_end = owner->colon;
574 break;
576 case '\357':
577 /* Treat "\357\200\242" (U+F022 in UTF-8) as if it were ":" (Bug#24656).
578 This works around a bug in the Linux CIFS kernel client, which can
579 mistakenly transliterate ':' to U+F022 in symlink contents.
580 See <https://bugzilla.redhat.com/show_bug.cgi?id=1384153>. */
581 if (! (boot[0] == '\200' && boot[1] == '\242'))
582 return -1;
583 boot += 2;
584 /* Fall through. */
585 case ':':
586 if (! c_isdigit (boot[0]))
587 return -1;
588 boot_time = strtoimax (boot, &lfinfo_end, 10);
589 break;
591 default:
592 return -1;
594 if (lfinfo_end != owner->user + lfinfolen)
595 return -1;
597 /* On current host? */
598 Lisp_Object system_name = Fsystem_name ();
599 if (STRINGP (system_name)
600 && dot - (at + 1) == SBYTES (system_name)
601 && memcmp (at + 1, SSDATA (system_name), SBYTES (system_name)) == 0)
603 if (pid == getpid ())
604 ret = 2; /* We own it. */
605 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
606 && (kill (pid, 0) >= 0 || errno == EPERM)
607 && (boot_time == 0
608 || (boot_time <= TYPE_MAXIMUM (time_t)
609 && within_one_second (boot_time, get_boot_time ()))))
610 ret = 1; /* An existing process on this machine owns it. */
611 /* The owner process is dead or has a strange pid, so try to
612 zap the lockfile. */
613 else
614 return unlink (lfname);
616 else
617 { /* If we wanted to support the check for stale locks on remote machines,
618 here's where we'd do it. */
619 ret = 1;
622 return ret;
626 /* Lock the lock named LFNAME if possible.
627 Return 0 in that case.
628 Return positive if some other process owns the lock, and info about
629 that process in CLASHER.
630 Return -1 if cannot lock for any other reason. */
632 static int
633 lock_if_free (lock_info_type *clasher, char *lfname)
635 int err;
636 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
638 switch (current_lock_owner (clasher, lfname))
640 case 2:
641 return 0; /* We ourselves locked it. */
642 case 1:
643 return 1; /* Someone else has it. */
644 case -1:
645 return -1; /* current_lock_owner returned strange error. */
648 /* We deleted a stale lock; try again to lock the file. */
651 return err ? -1 : 0;
654 /* lock_file locks file FN,
655 meaning it serves notice on the world that you intend to edit that file.
656 This should be done only when about to modify a file-visiting
657 buffer previously unmodified.
658 Do not (normally) call this for a buffer already modified,
659 as either the file is already locked, or the user has already
660 decided to go ahead without locking.
662 When this returns, either the lock is locked for us,
663 or lock creation failed,
664 or the user has said to go ahead without locking.
666 If the file is locked by someone else, this calls
667 ask-user-about-lock (a Lisp function) with two arguments,
668 the file name and info about the user who did the locking.
669 This function can signal an error, or return t meaning
670 take away the lock, or return nil meaning ignore the lock. */
672 void
673 lock_file (Lisp_Object fn)
675 Lisp_Object orig_fn, encoded_fn;
676 char *lfname;
677 lock_info_type lock_info;
678 USE_SAFE_ALLOCA;
680 /* Don't do locking while dumping Emacs.
681 Uncompressing wtmp files uses call-process, which does not work
682 in an uninitialized Emacs. */
683 if (! NILP (Vpurify_flag))
684 return;
686 orig_fn = fn;
687 fn = Fexpand_file_name (fn, Qnil);
688 #ifdef WINDOWSNT
689 /* Ensure we have only '/' separators, to avoid problems with
690 looking (inside fill_in_lock_file_name) for backslashes in file
691 names encoded by some DBCS codepage. */
692 dostounix_filename (SSDATA (fn));
693 #endif
694 encoded_fn = ENCODE_FILE (fn);
696 /* See if this file is visited and has changed on disk since it was
697 visited. */
699 register Lisp_Object subject_buf;
701 subject_buf = get_truename_buffer (orig_fn);
703 if (!NILP (subject_buf)
704 && NILP (Fverify_visited_file_modtime (subject_buf))
705 && !NILP (Ffile_exists_p (fn)))
706 call1 (intern ("ask-user-about-supersession-threat"), fn);
710 /* Don't do locking if the user has opted out. */
711 if (create_lockfiles)
714 /* Create the name of the lock-file for file fn */
715 MAKE_LOCK_NAME (lfname, encoded_fn);
717 /* Try to lock the lock. */
718 if (0 < lock_if_free (&lock_info, lfname))
720 /* Someone else has the lock. Consider breaking it. */
721 Lisp_Object attack;
722 char *dot = lock_info.dot;
723 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
724 static char const replacement[] = " (pid ";
725 int replacementlen = sizeof replacement - 1;
726 memmove (dot + replacementlen, dot + 1, pidlen);
727 strcpy (dot + replacementlen + pidlen, ")");
728 memcpy (dot, replacement, replacementlen);
729 attack = call2 (intern ("ask-user-about-lock"), fn,
730 build_string (lock_info.user));
731 /* Take the lock if the user said so. */
732 if (!NILP (attack))
733 lock_file_1 (lfname, 1);
735 SAFE_FREE ();
739 void
740 unlock_file (Lisp_Object fn)
742 char *lfname;
743 USE_SAFE_ALLOCA;
745 fn = Fexpand_file_name (fn, Qnil);
746 fn = ENCODE_FILE (fn);
748 MAKE_LOCK_NAME (lfname, fn);
750 if (current_lock_owner (0, lfname) == 2)
751 unlink (lfname);
753 SAFE_FREE ();
756 #else /* MSDOS */
757 void
758 lock_file (Lisp_Object fn)
762 void
763 unlock_file (Lisp_Object fn)
767 #endif /* MSDOS */
769 void
770 unlock_all_files (void)
772 register Lisp_Object tail, buf;
773 register struct buffer *b;
775 FOR_EACH_LIVE_BUFFER (tail, buf)
777 b = XBUFFER (buf);
778 if (STRINGP (BVAR (b, file_truename))
779 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
780 unlock_file (BVAR (b, file_truename));
784 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
785 0, 1, 0,
786 doc: /* Lock FILE, if current buffer is modified.
787 FILE defaults to current buffer's visited file,
788 or else nothing is done if current buffer isn't visiting a file.
790 If the option `create-lockfiles' is nil, this does nothing. */)
791 (Lisp_Object file)
793 if (NILP (file))
794 file = BVAR (current_buffer, file_truename);
795 else
796 CHECK_STRING (file);
797 if (SAVE_MODIFF < MODIFF
798 && !NILP (file))
799 lock_file (file);
800 return Qnil;
803 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
804 0, 0, 0,
805 doc: /* Unlock the file visited in the current buffer.
806 If the buffer is not modified, this does nothing because the file
807 should not be locked in that case. */)
808 (void)
810 if (SAVE_MODIFF < MODIFF
811 && STRINGP (BVAR (current_buffer, file_truename)))
812 unlock_file (BVAR (current_buffer, file_truename));
813 return Qnil;
816 /* Unlock the file visited in buffer BUFFER. */
818 void
819 unlock_buffer (struct buffer *buffer)
821 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
822 && STRINGP (BVAR (buffer, file_truename)))
823 unlock_file (BVAR (buffer, file_truename));
826 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
827 doc: /* Return a value indicating whether FILENAME is locked.
828 The value is nil if the FILENAME is not locked,
829 t if it is locked by you, else a string saying which user has locked it. */)
830 (Lisp_Object filename)
832 #ifdef MSDOS
833 return Qnil;
834 #else
835 Lisp_Object ret;
836 char *lfname;
837 int owner;
838 lock_info_type locker;
839 USE_SAFE_ALLOCA;
841 filename = Fexpand_file_name (filename, Qnil);
843 MAKE_LOCK_NAME (lfname, filename);
845 owner = current_lock_owner (&locker, lfname);
846 if (owner <= 0)
847 ret = Qnil;
848 else if (owner == 2)
849 ret = Qt;
850 else
851 ret = make_string (locker.user, locker.at - locker.user);
853 SAFE_FREE ();
854 return ret;
855 #endif
858 void
859 syms_of_filelock (void)
861 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
862 doc: /* The directory for writing temporary files. */);
863 Vtemporary_file_directory = Qnil;
865 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
866 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
867 create_lockfiles = 1;
869 defsubr (&Sunlock_buffer);
870 defsubr (&Slock_buffer);
871 defsubr (&Sfile_locked_p);