]> code.delx.au - gnu-emacs/blob - src/filelock.c
Merge from origin/emacs-25
[gnu-emacs] / src / filelock.c
1 /* Lock files for editing.
2
3 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2016 Free Software
4 Foundation, Inc.
5
6 Author: Richard King
7 (according to authors.el)
8
9 This file is part of GNU Emacs.
10
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.
15
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.
20
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/>. */
23
24
25 #include <config.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <signal.h>
29 #include <stdio.h>
30
31 #ifdef HAVE_PWD_H
32 #include <pwd.h>
33 #endif
34
35 #include <sys/file.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38
39 #ifdef __FreeBSD__
40 #include <sys/sysctl.h>
41 #endif /* __FreeBSD__ */
42
43 #include <errno.h>
44
45 #include <c-ctype.h>
46
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
55
56 #ifdef HAVE_UTMP_H
57 #include <utmp.h>
58 #endif
59
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
65
66 #ifndef WTMP_FILE
67 #define WTMP_FILE "/var/log/wtmp"
68 #endif
69
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.
74
75 When the host in the lock data is the current host, we can check if
76 the pid is valid with kill.
77
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.
87
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.
95
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.
99
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.
103
104 --karl@cs.umb.edu/karl@hq.ileaf.com.
105
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.
114
115 To summarize, race conditions can occur with either:
116
117 * Forced locks on MS-Windows systems.
118
119 * Non-forced locks on non-MS-Windows systems that support neither
120 hard nor symbolic links. */
121
122 \f
123 /* Return the time of the last system boot. */
124
125 static time_t boot_time;
126 static bool boot_time_initialized;
127
128 #ifdef BOOT_TIME
129 static void get_boot_time_1 (const char *, bool);
130 #endif
131
132 static time_t
133 get_boot_time (void)
134 {
135 #if defined (BOOT_TIME)
136 int counter;
137 #endif
138
139 if (boot_time_initialized)
140 return boot_time;
141 boot_time_initialized = 1;
142
143 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
144 {
145 int mib[2];
146 size_t size;
147 struct timeval boottime_val;
148
149 mib[0] = CTL_KERN;
150 mib[1] = KERN_BOOTTIME;
151 size = sizeof (boottime_val);
152
153 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
154 {
155 boot_time = boottime_val.tv_sec;
156 return boot_time;
157 }
158 }
159 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
160
161 if (BOOT_TIME_FILE)
162 {
163 struct stat st;
164 if (stat (BOOT_TIME_FILE, &st) == 0)
165 {
166 boot_time = st.st_mtime;
167 return boot_time;
168 }
169 }
170
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 */
179
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;
187
188 /* Try to get boot time from the current wtmp file. */
189 get_boot_time_1 (WTMP_FILE, 1);
190
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++)
193 {
194 char cmd_string[sizeof WTMP_FILE ".19.gz"];
195 Lisp_Object tempname, filename;
196 bool delete_flag = 0;
197
198 filename = Qnil;
199
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
205 {
206 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
207 WTMP_FILE, counter);
208 if (! NILP (Ffile_exists_p (tempname)))
209 {
210 /* The utmp functions on mescaline.gnu.org accept only
211 file names up to 8 characters long. Choose a 2
212 character long prefix, and call make_temp_file with
213 second arg non-zero, so that it will add not more
214 than 6 characters to the prefix. */
215 filename = Fexpand_file_name (build_string ("wt"),
216 Vtemporary_file_directory);
217 filename = make_temp_name (filename, 1);
218 CALLN (Fcall_process, build_string ("gzip"), Qnil,
219 list2 (QCfile, filename), Qnil,
220 build_string ("-cd"), tempname);
221 delete_flag = 1;
222 }
223 }
224
225 if (! NILP (filename))
226 {
227 get_boot_time_1 (SSDATA (filename), 1);
228 if (delete_flag)
229 unlink (SSDATA (filename));
230 }
231 }
232
233 return boot_time;
234 #else
235 return 0;
236 #endif
237 }
238
239 #ifdef BOOT_TIME
240 /* Try to get the boot time from wtmp file FILENAME.
241 This succeeds if that file contains a reboot record.
242
243 If FILENAME is zero, use the same file as before;
244 if no FILENAME has ever been specified, this is the utmp file.
245 Use the newest reboot record if NEWEST,
246 the first reboot record otherwise.
247 Ignore all reboot records on or before BOOT_TIME.
248 Success is indicated by setting BOOT_TIME to a larger value. */
249
250 void
251 get_boot_time_1 (const char *filename, bool newest)
252 {
253 struct utmp ut, *utp;
254
255 if (filename)
256 utmpname (filename);
257
258 setutent ();
259
260 while (1)
261 {
262 /* Find the next reboot record. */
263 ut.ut_type = BOOT_TIME;
264 utp = getutid (&ut);
265 if (! utp)
266 break;
267 /* Compare reboot times and use the newest one. */
268 if (utp->ut_time > boot_time)
269 {
270 boot_time = utp->ut_time;
271 if (! newest)
272 break;
273 }
274 /* Advance on element in the file
275 so that getutid won't repeat the same one. */
276 utp = getutent ();
277 if (! utp)
278 break;
279 }
280 endutent ();
281 }
282 #endif /* BOOT_TIME */
283 \f
284 /* An arbitrary limit on lock contents length. 8 K should be plenty
285 big enough in practice. */
286 enum { MAX_LFINFO = 8 * 1024 };
287
288 /* Here is the structure that stores information about a lock. */
289
290 typedef struct
291 {
292 /* Location of '@', '.', ':' in USER. If there's no colon, COLON
293 points to the end of USER. */
294 char *at, *dot, *colon;
295
296 /* Lock file contents USER@HOST.PID with an optional :BOOT_TIME
297 appended. This memory is used as a lock file contents buffer, so
298 it needs room for MAX_LFINFO + 1 bytes. A string " (pid NNNN)"
299 may be appended to the USER@HOST while generating a diagnostic,
300 so make room for its extra bytes (as opposed to ".NNNN") too. */
301 char user[MAX_LFINFO + 1 + sizeof " (pid )" - sizeof "."];
302 } lock_info_type;
303
304 /* Write the name of the lock file for FNAME into LOCKNAME. Length
305 will be that of FNAME plus two more for the leading ".#", plus one
306 for the null. */
307 #define MAKE_LOCK_NAME(lockname, fname) \
308 (lockname = SAFE_ALLOCA (SBYTES (fname) + 2 + 1), \
309 fill_in_lock_file_name (lockname, fname))
310
311 static void
312 fill_in_lock_file_name (char *lockfile, Lisp_Object fn)
313 {
314 char *last_slash = memrchr (SSDATA (fn), '/', SBYTES (fn));
315 char *base = last_slash + 1;
316 ptrdiff_t dirlen = base - SSDATA (fn);
317 memcpy (lockfile, SSDATA (fn), dirlen);
318 lockfile[dirlen] = '.';
319 lockfile[dirlen + 1] = '#';
320 strcpy (lockfile + dirlen + 2, base);
321 }
322
323 /* For some reason Linux kernels return EPERM on file systems that do
324 not support hard or symbolic links. This symbol documents the quirk.
325 There is no way to tell whether a symlink call fails due to
326 permissions issues or because links are not supported, but luckily
327 the lock file code should work either way. */
328 enum { LINKS_MIGHT_NOT_WORK = EPERM };
329
330 /* Rename OLD to NEW. If FORCE, replace any existing NEW.
331 It is OK if there are temporarily two hard links to OLD.
332 Return 0 if successful, -1 (setting errno) otherwise. */
333 static int
334 rename_lock_file (char const *old, char const *new, bool force)
335 {
336 #ifdef WINDOWSNT
337 return sys_rename_replace (old, new, force);
338 #else
339 if (! force)
340 {
341 struct stat st;
342
343 if (link (old, new) == 0)
344 return unlink (old) == 0 || errno == ENOENT ? 0 : -1;
345 if (errno != ENOSYS && errno != LINKS_MIGHT_NOT_WORK)
346 return -1;
347
348 /* 'link' does not work on this file system. This can occur on
349 a GNU/Linux host mounting a FAT32 file system. Fall back on
350 'rename' after checking that NEW does not exist. There is a
351 potential race condition since some other process may create
352 NEW immediately after the existence check, but it's the best
353 we can portably do here. */
354 if (lstat (new, &st) == 0 || errno == EOVERFLOW)
355 {
356 errno = EEXIST;
357 return -1;
358 }
359 if (errno != ENOENT)
360 return -1;
361 }
362
363 return rename (old, new);
364 #endif
365 }
366
367 /* Create the lock file LFNAME with contents LOCK_INFO_STR. Return 0 if
368 successful, an errno value on failure. If FORCE, remove any
369 existing LFNAME if necessary. */
370
371 static int
372 create_lock_file (char *lfname, char *lock_info_str, bool force)
373 {
374 #ifdef WINDOWSNT
375 /* Symlinks are supported only by later versions of Windows, and
376 creating them is a privileged operation that often triggers
377 User Account Control elevation prompts. Avoid the problem by
378 pretending that 'symlink' does not work. */
379 int err = ENOSYS;
380 #else
381 int err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
382 #endif
383
384 if (err == EEXIST && force)
385 {
386 unlink (lfname);
387 err = symlink (lock_info_str, lfname) == 0 ? 0 : errno;
388 }
389
390 if (err == ENOSYS || err == LINKS_MIGHT_NOT_WORK || err == ENAMETOOLONG)
391 {
392 static char const nonce_base[] = ".#-emacsXXXXXX";
393 char *last_slash = strrchr (lfname, '/');
394 ptrdiff_t lfdirlen = last_slash + 1 - lfname;
395 USE_SAFE_ALLOCA;
396 char *nonce = SAFE_ALLOCA (lfdirlen + sizeof nonce_base);
397 int fd;
398 memcpy (nonce, lfname, lfdirlen);
399 strcpy (nonce + lfdirlen, nonce_base);
400
401 fd = mkostemp (nonce, O_BINARY | O_CLOEXEC);
402 if (fd < 0)
403 err = errno;
404 else
405 {
406 ptrdiff_t lock_info_len;
407 if (! O_CLOEXEC)
408 fcntl (fd, F_SETFD, FD_CLOEXEC);
409 lock_info_len = strlen (lock_info_str);
410 err = 0;
411 /* Use 'write', not 'emacs_write', as garbage collection
412 might signal an error, which would leak FD. */
413 if (write (fd, lock_info_str, lock_info_len) != lock_info_len
414 || fchmod (fd, S_IRUSR | S_IRGRP | S_IROTH) != 0)
415 err = errno;
416 /* There is no need to call fsync here, as the contents of
417 the lock file need not survive system crashes. */
418 if (emacs_close (fd) != 0)
419 err = errno;
420 if (!err && rename_lock_file (nonce, lfname, force) != 0)
421 err = errno;
422 if (err)
423 unlink (nonce);
424 }
425
426 SAFE_FREE ();
427 }
428
429 return err;
430 }
431
432 /* Lock the lock file named LFNAME.
433 If FORCE, do so even if it is already locked.
434 Return 0 if successful, an error number on failure. */
435
436 static int
437 lock_file_1 (char *lfname, bool force)
438 {
439 /* Call this first because it can GC. */
440 printmax_t boot = get_boot_time ();
441
442 Lisp_Object luser_name = Fuser_login_name (Qnil);
443 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
444 Lisp_Object lhost_name = Fsystem_name ();
445 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
446 char lock_info_str[MAX_LFINFO + 1];
447 printmax_t pid = getpid ();
448
449 if (boot)
450 {
451 if (sizeof lock_info_str
452 <= snprintf (lock_info_str, sizeof lock_info_str,
453 "%s@%s.%"pMd":%"pMd,
454 user_name, host_name, pid, boot))
455 return ENAMETOOLONG;
456 }
457 else if (sizeof lock_info_str
458 <= snprintf (lock_info_str, sizeof lock_info_str,
459 "%s@%s.%"pMd,
460 user_name, host_name, pid))
461 return ENAMETOOLONG;
462
463 return create_lock_file (lfname, lock_info_str, force);
464 }
465
466 /* Return true if times A and B are no more than one second apart. */
467
468 static bool
469 within_one_second (time_t a, time_t b)
470 {
471 return (a - b >= -1 && a - b <= 1);
472 }
473 \f
474 /* On systems lacking ELOOP, test for an errno value that shouldn't occur. */
475 #ifndef ELOOP
476 # define ELOOP (-1)
477 #endif
478
479 /* Read the data for the lock file LFNAME into LFINFO. Read at most
480 MAX_LFINFO + 1 bytes. Return the number of bytes read, or -1
481 (setting errno) on error. */
482
483 static ptrdiff_t
484 read_lock_data (char *lfname, char lfinfo[MAX_LFINFO + 1])
485 {
486 ptrdiff_t nbytes;
487
488 while ((nbytes = readlinkat (AT_FDCWD, lfname, lfinfo, MAX_LFINFO + 1)) < 0
489 && errno == EINVAL)
490 {
491 int fd = emacs_open (lfname, O_RDONLY | O_BINARY | O_NOFOLLOW, 0);
492 if (0 <= fd)
493 {
494 /* Use read, not emacs_read, since FD isn't unwind-protected. */
495 ptrdiff_t read_bytes = read (fd, lfinfo, MAX_LFINFO + 1);
496 int read_errno = errno;
497 if (emacs_close (fd) != 0)
498 return -1;
499 errno = read_errno;
500 return read_bytes;
501 }
502
503 if (errno != ELOOP)
504 return -1;
505
506 /* readlinkat saw a non-symlink, but emacs_open saw a symlink.
507 The former must have been removed and replaced by the latter.
508 Try again. */
509 QUIT;
510 }
511
512 return nbytes;
513 }
514
515 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
516 1 if another process owns it (and set OWNER (if non-null) to info),
517 2 if the current process owns it,
518 or -1 if something is wrong with the locking mechanism. */
519
520 static int
521 current_lock_owner (lock_info_type *owner, char *lfname)
522 {
523 int ret;
524 lock_info_type local_owner;
525 ptrdiff_t lfinfolen;
526 intmax_t pid, boot_time;
527 char *at, *dot, *lfinfo_end;
528
529 /* Even if the caller doesn't want the owner info, we still have to
530 read it to determine return value. */
531 if (!owner)
532 owner = &local_owner;
533
534 /* If nonexistent lock file, all is well; otherwise, got strange error. */
535 lfinfolen = read_lock_data (lfname, owner->user);
536 if (lfinfolen < 0)
537 return errno == ENOENT ? 0 : -1;
538 if (MAX_LFINFO < lfinfolen)
539 return -1;
540 owner->user[lfinfolen] = 0;
541
542 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
543 /* The USER is everything before the last @. */
544 owner->at = at = memrchr (owner->user, '@', lfinfolen);
545 if (!at)
546 return -1;
547 owner->dot = dot = strrchr (at, '.');
548 if (!dot)
549 return -1;
550
551 /* The PID is everything from the last `.' to the `:'. */
552 if (! c_isdigit (dot[1]))
553 return -1;
554 errno = 0;
555 pid = strtoimax (dot + 1, &owner->colon, 10);
556 if (errno == ERANGE)
557 pid = -1;
558
559 /* After the `:', if there is one, comes the boot time. */
560 switch (owner->colon[0])
561 {
562 case 0:
563 boot_time = 0;
564 lfinfo_end = owner->colon;
565 break;
566
567 case ':':
568 if (! c_isdigit (owner->colon[1]))
569 return -1;
570 boot_time = strtoimax (owner->colon + 1, &lfinfo_end, 10);
571 break;
572
573 default:
574 return -1;
575 }
576 if (lfinfo_end != owner->user + lfinfolen)
577 return -1;
578
579 /* On current host? */
580 Lisp_Object system_name = Fsystem_name ();
581 if (STRINGP (system_name)
582 && dot - (at + 1) == SBYTES (system_name)
583 && memcmp (at + 1, SSDATA (system_name), SBYTES (system_name)) == 0)
584 {
585 if (pid == getpid ())
586 ret = 2; /* We own it. */
587 else if (0 < pid && pid <= TYPE_MAXIMUM (pid_t)
588 && (kill (pid, 0) >= 0 || errno == EPERM)
589 && (boot_time == 0
590 || (boot_time <= TYPE_MAXIMUM (time_t)
591 && within_one_second (boot_time, get_boot_time ()))))
592 ret = 1; /* An existing process on this machine owns it. */
593 /* The owner process is dead or has a strange pid, so try to
594 zap the lockfile. */
595 else
596 return unlink (lfname);
597 }
598 else
599 { /* If we wanted to support the check for stale locks on remote machines,
600 here's where we'd do it. */
601 ret = 1;
602 }
603
604 return ret;
605 }
606
607 \f
608 /* Lock the lock named LFNAME if possible.
609 Return 0 in that case.
610 Return positive if some other process owns the lock, and info about
611 that process in CLASHER.
612 Return -1 if cannot lock for any other reason. */
613
614 static int
615 lock_if_free (lock_info_type *clasher, char *lfname)
616 {
617 int err;
618 while ((err = lock_file_1 (lfname, 0)) == EEXIST)
619 {
620 switch (current_lock_owner (clasher, lfname))
621 {
622 case 2:
623 return 0; /* We ourselves locked it. */
624 case 1:
625 return 1; /* Someone else has it. */
626 case -1:
627 return -1; /* current_lock_owner returned strange error. */
628 }
629
630 /* We deleted a stale lock; try again to lock the file. */
631 }
632
633 return err ? -1 : 0;
634 }
635
636 /* lock_file locks file FN,
637 meaning it serves notice on the world that you intend to edit that file.
638 This should be done only when about to modify a file-visiting
639 buffer previously unmodified.
640 Do not (normally) call this for a buffer already modified,
641 as either the file is already locked, or the user has already
642 decided to go ahead without locking.
643
644 When this returns, either the lock is locked for us,
645 or lock creation failed,
646 or the user has said to go ahead without locking.
647
648 If the file is locked by someone else, this calls
649 ask-user-about-lock (a Lisp function) with two arguments,
650 the file name and info about the user who did the locking.
651 This function can signal an error, or return t meaning
652 take away the lock, or return nil meaning ignore the lock. */
653
654 void
655 lock_file (Lisp_Object fn)
656 {
657 Lisp_Object orig_fn, encoded_fn;
658 char *lfname;
659 lock_info_type lock_info;
660 USE_SAFE_ALLOCA;
661
662 /* Don't do locking while dumping Emacs.
663 Uncompressing wtmp files uses call-process, which does not work
664 in an uninitialized Emacs. */
665 if (! NILP (Vpurify_flag))
666 return;
667
668 orig_fn = fn;
669 fn = Fexpand_file_name (fn, Qnil);
670 #ifdef WINDOWSNT
671 /* Ensure we have only '/' separators, to avoid problems with
672 looking (inside fill_in_lock_file_name) for backslashes in file
673 names encoded by some DBCS codepage. */
674 dostounix_filename (SSDATA (fn));
675 #endif
676 encoded_fn = ENCODE_FILE (fn);
677
678 /* See if this file is visited and has changed on disk since it was
679 visited. */
680 {
681 register Lisp_Object subject_buf;
682
683 subject_buf = get_truename_buffer (orig_fn);
684
685 if (!NILP (subject_buf)
686 && NILP (Fverify_visited_file_modtime (subject_buf))
687 && !NILP (Ffile_exists_p (fn)))
688 call1 (intern ("ask-user-about-supersession-threat"), fn);
689
690 }
691
692 /* Don't do locking if the user has opted out. */
693 if (create_lockfiles)
694 {
695
696 /* Create the name of the lock-file for file fn */
697 MAKE_LOCK_NAME (lfname, encoded_fn);
698
699 /* Try to lock the lock. */
700 if (0 < lock_if_free (&lock_info, lfname))
701 {
702 /* Someone else has the lock. Consider breaking it. */
703 Lisp_Object attack;
704 char *dot = lock_info.dot;
705 ptrdiff_t pidlen = lock_info.colon - (dot + 1);
706 static char const replacement[] = " (pid ";
707 int replacementlen = sizeof replacement - 1;
708 memmove (dot + replacementlen, dot + 1, pidlen);
709 strcpy (dot + replacementlen + pidlen, ")");
710 memcpy (dot, replacement, replacementlen);
711 attack = call2 (intern ("ask-user-about-lock"), fn,
712 build_string (lock_info.user));
713 /* Take the lock if the user said so. */
714 if (!NILP (attack))
715 lock_file_1 (lfname, 1);
716 }
717 SAFE_FREE ();
718 }
719 }
720
721 void
722 unlock_file (Lisp_Object fn)
723 {
724 char *lfname;
725 USE_SAFE_ALLOCA;
726
727 fn = Fexpand_file_name (fn, Qnil);
728 fn = ENCODE_FILE (fn);
729
730 MAKE_LOCK_NAME (lfname, fn);
731
732 if (current_lock_owner (0, lfname) == 2)
733 unlink (lfname);
734
735 SAFE_FREE ();
736 }
737
738 void
739 unlock_all_files (void)
740 {
741 register Lisp_Object tail, buf;
742 register struct buffer *b;
743
744 FOR_EACH_LIVE_BUFFER (tail, buf)
745 {
746 b = XBUFFER (buf);
747 if (STRINGP (BVAR (b, file_truename))
748 && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
749 unlock_file (BVAR (b, file_truename));
750 }
751 }
752 \f
753 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
754 0, 1, 0,
755 doc: /* Lock FILE, if current buffer is modified.
756 FILE defaults to current buffer's visited file,
757 or else nothing is done if current buffer isn't visiting a file.
758
759 If the option `create-lockfiles' is nil, this does nothing. */)
760 (Lisp_Object file)
761 {
762 if (NILP (file))
763 file = BVAR (current_buffer, file_truename);
764 else
765 CHECK_STRING (file);
766 if (SAVE_MODIFF < MODIFF
767 && !NILP (file))
768 lock_file (file);
769 return Qnil;
770 }
771
772 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
773 0, 0, 0,
774 doc: /* Unlock the file visited in the current buffer.
775 If the buffer is not modified, this does nothing because the file
776 should not be locked in that case. */)
777 (void)
778 {
779 if (SAVE_MODIFF < MODIFF
780 && STRINGP (BVAR (current_buffer, file_truename)))
781 unlock_file (BVAR (current_buffer, file_truename));
782 return Qnil;
783 }
784
785 /* Unlock the file visited in buffer BUFFER. */
786
787 void
788 unlock_buffer (struct buffer *buffer)
789 {
790 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
791 && STRINGP (BVAR (buffer, file_truename)))
792 unlock_file (BVAR (buffer, file_truename));
793 }
794
795 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
796 doc: /* Return a value indicating whether FILENAME is locked.
797 The value is nil if the FILENAME is not locked,
798 t if it is locked by you, else a string saying which user has locked it. */)
799 (Lisp_Object filename)
800 {
801 Lisp_Object ret;
802 char *lfname;
803 int owner;
804 lock_info_type locker;
805 USE_SAFE_ALLOCA;
806
807 filename = Fexpand_file_name (filename, Qnil);
808
809 MAKE_LOCK_NAME (lfname, filename);
810
811 owner = current_lock_owner (&locker, lfname);
812 if (owner <= 0)
813 ret = Qnil;
814 else if (owner == 2)
815 ret = Qt;
816 else
817 ret = make_string (locker.user, locker.at - locker.user);
818
819 SAFE_FREE ();
820 return ret;
821 }
822
823 void
824 syms_of_filelock (void)
825 {
826 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
827 doc: /* The directory for writing temporary files. */);
828 Vtemporary_file_directory = Qnil;
829
830 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
831 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
832 create_lockfiles = 1;
833
834 defsubr (&Sunlock_buffer);
835 defsubr (&Slock_buffer);
836 defsubr (&Sfile_locked_p);
837 }