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