5cd187243acf69cc722e0424e59ccafcd1524d87
[mmh] / sbr / lock_file.c
1
2 /*
3  * lock.c -- routines to lock/unlock files
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 /* Modified by Ruud de Rooij to support Miquel van Smoorenburg's liblockfile
13  *
14  * Since liblockfile locking shares most of its code with dot locking, it
15  * is enabled by defining both DOT_LOCKING and HAVE_LIBLOCKFILE.
16  *
17  * Ruud de Rooij <ruud@debian.org>  Sun, 28 Mar 1999 15:34:03 +0200
18  */
19  
20 #include <h/mh.h>
21 #include <h/signals.h>
22
23 #ifdef TIME_WITH_SYS_TIME
24 # include <sys/time.h>
25 # include <time.h>
26 #else
27 # ifdef TM_IN_SYS_TIME
28 #  include <sys/time.h>
29 # else
30 #  include <time.h>
31 # endif
32 #endif
33
34 #ifdef HAVE_ERRNO_H
35 # include <errno.h>
36 #endif
37
38 #ifdef MMDFONLY
39 # include <mmdfonly.h>
40 # include <lockonly.h>
41 #endif /* MMDFONLY */
42
43 #ifdef HAVE_FCNTL_H
44 # include <fcntl.h>
45 #else
46 # include <sys/file.h>
47 #endif
48
49 #if defined(LOCKF_LOCKING) || defined(FLOCK_LOCKING)
50 # include <sys/file.h>
51 #endif
52
53 #include <signal.h>
54
55 #if defined(HAVE_LIBLOCKFILE)
56 #include <lockfile.h>
57 #endif
58
59 extern int errno;
60
61 #ifdef LOCKDIR
62 char *lockdir = LOCKDIR;
63 #endif
64
65 /* Are we using any kernel locking? */
66 #if defined (FLOCK_LOCKING) || defined(LOCKF_LOCKING) || defined(FCNTL_LOCKING)
67 # define KERNEL_LOCKING
68 #endif
69
70 #ifdef DOT_LOCKING
71
72 /* struct for getting name of lock file to create */
73 struct lockinfo {
74     char curlock[BUFSIZ];
75 #if !defined(HAVE_LIBLOCKFILE)
76     char tmplock[BUFSIZ];
77 #endif
78 };
79
80 /*
81  * Amount of time to wait before
82  * updating ctime of lock file.
83  */
84 #define NSECS 20
85
86 #if !defined(HAVE_LIBLOCKFILE)
87 /*
88  * How old does a lock file need to be
89  * before we remove it.
90  */
91 #define RSECS 180
92 #endif /* HAVE_LIBLOCKFILE */
93
94 /* struct for recording and updating locks */
95 struct lock {
96     int l_fd;
97     char *l_lock;
98     struct lock *l_next;
99 };
100
101 /* top of list containing all open locks */
102 static struct lock *l_top = NULL;
103 #endif /* DOT_LOCKING */
104
105 /*
106  * static prototypes
107  */
108 #ifdef KERNEL_LOCKING
109 static int lkopen_kernel (char *, int, mode_t);
110 #endif
111
112 #ifdef DOT_LOCKING
113 static int lkopen_dot (char *, int, mode_t);
114 static int lockit (struct lockinfo *);
115 static void lockname (char *, struct lockinfo *, int);
116 static void timerON (char *, int);
117 static void timerOFF (int);
118 static RETSIGTYPE alrmser (int);
119 #endif
120
121
122 /*
123  * Base routine to open and lock a file,
124  * and return a file descriptor.
125  */
126
127 int
128 lkopen (char *file, int access, mode_t mode)
129 {
130 #ifdef KERNEL_LOCKING
131     return lkopen_kernel(file, access, mode);
132 #endif
133
134 #ifdef DOT_LOCKING
135     return lkopen_dot(file, access, mode);
136 #endif
137 }
138
139
140 /*
141  * Base routine to close and unlock a file,
142  * given a file descriptor.
143  */
144
145 int
146 lkclose (int fd, char *file)
147 {
148 #ifdef FCNTL_LOCKING
149     struct flock buf;
150 #endif
151
152 #ifdef DOT_LOCKING
153     struct lockinfo lkinfo;
154 #endif
155
156     if (fd == -1)
157         return 0;
158
159 #ifdef FCNTL_LOCKING
160     buf.l_type   = F_UNLCK;
161     buf.l_whence = SEEK_SET;
162     buf.l_start  = 0;
163     buf.l_len    = 0;
164     fcntl(fd, F_SETLK, &buf);
165 #endif
166
167 #ifdef FLOCK_LOCKING
168     flock (fd, LOCK_UN);
169 #endif
170
171 #ifdef LOCKF_LOCKING
172     /* make sure we unlock the whole thing */
173     lseek (fd, (off_t) 0, SEEK_SET);
174     lockf (fd, F_ULOCK, 0L);
175 #endif  
176
177 #ifdef DOT_LOCKING
178     lockname (file, &lkinfo, 0);        /* get name of lock file */
179 #if !defined(HAVE_LIBLOCKFILE)
180     unlink (lkinfo.curlock);            /* remove lock file      */
181 #else
182     lockfile_remove(lkinfo.curlock);
183 #endif /* HAVE_LIBLOCKFILE */
184     timerOFF (fd);                      /* turn off lock timer   */
185 #endif /* DOT_LOCKING */
186
187     return (close (fd));
188 }
189
190
191 /*
192  * Base routine to open and lock a file,
193  * and return a FILE pointer
194  */
195
196 FILE *
197 lkfopen (char *file, char *mode)
198 {
199     int fd, access;
200     FILE *fp;
201
202     if (strcmp (mode, "r") == 0)
203         access = O_RDONLY;
204     else if (strcmp (mode, "r+") == 0)
205         access = O_RDWR;
206     else if (strcmp (mode, "w") == 0)
207         access = O_WRONLY | O_CREAT | O_TRUNC;
208     else if (strcmp (mode, "w+") == 0)
209         access = O_RDWR | O_CREAT | O_TRUNC;
210     else if (strcmp (mode, "a") == 0)
211         access = O_WRONLY | O_CREAT | O_APPEND;
212     else if (strcmp (mode, "a+") == 0)
213         access = O_RDWR | O_CREAT | O_APPEND;
214     else {
215         errno = EINVAL;
216         return NULL;
217     }
218
219     if ((fd = lkopen (file, access, 0666)) == -1)
220         return NULL;
221
222     if ((fp = fdopen (fd, mode)) == NULL) {
223         close (fd);
224         return NULL;
225     }
226
227     return fp;
228 }
229
230
231 /*
232  * Base routine to close and unlock a file,
233  * given a FILE pointer
234  */
235
236 int
237 lkfclose (FILE *fp, char *file)
238 {
239 #ifdef FCNTL_LOCKING
240     struct flock buf;
241 #endif
242
243 #ifdef DOT_LOCKING
244     struct lockinfo lkinfo;
245 #endif
246
247     if (fp == NULL)
248         return 0;
249
250 #ifdef FCNTL_LOCKING
251     buf.l_type   = F_UNLCK;
252     buf.l_whence = SEEK_SET;
253     buf.l_start  = 0;
254     buf.l_len    = 0;
255     fcntl(fileno(fp), F_SETLK, &buf);
256 #endif
257
258 #ifdef FLOCK_LOCKING
259     flock (fileno(fp), LOCK_UN);
260 #endif
261
262 #ifdef LOCKF_LOCKING
263     /* make sure we unlock the whole thing */
264     fseek (fp, 0L, SEEK_SET);
265     lockf (fileno(fp), F_ULOCK, 0L);
266 #endif
267
268 #ifdef DOT_LOCKING
269     lockname (file, &lkinfo, 0);        /* get name of lock file */
270 #if !defined(HAVE_LIBLOCKFILE)
271     unlink (lkinfo.curlock);            /* remove lock file      */
272 #else
273     lockfile_remove(lkinfo.curlock);
274 #endif /* HAVE_LIBLOCKFILE */
275     timerOFF (fileno(fp));              /* turn off lock timer   */
276 #endif /* DOT_LOCKING */
277
278     return (fclose (fp));
279 }
280
281
282 #ifdef KERNEL_LOCKING
283
284 /*
285  * open and lock a file, using kernel locking
286  */
287
288 static int
289 lkopen_kernel (char *file, int access, mode_t mode)
290 {
291     int fd, i, j;
292
293 # ifdef FCNTL_LOCKING
294     struct flock buf;
295 # endif /* FCNTL_LOCKING */
296
297     for (i = 0; i < 5; i++) {
298
299 # if defined(LOCKF_LOCKING) || defined(FCNTL_LOCKING)
300         /* remember the original mode */
301         j = access;
302
303         /* make sure we open at the beginning */
304         access &= ~O_APPEND;
305
306         /*
307          * We MUST have write permission or
308          * lockf/fcntl() won't work
309          */
310         if ((access & 03) == O_RDONLY) {
311             access &= ~O_RDONLY;
312             access |= O_RDWR;
313         }
314 # endif /* LOCKF_LOCKING || FCNTL_LOCKING */
315
316         if ((fd = open (file, access | O_NDELAY, mode)) == -1)
317             return -1;
318
319 # ifdef FCNTL_LOCKING
320         buf.l_type   = F_WRLCK;
321         buf.l_whence = SEEK_SET;
322         buf.l_start  = 0;
323         buf.l_len    = 0;
324         if (fcntl (fd, F_SETLK, &buf) != -1)
325             return fd;
326 # endif
327
328 # ifdef FLOCK_LOCKING
329         if (flock (fd, (((access & 03) == O_RDONLY) ? LOCK_SH : LOCK_EX)
330                    | LOCK_NB) != -1)
331             return fd;
332 # endif
333
334 # ifdef LOCKF_LOCKING
335         if (lockf (fd, F_TLOCK, 0L) != -1) {
336             /* see if we should be at the end */
337             if (j & O_APPEND)
338                 lseek (fd, (off_t) 0, SEEK_END);
339             return fd;
340         }
341 # endif
342
343         j = errno;
344         close (fd);
345         admonish (file, "lock did not succeed, waiting");
346         sleep (5);
347     }
348
349     close (fd);
350     errno = j;
351     return -1;
352 }
353
354 #endif /* KERNEL_LOCKING */
355
356
357 #ifdef DOT_LOCKING
358
359 /*
360  * open and lock a file, using dot locking
361  */
362
363 static int
364 lkopen_dot (char *file, int access, mode_t mode)
365 {
366     int i, fd;
367     time_t curtime;
368     struct lockinfo lkinfo;
369     struct stat st;
370
371     /* open the file */
372     if ((fd = open (file, access, mode)) == -1)
373         return -1;
374
375     /*
376      * Get the name of the eventual lock file, as well
377      * as a name for a temporary lock file.
378      */
379     lockname (file, &lkinfo, 1);
380
381 #if !defined(HAVE_LIBLOCKFILE)
382     for (i = 0;;) {
383         /* attempt to create lock file */
384         if (lockit (&lkinfo) == 0) {
385             /* if successful, turn on timer and return */
386             timerON (lkinfo.curlock, fd);
387             return fd;
388         } else {
389             /*
390              * Abort locking, if we fail to lock after 5 attempts
391              * and are never able to stat the lock file.
392              */
393             if (stat (lkinfo.curlock, &st) == -1) {
394                 if (i++ > 5)
395                     return -1;
396                 sleep (5);
397             } else {
398                 i = 0;
399                 time (&curtime);
400
401                 /* check for stale lockfile, else sleep */
402                 if (curtime > st.st_ctime + RSECS)
403                     unlink (lkinfo.curlock);
404                 else
405                     sleep (5);
406             }
407         }
408     }
409 #else
410     if (lockfile_create(lkinfo.curlock, 5, 0) == L_SUCCESS) {
411         timerON(lkinfo.curlock, fd);
412         return fd;
413     }
414     else {
415         close(fd);
416         return -1;
417     }
418 #endif /* HAVE_LIBLOCKFILE */
419 }
420
421 #if !defined(HAVE_LIBLOCKFILE)
422 /*
423  * Routine that actually tries to create
424  * the lock file.
425  */
426
427 static int
428 lockit (struct lockinfo *li)
429 {
430     int fd;
431     char *curlock, *tmplock;
432
433 #if 0
434     char buffer[128];
435 #endif
436
437     curlock = li->curlock;
438     tmplock = li->tmplock;
439
440 #ifdef HAVE_MKSTEMP
441     if ((fd = mkstemp(tmplock)) == -1)
442         return -1;
443 #else
444     if (mktemp(tmplock) == NULL)
445         return -1;
446     if (unlink(tmplock) == -1 && errno != ENOENT)
447         return -1;
448     /* create the temporary lock file */
449     if ((fd = creat(tmplock, 0600)) == -1)
450         return -1;
451 #endif
452
453 #if 0
454     /* write our process id into lock file */
455     snprintf (buffer, sizeof(buffer), "nmh lock: pid %d\n", (int) getpid());
456     write(fd, buffer, strlen(buffer) + 1);
457 #endif
458
459     close (fd);
460
461     /*
462      * Now try to create the real lock file
463      * by linking to the temporary file.
464      */
465     fd = link(tmplock, curlock);
466     unlink(tmplock);
467
468     return (fd == -1 ? -1 : 0);
469 }
470 #endif /* HAVE_LIBLOCKFILE */
471
472 /*
473  * Get name of lock file, and temporary lock file
474  */
475
476 static void
477 lockname (char *file, struct lockinfo *li, int isnewlock)
478 {
479     int bplen, tmplen;
480     char *bp, *cp;
481
482 #if 0
483     struct stat st;
484 #endif
485
486     if ((cp = strrchr (file, '/')) == NULL || *++cp == 0)
487         cp = file;
488
489     bp = li->curlock;
490     bplen = 0;
491 #ifdef LOCKDIR
492     snprintf (bp, sizeof(li->curlock), "%s/", lockdir);
493     tmplen = strlen (bp);
494     bp    += tmplen;
495     bplen += tmplen;
496 #else
497     if (cp != file) {
498         snprintf (bp, sizeof(li->curlock), "%.*s", cp - file, file);
499         tmplen = strlen (bp);
500         bp    += tmplen;
501         bplen += tmplen;
502     }
503 #endif
504
505 #if 0
506     /*
507      * mmdf style dot locking.  Currently not supported.
508      * If we start supporting mmdf style dot locking,
509      * we will need to change the return value of lockname
510      */
511     if (stat (file, &st) == -1)
512         return -1;
513
514     snprintf (bp, sizeof(li->curlock) - bplen, "LCK%05d.%05d",
515         st.st_dev, st.st_ino);
516 #endif
517
518     snprintf (bp, sizeof(li->curlock) - bplen, "%s.lock", cp);
519
520 #if !defined(HAVE_LIBLOCKFILE)
521     /*
522      * If this is for a new lock, create a name for
523      * the temporary lock file for lockit()
524      */
525     if (isnewlock) {
526         if ((cp = strrchr (li->curlock, '/')) == NULL || *++cp == 0)
527             strncpy (li->tmplock, ",LCK.XXXXXX", sizeof(li->tmplock));
528         else
529             snprintf (li->tmplock, sizeof(li->tmplock), "%.*s,LCK.XXXXXX",
530                      cp - li->curlock, li->curlock);
531     }
532 #endif
533 }
534
535
536 /*
537  * Add new lockfile to the list of open lockfiles
538  * and start the lock file timer.
539  */
540
541 static void
542 timerON (char *curlock, int fd)
543 {
544     struct lock *lp;
545     size_t len;
546
547     if (!(lp = (struct lock *) malloc (sizeof(*lp))))
548         return;
549
550     len = strlen(curlock) + 1;
551     lp->l_fd = fd;
552     if (!(lp->l_lock = malloc (len))) {
553         free ((char *) lp);
554         return;
555     }
556     memcpy (lp->l_lock, curlock, len);
557     lp->l_next = l_top;
558
559     if (!l_top) {
560         /* perhaps SIGT{STP,TIN,TOU} ? */
561         SIGNAL (SIGALRM, alrmser);
562         alarm (NSECS);
563     }
564
565     l_top = lp;
566 }
567
568
569 /*
570  * Search through the list of lockfiles for the
571  * current lockfile, and remove it from the list.
572  */
573
574 static void
575 timerOFF (int fd)
576 {
577     struct lock *pp, *lp;
578
579     alarm(0);
580
581     if (l_top) {
582         for (pp = lp = l_top; lp; pp = lp, lp = lp->l_next) {
583             if (lp->l_fd == fd)
584                 break;
585         }
586         if (lp) {
587             if (lp == l_top)
588                 l_top = lp->l_next;
589             else
590                 pp->l_next = lp->l_next;
591
592             free (lp->l_lock);
593             free (lp);
594         }
595     }
596
597     /* if there are locks left, restart timer */
598     if (l_top)
599         alarm (NSECS);
600 }
601
602
603 /*
604  * If timer goes off, we update the ctime of all open
605  * lockfiles, so another command doesn't remove them.
606  */
607
608 static RETSIGTYPE
609 alrmser (int sig)
610 {
611     int j;
612     char *lockfile;
613     struct lock *lp;
614
615 #ifndef RELIABLE_SIGNALS
616     SIGNAL (SIGALRM, alrmser);
617 #endif
618
619     /* update the ctime of all the lock files */
620     for (lp = l_top; lp; lp = lp->l_next) {
621         lockfile = lp->l_lock;
622 #if !defined(HAVE_LIBLOCKFILE)
623         if (*lockfile && (j = creat (lockfile, 0600)) != -1)
624             close (j);
625 #else
626     lockfile_touch(lockfile);
627 #endif
628     }
629
630     /* restart the alarm */
631     alarm (NSECS);
632 }
633
634 #endif /* DOT_LOCKING */