* lisp/font-lock.el (lisp-font-lock-keywords-2): Fix highlighting of
[bpt/emacs.git] / src / filelock.c
CommitLineData
b97771fc 1/* Lock files for editing.
ab422c4d
PE
2 Copyright (C) 1985-1987, 1993-1994, 1996, 1998-2013 Free Software
3 Foundation, Inc.
8489eb67
RS
4
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
8489eb67 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
8489eb67
RS
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
8489eb67
RS
19
20
68c45bf0 21#include <config.h>
8489eb67
RS
22#include <sys/types.h>
23#include <sys/stat.h>
dfcf069d 24#include <signal.h>
2decc5a9 25#include <stdio.h>
bfb61299 26
5b9c0a1d 27#ifdef HAVE_PWD_H
8489eb67 28#include <pwd.h>
5b9c0a1d 29#endif
bfb61299 30
8489eb67 31#include <sys/file.h>
8489eb67 32#include <fcntl.h>
dfcf069d 33#include <unistd.h>
dfcf069d 34
f805a125 35#ifdef __FreeBSD__
f805a125
KH
36#include <sys/sysctl.h>
37#endif /* __FreeBSD__ */
38
e5ef3cdf 39#include <errno.h>
e5ef3cdf 40
8489eb67 41#include "lisp.h"
d2f6dae8 42#include "character.h"
e5560ff7 43#include "buffer.h"
f4a4528d 44#include "coding.h"
9177d978 45#include "systime.h"
343a2aef
EZ
46#ifdef WINDOWSNT
47#include "w32.h" /* for dostounix_filename */
48#endif
8489eb67 49
8489eb67 50#ifdef CLASH_DETECTION
e788eecc 51
c6d09b8d 52#ifdef HAVE_UTMP_H
e788eecc 53#include <utmp.h>
c6d09b8d 54#endif
77e544a4 55
a48de9b2
PE
56/* A file whose last-modified time is just after the most recent boot.
57 Define this to be NULL to disable checking for this file. */
58#ifndef BOOT_TIME_FILE
59#define BOOT_TIME_FILE "/var/run/random-seed"
60#endif
61
77e544a4
RS
62#ifndef WTMP_FILE
63#define WTMP_FILE "/var/log/wtmp"
64#endif
177c0ea7 65
8dbbc384
RS
66/* The strategy: to lock a file FN, create a symlink .#FN in FN's
67 directory, with link data `user@host.pid'. This avoids a single
68 mount (== failure) point for lock files.
69
70 When the host in the lock data is the current host, we can check if
71 the pid is valid with kill.
177c0ea7 72
8dbbc384
RS
73 Otherwise, we could look at a separate file that maps hostnames to
74 reboot times to see if the remote pid can possibly be valid, since we
75 don't want Emacs to have to communicate via pipes or sockets or
76 whatever to other processes, either locally or remotely; rms says
77 that's too unreliable. Hence the separate file, which could
78 theoretically be updated by daemons running separately -- but this
79 whole idea is unimplemented; in practice, at least in our
1c4f857c 80 environment, it seems such stale locks arise fairly infrequently, and
8dbbc384
RS
81 Emacs' standard methods of dealing with clashes suffice.
82
83 We use symlinks instead of normal files because (1) they can be
84 stored more efficiently on the filesystem, since the kernel knows
85 they will be small, and (2) all the info about the lock can be read
86 in a single system call (readlink). Although we could use regular
1c4f857c 87 files to be useful on old systems lacking symlinks, nowadays
8dbbc384
RS
88 virtually all such systems are probably single-user anyway, so it
89 didn't seem worth the complication.
177c0ea7 90
8dbbc384
RS
91 Similarly, we don't worry about a possible 14-character limit on
92 file names, because those are all the same systems that don't have
93 symlinks.
177c0ea7 94
8dbbc384
RS
95 This is compatible with the locking scheme used by Interleaf (which
96 has contributed this implementation for Emacs), and was designed by
97 Ethan Jacobson, Kimbo Mundy, and others.
177c0ea7 98
8dbbc384 99 --karl@cs.umb.edu/karl@hq.ileaf.com. */
8489eb67 100
8dbbc384 101\f
15e88d21
RS
102/* Return the time of the last system boot. */
103
104static time_t boot_time;
f75d7a91 105static bool boot_time_initialized;
15e88d21 106
2f2500ef 107#ifdef BOOT_TIME
f75d7a91 108static void get_boot_time_1 (const char *, bool);
2f2500ef
DL
109#endif
110
15e88d21 111static time_t
971de7fb 112get_boot_time (void)
15e88d21 113{
9d2818d6 114#if defined (BOOT_TIME)
9177d978 115 int counter;
2decc5a9 116#endif
15e88d21 117
b97771fc 118 if (boot_time_initialized)
15e88d21 119 return boot_time;
b97771fc 120 boot_time_initialized = 1;
15e88d21 121
f805a125
KH
122#if defined (CTL_KERN) && defined (KERN_BOOTTIME)
123 {
124 int mib[2];
125 size_t size;
126 struct timeval boottime_val;
127
128 mib[0] = CTL_KERN;
129 mib[1] = KERN_BOOTTIME;
130 size = sizeof (boottime_val);
131
132 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
133 {
134 boot_time = boottime_val.tv_sec;
135 return boot_time;
136 }
137 }
138#endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
9177d978 139
a48de9b2
PE
140 if (BOOT_TIME_FILE)
141 {
142 struct stat st;
143 if (stat (BOOT_TIME_FILE, &st) == 0)
144 {
145 boot_time = st.st_mtime;
146 return boot_time;
147 }
148 }
149
9d2818d6 150#if defined (BOOT_TIME)
b97771fc
RS
151#ifndef CANNOT_DUMP
152 /* The utmp routines maintain static state.
153 Don't touch that state unless we are initialized,
154 since it might not survive dumping. */
155 if (! initialized)
156 return boot_time;
157#endif /* not CANNOT_DUMP */
158
159 /* Try to get boot time from utmp before wtmp,
160 since utmp is typically much smaller than wtmp.
161 Passing a null pointer causes get_boot_time_1
162 to inspect the default file, namely utmp. */
163 get_boot_time_1 ((char *) 0, 0);
164 if (boot_time)
165 return boot_time;
166
9177d978 167 /* Try to get boot time from the current wtmp file. */
b97771fc 168 get_boot_time_1 (WTMP_FILE, 1);
9177d978
RS
169
170 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
b97771fc 171 for (counter = 0; counter < 20 && ! boot_time; counter++)
9177d978 172 {
882f0d81 173 char cmd_string[sizeof WTMP_FILE ".19.gz"];
9177d978 174 Lisp_Object tempname, filename;
f75d7a91 175 bool delete_flag = 0;
9177d978
RS
176
177 filename = Qnil;
178
a8290ec3
DA
179 tempname = make_formatted_string
180 (cmd_string, "%s.%d", WTMP_FILE, counter);
29a2adb0 181 if (! NILP (Ffile_exists_p (tempname)))
9177d978
RS
182 filename = tempname;
183 else
184 {
a8290ec3
DA
185 tempname = make_formatted_string (cmd_string, "%s.%d.gz",
186 WTMP_FILE, counter);
9177d978
RS
187 if (! NILP (Ffile_exists_p (tempname)))
188 {
189 Lisp_Object args[6];
f1d367aa
GM
190
191 /* The utmp functions on mescaline.gnu.org accept only
192 file names up to 8 characters long. Choose a 2
193 character long prefix, and call make_temp_file with
194 second arg non-zero, so that it will add not more
195 than 6 characters to the prefix. */
882f0d81 196 filename = Fexpand_file_name (build_string ("wt"),
5f8d6a10 197 Vtemporary_file_directory);
882f0d81
PE
198 filename = make_temp_name (filename, 1);
199 args[0] = build_string ("gzip");
9177d978 200 args[1] = Qnil;
882f0d81 201 args[2] = list2 (QCfile, filename);
9177d978 202 args[3] = Qnil;
882f0d81
PE
203 args[4] = build_string ("-cd");
204 args[5] = tempname;
9177d978 205 Fcall_process (6, args);
9177d978
RS
206 delete_flag = 1;
207 }
208 }
209
210 if (! NILP (filename))
211 {
42a5b22f 212 get_boot_time_1 (SSDATA (filename), 1);
9177d978 213 if (delete_flag)
42a5b22f 214 unlink (SSDATA (filename));
9177d978
RS
215 }
216 }
217
218 return boot_time;
219#else
220 return 0;
221#endif
222}
223
e9f22ced 224#ifdef BOOT_TIME
9177d978
RS
225/* Try to get the boot time from wtmp file FILENAME.
226 This succeeds if that file contains a reboot record.
9177d978 227
b97771fc
RS
228 If FILENAME is zero, use the same file as before;
229 if no FILENAME has ever been specified, this is the utmp file.
f75d7a91 230 Use the newest reboot record if NEWEST,
b97771fc
RS
231 the first reboot record otherwise.
232 Ignore all reboot records on or before BOOT_TIME.
233 Success is indicated by setting BOOT_TIME to a larger value. */
234
2f2500ef 235void
f75d7a91 236get_boot_time_1 (const char *filename, bool newest)
9177d978
RS
237{
238 struct utmp ut, *utp;
77e544a4
RS
239 int desc;
240
b97771fc
RS
241 if (filename)
242 {
243 /* On some versions of IRIX, opening a nonexistent file name
244 is likely to crash in the utmp routines. */
68c45bf0 245 desc = emacs_open (filename, O_RDONLY, 0);
b97771fc
RS
246 if (desc < 0)
247 return;
248
68c45bf0 249 emacs_close (desc);
b97771fc
RS
250
251 utmpname (filename);
252 }
9177d978 253
c321b190 254 setutent ();
b97771fc 255
c321b190
RS
256 while (1)
257 {
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)
b97771fc
RS
265 {
266 boot_time = utp->ut_time;
267 if (! newest)
268 break;
269 }
c321b190
RS
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;
275 }
15e88d21 276 endutent ();
15e88d21 277}
e9f22ced 278#endif /* BOOT_TIME */
15e88d21 279\f
8dbbc384 280/* Here is the structure that stores information about a lock. */
32676c08 281
8dbbc384
RS
282typedef struct
283{
284 char *user;
285 char *host;
882f0d81 286 pid_t pid;
15e88d21 287 time_t boot_time;
8dbbc384 288} lock_info_type;
32676c08 289
8dbbc384
RS
290/* Free the two dynamically-allocated pieces in PTR. */
291#define FREE_LOCK_INFO(i) do { xfree ((i).user); xfree ((i).host); } while (0)
e31fbc7a 292
e31fbc7a 293
343a2aef
EZ
294/* Write the name of the lock file for FNAME into LOCKNAME. Length
295 will be that of FN plus two more for the leading `.#' plus 1 for
296 the trailing period plus one for the digit after it plus one for
297 the null. */
298#define MAKE_LOCK_NAME(LOCKNAME, FNAME) \
299 (LOCKNAME = alloca (SBYTES (FNAME) + 2 + 1 + 1 + 1), \
300 fill_in_lock_file_name (LOCKNAME, (FNAME)))
301
302#ifdef WINDOWSNT
303/* 256 chars for user, 1024 chars for host, 10 digits for each of 2 int's. */
304#define MAX_LFINFO (256 + 1024 + 10 + 10 + 2)
305 /* min size: .@PID */
306#define IS_LOCK_FILE(ST) (MAX_LFINFO >= (ST).st_size && (ST).st_size >= 3)
307#else
308#define IS_LOCK_FILE(ST) S_ISLNK ((ST).st_mode)
309#endif
e31fbc7a 310
8dbbc384 311static void
971de7fb 312fill_in_lock_file_name (register char *lockfile, register Lisp_Object fn)
e31fbc7a 313{
c293e30c 314 ptrdiff_t length = SBYTES (fn);
8dbbc384 315 register char *p;
c1355e1f
GM
316 struct stat st;
317 int count = 0;
8dbbc384 318
42a5b22f 319 strcpy (lockfile, SSDATA (fn));
8dbbc384
RS
320
321 /* Shift the nondirectory part of the file name (including the null)
322 right two characters. Here is one of the places where we'd have to
323 do something to support 14-character-max file names. */
c293e30c 324 for (p = lockfile + length; p != lockfile && *p != '/'; p--)
8dbbc384 325 p[2] = *p;
177c0ea7 326
8dbbc384
RS
327 /* Insert the `.#'. */
328 p[1] = '.';
329 p[2] = '#';
c1355e1f 330
1938d88c 331 p = lockfile + length + 2;
c1355e1f 332
343a2aef 333 while (lstat (lockfile, &st) == 0 && !IS_LOCK_FILE (st))
c1355e1f
GM
334 {
335 if (count > 9)
336 {
337 *p = '\0';
338 return;
339 }
340 sprintf (p, ".%d", count++);
341 }
8dbbc384 342}
e31fbc7a 343
343a2aef
EZ
344static int
345create_lock_file (char *lfname, char *lock_info_str, bool force)
346{
347 int err;
348
349#ifdef WINDOWSNT
350 /* Symlinks are supported only by latest versions of Windows, and
351 creating them is a privileged operation that often triggers UAC
352 elevation prompts. Therefore, instead of using symlinks, we
353 create a regular file with the lock info written as its
354 contents. */
355 {
356 int fd = emacs_open (lfname, O_WRONLY | O_BINARY | O_CREAT | O_EXCL,
357 S_IREAD | S_IWRITE);
358
359 if (fd < 0 && errno == EEXIST && force)
360 fd = emacs_open (lfname, O_WRONLY | O_BINARY | O_TRUNC,
361 S_IREAD | S_IWRITE);
362 if (fd >= 0)
363 {
364 ssize_t lock_info_len = strlen (lock_info_str);
365
366 err = 0;
367 if (emacs_write (fd, lock_info_str, lock_info_len) != lock_info_len)
368 err = -1;
369 if (emacs_close (fd))
370 err = -1;
371 }
372 else
373 err = -1;
374 }
375#else
376 err = symlink (lock_info_str, lfname);
377 if (errno == EEXIST && force)
378 {
379 unlink (lfname);
380 err = symlink (lock_info_str, lfname);
381 }
382#endif
383
384 return err;
385}
386
8dbbc384 387/* Lock the lock file named LFNAME.
f75d7a91
PE
388 If FORCE, do so even if it is already locked.
389 Return true if successful. */
e31fbc7a 390
f75d7a91
PE
391static bool
392lock_file_1 (char *lfname, bool force)
8dbbc384 393{
98c6f1e3 394 int err;
b5cd1905
PE
395 int symlink_errno;
396 USE_SAFE_ALLOCA;
662c2ef2 397
4ba93ac0 398 /* Call this first because it can GC. */
98c6f1e3
PE
399 printmax_t boot = get_boot_time ();
400
401 Lisp_Object luser_name = Fuser_login_name (Qnil);
402 char const *user_name = STRINGP (luser_name) ? SSDATA (luser_name) : "";
403 Lisp_Object lhost_name = Fsystem_name ();
404 char const *host_name = STRINGP (lhost_name) ? SSDATA (lhost_name) : "";
405 ptrdiff_t lock_info_size = (strlen (user_name) + strlen (host_name)
406 + 2 * INT_STRLEN_BOUND (printmax_t)
407 + sizeof "@.:");
408 char *lock_info_str = SAFE_ALLOCA (lock_info_size);
409 printmax_t pid = getpid ();
8dbbc384 410
b5cd1905
PE
411 esprintf (lock_info_str, boot ? "%s@%s.%"pMd":%"pMd : "%s@%s.%"pMd,
412 user_name, host_name, pid, boot);
343a2aef 413 err = create_lock_file (lfname, lock_info_str, force);
e31fbc7a 414
b5cd1905
PE
415 symlink_errno = errno;
416 SAFE_FREE ();
417 errno = symlink_errno;
8dbbc384
RS
418 return err == 0;
419}
e31fbc7a 420
f75d7a91 421/* Return true if times A and B are no more than one second apart. */
32676c08 422
f75d7a91 423static bool
971de7fb 424within_one_second (time_t a, time_t b)
9177d978
RS
425{
426 return (a - b >= -1 && a - b <= 1);
427}
8dbbc384 428\f
343a2aef
EZ
429static Lisp_Object
430read_lock_data (char *lfname)
431{
432#ifndef WINDOWSNT
433 return emacs_readlinkat (AT_FDCWD, lfname);
434#else
435 int fd = emacs_open (lfname, O_RDONLY | O_BINARY, S_IREAD);
436 ssize_t nbytes;
437 char lfinfo[MAX_LFINFO + 1];
438
439 if (fd < 0)
440 return Qnil;
441
442 nbytes = emacs_read (fd, lfinfo, MAX_LFINFO);
443 emacs_close (fd);
444
445 if (nbytes > 0)
446 {
447 lfinfo[nbytes] = '\0';
448 return build_string (lfinfo);
449 }
450 else
451 return Qnil;
452#endif
453}
454
8dbbc384
RS
455/* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
456 1 if another process owns it (and set OWNER (if non-null) to info),
457 2 if the current process owns it,
458 or -1 if something is wrong with the locking mechanism. */
e31fbc7a 459
8dbbc384 460static int
971de7fb 461current_lock_owner (lock_info_type *owner, char *lfname)
32676c08 462{
d1fdcab7 463 int ret;
882f0d81
PE
464 ptrdiff_t len;
465 lock_info_type local_owner;
466 intmax_t n;
15e88d21 467 char *at, *dot, *colon;
343a2aef 468 Lisp_Object lfinfo_object = read_lock_data (lfname);
8654f9d7
PE
469 char *lfinfo;
470 struct gcpro gcpro1;
177c0ea7 471
8dbbc384 472 /* If nonexistent lock file, all is well; otherwise, got strange error. */
8654f9d7 473 if (NILP (lfinfo_object))
d1fdcab7 474 return errno == ENOENT ? 0 : -1;
8654f9d7 475 lfinfo = SSDATA (lfinfo_object);
177c0ea7 476
8dbbc384 477 /* Even if the caller doesn't want the owner info, we still have to
882f0d81 478 read it to determine return value. */
8dbbc384 479 if (!owner)
882f0d81 480 owner = &local_owner;
177c0ea7 481
15e88d21 482 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
50624218 483 /* The USER is everything before the last @. */
8966b757
AS
484 at = strrchr (lfinfo, '@');
485 dot = strrchr (lfinfo, '.');
15e88d21 486 if (!at || !dot)
8654f9d7 487 return -1;
8dbbc384 488 len = at - lfinfo;
8654f9d7 489 GCPRO1 (lfinfo_object);
23f86fce 490 owner->user = xmalloc (len + 1);
882f0d81 491 memcpy (owner->user, lfinfo, len);
8dbbc384 492 owner->user[len] = 0;
177c0ea7 493
15e88d21 494 /* The PID is everything from the last `.' to the `:'. */
882f0d81
PE
495 errno = 0;
496 n = strtoimax (dot + 1, NULL, 10);
497 owner->pid =
498 ((0 <= n && n <= TYPE_MAXIMUM (pid_t)
499 && (TYPE_MAXIMUM (pid_t) < INTMAX_MAX || errno != ERANGE))
500 ? n : 0);
501
502 colon = strchr (dot + 1, ':');
15e88d21 503 /* After the `:', if there is one, comes the boot time. */
882f0d81
PE
504 n = 0;
505 if (colon)
506 {
507 errno = 0;
508 n = strtoimax (colon + 1, NULL, 10);
509 }
510 owner->boot_time =
511 ((0 <= n && n <= TYPE_MAXIMUM (time_t)
512 && (TYPE_MAXIMUM (time_t) < INTMAX_MAX || errno != ERANGE))
513 ? n : 0);
32676c08 514
8dbbc384
RS
515 /* The host is everything in between. */
516 len = dot - at - 1;
23f86fce 517 owner->host = xmalloc (len + 1);
882f0d81 518 memcpy (owner->host, at + 1, len);
8dbbc384 519 owner->host[len] = 0;
32676c08 520
8dbbc384 521 /* We're done looking at the link info. */
8654f9d7 522 UNGCPRO;
177c0ea7 523
8dbbc384 524 /* On current host? */
662c2ef2 525 if (STRINGP (Fsystem_name ())
42a5b22f 526 && strcmp (owner->host, SSDATA (Fsystem_name ())) == 0)
32676c08 527 {
8dbbc384
RS
528 if (owner->pid == getpid ())
529 ret = 2; /* We own it. */
72dcef0e 530 else if (owner->pid > 0
15e88d21
RS
531 && (kill (owner->pid, 0) >= 0 || errno == EPERM)
532 && (owner->boot_time == 0
9177d978 533 || within_one_second (owner->boot_time, get_boot_time ())))
8dbbc384 534 ret = 1; /* An existing process on this machine owns it. */
8dbbc384
RS
535 /* The owner process is dead or has a strange pid (<=0), so try to
536 zap the lockfile. */
72dcef0e 537 else if (unlink (lfname) < 0)
8dbbc384 538 ret = -1;
72dcef0e
RS
539 else
540 ret = 0;
32676c08 541 }
8dbbc384
RS
542 else
543 { /* If we wanted to support the check for stale locks on remote machines,
544 here's where we'd do it. */
545 ret = 1;
546 }
177c0ea7 547
8dbbc384 548 /* Avoid garbage. */
882f0d81 549 if (owner == &local_owner || ret <= 0)
8dbbc384
RS
550 {
551 FREE_LOCK_INFO (*owner);
552 }
553 return ret;
32676c08
JB
554}
555
8dbbc384
RS
556\f
557/* Lock the lock named LFNAME if possible.
558 Return 0 in that case.
559 Return positive if some other process owns the lock, and info about
560 that process in CLASHER.
561 Return -1 if cannot lock for any other reason. */
8489eb67 562
8dbbc384 563static int
971de7fb 564lock_if_free (lock_info_type *clasher, register char *lfname)
8dbbc384 565{
f75d7a91 566 while (! lock_file_1 (lfname, 0))
8dbbc384
RS
567 {
568 int locker;
e0e0205b 569
8dbbc384
RS
570 if (errno != EEXIST)
571 return -1;
177c0ea7 572
8dbbc384
RS
573 locker = current_lock_owner (clasher, lfname);
574 if (locker == 2)
575 {
576 FREE_LOCK_INFO (*clasher);
577 return 0; /* We ourselves locked it. */
578 }
579 else if (locker == 1)
580 return 1; /* Someone else has it. */
5df0b2fa 581 else if (locker == -1)
ae1ef097 582 return -1; /* current_lock_owner returned strange error. */
8dbbc384 583
cfc01fa7 584 /* We deleted a stale lock; try again to lock the file. */
8dbbc384
RS
585 }
586 return 0;
8489eb67
RS
587}
588
8dbbc384 589/* lock_file locks file FN,
8489eb67
RS
590 meaning it serves notice on the world that you intend to edit that file.
591 This should be done only when about to modify a file-visiting
592 buffer previously unmodified.
8dbbc384 593 Do not (normally) call this for a buffer already modified,
8489eb67
RS
594 as either the file is already locked, or the user has already
595 decided to go ahead without locking.
596
8dbbc384 597 When this returns, either the lock is locked for us,
8489eb67
RS
598 or the user has said to go ahead without locking.
599
8dbbc384 600 If the file is locked by someone else, this calls
8489eb67 601 ask-user-about-lock (a Lisp function) with two arguments,
8dbbc384 602 the file name and info about the user who did the locking.
8489eb67
RS
603 This function can signal an error, or return t meaning
604 take away the lock, or return nil meaning ignore the lock. */
605
8489eb67 606void
971de7fb 607lock_file (Lisp_Object fn)
8489eb67 608{
f4a4528d 609 register Lisp_Object attack, orig_fn, encoded_fn;
8dbbc384 610 register char *lfname, *locker;
b5cd1905 611 ptrdiff_t locker_size;
8dbbc384 612 lock_info_type lock_info;
a81d11a3 613 printmax_t pid;
3edc33a4 614 struct gcpro gcpro1;
b5cd1905 615 USE_SAFE_ALLOCA;
8489eb67 616
836d29b3
DA
617 /* Don't do locking if the user has opted out. */
618 if (! create_lockfiles)
619 return;
620
33bae690
RS
621 /* Don't do locking while dumping Emacs.
622 Uncompressing wtmp files uses call-process, which does not work
623 in an uninitialized Emacs. */
624 if (! NILP (Vpurify_flag))
625 return;
626
5383bc6d 627 orig_fn = fn;
8af8a9ca 628 GCPRO1 (fn);
1e89de84 629 fn = Fexpand_file_name (fn, Qnil);
343a2aef
EZ
630#ifdef WINDOWSNT
631 /* Ensure we have only '/' separators, to avoid problems with
632 looking (inside fill_in_lock_file_name) for backslashes in file
633 names encoded by some DBCS codepage. */
634 dostounix_filename (SSDATA (fn), 1);
635#endif
f4a4528d 636 encoded_fn = ENCODE_FILE (fn);
1e89de84 637
8dbbc384 638 /* Create the name of the lock-file for file fn */
f4a4528d 639 MAKE_LOCK_NAME (lfname, encoded_fn);
8489eb67 640
32676c08
JB
641 /* See if this file is visited and has changed on disk since it was
642 visited. */
8489eb67 643 {
a57bc488 644 register Lisp_Object subject_buf;
3036594f 645
5383bc6d 646 subject_buf = get_truename_buffer (orig_fn);
3036594f 647
265a9e55
JB
648 if (!NILP (subject_buf)
649 && NILP (Fverify_visited_file_modtime (subject_buf))
650 && !NILP (Ffile_exists_p (fn)))
8489eb67 651 call1 (intern ("ask-user-about-supersession-threat"), fn);
3036594f 652
8489eb67 653 }
8af8a9ca 654 UNGCPRO;
8489eb67
RS
655
656 /* Try to lock the lock. */
8dbbc384
RS
657 if (lock_if_free (&lock_info, lfname) <= 0)
658 /* Return now if we have locked it, or if lock creation failed */
8489eb67
RS
659 return;
660
661 /* Else consider breaking the lock */
b5cd1905
PE
662 locker_size = (strlen (lock_info.user) + strlen (lock_info.host)
663 + INT_STRLEN_BOUND (printmax_t)
664 + sizeof "@ (pid )");
98c6f1e3 665 locker = SAFE_ALLOCA (locker_size);
882f0d81 666 pid = lock_info.pid;
b5cd1905
PE
667 esprintf (locker, "%s@%s (pid %"pMd")",
668 lock_info.user, lock_info.host, pid);
8dbbc384 669 FREE_LOCK_INFO (lock_info);
177c0ea7 670
8dbbc384 671 attack = call2 (intern ("ask-user-about-lock"), fn, build_string (locker));
b5cd1905 672 SAFE_FREE ();
265a9e55 673 if (!NILP (attack))
8489eb67
RS
674 /* User says take the lock */
675 {
8dbbc384 676 lock_file_1 (lfname, 1);
8489eb67
RS
677 return;
678 }
679 /* User says ignore the lock */
680}
681
8489eb67 682void
971de7fb 683unlock_file (register Lisp_Object fn)
8489eb67
RS
684{
685 register char *lfname;
686
1e89de84 687 fn = Fexpand_file_name (fn, Qnil);
88eace34 688 fn = ENCODE_FILE (fn);
1e89de84 689
7b92975f 690 MAKE_LOCK_NAME (lfname, fn);
8489eb67 691
8dbbc384 692 if (current_lock_owner (0, lfname) == 2)
8489eb67 693 unlink (lfname);
8489eb67
RS
694}
695
696void
971de7fb 697unlock_all_files (void)
8489eb67
RS
698{
699 register Lisp_Object tail;
700 register struct buffer *b;
701
8e50cc2d 702 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
8489eb67 703 {
03699b14 704 b = XBUFFER (XCDR (XCAR (tail)));
4b4deea2 705 if (STRINGP (BVAR (b, file_truename)) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
1c343051 706 {
5e617bc2 707 unlock_file (BVAR (b, file_truename));
1c343051 708 }
8489eb67
RS
709 }
710}
8489eb67
RS
711\f
712DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
335c5470
PJ
713 0, 1, 0,
714 doc: /* Lock FILE, if current buffer is modified.
715FILE defaults to current buffer's visited file,
716or else nothing is done if current buffer isn't visiting a file. */)
5842a27b 717 (Lisp_Object file)
8489eb67 718{
e9319ef2 719 if (NILP (file))
4b4deea2 720 file = BVAR (current_buffer, file_truename);
8489eb67 721 else
b7826503 722 CHECK_STRING (file);
6a140159 723 if (SAVE_MODIFF < MODIFF
e9319ef2
EN
724 && !NILP (file))
725 lock_file (file);
177c0ea7 726 return Qnil;
8489eb67
RS
727}
728
a7ca3326 729DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
335c5470 730 0, 0, 0,
3bfb8921
RS
731 doc: /* Unlock the file visited in the current buffer.
732If the buffer is not modified, this does nothing because the file
733should not be locked in that case. */)
5842a27b 734 (void)
8489eb67 735{
6a140159 736 if (SAVE_MODIFF < MODIFF
4b4deea2
TT
737 && STRINGP (BVAR (current_buffer, file_truename)))
738 unlock_file (BVAR (current_buffer, file_truename));
8489eb67
RS
739 return Qnil;
740}
741
8489eb67
RS
742/* Unlock the file visited in buffer BUFFER. */
743
d07e0802 744void
971de7fb 745unlock_buffer (struct buffer *buffer)
8489eb67 746{
6a140159 747 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
4b4deea2
TT
748 && STRINGP (BVAR (buffer, file_truename)))
749 unlock_file (BVAR (buffer, file_truename));
8489eb67
RS
750}
751
8105cbf7 752DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
3bfb8921
RS
753 doc: /* Return a value indicating whether FILENAME is locked.
754The value is nil if the FILENAME is not locked,
755t if it is locked by you, else a string saying which user has locked it. */)
5842a27b 756 (Lisp_Object filename)
8489eb67 757{
8dbbc384 758 Lisp_Object ret;
8489eb67
RS
759 register char *lfname;
760 int owner;
8dbbc384 761 lock_info_type locker;
8489eb67 762
e9319ef2 763 filename = Fexpand_file_name (filename, Qnil);
8489eb67 764
e9319ef2 765 MAKE_LOCK_NAME (lfname, filename);
8489eb67 766
8dbbc384 767 owner = current_lock_owner (&locker, lfname);
8489eb67 768 if (owner <= 0)
8dbbc384
RS
769 ret = Qnil;
770 else if (owner == 2)
771 ret = Qt;
772 else
773 ret = build_string (locker.user);
774
775 if (owner > 0)
776 FREE_LOCK_INFO (locker);
777
778 return ret;
8489eb67 779}
a3fd58aa 780
ffe75e6b
EZ
781#endif /* CLASH_DETECTION */
782
dfcf069d 783void
971de7fb 784syms_of_filelock (void)
8489eb67 785{
29208e82 786 DEFVAR_LISP ("temporary-file-directory", Vtemporary_file_directory,
335c5470 787 doc: /* The directory for writing temporary files. */);
5f8d6a10
RS
788 Vtemporary_file_directory = Qnil;
789
836d29b3
DA
790 DEFVAR_BOOL ("create-lockfiles", create_lockfiles,
791 doc: /* Non-nil means use lockfiles to avoid editing collisions. */);
792 create_lockfiles = 1;
793
ffe75e6b 794#ifdef CLASH_DETECTION
8489eb67
RS
795 defsubr (&Sunlock_buffer);
796 defsubr (&Slock_buffer);
797 defsubr (&Sfile_locked_p);
ffe75e6b 798#endif
8489eb67 799}