Merge changes from emacs-23 branch
[bpt/emacs.git] / src / filelock.c
1 /* Lock files for editing.
2 Copyright (C) 1985, 1986, 1987, 1993, 1994, 1996, 1998, 1999, 2000, 2001,
3 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <signal.h>
26 #include <stdio.h>
27 #include <setjmp.h>
28
29 #ifdef HAVE_PWD_H
30 #include <pwd.h>
31 #endif
32
33 #include <sys/file.h>
34 #ifdef HAVE_FCNTL_H
35 #include <fcntl.h>
36 #endif
37 #include <string.h>
38
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 #ifdef __FreeBSD__
44 #include <sys/sysctl.h>
45 #endif /* __FreeBSD__ */
46
47 #include <errno.h>
48
49 #include "lisp.h"
50 #include "buffer.h"
51 #include "character.h"
52 #include "coding.h"
53 #include "systime.h"
54
55 /* The directory for writing temporary files. */
56
57 Lisp_Object Vtemporary_file_directory;
58
59 #ifdef CLASH_DETECTION
60
61 #ifdef HAVE_UTMP_H
62 #include <utmp.h>
63 #endif
64
65 #if !defined (S_ISLNK) && defined (S_IFLNK)
66 #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
67 #endif
68
69 /* A file whose last-modified time is just after the most recent boot.
70 Define this to be NULL to disable checking for this file. */
71 #ifndef BOOT_TIME_FILE
72 #define BOOT_TIME_FILE "/var/run/random-seed"
73 #endif
74
75 #ifndef WTMP_FILE
76 #define WTMP_FILE "/var/log/wtmp"
77 #endif
78
79 /* The strategy: to lock a file FN, create a symlink .#FN in FN's
80 directory, with link data `user@host.pid'. This avoids a single
81 mount (== failure) point for lock files.
82
83 When the host in the lock data is the current host, we can check if
84 the pid is valid with kill.
85
86 Otherwise, we could look at a separate file that maps hostnames to
87 reboot times to see if the remote pid can possibly be valid, since we
88 don't want Emacs to have to communicate via pipes or sockets or
89 whatever to other processes, either locally or remotely; rms says
90 that's too unreliable. Hence the separate file, which could
91 theoretically be updated by daemons running separately -- but this
92 whole idea is unimplemented; in practice, at least in our
93 environment, it seems such stale locks arise fairly infrequently, and
94 Emacs' standard methods of dealing with clashes suffice.
95
96 We use symlinks instead of normal files because (1) they can be
97 stored more efficiently on the filesystem, since the kernel knows
98 they will be small, and (2) all the info about the lock can be read
99 in a single system call (readlink). Although we could use regular
100 files to be useful on old systems lacking symlinks, nowadays
101 virtually all such systems are probably single-user anyway, so it
102 didn't seem worth the complication.
103
104 Similarly, we don't worry about a possible 14-character limit on
105 file names, because those are all the same systems that don't have
106 symlinks.
107
108 This is compatible with the locking scheme used by Interleaf (which
109 has contributed this implementation for Emacs), and was designed by
110 Ethan Jacobson, Kimbo Mundy, and others.
111
112 --karl@cs.umb.edu/karl@hq.ileaf.com. */
113
114 \f
115 /* Return the time of the last system boot. */
116
117 static time_t boot_time;
118 static int boot_time_initialized;
119
120 #ifdef BOOT_TIME
121 static void get_boot_time_1 (char *, int);
122 #endif
123
124 static time_t
125 get_boot_time (void)
126 {
127 #if defined (BOOT_TIME)
128 int counter;
129 #endif
130
131 if (boot_time_initialized)
132 return boot_time;
133 boot_time_initialized = 1;
134
135 #if defined (CTL_KERN) && defined (KERN_BOOTTIME)
136 {
137 int mib[2];
138 size_t size;
139 struct timeval boottime_val;
140
141 mib[0] = CTL_KERN;
142 mib[1] = KERN_BOOTTIME;
143 size = sizeof (boottime_val);
144
145 if (sysctl (mib, 2, &boottime_val, &size, NULL, 0) >= 0)
146 {
147 boot_time = boottime_val.tv_sec;
148 return boot_time;
149 }
150 }
151 #endif /* defined (CTL_KERN) && defined (KERN_BOOTTIME) */
152
153 if (BOOT_TIME_FILE)
154 {
155 struct stat st;
156 if (stat (BOOT_TIME_FILE, &st) == 0)
157 {
158 boot_time = st.st_mtime;
159 return boot_time;
160 }
161 }
162
163 #if defined (BOOT_TIME)
164 #ifndef CANNOT_DUMP
165 /* The utmp routines maintain static state.
166 Don't touch that state unless we are initialized,
167 since it might not survive dumping. */
168 if (! initialized)
169 return boot_time;
170 #endif /* not CANNOT_DUMP */
171
172 /* Try to get boot time from utmp before wtmp,
173 since utmp is typically much smaller than wtmp.
174 Passing a null pointer causes get_boot_time_1
175 to inspect the default file, namely utmp. */
176 get_boot_time_1 ((char *) 0, 0);
177 if (boot_time)
178 return boot_time;
179
180 /* Try to get boot time from the current wtmp file. */
181 get_boot_time_1 (WTMP_FILE, 1);
182
183 /* If we did not find a boot time in wtmp, look at wtmp, and so on. */
184 for (counter = 0; counter < 20 && ! boot_time; counter++)
185 {
186 char cmd_string[100];
187 Lisp_Object tempname, filename;
188 int delete_flag = 0;
189
190 filename = Qnil;
191
192 sprintf (cmd_string, "%s.%d", WTMP_FILE, counter);
193 tempname = build_string (cmd_string);
194 if (! NILP (Ffile_exists_p (tempname)))
195 filename = tempname;
196 else
197 {
198 sprintf (cmd_string, "%s.%d.gz", WTMP_FILE, counter);
199 tempname = build_string (cmd_string);
200 if (! NILP (Ffile_exists_p (tempname)))
201 {
202 Lisp_Object args[6];
203
204 /* The utmp functions on mescaline.gnu.org accept only
205 file names up to 8 characters long. Choose a 2
206 character long prefix, and call make_temp_file with
207 second arg non-zero, so that it will add not more
208 than 6 characters to the prefix. */
209 tempname = Fexpand_file_name (build_string ("wt"),
210 Vtemporary_file_directory);
211 tempname = make_temp_name (tempname, 1);
212 args[0] = Vshell_file_name;
213 args[1] = Qnil;
214 args[2] = Qnil;
215 args[3] = Qnil;
216 args[4] = build_string ("-c");
217 sprintf (cmd_string, "gunzip < %s.%d.gz > %s",
218 WTMP_FILE, counter, SDATA (tempname));
219 args[5] = build_string (cmd_string);
220 Fcall_process (6, args);
221 filename = tempname;
222 delete_flag = 1;
223 }
224 }
225
226 if (! NILP (filename))
227 {
228 get_boot_time_1 (SDATA (filename), 1);
229 if (delete_flag)
230 unlink (SDATA (filename));
231 }
232 }
233
234 return boot_time;
235 #else
236 return 0;
237 #endif
238 }
239
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.
243
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 is nonzero,
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. */
250
251 void
252 get_boot_time_1 (char *filename, int newest)
253 {
254 struct utmp ut, *utp;
255 int desc;
256
257 if (filename)
258 {
259 /* On some versions of IRIX, opening a nonexistent file name
260 is likely to crash in the utmp routines. */
261 desc = emacs_open (filename, O_RDONLY, 0);
262 if (desc < 0)
263 return;
264
265 emacs_close (desc);
266
267 utmpname (filename);
268 }
269
270 setutent ();
271
272 while (1)
273 {
274 /* Find the next reboot record. */
275 ut.ut_type = BOOT_TIME;
276 utp = getutid (&ut);
277 if (! utp)
278 break;
279 /* Compare reboot times and use the newest one. */
280 if (utp->ut_time > boot_time)
281 {
282 boot_time = utp->ut_time;
283 if (! newest)
284 break;
285 }
286 /* Advance on element in the file
287 so that getutid won't repeat the same one. */
288 utp = getutent ();
289 if (! utp)
290 break;
291 }
292 endutent ();
293 }
294 #endif /* BOOT_TIME */
295 \f
296 /* Here is the structure that stores information about a lock. */
297
298 typedef struct
299 {
300 char *user;
301 char *host;
302 unsigned long pid;
303 time_t boot_time;
304 } lock_info_type;
305
306 /* When we read the info back, we might need this much more,
307 enough for decimal representation plus null. */
308 #define LOCK_PID_MAX (4 * sizeof (unsigned long))
309
310 /* Free the two dynamically-allocated pieces in PTR. */
311 #define FREE_LOCK_INFO(i) do { xfree ((i).user); xfree ((i).host); } while (0)
312
313
314 /* Write the name of the lock file for FN into LFNAME. Length will be
315 that of FN plus two more for the leading `.#' plus 1 for the
316 trailing period plus one for the digit after it plus one for the
317 null. */
318 #define MAKE_LOCK_NAME(lock, file) \
319 (lock = (char *) alloca (SBYTES (file) + 2 + 1 + 1 + 1), \
320 fill_in_lock_file_name (lock, (file)))
321
322 static void
323 fill_in_lock_file_name (register char *lockfile, register Lisp_Object fn)
324 {
325 register char *p;
326 struct stat st;
327 int count = 0;
328
329 strcpy (lockfile, SDATA (fn));
330
331 /* Shift the nondirectory part of the file name (including the null)
332 right two characters. Here is one of the places where we'd have to
333 do something to support 14-character-max file names. */
334 for (p = lockfile + strlen (lockfile); p != lockfile && *p != '/'; p--)
335 p[2] = *p;
336
337 /* Insert the `.#'. */
338 p[1] = '.';
339 p[2] = '#';
340
341 p = p + strlen (p);
342
343 while (lstat (lockfile, &st) == 0 && !S_ISLNK (st.st_mode))
344 {
345 if (count > 9)
346 {
347 *p = '\0';
348 return;
349 }
350 sprintf (p, ".%d", count++);
351 }
352 }
353
354 /* Lock the lock file named LFNAME.
355 If FORCE is nonzero, we do so even if it is already locked.
356 Return 1 if successful, 0 if not. */
357
358 static int
359 lock_file_1 (char *lfname, int force)
360 {
361 register int err;
362 time_t boot_time;
363 char *user_name;
364 char *host_name;
365 char *lock_info_str;
366
367 /* Call this first because it can GC. */
368 boot_time = get_boot_time ();
369
370 if (STRINGP (Fuser_login_name (Qnil)))
371 user_name = (char *)SDATA (Fuser_login_name (Qnil));
372 else
373 user_name = "";
374 if (STRINGP (Fsystem_name ()))
375 host_name = (char *)SDATA (Fsystem_name ());
376 else
377 host_name = "";
378 lock_info_str = (char *)alloca (strlen (user_name) + strlen (host_name)
379 + LOCK_PID_MAX + 30);
380
381 if (boot_time)
382 sprintf (lock_info_str, "%s@%s.%lu:%lu", user_name, host_name,
383 (unsigned long) getpid (), (unsigned long) boot_time);
384 else
385 sprintf (lock_info_str, "%s@%s.%lu", user_name, host_name,
386 (unsigned long) getpid ());
387
388 err = symlink (lock_info_str, lfname);
389 if (errno == EEXIST && force)
390 {
391 unlink (lfname);
392 err = symlink (lock_info_str, lfname);
393 }
394
395 return err == 0;
396 }
397
398 /* Return 1 if times A and B are no more than one second apart. */
399
400 int
401 within_one_second (time_t a, time_t b)
402 {
403 return (a - b >= -1 && a - b <= 1);
404 }
405 \f
406 /* Return 0 if nobody owns the lock file LFNAME or the lock is obsolete,
407 1 if another process owns it (and set OWNER (if non-null) to info),
408 2 if the current process owns it,
409 or -1 if something is wrong with the locking mechanism. */
410
411 static int
412 current_lock_owner (lock_info_type *owner, char *lfname)
413 {
414 int len, ret;
415 int local_owner = 0;
416 char *at, *dot, *colon;
417 char *lfinfo = 0;
418 int bufsize = 50;
419 /* Read arbitrarily-long contents of symlink. Similar code in
420 file-symlink-p in fileio.c. */
421 do
422 {
423 bufsize *= 2;
424 lfinfo = (char *) xrealloc (lfinfo, bufsize);
425 errno = 0;
426 len = readlink (lfname, lfinfo, bufsize);
427 #ifdef ERANGE
428 /* HP-UX reports ERANGE if the buffer is too small. */
429 if (len == -1 && errno == ERANGE)
430 len = bufsize;
431 #endif
432 }
433 while (len >= bufsize);
434
435 /* If nonexistent lock file, all is well; otherwise, got strange error. */
436 if (len == -1)
437 {
438 xfree (lfinfo);
439 return errno == ENOENT ? 0 : -1;
440 }
441
442 /* Link info exists, so `len' is its length. Null terminate. */
443 lfinfo[len] = 0;
444
445 /* Even if the caller doesn't want the owner info, we still have to
446 read it to determine return value, so allocate it. */
447 if (!owner)
448 {
449 owner = (lock_info_type *) alloca (sizeof (lock_info_type));
450 local_owner = 1;
451 }
452
453 /* Parse USER@HOST.PID:BOOT_TIME. If can't parse, return -1. */
454 /* The USER is everything before the last @. */
455 at = strrchr (lfinfo, '@');
456 dot = strrchr (lfinfo, '.');
457 if (!at || !dot)
458 {
459 xfree (lfinfo);
460 return -1;
461 }
462 len = at - lfinfo;
463 owner->user = (char *) xmalloc (len + 1);
464 strncpy (owner->user, lfinfo, len);
465 owner->user[len] = 0;
466
467 /* The PID is everything from the last `.' to the `:'. */
468 owner->pid = atoi (dot + 1);
469 colon = dot;
470 while (*colon && *colon != ':')
471 colon++;
472 /* After the `:', if there is one, comes the boot time. */
473 if (*colon == ':')
474 owner->boot_time = atoi (colon + 1);
475 else
476 owner->boot_time = 0;
477
478 /* The host is everything in between. */
479 len = dot - at - 1;
480 owner->host = (char *) xmalloc (len + 1);
481 strncpy (owner->host, at + 1, len);
482 owner->host[len] = 0;
483
484 /* We're done looking at the link info. */
485 xfree (lfinfo);
486
487 /* On current host? */
488 if (STRINGP (Fsystem_name ())
489 && strcmp (owner->host, SDATA (Fsystem_name ())) == 0)
490 {
491 if (owner->pid == getpid ())
492 ret = 2; /* We own it. */
493 else if (owner->pid > 0
494 && (kill (owner->pid, 0) >= 0 || errno == EPERM)
495 && (owner->boot_time == 0
496 || within_one_second (owner->boot_time, get_boot_time ())))
497 ret = 1; /* An existing process on this machine owns it. */
498 /* The owner process is dead or has a strange pid (<=0), so try to
499 zap the lockfile. */
500 else if (unlink (lfname) < 0)
501 ret = -1;
502 else
503 ret = 0;
504 }
505 else
506 { /* If we wanted to support the check for stale locks on remote machines,
507 here's where we'd do it. */
508 ret = 1;
509 }
510
511 /* Avoid garbage. */
512 if (local_owner || ret <= 0)
513 {
514 FREE_LOCK_INFO (*owner);
515 }
516 return ret;
517 }
518
519 \f
520 /* Lock the lock named LFNAME if possible.
521 Return 0 in that case.
522 Return positive if some other process owns the lock, and info about
523 that process in CLASHER.
524 Return -1 if cannot lock for any other reason. */
525
526 static int
527 lock_if_free (lock_info_type *clasher, register char *lfname)
528 {
529 while (lock_file_1 (lfname, 0) == 0)
530 {
531 int locker;
532
533 if (errno != EEXIST)
534 return -1;
535
536 locker = current_lock_owner (clasher, lfname);
537 if (locker == 2)
538 {
539 FREE_LOCK_INFO (*clasher);
540 return 0; /* We ourselves locked it. */
541 }
542 else if (locker == 1)
543 return 1; /* Someone else has it. */
544 else if (locker == -1)
545 return -1; /* current_lock_owner returned strange error. */
546
547 /* We deleted a stale lock; try again to lock the file. */
548 }
549 return 0;
550 }
551
552 /* lock_file locks file FN,
553 meaning it serves notice on the world that you intend to edit that file.
554 This should be done only when about to modify a file-visiting
555 buffer previously unmodified.
556 Do not (normally) call this for a buffer already modified,
557 as either the file is already locked, or the user has already
558 decided to go ahead without locking.
559
560 When this returns, either the lock is locked for us,
561 or the user has said to go ahead without locking.
562
563 If the file is locked by someone else, this calls
564 ask-user-about-lock (a Lisp function) with two arguments,
565 the file name and info about the user who did the locking.
566 This function can signal an error, or return t meaning
567 take away the lock, or return nil meaning ignore the lock. */
568
569 void
570 lock_file (Lisp_Object fn)
571 {
572 register Lisp_Object attack, orig_fn, encoded_fn;
573 register char *lfname, *locker;
574 lock_info_type lock_info;
575 struct gcpro gcpro1;
576
577 /* Don't do locking while dumping Emacs.
578 Uncompressing wtmp files uses call-process, which does not work
579 in an uninitialized Emacs. */
580 if (! NILP (Vpurify_flag))
581 return;
582
583 orig_fn = fn;
584 GCPRO1 (fn);
585 fn = Fexpand_file_name (fn, Qnil);
586 encoded_fn = ENCODE_FILE (fn);
587
588 /* Create the name of the lock-file for file fn */
589 MAKE_LOCK_NAME (lfname, encoded_fn);
590
591 /* See if this file is visited and has changed on disk since it was
592 visited. */
593 {
594 register Lisp_Object subject_buf;
595
596 subject_buf = get_truename_buffer (orig_fn);
597
598 if (!NILP (subject_buf)
599 && NILP (Fverify_visited_file_modtime (subject_buf))
600 && !NILP (Ffile_exists_p (fn)))
601 call1 (intern ("ask-user-about-supersession-threat"), fn);
602
603 }
604 UNGCPRO;
605
606 /* Try to lock the lock. */
607 if (lock_if_free (&lock_info, lfname) <= 0)
608 /* Return now if we have locked it, or if lock creation failed */
609 return;
610
611 /* Else consider breaking the lock */
612 locker = (char *) alloca (strlen (lock_info.user) + strlen (lock_info.host)
613 + LOCK_PID_MAX + 9);
614 sprintf (locker, "%s@%s (pid %lu)", lock_info.user, lock_info.host,
615 lock_info.pid);
616 FREE_LOCK_INFO (lock_info);
617
618 attack = call2 (intern ("ask-user-about-lock"), fn, build_string (locker));
619 if (!NILP (attack))
620 /* User says take the lock */
621 {
622 lock_file_1 (lfname, 1);
623 return;
624 }
625 /* User says ignore the lock */
626 }
627
628 void
629 unlock_file (register Lisp_Object fn)
630 {
631 register char *lfname;
632
633 fn = Fexpand_file_name (fn, Qnil);
634 fn = ENCODE_FILE (fn);
635
636 MAKE_LOCK_NAME (lfname, fn);
637
638 if (current_lock_owner (0, lfname) == 2)
639 unlink (lfname);
640 }
641
642 void
643 unlock_all_files (void)
644 {
645 register Lisp_Object tail;
646 register struct buffer *b;
647
648 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
649 {
650 b = XBUFFER (XCDR (XCAR (tail)));
651 if (STRINGP (b->file_truename) && BUF_SAVE_MODIFF (b) < BUF_MODIFF (b))
652 {
653 unlock_file(b->file_truename);
654 }
655 }
656 }
657 \f
658 DEFUN ("lock-buffer", Flock_buffer, Slock_buffer,
659 0, 1, 0,
660 doc: /* Lock FILE, if current buffer is modified.
661 FILE defaults to current buffer's visited file,
662 or else nothing is done if current buffer isn't visiting a file. */)
663 (Lisp_Object file)
664 {
665 if (NILP (file))
666 file = current_buffer->file_truename;
667 else
668 CHECK_STRING (file);
669 if (SAVE_MODIFF < MODIFF
670 && !NILP (file))
671 lock_file (file);
672 return Qnil;
673 }
674
675 DEFUN ("unlock-buffer", Funlock_buffer, Sunlock_buffer,
676 0, 0, 0,
677 doc: /* Unlock the file visited in the current buffer.
678 If the buffer is not modified, this does nothing because the file
679 should not be locked in that case. */)
680 (void)
681 {
682 if (SAVE_MODIFF < MODIFF
683 && STRINGP (current_buffer->file_truename))
684 unlock_file (current_buffer->file_truename);
685 return Qnil;
686 }
687
688 /* Unlock the file visited in buffer BUFFER. */
689
690 void
691 unlock_buffer (struct buffer *buffer)
692 {
693 if (BUF_SAVE_MODIFF (buffer) < BUF_MODIFF (buffer)
694 && STRINGP (buffer->file_truename))
695 unlock_file (buffer->file_truename);
696 }
697
698 DEFUN ("file-locked-p", Ffile_locked_p, Sfile_locked_p, 1, 1, 0,
699 doc: /* Return a value indicating whether FILENAME is locked.
700 The value is nil if the FILENAME is not locked,
701 t if it is locked by you, else a string saying which user has locked it. */)
702 (Lisp_Object filename)
703 {
704 Lisp_Object ret;
705 register char *lfname;
706 int owner;
707 lock_info_type locker;
708
709 filename = Fexpand_file_name (filename, Qnil);
710
711 MAKE_LOCK_NAME (lfname, filename);
712
713 owner = current_lock_owner (&locker, lfname);
714 if (owner <= 0)
715 ret = Qnil;
716 else if (owner == 2)
717 ret = Qt;
718 else
719 ret = build_string (locker.user);
720
721 if (owner > 0)
722 FREE_LOCK_INFO (locker);
723
724 return ret;
725 }
726 \f
727 /* Initialization functions. */
728
729 void
730 init_filelock (void)
731 {
732 boot_time = 0;
733 boot_time_initialized = 0;
734 }
735
736 void
737 syms_of_filelock (void)
738 {
739 DEFVAR_LISP ("temporary-file-directory", &Vtemporary_file_directory,
740 doc: /* The directory for writing temporary files. */);
741 Vtemporary_file_directory = Qnil;
742
743 defsubr (&Sunlock_buffer);
744 defsubr (&Slock_buffer);
745 defsubr (&Sfile_locked_p);
746 }
747
748 #endif /* CLASH_DETECTION */
749
750 /* arch-tag: e062676d-50b2-4be0-ab96-197c81b181a1
751 (do not change this comment) */