]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_lock.c
Merge master
[netatalk.git] / libatalk / adouble / ad_lock.c
1 /* 
2  * Copyright (c) 1998,1999 Adrian Sun (asun@zoology.washington.edu)
3  * All Rights Reserved. See COPYRIGHT for more information.
4  *
5  * Byte-range locks. This uses either whole-file flocks to fake byte
6  * locks or fcntl-based actual byte locks. Because fcntl locks are
7  * process-oriented, we need to keep around a list of file descriptors
8  * that refer to the same file. Currently, this doesn't serialize access 
9  * to the locks. as a result, there's the potential for race conditions. 
10  *
11  * TODO: fix the race when reading/writing.
12  *       keep a pool of both locks and reference counters around so that
13  *       we can save on mallocs. we should also use a tree to keep things
14  *       sorted.
15  */
16
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif /* HAVE_CONFIG_H */
20
21 #include <atalk/adouble.h>
22 #include <atalk/logger.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <inttypes.h>
28
29 #include <string.h>
30
31 #include "ad_lock.h"
32
33 /* translate between ADLOCK styles and specific locking mechanisms */
34 #define XLATE_FLOCK(type) ((type) == ADLOCK_RD ? LOCK_SH : \
35 ((type) == ADLOCK_WR ? LOCK_EX : \
36  ((type) == ADLOCK_CLR ? LOCK_UN : -1)))
37
38 /* ----------------------- */
39 static int set_lock(int fd, int cmd,  struct flock *lock)
40 {
41   if (fd == -2) {
42       /* We assign fd = -2 for symlinks -> do nothing */
43       if (cmd == F_GETLK)
44             lock->l_type = F_UNLCK;
45       return 0;
46   }
47   return fcntl(fd, cmd, lock);
48 }
49
50 /* ----------------------- */
51 static int XLATE_FCNTL_LOCK(int type) 
52 {
53     switch(type) {
54     case ADLOCK_RD:
55         return F_RDLCK;
56     case ADLOCK_WR:
57          return F_WRLCK;
58     case ADLOCK_CLR:
59          return F_UNLCK;
60     }
61     return -1;
62 }
63
64 /* ----------------------- */
65 static int OVERLAP(off_t a, off_t alen, off_t b, off_t blen) 
66 {
67     return (!alen && a <= b) || 
68         (!blen && b <= a) || 
69         ( (a + alen > b) && (b + blen > a) );
70 }
71
72 /* allocation for lock regions. we allocate aggressively and shrink
73  * only in large chunks. */
74 #define ARRAY_BLOCK_SIZE 10 
75 #define ARRAY_FREE_DELTA 100
76
77 /* remove a lock and compact space if necessary */
78 static void adf_freelock(struct ad_fd *ad, const int i)
79 {
80     adf_lock_t *lock = ad->adf_lock + i;
81
82     if (--(*lock->refcount) < 1) {
83         free(lock->refcount); 
84         if (!ad->adf_excl) {
85             lock->lock.l_type = F_UNLCK;
86             set_lock(ad->adf_fd, F_SETLK, &lock->lock); /* unlock */
87         }
88     }
89
90     ad->adf_lockcount--;
91
92     /* move another lock into the empty space */
93     if (i < ad->adf_lockcount) {
94         memcpy(lock, lock + ad->adf_lockcount - i, sizeof(adf_lock_t));
95     }
96
97     /* free extra cruft if we go past a boundary. we always want to
98      * keep at least some stuff around for allocations. this wastes
99      * a bit of space to save time on reallocations. */
100     if ((ad->adf_lockmax > ARRAY_FREE_DELTA) &&
101         (ad->adf_lockcount + ARRAY_FREE_DELTA < ad->adf_lockmax)) {
102             struct adf_lock_t *tmp;
103
104             tmp = (struct adf_lock_t *) 
105                     realloc(ad->adf_lock, sizeof(adf_lock_t)*
106                             (ad->adf_lockcount + ARRAY_FREE_DELTA));
107             if (tmp) {
108                 ad->adf_lock = tmp;
109                 ad->adf_lockmax = ad->adf_lockcount + ARRAY_FREE_DELTA;
110             }
111     }
112 }
113
114
115 /* this needs to deal with the following cases:
116  * 1) fork is the only user of the lock 
117  * 2) fork shares a read lock with another open fork
118  *
119  * i converted to using arrays of locks. everytime a lock
120  * gets removed, we shift all of the locks down.
121  */
122 static void adf_unlock(struct ad_fd *ad, const int fork)
123 {
124     adf_lock_t *lock = ad->adf_lock;
125     int i;
126
127     for (i = 0; i < ad->adf_lockcount; i++) {
128       
129       if (lock[i].user == fork) {
130         /* we're really going to delete this lock. note: read locks
131            are the only ones that allow refcounts > 1 */
132          adf_freelock(ad, i);
133          i--; /* we shifted things down, so we need to backtrack */
134          /* unlikely but realloc may have change adf_lock */
135          lock = ad->adf_lock;       
136       }
137     }
138 }
139
140 /* relock any byte lock that overlaps off/len. unlock everything
141  * else. */
142 static void adf_relockrange(struct ad_fd *ad, int fd, off_t off, off_t len)
143 {
144     adf_lock_t *lock = ad->adf_lock;
145     int i;
146     
147     if (!ad->adf_excl) for (i = 0; i < ad->adf_lockcount; i++) {
148       if (OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
149         set_lock(fd, F_SETLK, &lock[i].lock);
150     }
151 }
152
153
154 /* find a byte lock that overlaps off/len for a particular open fork */
155 static int adf_findlock(struct ad_fd *ad,
156                         const int fork, const int type,
157                         const off_t off,
158                         const off_t len)
159 {
160   adf_lock_t *lock = ad->adf_lock;
161   int i;
162   
163   for (i = 0; i < ad->adf_lockcount; i++) {
164     if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK)) ||
165         ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK))) &&
166         (lock[i].user == fork) && 
167         OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) {
168       return i;
169     }
170   }
171   return -1;
172 }
173
174
175 /* search other fork lock lists */
176 static int adf_findxlock(struct ad_fd *ad, 
177                          const int fork, const int type,
178                          const off_t off,
179                          const off_t len)
180 {
181   adf_lock_t *lock = ad->adf_lock;
182   int i;
183   
184   for (i = 0; i < ad->adf_lockcount; i++) {
185     if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK)) ||
186          ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK))) &&
187         (lock[i].user != fork) && 
188         OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
189             return i;
190   } 
191   return -1;
192 }
193
194 /* okay, this needs to do the following:
195  * 1) check current list of locks. error on conflict.
196  * 2) apply the lock. error on conflict with another process.
197  * 3) update the list of locks this file has.
198  * 
199  * NOTE: this treats synchronization locks a little differently. we
200  *       do the following things for those:
201  *       1) if the header file exists, all the locks go in the beginning
202  *          of that.
203  *       2) if the header file doesn't exist, we stick the locks
204  *          in the locations specified by AD_FILELOCK_RD/WR.
205  */
206 #define LOCK_DATA_WR (0)
207 #define LOCK_DATA_RD (1)
208 #define LOCK_RSRC_WR (2)
209 #define LOCK_RSRC_RD (3)
210
211 #define LOCK_RSRC_DRD (4)
212 #define LOCK_RSRC_DWR (5)
213 #define LOCK_DATA_DRD (6)
214 #define LOCK_DATA_DWR (7)
215
216 #define LOCK_RSRC_NONE (8)
217 #define LOCK_DATA_NONE (9)
218
219 /* -------------- 
220         translate a data fork lock to an offset
221 */
222
223 static off_t df2off(off_t off)
224 {
225     off_t start = off;
226         if (off == AD_FILELOCK_OPEN_WR)
227                 start = LOCK_DATA_WR;
228         else if (off == AD_FILELOCK_OPEN_RD)
229                 start = LOCK_DATA_RD;
230     else if (off == AD_FILELOCK_DENY_RD)
231                 start = LOCK_DATA_DRD;
232         else if (off == AD_FILELOCK_DENY_WR)
233                 start = LOCK_DATA_DWR;
234         else if (off == AD_FILELOCK_OPEN_NONE)
235                 start = LOCK_DATA_NONE;
236         return start;
237 }
238
239 /* -------------- 
240         translate a resource fork lock to an offset
241 */
242
243 static off_t hf2off(off_t off)
244 {
245     off_t start = off;
246         if (off == AD_FILELOCK_OPEN_WR)
247                 start = LOCK_RSRC_WR;
248         else if (off == AD_FILELOCK_OPEN_RD)
249                 start = LOCK_RSRC_RD;
250     else if (off == AD_FILELOCK_DENY_RD)
251                 start = LOCK_RSRC_DRD;
252         else if (off == AD_FILELOCK_DENY_WR)
253                 start = LOCK_RSRC_DWR;
254         else if (off == AD_FILELOCK_OPEN_NONE)
255                 start = LOCK_RSRC_NONE;
256         return start;
257 }
258
259 /* ------------------ */
260 int ad_lock(struct adouble *ad, const uint32_t eid, const int locktype,
261             const off_t off, const off_t len, const int fork)
262 {
263   struct flock lock;
264   struct ad_fd *adf;
265   adf_lock_t *adflock;
266   int oldlock;
267   int i;
268   int type;  
269
270   lock.l_start = off;
271   type = locktype;
272   if (eid == ADEID_DFORK) {
273     adf = &ad->ad_data_fork;
274     if ((type & ADLOCK_FILELOCK)) {
275         if (ad_meta_fileno(ad) != -1) { /* META */
276             adf = ad->ad_mdp;
277             lock.l_start = df2off(off);
278         }
279     }
280   } else { /* rfork */
281     if (ad_meta_fileno(ad) == -1 || ad_reso_fileno(ad) == -1) {
282         /* there's no meta data. return a lock error 
283          * otherwise if a second process is able to create it
284          * locks are a mess.
285          */
286         errno = EACCES;
287         return -1;
288     }
289     if (type & ADLOCK_FILELOCK) {
290       adf = ad->ad_mdp;                 /* either resource or meta data (set in ad_open) */
291       lock.l_start = hf2off(off);
292     }
293     else {
294       /* we really want the resource fork it's a byte lock */
295       adf = &ad->ad_resource_fork;
296       lock.l_start += ad_getentryoff(ad, eid);
297     }
298   }
299   /* NOTE: we can't write lock a read-only file. on those, we just
300     * make sure that we have a read lock set. that way, we at least prevent
301     * someone else from really setting a deny read/write on the file. 
302     */
303   if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
304       type = (type & ~ADLOCK_WR) | ADLOCK_RD;
305   }
306   
307   lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
308   lock.l_whence = SEEK_SET;
309   lock.l_len = len;
310
311   /* byte_lock(len=-1) lock whole file */
312   if (len == BYTELOCK_MAX) {
313       lock.l_len -= lock.l_start; /* otherwise  EOVERFLOW error */
314   }
315
316   /* see if it's locked by another fork. 
317    * NOTE: this guarantees that any existing locks must be at most
318    * read locks. we use ADLOCK_WR/RD because F_RD/WRLCK aren't
319    * guaranteed to be ORable. */
320   if (adf_findxlock(adf, fork, ADLOCK_WR | 
321                     ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
322                     lock.l_start, lock.l_len) > -1) {
323     errno = EACCES;
324     return -1;
325   }
326   
327   /* look for any existing lock that we may have */
328   i = adf_findlock(adf, fork, ADLOCK_RD | ADLOCK_WR, lock.l_start, lock.l_len);
329   adflock = (i < 0) ? NULL : adf->adf_lock + i;
330
331   /* here's what we check for:
332      1) we're trying to re-lock a lock, but we didn't specify an update.
333      2) we're trying to free only part of a lock. 
334      3) we're trying to free a non-existent lock. */
335   if ( (!adflock && (lock.l_type == F_UNLCK))
336        ||
337        (adflock
338         && !(type & ADLOCK_UPGRADE)
339         && ((lock.l_type != F_UNLCK)
340             || (adflock->lock.l_start != lock.l_start)
341             || (adflock->lock.l_len != lock.l_len) ))
342       ) {
343       errno = EINVAL;
344       return -1;
345   }
346
347
348   /* now, update our list of locks */
349   /* clear the lock */
350   if (lock.l_type == F_UNLCK) { 
351     adf_freelock(adf, i);
352     return 0;
353   }
354
355   /* attempt to lock the file. */
356   if (!adf->adf_excl && set_lock(adf->adf_fd, F_SETLK, &lock) < 0) 
357     return -1;
358
359   /* we upgraded this lock. */
360   if (adflock && (type & ADLOCK_UPGRADE)) {
361     memcpy(&adflock->lock, &lock, sizeof(lock));
362     return 0;
363   } 
364
365   /* it wasn't an upgrade */
366   oldlock = -1;
367   if (lock.l_type == F_RDLCK) {
368     oldlock = adf_findxlock(adf, fork, ADLOCK_RD, lock.l_start, lock.l_len);
369   } 
370     
371   /* no more space. this will also happen if lockmax == lockcount == 0 */
372   if (adf->adf_lockmax == adf->adf_lockcount) { 
373     adf_lock_t *tmp = (adf_lock_t *) 
374             realloc(adf->adf_lock, sizeof(adf_lock_t)*
375                     (adf->adf_lockmax + ARRAY_BLOCK_SIZE));
376     if (!tmp)
377       goto fcntl_lock_err;
378     adf->adf_lock = tmp;
379     adf->adf_lockmax += ARRAY_BLOCK_SIZE;
380   } 
381   adflock = adf->adf_lock + adf->adf_lockcount;
382
383   /* fill in fields */
384   memcpy(&adflock->lock, &lock, sizeof(lock));
385   adflock->user = fork;
386   if (oldlock > -1) {
387     adflock->refcount = (adf->adf_lock + oldlock)->refcount;
388   } else if ((adflock->refcount = calloc(1, sizeof(int))) == NULL) {
389     goto fcntl_lock_err;
390   }
391   
392   (*adflock->refcount)++;
393   adf->adf_lockcount++;
394   return 0;
395
396 fcntl_lock_err:
397   lock.l_type = F_UNLCK;
398   if (!adf->adf_excl) set_lock(adf->adf_fd, F_SETLK, &lock);
399   return -1;
400   return 0;
401 }
402
403 /* -------------------------
404    we are using lock as tristate variable
405    
406    we have a lock ==> 1
407    no             ==> 0
408    error          ==> -1
409       
410 */
411 static int testlock(struct ad_fd *adf, off_t off, off_t len)
412 {
413   struct flock lock;
414   adf_lock_t *plock;
415   int i;
416
417   lock.l_start = off;
418
419   plock = adf->adf_lock;
420   lock.l_whence = SEEK_SET;
421   lock.l_len = len;
422
423   /* Do we have a lock? */
424   for (i = 0; i < adf->adf_lockcount; i++) {
425     if (OVERLAP(lock.l_start, 1, plock[i].lock.l_start, plock[i].lock.l_len)) 
426         return 1;   /* */
427   }
428   /* Does another process have a lock? 
429   */
430   lock.l_type = (adf->adf_flags & O_RDWR) ?F_WRLCK : F_RDLCK;
431
432   if (set_lock(adf->adf_fd, F_GETLK, &lock) < 0) {
433       /* is that kind of error possible ?*/
434       return (errno == EACCES || errno == EAGAIN)?1:-1;
435   }
436   
437   if (lock.l_type == F_UNLCK) {
438       return 0;
439   }
440   return 1;
441   return 0;
442 }
443
444
445 /* -------------------------
446 */
447 int ad_tmplock(struct adouble *ad, const uint32_t eid, const int locktype,
448                const off_t off, const off_t len, const int fork)
449 {
450   struct flock lock;
451   struct ad_fd *adf;
452   int err;
453   int type;  
454
455   lock.l_start = off;
456   type = locktype;
457   if (eid == ADEID_DFORK) {
458     adf = &ad->ad_data_fork;
459   } else {
460     /* FIXME META */
461     adf = &ad->ad_resource_fork;
462     if (adf->adf_fd == -1) {
463         /* there's no resource fork. return success */
464         return 0;
465     }
466     /* if ADLOCK_FILELOCK we want a lock from offset 0
467      * it's used when deleting a file:
468      * in open we put read locks on meta datas
469      * in delete a write locks on the whole file
470      * so if the file is open by somebody else it fails
471     */
472     if (!(type & ADLOCK_FILELOCK))
473         lock.l_start += ad_getentryoff(ad, eid);
474   }
475
476   if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
477       type = (type & ~ADLOCK_WR) | ADLOCK_RD;
478   }
479   
480   lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
481   lock.l_whence = SEEK_SET;
482   lock.l_len = len;
483
484   /* see if it's locked by another fork. */
485   if (fork && adf_findxlock(adf, fork, ADLOCK_WR | 
486                     ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
487                     lock.l_start, lock.l_len) > -1) {
488     errno = EACCES;
489     return -1;
490   }
491
492   /* okay, we might have ranges byte-locked. we need to make sure that
493    * we restore the appropriate ranges once we're done. so, we check
494    * for overlap on an unlock and relock. 
495    * XXX: in the future, all the byte locks will be sorted and contiguous.
496    *      we just want to upgrade all the locks and then downgrade them
497    *      here. */
498   if (!adf->adf_excl) {
499        err = set_lock(adf->adf_fd, F_SETLK, &lock);
500   }
501   else {
502       err = 0;
503   }
504   if (!err && (lock.l_type == F_UNLCK))
505     adf_relockrange(adf, adf->adf_fd, lock.l_start, len);
506
507   return err;
508 }
509
510 /* --------------------- */
511 void ad_unlock(struct adouble *ad, const int fork)
512 {
513   if (ad_data_fileno(ad) != -1) {
514     adf_unlock(&ad->ad_data_fork, fork);
515   }
516   if (ad_reso_fileno(ad) != -1) {
517     adf_unlock(&ad->ad_resource_fork, fork);
518   }
519 }
520
521 /******************************************************************************
522  * Public functions
523  ******************************************************************************/
524
525 /* --------------- */
526 int ad_testlock(struct adouble *ad, int eid, const off_t off)
527 {
528   struct ad_fd *adf;
529   off_t      lock_offset;
530
531   lock_offset = off;
532   if (eid == ADEID_DFORK) {
533     adf = &ad->ad_data_fork;
534     if (ad_meta_fileno(ad) != -1) {
535         adf = ad->ad_mdp;
536         lock_offset = df2off(off);
537     }
538   } 
539   else { /* rfork */
540     if (ad_meta_fileno(ad) == -1) {
541         /* there's no resource fork. return no lock */
542         return 0;
543     }
544     adf = ad->ad_mdp;
545     lock_offset = hf2off(off);
546   }
547   return testlock(adf, lock_offset, 1);
548 }
549
550 /* -------------------------
551    return if a file is open by another process.
552    Optimized for the common case:
553    - there's no locks held by another process (clients)
554    - or we already know the answer and don't need to test.
555 */
556 uint16_t ad_openforks(struct adouble *ad, uint16_t attrbits)
557 {
558   u_int16_t ret = 0;
559   struct ad_fd *adf;
560   off_t off;
561
562   if (!(attrbits & (ATTRBIT_DOPEN | ATTRBIT_ROPEN))) {
563       off_t len;
564       /* XXX know the locks layout: 
565          AD_FILELOCK_OPEN_WR is first 
566          and use it for merging requests
567       */
568       if (ad_meta_fileno(ad) != -1) {
569           /* there's a resource fork test the four bytes for
570            * data RW/RD and fork RW/RD locks in one request
571           */
572           adf = ad->ad_mdp;
573           off = LOCK_DATA_WR;
574           len = 4;
575       }
576       else {
577           /* no resource fork, only data RD/RW may exist */
578           adf = &ad->ad_data_fork;
579           off = AD_FILELOCK_OPEN_WR;
580           len = 2;
581       }
582       if (!testlock(adf, off, len))
583           return ret;
584   }
585   /* either there's a lock or we already know one 
586      fork is open
587   */
588   if (!(attrbits & ATTRBIT_DOPEN)) {
589       if (ad_meta_fileno(ad) != -1) {
590           adf = ad->ad_mdp;
591           off = LOCK_DATA_WR;
592       }
593       else {
594           adf = &ad->ad_data_fork;
595           off = AD_FILELOCK_OPEN_WR;
596       }
597       ret = testlock(adf, off, 2) > 0? ATTRBIT_DOPEN : 0;
598   }
599
600   if (!(attrbits & ATTRBIT_ROPEN)) {
601       if (ad_meta_fileno(ad) != -1) {
602           adf = ad->ad_mdp;
603           off = LOCK_RSRC_WR;
604           ret |= testlock(adf, off, 2) > 0? ATTRBIT_ROPEN : 0;
605       }
606   }
607
608   return ret;
609 }
610
611 /* -------------------------
612    the fork is opened in Read Write, Deny Read, Deny Write mode
613    lock the whole file once   
614 */
615 int ad_excl_lock(struct adouble *ad, const uint32_t eid)
616 {
617   struct ad_fd *adf;
618   struct flock lock;
619   int    err;
620   
621   lock.l_start = 0;
622   lock.l_type = F_WRLCK;
623   lock.l_whence = SEEK_SET;
624   lock.l_len = 0;
625
626   if (eid == ADEID_DFORK) {
627     adf = &ad->ad_data_fork;
628   } else {
629     adf = &ad->ad_resource_fork;
630     lock.l_start = ad_getentryoff(ad, eid);
631   }
632   
633   err = set_lock(adf->adf_fd, F_SETLK, &lock);
634   if (!err)
635       adf->adf_excl = 1;
636   return err;
637 }