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