1 /* Lock files for editing.
3 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2016 Free Software
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/>. */
26 #include <sys/types.h>
40 #include <sys/sysctl.h>
41 #endif /* __FreeBSD__ */
52 #include <sys/socket.h> /* for fcntl */
53 #include "w32.h" /* for dostounix_filename */
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"
67 #define WTMP_FILE "/var/log/wtmp"
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
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
;
129 static void get_boot_time_1 (const char *, bool);
135 #if defined (BOOT_TIME)
139 if (boot_time_initialized
)
141 boot_time_initialized
= 1;
143 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
147 struct timeval boottime_val
;
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
;
159 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
164 if (stat (BOOT_TIME_FILE
, &st
) == 0)
166 boot_time
= st
.st_mtime
;
171 #if defined (BOOT_TIME)
173 /* The utmp routines maintain static state.
174 Don't touch that state unless we are initialized,
175 since it might not survive dumping. */
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);
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 Lisp_Object filename
= Qnil
;
195 bool delete_flag
= false;
196 char cmd_string
[sizeof WTMP_FILE
".19.gz"];
197 AUTO_STRING_WITH_LEN (tempname
, cmd_string
,
198 sprintf (cmd_string
, "%s.%d", WTMP_FILE
, counter
));
199 if (! NILP (Ffile_exists_p (tempname
)))
203 tempname
= make_formatted_string (cmd_string
, "%s.%d.gz",
205 if (! NILP (Ffile_exists_p (tempname
)))
207 /* The utmp functions on mescaline.gnu.org accept only
208 file names up to 8 characters long. Choose a 2
209 character long prefix, and call make_temp_file with
210 second arg non-zero, so that it will add not more
211 than 6 characters to the prefix. */
212 filename
= Fexpand_file_name (build_string ("wt"),
213 Vtemporary_file_directory
);
214 filename
= make_temp_name (filename
, 1);
215 CALLN (Fcall_process
, build_string ("gzip"), Qnil
,
216 list2 (QCfile
, filename
), Qnil
,
217 build_string ("-cd"), tempname
);
222 if (! NILP (filename
))
224 get_boot_time_1 (SSDATA (filename
), 1);
226 unlink (SSDATA (filename
));
237 /* Try to get the boot time from wtmp file FILENAME.
238 This succeeds if that file contains a reboot record.
240 If FILENAME is zero, use the same file as before;
241 if no FILENAME has ever been specified, this is the utmp file.
242 Use the newest reboot record if NEWEST,
243 the first reboot record otherwise.
244 Ignore all reboot records on or before BOOT_TIME.
245 Success is indicated by setting BOOT_TIME to a larger value. */
248 get_boot_time_1 (const char *filename
, bool newest
)
250 struct utmp ut
, *utp
;
259 /* Find the next reboot record. */
260 ut
.ut_type
= BOOT_TIME
;
264 /* Compare reboot times and use the newest one. */
265 if (utp
->ut_time
> boot_time
)
267 boot_time
= utp
->ut_time
;
271 /* Advance on element in the file
272 so that getutid won't repeat the same one. */
279 #endif /* BOOT_TIME */
281 /* An arbitrary limit on lock contents length. 8 K should be plenty
282 big enough in practice. */
283 enum { MAX_LFINFO
= 8 * 1024 };
285 /* Here is the structure that stores information about a lock. */
289 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
290 points to the end of USER. */
291 char *at
, *dot
, *colon
;
293 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
294 appended. This memory is used as a lock file contents buffer, so
295 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
296 may be appended to the USER@HOST while generating a diagnostic,
297 so make room for its extra bytes (as opposed to ".NNNN") too. */
298 char user
[MAX_LFINFO
+ 1 + sizeof " (pid )" - sizeof "."];
301 /* Write the name of the lock file for FNAME into LOCKNAME. Length
302 will be that of FNAME plus two more for the leading ".#", plus one
304 #define MAKE_LOCK_NAME(lockname, fname) \
305 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
306 fill_in_lock_file_name (lockname, fname))
309 fill_in_lock_file_name (char *lockfile
, Lisp_Object fn
)
311 char *last_slash
= memrchr (SSDATA (fn
), '/', SBYTES (fn
));
312 char *base
= last_slash
+ 1;
313 ptrdiff_t dirlen
= base
- SSDATA (fn
);
314 memcpy (lockfile
, SSDATA (fn
), dirlen
);
315 lockfile
[dirlen
] = '.';
316 lockfile
[dirlen
+ 1] = '#';
317 strcpy (lockfile
+ dirlen
+ 2, base
);
320 /* For some reason Linux kernels return EPERM on file systems that do
321 not support hard or symbolic links. This symbol documents the quirk.
322 There is no way to tell whether a symlink call fails due to
323 permissions issues or because links are not supported, but luckily
324 the lock file code should work either way. */
325 enum { LINKS_MIGHT_NOT_WORK
= EPERM
};
327 /* Rename OLD to NEW. If FORCE, replace any existing NEW.
328 It is OK if there are temporarily two hard links to OLD.
329 Return 0 if successful, -1 (setting errno) otherwise. */
331 rename_lock_file (char const *old
, char const *new, bool force
)
334 return sys_rename_replace (old
, new, force
);
340 if (link (old
, new) == 0)
341 return unlink (old
) == 0 || errno
== ENOENT
? 0 : -1;
342 if (errno
!= ENOSYS
&& errno
!= LINKS_MIGHT_NOT_WORK
)
345 /* 'link' does not work on this file system. This can occur on
346 a GNU/Linux host mounting a FAT32 file system. Fall back on
347 'rename' after checking that NEW does not exist. There is a
348 potential race condition since some other process may create
349 NEW immediately after the existence check, but it's the best
350 we can portably do here. */
351 if (lstat (new, &st
) == 0 || errno
== EOVERFLOW
)
360 return rename (old
, new);
364 /* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
365 successful, an errno value on failure. If FORCE, remove any
366 existing LFNAME if necessary. */
369 create_lock_file (char *lfname
, char *lock_info_str
, bool force
)
372 /* Symlinks are supported only by later versions of Windows, and
373 creating them is a privileged operation that often triggers
374 User Account Control elevation prompts. Avoid the problem by
375 pretending that 'symlink' does not work. */
378 int err
= symlink (lock_info_str
, lfname
) == 0 ? 0 : errno
;
381 if (err
== EEXIST
&& force
)
384 err
= symlink (lock_info_str
, lfname
) == 0 ? 0 : errno
;
387 if (err
== ENOSYS
|| err
== LINKS_MIGHT_NOT_WORK
|| err
== ENAMETOOLONG
)
389 static char const nonce_base
[] = ".#-emacsXXXXXX";
390 char *last_slash
= strrchr (lfname
, '/');
391 ptrdiff_t lfdirlen
= last_slash
+ 1 - lfname
;
393 char *nonce
= SAFE_ALLOCA (lfdirlen
+ sizeof nonce_base
);
395 memcpy (nonce
, lfname
, lfdirlen
);
396 strcpy (nonce
+ lfdirlen
, nonce_base
);
398 fd
= mkostemp (nonce
, O_BINARY
| O_CLOEXEC
);
403 ptrdiff_t lock_info_len
;
405 fcntl (fd
, F_SETFD
, FD_CLOEXEC
);
406 lock_info_len
= strlen (lock_info_str
);
408 /* Use 'write', not 'emacs_write', as garbage collection
409 might signal an error, which would leak FD. */
410 if (write (fd
, lock_info_str
, lock_info_len
) != lock_info_len
411 || fchmod (fd
, S_IRUSR
| S_IRGRP
| S_IROTH
) != 0)
413 /* There is no need to call fsync here, as the contents of
414 the lock file need not survive system crashes. */
415 if (emacs_close (fd
) != 0)
417 if (!err
&& rename_lock_file (nonce
, lfname
, force
) != 0)
429 /* Lock the lock file named LFNAME.
430 If FORCE, do so even if it is already locked.
431 Return 0 if successful, an error number on failure. */
434 lock_file_1 (char *lfname
, bool force
)
436 /* Call this first because it can GC. */
437 printmax_t boot
= get_boot_time ();
439 Lisp_Object luser_name
= Fuser_login_name (Qnil
);
440 char const *user_name
= STRINGP (luser_name
) ? SSDATA (luser_name
) : "";
441 Lisp_Object lhost_name
= Fsystem_name ();
442 char const *host_name
= STRINGP (lhost_name
) ? SSDATA (lhost_name
) : "";
443 char lock_info_str
[MAX_LFINFO
+ 1];
444 printmax_t pid
= getpid ();
448 if (sizeof lock_info_str
449 <= snprintf (lock_info_str
, sizeof lock_info_str
,
451 user_name
, host_name
, pid
, boot
))
454 else if (sizeof lock_info_str
455 <= snprintf (lock_info_str
, sizeof lock_info_str
,
457 user_name
, host_name
, pid
))
460 return create_lock_file (lfname
, lock_info_str
, force
);
463 /* Return true if times A and B are no more than one second apart. */
466 within_one_second (time_t a
, time_t b
)
468 return (a
- b
>= -1 && a
- b
<= 1);
471 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
476 /* Read the data for the lock file LFNAME into LFINFO. Read at most
477 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
478 (setting errno) on error. */
481 read_lock_data (char *lfname
, char lfinfo
[MAX_LFINFO
+ 1])
485 while ((nbytes
= readlinkat (AT_FDCWD
, lfname
, lfinfo
, MAX_LFINFO
+ 1)) < 0
488 int fd
= emacs_open (lfname
, O_RDONLY
| O_NOFOLLOW
, 0);
491 /* Use read, not emacs_read, since FD isn't unwind-protected. */
492 ptrdiff_t read_bytes
= read (fd
, lfinfo
, MAX_LFINFO
+ 1);
493 int read_errno
= errno
;
494 if (emacs_close (fd
) != 0)
503 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
504 The former must have been removed and replaced by the latter.
512 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
513 1 if another process owns it (and set OWNER (if non-null) to info),
514 2 if the current process owns it,
515 or -1 if something is wrong with the locking mechanism. */
518 current_lock_owner (lock_info_type
*owner
, char *lfname
)
521 lock_info_type local_owner
;
523 intmax_t pid
, boot_time
;
524 char *at
, *dot
, *lfinfo_end
;
526 /* Even if the caller doesn't want the owner info, we still have to
527 read it to determine return value. */
529 owner
= &local_owner
;
531 /* If nonexistent lock file, all is well; otherwise, got strange error. */
532 lfinfolen
= read_lock_data (lfname
, owner
->user
);
534 return errno
== ENOENT
? 0 : -1;
535 if (MAX_LFINFO
< lfinfolen
)
537 owner
->user
[lfinfolen
] = 0;
539 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
540 /* The USER is everything before the last @. */
541 owner
->at
= at
= memrchr (owner
->user
, '@', lfinfolen
);
544 owner
->dot
= dot
= strrchr (at
, '.');
548 /* The PID is everything from the last `.' to the `:'. */
549 if (! c_isdigit (dot
[1]))
552 pid
= strtoimax (dot
+ 1, &owner
->colon
, 10);
556 /* After the `:', if there is one, comes the boot time. */
557 switch (owner
->colon
[0])
561 lfinfo_end
= owner
->colon
;
565 if (! c_isdigit (owner
->colon
[1]))
567 boot_time
= strtoimax (owner
->colon
+ 1, &lfinfo_end
, 10);
573 if (lfinfo_end
!= owner
->user
+ lfinfolen
)
576 /* On current host? */
577 Lisp_Object system_name
= Fsystem_name ();
578 if (STRINGP (system_name
)
579 && dot
- (at
+ 1) == SBYTES (system_name
)
580 && memcmp (at
+ 1, SSDATA (system_name
), SBYTES (system_name
)) == 0)
582 if (pid
== getpid ())
583 ret
= 2; /* We own it. */
584 else if (0 < pid
&& pid
<= TYPE_MAXIMUM (pid_t
)
585 && (kill (pid
, 0) >= 0 || errno
== EPERM
)
587 || (boot_time
<= TYPE_MAXIMUM (time_t)
588 && within_one_second (boot_time
, get_boot_time ()))))
589 ret
= 1; /* An existing process on this machine owns it. */
590 /* The owner process is dead or has a strange pid, so try to
593 return unlink (lfname
);
596 { /* If we wanted to support the check for stale locks on remote machines,
597 here's where we'd do it. */
605 /* Lock the lock named LFNAME if possible.
606 Return 0 in that case.
607 Return positive if some other process owns the lock, and info about
608 that process in CLASHER.
609 Return -1 if cannot lock for any other reason. */
612 lock_if_free (lock_info_type
*clasher
, char *lfname
)
615 while ((err
= lock_file_1 (lfname
, 0)) == EEXIST
)
617 switch (current_lock_owner (clasher
, lfname
))
620 return 0; /* We ourselves locked it. */
622 return 1; /* Someone else has it. */
624 return -1; /* current_lock_owner returned strange error. */
627 /* We deleted a stale lock; try again to lock the file. */
633 /* lock_file locks file FN,
634 meaning it serves notice on the world that you intend to edit that file.
635 This should be done only when about to modify a file-visiting
636 buffer previously unmodified.
637 Do not (normally) call this for a buffer already modified,
638 as either the file is already locked, or the user has already
639 decided to go ahead without locking.
641 When this returns, either the lock is locked for us,
642 or lock creation failed,
643 or the user has said to go ahead without locking.
645 If the file is locked by someone else, this calls
646 ask-user-about-lock (a Lisp function) with two arguments,
647 the file name and info about the user who did the locking.
648 This function can signal an error, or return t meaning
649 take away the lock, or return nil meaning ignore the lock. */
652 lock_file (Lisp_Object fn
)
654 Lisp_Object orig_fn
, encoded_fn
;
656 lock_info_type lock_info
;
659 /* Don't do locking while dumping Emacs.
660 Uncompressing wtmp files uses call-process, which does not work
661 in an uninitialized Emacs. */
662 if (! NILP (Vpurify_flag
))
666 fn
= Fexpand_file_name (fn
, Qnil
);
668 /* Ensure we have only '/' separators, to avoid problems with
669 looking (inside fill_in_lock_file_name) for backslashes in file
670 names encoded by some DBCS codepage. */
671 dostounix_filename (SSDATA (fn
));
673 encoded_fn
= ENCODE_FILE (fn
);
675 /* See if this file is visited and has changed on disk since it was
678 register Lisp_Object subject_buf
;
680 subject_buf
= get_truename_buffer (orig_fn
);
682 if (!NILP (subject_buf
)
683 && NILP (Fverify_visited_file_modtime (subject_buf
))
684 && !NILP (Ffile_exists_p (fn
)))
685 call1 (intern ("ask-user-about-supersession-threat"), fn
);
689 /* Don't do locking if the user has opted out. */
690 if (create_lockfiles
)
693 /* Create the name of the lock-file for file fn */
694 MAKE_LOCK_NAME (lfname
, encoded_fn
);
696 /* Try to lock the lock. */
697 if (0 < lock_if_free (&lock_info
, lfname
))
699 /* Someone else has the lock. Consider breaking it. */
701 char *dot
= lock_info
.dot
;
702 ptrdiff_t pidlen
= lock_info
.colon
- (dot
+ 1);
703 static char const replacement
[] = " (pid ";
704 int replacementlen
= sizeof replacement
- 1;
705 memmove (dot
+ replacementlen
, dot
+ 1, pidlen
);
706 strcpy (dot
+ replacementlen
+ pidlen
, ")");
707 memcpy (dot
, replacement
, replacementlen
);
708 attack
= call2 (intern ("ask-user-about-lock"), fn
,
709 build_string (lock_info
.user
));
710 /* Take the lock if the user said so. */
712 lock_file_1 (lfname
, 1);
719 unlock_file (Lisp_Object fn
)
724 fn
= Fexpand_file_name (fn
, Qnil
);
725 fn
= ENCODE_FILE (fn
);
727 MAKE_LOCK_NAME (lfname
, fn
);
729 if (current_lock_owner (0, lfname
) == 2)
736 unlock_all_files (void)
738 register Lisp_Object tail
, buf
;
739 register struct buffer
*b
;
741 FOR_EACH_LIVE_BUFFER (tail
, buf
)
744 if (STRINGP (BVAR (b
, file_truename
))
745 && BUF_SAVE_MODIFF (b
) < BUF_MODIFF (b
))
746 unlock_file (BVAR (b
, file_truename
));
750 DEFUN ("lock-buffer", Flock_buffer
, Slock_buffer
,
752 doc
: /* Lock FILE, if current buffer is modified.
753 FILE defaults to current buffer's visited file,
754 or else nothing is done if current buffer isn't visiting a file.
756 If the option `create-lockfiles' is nil, this does nothing. */)
760 file
= BVAR (current_buffer
, file_truename
);
763 if (SAVE_MODIFF
< MODIFF
769 DEFUN ("unlock-buffer", Funlock_buffer
, Sunlock_buffer
,
771 doc
: /* Unlock the file visited in the current buffer.
772 If the buffer is not modified, this does nothing because the file
773 should not be locked in that case. */)
776 if (SAVE_MODIFF
< MODIFF
777 && STRINGP (BVAR (current_buffer
, file_truename
)))
778 unlock_file (BVAR (current_buffer
, file_truename
));
782 /* Unlock the file visited in buffer BUFFER. */
785 unlock_buffer (struct buffer
*buffer
)
787 if (BUF_SAVE_MODIFF (buffer
) < BUF_MODIFF (buffer
)
788 && STRINGP (BVAR (buffer
, file_truename
)))
789 unlock_file (BVAR (buffer
, file_truename
));
792 DEFUN ("file-locked-p", Ffile_locked_p
, Sfile_locked_p
, 1, 1, 0,
793 doc
: /* Return a value indicating whether FILENAME is locked.
794 The value is nil if the FILENAME is not locked,
795 t if it is locked by you, else a string saying which user has locked it. */)
796 (Lisp_Object filename
)
801 lock_info_type locker
;
804 filename
= Fexpand_file_name (filename
, Qnil
);
806 MAKE_LOCK_NAME (lfname
, filename
);
808 owner
= current_lock_owner (&locker
, lfname
);
814 ret
= make_string (locker
.user
, locker
.at
- locker
.user
);
821 syms_of_filelock (void)
823 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory
,
824 doc
: /* The directory for writing temporary files. */);
825 Vtemporary_file_directory
= Qnil
;
827 DEFVAR_BOOL ("create-lockfiles", create_lockfiles
,
828 doc
: /* Non-nil means use lockfiles to avoid editing collisions. */);
829 create_lockfiles
= 1;
831 defsubr (&Sunlock_buffer
);
832 defsubr (&Slock_buffer
);
833 defsubr (&Sfile_locked_p
);