* patch #3966: Create a mh_xmalloc function to prevent mistakes when
[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 MMDFONLY
40 # include <mmdfonly.h>
41 # include <lockonly.h>
42 #endif /* MMDFONLY */
43
44 #ifdef HAVE_FCNTL_H
45 # include <fcntl.h>
46 #else
47 # include <sys/file.h>
48 #endif
49
50 #if defined(LOCKF_LOCKING) || defined(FLOCK_LOCKING)
51 # include <sys/file.h>
52 #endif
53
54 #include <signal.h>
55
56 #if defined(HAVE_LIBLOCKFILE)
57 #include <lockfile.h>
58 #endif
59
60 #ifdef LOCKDIR
61 char *lockdir = LOCKDIR;
62 #endif
63
64 /* Are we using any kernel locking? */
65 #if defined (FLOCK_LOCKING) || defined(LOCKF_LOCKING) || defined(FCNTL_LOCKING)
66 # define KERNEL_LOCKING
67 #endif
68
69 #ifdef DOT_LOCKING
70
71 /* struct for getting name of lock file to create */
72 struct lockinfo {
73     char curlock[BUFSIZ];
74 #if !defined(HAVE_LIBLOCKFILE)
75     char tmplock[BUFSIZ];
76 #endif
77 };
78
79 /*
80  * Amount of time to wait before
81  * updating ctime of lock file.
82  */
83 #define NSECS 20
84
85 #if !defined(HAVE_LIBLOCKFILE)
86 /*
87  * How old does a lock file need to be
88  * before we remove it.
89  */
90 #define RSECS 180
91 #endif /* HAVE_LIBLOCKFILE */
92
93 /* struct for recording and updating locks */
94 struct lock {
95     int l_fd;
96     char *l_lock;
97     struct lock *l_next;
98 };
99
100 /* top of list containing all open locks */
101 static struct lock *l_top = NULL;
102 #endif /* DOT_LOCKING */
103
104 /*
105  * static prototypes
106  */
107 #ifdef KERNEL_LOCKING
108 static int lkopen_kernel (char *, int, mode_t);
109 #endif
110
111 #ifdef DOT_LOCKING
112 static int lkopen_dot (char *, int, mode_t);
113 static int lockit (struct lockinfo *);
114 static void lockname (char *, struct lockinfo *, int);
115 static void timerON (char *, int);
116 static void timerOFF (int);
117 static RETSIGTYPE alrmser (int);
118 #endif
119
120
121 /*
122  * Base routine to open and lock a file,
123  * and return a file descriptor.
124  */
125
126 int
127 lkopen (char *file, int access, mode_t mode)
128 {
129 #ifdef KERNEL_LOCKING
130     return lkopen_kernel(file, access, mode);
131 #endif
132
133 #ifdef DOT_LOCKING
134     return lkopen_dot(file, access, mode);
135 #endif
136 }
137
138
139 /*
140  * Base routine to close and unlock a file,
141  * given a file descriptor.
142  */
143
144 int
145 lkclose (int fd, char *file)
146 {
147 #ifdef FCNTL_LOCKING
148     struct flock buf;
149 #endif
150
151 #ifdef DOT_LOCKING
152     struct lockinfo lkinfo;
153 #endif
154
155     if (fd == -1)
156         return 0;
157
158 #ifdef FCNTL_LOCKING
159     buf.l_type   = F_UNLCK;
160     buf.l_whence = SEEK_SET;
161     buf.l_start  = 0;
162     buf.l_len    = 0;
163     fcntl(fd, F_SETLK, &buf);
164 #endif
165
166 #ifdef FLOCK_LOCKING
167     flock (fd, LOCK_UN);
168 #endif
169
170 #ifdef LOCKF_LOCKING
171     /* make sure we unlock the whole thing */
172     lseek (fd, (off_t) 0, SEEK_SET);
173     lockf (fd, F_ULOCK, 0L);
174 #endif  
175
176 #ifdef DOT_LOCKING
177     lockname (file, &lkinfo, 0);        /* get name of lock file */
178 #if !defined(HAVE_LIBLOCKFILE)
179     unlink (lkinfo.curlock);            /* remove lock file      */
180 #else
181     lockfile_remove(lkinfo.curlock);
182 #endif /* HAVE_LIBLOCKFILE */
183     timerOFF (fd);                      /* turn off lock timer   */
184 #endif /* DOT_LOCKING */
185
186     return (close (fd));
187 }
188
189
190 /*
191  * Base routine to open and lock a file,
192  * and return a FILE pointer
193  */
194
195 FILE *
196 lkfopen (char *file, char *mode)
197 {
198     int fd, access;
199     FILE *fp;
200
201     if (strcmp (mode, "r") == 0)
202         access = O_RDONLY;
203     else if (strcmp (mode, "r+") == 0)
204         access = O_RDWR;
205     else if (strcmp (mode, "w") == 0)
206         access = O_WRONLY | O_CREAT | O_TRUNC;
207     else if (strcmp (mode, "w+") == 0)
208         access = O_RDWR | O_CREAT | O_TRUNC;
209     else if (strcmp (mode, "a") == 0)
210         access = O_WRONLY | O_CREAT | O_APPEND;
211     else if (strcmp (mode, "a+") == 0)
212         access = O_RDWR | O_CREAT | O_APPEND;
213     else {
214         errno = EINVAL;
215         return NULL;
216     }
217
218     if ((fd = lkopen (file, access, 0666)) == -1)
219         return NULL;
220
221     if ((fp = fdopen (fd, mode)) == NULL) {
222         close (fd);
223         return NULL;
224     }
225
226     return fp;
227 }
228
229
230 /*
231  * Base routine to close and unlock a file,
232  * given a FILE pointer
233  */
234
235 int
236 lkfclose (FILE *fp, char *file)
237 {
238 #ifdef FCNTL_LOCKING
239     struct flock buf;
240 #endif
241
242 #ifdef DOT_LOCKING
243     struct lockinfo lkinfo;
244 #endif
245
246     if (fp == NULL)
247         return 0;
248
249 #ifdef FCNTL_LOCKING
250     buf.l_type   = F_UNLCK;
251     buf.l_whence = SEEK_SET;
252     buf.l_start  = 0;
253     buf.l_len    = 0;
254     fcntl(fileno(fp), F_SETLK, &buf);
255 #endif
256
257 #ifdef FLOCK_LOCKING
258     flock (fileno(fp), LOCK_UN);
259 #endif
260
261 #ifdef LOCKF_LOCKING
262     /* make sure we unlock the whole thing */
263     fseek (fp, 0L, SEEK_SET);
264     lockf (fileno(fp), F_ULOCK, 0L);
265 #endif
266
267 #ifdef DOT_LOCKING
268     lockname (file, &lkinfo, 0);        /* get name of lock file */
269 #if !defined(HAVE_LIBLOCKFILE)
270     unlink (lkinfo.curlock);            /* remove lock file      */
271 #else
272     lockfile_remove(lkinfo.curlock);
273 #endif /* HAVE_LIBLOCKFILE */
274     timerOFF (fileno(fp));              /* turn off lock timer   */
275 #endif /* DOT_LOCKING */
276
277     return (fclose (fp));
278 }
279
280
281 #ifdef KERNEL_LOCKING
282
283 /*
284  * open and lock a file, using kernel locking
285  */
286
287 static int
288 lkopen_kernel (char *file, int access, mode_t mode)
289 {
290     int fd, i, j;
291
292 # ifdef FCNTL_LOCKING
293     struct flock buf;
294 # endif /* FCNTL_LOCKING */
295
296     for (i = 0; i < 5; i++) {
297
298 # if defined(LOCKF_LOCKING) || defined(FCNTL_LOCKING)
299         /* remember the original mode */
300         j = access;
301
302         /* make sure we open at the beginning */
303         access &= ~O_APPEND;
304
305         /*
306          * We MUST have write permission or
307          * lockf/fcntl() won't work
308          */
309         if ((access & 03) == O_RDONLY) {
310             access &= ~O_RDONLY;
311             access |= O_RDWR;
312         }
313 # endif /* LOCKF_LOCKING || FCNTL_LOCKING */
314
315         if ((fd = open (file, access | O_NDELAY, mode)) == -1)
316             return -1;
317
318 # ifdef FCNTL_LOCKING
319         buf.l_type   = F_WRLCK;
320         buf.l_whence = SEEK_SET;
321         buf.l_start  = 0;
322         buf.l_len    = 0;
323         if (fcntl (fd, F_SETLK, &buf) != -1)
324             return fd;
325 # endif
326
327 # ifdef FLOCK_LOCKING
328         if (flock (fd, (((access & 03) == O_RDONLY) ? LOCK_SH : LOCK_EX)
329                    | LOCK_NB) != -1)
330             return fd;
331 # endif
332
333 # ifdef LOCKF_LOCKING
334         if (lockf (fd, F_TLOCK, 0L) != -1) {
335             /* see if we should be at the end */
336             if (j & O_APPEND)
337                 lseek (fd, (off_t) 0, SEEK_END);
338             return fd;
339         }
340 # endif
341
342         j = errno;
343         close (fd);
344         sleep (5);
345     }
346
347     close (fd);
348     errno = j;
349     return -1;
350 }
351
352 #endif /* KERNEL_LOCKING */
353
354
355 #ifdef DOT_LOCKING
356
357 /*
358  * open and lock a file, using dot locking
359  */
360
361 static int
362 lkopen_dot (char *file, int access, mode_t mode)
363 {
364     int i, fd;
365     time_t curtime;
366     struct lockinfo lkinfo;
367     struct stat st;
368
369     /* open the file */
370     if ((fd = open (file, access, mode)) == -1)
371         return -1;
372
373     /*
374      * Get the name of the eventual lock file, as well
375      * as a name for a temporary lock file.
376      */
377     lockname (file, &lkinfo, 1);
378
379 #if !defined(HAVE_LIBLOCKFILE)
380     for (i = 0;;) {
381         /* attempt to create lock file */
382         if (lockit (&lkinfo) == 0) {
383             /* if successful, turn on timer and return */
384             timerON (lkinfo.curlock, fd);
385             return fd;
386         } else {
387             /*
388              * Abort locking, if we fail to lock after 5 attempts
389              * and are never able to stat the lock file.
390              */
391             if (stat (lkinfo.curlock, &st) == -1) {
392                 if (i++ > 5)
393                     return -1;
394                 sleep (5);
395             } else {
396                 i = 0;
397                 time (&curtime);
398
399                 /* check for stale lockfile, else sleep */
400                 if (curtime > st.st_ctime + RSECS)
401                     unlink (lkinfo.curlock);
402                 else
403                     sleep (5);
404             }
405             lockname (file, &lkinfo, 1);
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     int j;
607     char *lockfile;
608     struct lock *lp;
609
610 #ifndef RELIABLE_SIGNALS
611     SIGNAL (SIGALRM, alrmser);
612 #endif
613
614     /* update the ctime of all the lock files */
615     for (lp = l_top; lp; lp = lp->l_next) {
616         lockfile = lp->l_lock;
617 #if !defined(HAVE_LIBLOCKFILE)
618         if (*lockfile && (j = creat (lockfile, 0600)) != -1)
619             close (j);
620 #else
621     lockfile_touch(lockfile);
622 #endif
623     }
624
625     /* restart the alarm */
626     alarm (NSECS);
627 }
628
629 #endif /* DOT_LOCKING */